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