provider.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. }
  166. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  167. structValue := reflect.ValueOf(obj).Elem()
  168. structFieldValue := structValue.FieldByName(name)
  169. if !structFieldValue.IsValid() {
  170. return fmt.Errorf("No such field: %s in obj", name)
  171. }
  172. if !structFieldValue.CanSet() {
  173. return fmt.Errorf("Cannot set %s field value", name)
  174. }
  175. structFieldType := structFieldValue.Type()
  176. val := reflect.ValueOf(value)
  177. if structFieldType != val.Type() {
  178. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  179. }
  180. structFieldValue.Set(val)
  181. return nil
  182. }
  183. type NodePrice struct {
  184. CPU string
  185. RAM string
  186. GPU string
  187. }
  188. type CustomProvider struct {
  189. Clientset *kubernetes.Clientset
  190. Pricing map[string]*NodePrice
  191. SpotLabel string
  192. SpotLabelValue string
  193. GPULabel string
  194. GPULabelValue string
  195. DownloadPricingDataLock sync.RWMutex
  196. }
  197. func (*CustomProvider) GetLocalStorageQuery() (string, error) {
  198. return "", nil
  199. }
  200. func (*CustomProvider) GetConfig() (*CustomPricing, error) {
  201. return GetDefaultPricingData("default.json")
  202. }
  203. func (*CustomProvider) GetManagementPlatform() (string, error) {
  204. return "", nil
  205. }
  206. func (cprov *CustomProvider) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  207. c, err := GetDefaultPricingData("default.json")
  208. if err != nil {
  209. return nil, err
  210. }
  211. path := os.Getenv("CONFIG_PATH")
  212. if path == "" {
  213. path = "/models/"
  214. }
  215. a := make(map[string]string)
  216. err = json.NewDecoder(r).Decode(&a)
  217. if err != nil {
  218. return nil, err
  219. }
  220. for k, v := range a {
  221. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  222. err := SetCustomPricingField(c, kUpper, v)
  223. if err != nil {
  224. return nil, err
  225. }
  226. }
  227. cj, err := json.Marshal(c)
  228. if err != nil {
  229. return nil, err
  230. }
  231. configPath := path + "default.json"
  232. err = ioutil.WriteFile(configPath, cj, 0644)
  233. if err != nil {
  234. return nil, err
  235. }
  236. defer cprov.DownloadPricingData()
  237. return c, nil
  238. }
  239. func (*CustomProvider) ClusterInfo() (map[string]string, error) {
  240. m := make(map[string]string)
  241. m["provider"] = "custom"
  242. return m, nil
  243. }
  244. func (*CustomProvider) AddServiceKey(url.Values) error {
  245. return nil
  246. }
  247. func (*CustomProvider) GetDisks() ([]byte, error) {
  248. return nil, nil
  249. }
  250. func (c *CustomProvider) AllNodePricing() (interface{}, error) {
  251. c.DownloadPricingDataLock.RLock()
  252. defer c.DownloadPricingDataLock.RUnlock()
  253. return c.Pricing, nil
  254. }
  255. func (c *CustomProvider) NodePricing(key Key) (*Node, error) {
  256. c.DownloadPricingDataLock.RLock()
  257. defer c.DownloadPricingDataLock.RUnlock()
  258. k := key.Features()
  259. var gpuCount string
  260. if _, ok := c.Pricing[k]; !ok {
  261. k = "default"
  262. }
  263. if key.GPUType() != "" {
  264. k += ",gpu" // TODO: support multiple custom gpu types.
  265. gpuCount = "1" // TODO: support more than one gpu.
  266. }
  267. return &Node{
  268. VCPUCost: c.Pricing[k].CPU,
  269. RAMCost: c.Pricing[k].RAM,
  270. GPUCost: c.Pricing[k].GPU,
  271. GPU: gpuCount,
  272. }, nil
  273. }
  274. func (c *CustomProvider) DownloadPricingData() error {
  275. c.DownloadPricingDataLock.Lock()
  276. defer c.DownloadPricingDataLock.Unlock()
  277. if c.Pricing == nil {
  278. m := make(map[string]*NodePrice)
  279. c.Pricing = m
  280. }
  281. p, err := GetDefaultPricingData("default.json")
  282. if err != nil {
  283. return err
  284. }
  285. c.SpotLabel = p.SpotLabel
  286. c.SpotLabelValue = p.SpotLabelValue
  287. c.GPULabel = p.GpuLabel
  288. c.GPULabelValue = p.GpuLabelValue
  289. c.Pricing["default"] = &NodePrice{
  290. CPU: p.CPU,
  291. RAM: p.RAM,
  292. }
  293. c.Pricing["default,spot"] = &NodePrice{
  294. CPU: p.SpotCPU,
  295. RAM: p.SpotRAM,
  296. }
  297. c.Pricing["default,gpu"] = &NodePrice{
  298. CPU: p.CPU,
  299. RAM: p.RAM,
  300. GPU: p.GPU,
  301. }
  302. return nil
  303. }
  304. type customProviderKey struct {
  305. SpotLabel string
  306. SpotLabelValue string
  307. GPULabel string
  308. GPULabelValue string
  309. Labels map[string]string
  310. }
  311. func (c *customProviderKey) GPUType() string {
  312. if t, ok := c.Labels[c.GPULabel]; ok {
  313. return t
  314. }
  315. return ""
  316. }
  317. func (c *customProviderKey) ID() string {
  318. return ""
  319. }
  320. func (c *customProviderKey) Features() string {
  321. if c.Labels[c.SpotLabel] != "" && c.Labels[c.SpotLabel] == c.SpotLabelValue {
  322. return "default,spot"
  323. }
  324. return "default" // TODO: multiple custom pricing support.
  325. }
  326. func (c *CustomProvider) GetKey(labels map[string]string) Key {
  327. return &customProviderKey{
  328. SpotLabel: c.SpotLabel,
  329. SpotLabelValue: c.SpotLabelValue,
  330. GPULabel: c.GPULabel,
  331. GPULabelValue: c.GPULabelValue,
  332. Labels: labels,
  333. }
  334. }
  335. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  336. // "start" and "end" are dates of the format YYYY-MM-DD
  337. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  338. func (*CustomProvider) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  339. return nil, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  340. }
  341. func (*CustomProvider) QuerySQL(query string) ([]byte, error) {
  342. return nil, nil
  343. }
  344. func (c *CustomProvider) PVPricing(pvk PVKey) (*PV, error) {
  345. cpricing, err := GetDefaultPricingData("default")
  346. if err != nil {
  347. return nil, err
  348. }
  349. return &PV{
  350. Cost: cpricing.Storage,
  351. }, nil
  352. }
  353. func (*CustomProvider) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  354. return &awsPVKey{
  355. Labels: pv.Labels,
  356. StorageClassName: pv.Spec.StorageClassName,
  357. }
  358. }
  359. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  360. func NewProvider(clientset *kubernetes.Clientset, apiKey string) (Provider, error) {
  361. if metadata.OnGCE() {
  362. klog.V(3).Info("metadata reports we are in GCE")
  363. if apiKey == "" {
  364. return nil, errors.New("Supply a GCP Key to start getting data")
  365. }
  366. return &GCP{
  367. Clientset: clientset,
  368. APIKey: apiKey,
  369. }, nil
  370. }
  371. nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  372. if err != nil {
  373. return nil, err
  374. }
  375. provider := strings.ToLower(nodes.Items[0].Spec.ProviderID)
  376. if strings.HasPrefix(provider, "aws") {
  377. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  378. return &AWS{
  379. Clientset: clientset,
  380. }, nil
  381. } else if strings.HasPrefix(provider, "azure") {
  382. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  383. return &Azure{
  384. Clientset: clientset,
  385. }, nil
  386. } else {
  387. klog.V(2).Info("Unsupported provider, falling back to default")
  388. return &CustomProvider{
  389. Clientset: clientset,
  390. }, nil
  391. }
  392. }