provider.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. package cloud
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/url"
  9. "os"
  10. "reflect"
  11. "strings"
  12. "sync"
  13. "k8s.io/klog"
  14. "cloud.google.com/go/compute/metadata"
  15. v1 "k8s.io/api/core/v1"
  16. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  17. "k8s.io/client-go/kubernetes"
  18. )
  19. // Node is the interface by which the provider and cost model communicate Node prices.
  20. // The provider will best-effort try to fill out this struct.
  21. type Node struct {
  22. Cost string `json:"hourlyCost"`
  23. VCPU string `json:"CPU"`
  24. VCPUCost string `json:"CPUHourlyCost"`
  25. RAM string `json:"RAM"`
  26. RAMBytes string `json:"RAMBytes"`
  27. RAMCost string `json:"RAMGBHourlyCost"`
  28. Storage string `json:"storage"`
  29. StorageCost string `json:"storageHourlyCost"`
  30. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  31. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  32. UsageType string `json:"usageType"`
  33. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  34. GPUName string `json:"gpuName"`
  35. GPUCost string `json:"gpuCost"`
  36. }
  37. // PV is the interface by which the provider and cost model communicate PV prices.
  38. // The provider will best-effort try to fill out this struct.
  39. type PV struct {
  40. Cost string `json:"hourlyCost"`
  41. Class string `json:"storageClass"`
  42. Size string `json:"size"`
  43. Region string `json:"region"`
  44. Parameters map[string]string `json:"parameters"`
  45. }
  46. // Key represents a way for nodes to match between the k8s API and a pricing API
  47. type Key interface {
  48. ID() string // ID represents an exact match
  49. Features() string // Features are a comma separated string of node metadata that could match pricing
  50. GPUType() string // GPUType returns "" if no GPU exists, but the name of the GPU otherwise
  51. }
  52. type PVKey interface {
  53. Features() string
  54. }
  55. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  56. type OutOfClusterAllocation struct {
  57. Aggregator string `json:"aggregator"`
  58. Environment string `json:"environment"`
  59. Service string `json:"service"`
  60. Cost float64 `json:"cost"`
  61. Cluster string `json:"cluster"`
  62. }
  63. // Provider represents a k8s provider.
  64. type Provider interface {
  65. ClusterName() ([]byte, error)
  66. AddServiceKey(url.Values) error
  67. GetDisks() ([]byte, error)
  68. NodePricing(Key) (*Node, error)
  69. PVPricing(PVKey) (*PV, error)
  70. AllNodePricing() (interface{}, error)
  71. DownloadPricingData() error
  72. GetKey(map[string]string) Key
  73. GetPVKey(*v1.PersistentVolume, map[string]string) PVKey
  74. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  75. GetConfig() (*CustomPricing, error)
  76. ExternalAllocations(string, string, string) ([]*OutOfClusterAllocation, error)
  77. }
  78. // GetDefaultPricingData will search for a json file representing pricing data in /models/ and use it for base pricing info.
  79. func GetDefaultPricingData(fname string) (*CustomPricing, error) {
  80. path := os.Getenv("CONFIG_PATH")
  81. if path == "" {
  82. path = "/models/"
  83. }
  84. path += fname
  85. if _, err := os.Stat(path); err == nil {
  86. jsonFile, err := os.Open(path)
  87. if err != nil {
  88. return nil, err
  89. }
  90. defer jsonFile.Close()
  91. byteValue, err := ioutil.ReadAll(jsonFile)
  92. if err != nil {
  93. return nil, err
  94. }
  95. var customPricing = &CustomPricing{}
  96. err = json.Unmarshal([]byte(byteValue), customPricing)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return customPricing, nil
  101. } else if os.IsNotExist(err) {
  102. c := &CustomPricing{
  103. Provider: fname,
  104. Description: "Default prices based on GCP us-central1",
  105. CPU: "0.031611",
  106. SpotCPU: "0.006655",
  107. RAM: "0.004237",
  108. SpotRAM: "0.000892",
  109. GPU: "0.95",
  110. CustomPricesEnabled: "false",
  111. }
  112. cj, err := json.Marshal(c)
  113. if err != nil {
  114. return nil, err
  115. }
  116. err = ioutil.WriteFile(path, cj, 0644)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return c, nil
  121. } else {
  122. return nil, err
  123. }
  124. }
  125. const KeyUpdateType = "athenainfo"
  126. type CustomPricing struct {
  127. Provider string `json:"provider"`
  128. Description string `json:"description"`
  129. CPU string `json:"CPU"`
  130. SpotCPU string `json:"spotCPU"`
  131. RAM string `json:"RAM"`
  132. SpotRAM string `json:"spotRAM"`
  133. GPU string `json:"GPU"`
  134. SpotLabel string `json:"spotLabel,omitempty"`
  135. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  136. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  137. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  138. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  139. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  140. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  141. ProjectID string `json:"projectID,omitempty"`
  142. AthenaBucketName string `json:"athenaBucketName"`
  143. AthenaRegion string `json:"athenaRegion"`
  144. AthenaDatabase string `json:"athenaDatabase"`
  145. AthenaTable string `json:"athenaTable"`
  146. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  147. CustomPricesEnabled string `json:"customPricesEnabled"`
  148. }
  149. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  150. structValue := reflect.ValueOf(obj).Elem()
  151. structFieldValue := structValue.FieldByName(name)
  152. if !structFieldValue.IsValid() {
  153. return fmt.Errorf("No such field: %s in obj", name)
  154. }
  155. if !structFieldValue.CanSet() {
  156. return fmt.Errorf("Cannot set %s field value", name)
  157. }
  158. structFieldType := structFieldValue.Type()
  159. val := reflect.ValueOf(value)
  160. if structFieldType != val.Type() {
  161. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  162. }
  163. structFieldValue.Set(val)
  164. return nil
  165. }
  166. type NodePrice struct {
  167. CPU string
  168. RAM string
  169. }
  170. type CustomProvider struct {
  171. Clientset *kubernetes.Clientset
  172. Pricing map[string]*NodePrice
  173. SpotLabel string
  174. SpotLabelValue string
  175. DownloadPricingDataLock sync.RWMutex
  176. }
  177. func (*CustomProvider) GetConfig() (*CustomPricing, error) {
  178. return GetDefaultPricingData("default.json")
  179. }
  180. func (*CustomProvider) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  181. c, err := GetDefaultPricingData("default.json")
  182. if err != nil {
  183. return nil, err
  184. }
  185. path := os.Getenv("CONFIG_PATH")
  186. if path == "" {
  187. path = "/models/"
  188. }
  189. a := make(map[string]string)
  190. err = json.NewDecoder(r).Decode(&a)
  191. if err != nil {
  192. return nil, err
  193. }
  194. for k, v := range a {
  195. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  196. err := SetCustomPricingField(c, kUpper, v)
  197. if err != nil {
  198. return nil, err
  199. }
  200. }
  201. cj, err := json.Marshal(c)
  202. if err != nil {
  203. return nil, err
  204. }
  205. configPath := path + "default.json"
  206. err = ioutil.WriteFile(configPath, cj, 0644)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return c, nil
  211. }
  212. func (*CustomProvider) ClusterName() ([]byte, error) {
  213. return nil, nil
  214. }
  215. func (*CustomProvider) AddServiceKey(url.Values) error {
  216. return nil
  217. }
  218. func (*CustomProvider) GetDisks() ([]byte, error) {
  219. return nil, nil
  220. }
  221. func (c *CustomProvider) AllNodePricing() (interface{}, error) {
  222. c.DownloadPricingDataLock.RLock()
  223. defer c.DownloadPricingDataLock.RUnlock()
  224. return c.Pricing, nil
  225. }
  226. func (c *CustomProvider) NodePricing(key Key) (*Node, error) {
  227. c.DownloadPricingDataLock.RLock()
  228. defer c.DownloadPricingDataLock.RUnlock()
  229. k := key.Features()
  230. if _, ok := c.Pricing[k]; !ok {
  231. k = "default"
  232. }
  233. return &Node{
  234. VCPUCost: c.Pricing[k].CPU,
  235. RAMCost: c.Pricing[k].RAM,
  236. }, nil
  237. }
  238. func (c *CustomProvider) DownloadPricingData() error {
  239. c.DownloadPricingDataLock.Lock()
  240. defer c.DownloadPricingDataLock.Unlock()
  241. if c.Pricing == nil {
  242. m := make(map[string]*NodePrice)
  243. c.Pricing = m
  244. }
  245. p, err := GetDefaultPricingData("default.json")
  246. if err != nil {
  247. return err
  248. }
  249. c.Pricing["default"] = &NodePrice{
  250. CPU: p.CPU,
  251. RAM: p.RAM,
  252. }
  253. c.Pricing["default,spot"] = &NodePrice{
  254. CPU: p.SpotCPU,
  255. RAM: p.SpotRAM,
  256. }
  257. return nil
  258. }
  259. type customProviderKey struct {
  260. SpotLabel string
  261. SpotLabelValue string
  262. Labels map[string]string
  263. }
  264. func (c *customProviderKey) GPUType() string {
  265. return ""
  266. }
  267. func (c *customProviderKey) ID() string {
  268. return ""
  269. }
  270. func (c *customProviderKey) Features() string {
  271. if c.Labels[c.SpotLabel] != "" && c.Labels[c.SpotLabel] == c.SpotLabelValue {
  272. return "default,spot"
  273. }
  274. return "default" // TODO: multiple custom pricing support.
  275. }
  276. func (c *CustomProvider) GetKey(labels map[string]string) Key {
  277. return &customProviderKey{
  278. SpotLabel: c.SpotLabel,
  279. SpotLabelValue: c.SpotLabelValue,
  280. Labels: labels,
  281. }
  282. }
  283. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  284. // "start" and "end" are dates of the format YYYY-MM-DD
  285. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  286. func (*CustomProvider) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  287. return nil, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  288. }
  289. func (*CustomProvider) QuerySQL(query string) ([]byte, error) {
  290. return nil, nil
  291. }
  292. func (*CustomProvider) PVPricing(pvk PVKey) (*PV, error) {
  293. return nil, nil
  294. }
  295. func (*CustomProvider) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  296. return &awsPVKey{
  297. Labels: pv.Labels,
  298. StorageClassName: pv.Spec.StorageClassName,
  299. }
  300. }
  301. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  302. func NewProvider(clientset *kubernetes.Clientset, apiKey string) (Provider, error) {
  303. if metadata.OnGCE() {
  304. klog.V(3).Info("metadata reports we are in GCE")
  305. if apiKey == "" {
  306. return nil, errors.New("Supply a GCP Key to start getting data")
  307. }
  308. return &GCP{
  309. Clientset: clientset,
  310. APIKey: apiKey,
  311. }, nil
  312. }
  313. nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  314. if err != nil {
  315. return nil, err
  316. }
  317. provider := strings.ToLower(nodes.Items[0].Spec.ProviderID)
  318. if strings.HasPrefix(provider, "aws") {
  319. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  320. return &AWS{
  321. Clientset: clientset,
  322. }, nil
  323. } else if strings.HasPrefix(provider, "azure") {
  324. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  325. return &Azure{
  326. CustomProvider: &CustomProvider{
  327. Clientset: clientset,
  328. },
  329. }, nil
  330. } else {
  331. klog.V(2).Info("Unsupported provider, falling back to default")
  332. return &CustomProvider{
  333. Clientset: clientset,
  334. }, nil
  335. }
  336. }