provider.go 12 KB

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