provider.go 13 KB

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