provider.go 11 KB

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