provider.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. "k8s.io/klog"
  13. "cloud.google.com/go/compute/metadata"
  14. v1 "k8s.io/api/core/v1"
  15. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  16. "k8s.io/client-go/kubernetes"
  17. )
  18. // Node is the interface by which the provider and cost model communicate Node prices.
  19. // The provider will best-effort try to fill out this struct.
  20. type Node struct {
  21. Cost string `json:"hourlyCost"`
  22. VCPU string `json:"CPU"`
  23. VCPUCost string `json:"CPUHourlyCost"`
  24. RAM string `json:"RAM"`
  25. RAMBytes string `json:"RAMBytes"`
  26. RAMCost string `json:"RAMGBHourlyCost"`
  27. Storage string `json:"storage"`
  28. StorageCost string `json:"storageHourlyCost"`
  29. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  30. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  31. UsageType string `json:"usageType"`
  32. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  33. GPUName string `json:"gpuName"`
  34. GPUCost string `json:"gpuCost"`
  35. }
  36. // PV is the interface by which the provider and cost model communicate PV prices.
  37. // The provider will best-effort try to fill out this struct.
  38. type PV struct {
  39. Cost string `json:"hourlyCost"`
  40. Class string `json:"storageClass"`
  41. Size string `json:"size"`
  42. Region string `json:"region"`
  43. Parameters map[string]string `json:"parameters"`
  44. }
  45. // Key represents a way for nodes to match between the k8s API and a pricing API
  46. type Key interface {
  47. ID() string // ID represents an exact match
  48. Features() string // Features are a comma separated string of node metadata that could match pricing
  49. GPUType() string // GPUType returns "" if no GPU exists, but the name of the GPU otherwise
  50. }
  51. type PVKey interface {
  52. Features() string
  53. }
  54. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  55. type OutOfClusterAllocation struct {
  56. Aggregator string `json:"aggregator"`
  57. Environment string `json:"environment"`
  58. Service string `json:"service"`
  59. Cost float64 `json:"cost"`
  60. Cluster string `json:"cluster"`
  61. }
  62. // Provider represents a k8s provider.
  63. type Provider interface {
  64. ClusterName() ([]byte, error)
  65. AddServiceKey(url.Values) error
  66. GetDisks() ([]byte, error)
  67. NodePricing(Key) (*Node, error)
  68. PVPricing(PVKey) (*PV, error)
  69. AllNodePricing() (interface{}, error)
  70. DownloadPricingData() error
  71. GetKey(map[string]string) Key
  72. GetPVKey(*v1.PersistentVolume, map[string]string) PVKey
  73. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  74. GetConfig() (*CustomPricing, error)
  75. ExternalAllocations(string, string, string) ([]*OutOfClusterAllocation, error)
  76. }
  77. // GetDefaultPricingData will search for a json file representing pricing data in /models/ and use it for base pricing info.
  78. func GetDefaultPricingData(fname string) (*CustomPricing, error) {
  79. path := os.Getenv("CONFIG_PATH")
  80. if path == "" {
  81. path = "/models/"
  82. }
  83. path += fname
  84. if _, err := os.Stat(path); err == nil {
  85. jsonFile, err := os.Open(path)
  86. if err != nil {
  87. return nil, err
  88. }
  89. defer jsonFile.Close()
  90. byteValue, err := ioutil.ReadAll(jsonFile)
  91. if err != nil {
  92. return nil, err
  93. }
  94. var customPricing = &CustomPricing{}
  95. err = json.Unmarshal([]byte(byteValue), customPricing)
  96. if err != nil {
  97. return nil, err
  98. }
  99. return customPricing, nil
  100. } else if os.IsNotExist(err) {
  101. c := &CustomPricing{
  102. Provider: fname,
  103. Description: "Default prices based on GCP us-central1",
  104. CPU: "0.031611",
  105. SpotCPU: "0.006655",
  106. RAM: "0.004237",
  107. SpotRAM: "0.000892",
  108. GPU: "0.95",
  109. CustomPricesEnabled: "false",
  110. }
  111. cj, err := json.Marshal(c)
  112. if err != nil {
  113. return nil, err
  114. }
  115. err = ioutil.WriteFile(path, cj, 0644)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return c, nil
  120. } else {
  121. return nil, err
  122. }
  123. }
  124. const KeyUpdateType = "athenainfo"
  125. type CustomPricing struct {
  126. Provider string `json:"provider"`
  127. Description string `json:"description"`
  128. CPU string `json:"CPU"`
  129. SpotCPU string `json:"spotCPU"`
  130. RAM string `json:"RAM"`
  131. SpotRAM string `json:"spotRAM"`
  132. GPU string `json:"GPU"`
  133. SpotLabel string `json:"spotLabel,omitempty"`
  134. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  135. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  136. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  137. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  138. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  139. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  140. ProjectID string `json:"projectID,omitempty"`
  141. AthenaBucketName string `json:"athenaBucketName"`
  142. AthenaRegion string `json:"athenaRegion"`
  143. AthenaDatabase string `json:"athenaDatabase"`
  144. AthenaTable string `json:"athenaTable"`
  145. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  146. CustomPricesEnabled string `json:"customPricesEnabled"`
  147. }
  148. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  149. structValue := reflect.ValueOf(obj).Elem()
  150. structFieldValue := structValue.FieldByName(name)
  151. if !structFieldValue.IsValid() {
  152. return fmt.Errorf("No such field: %s in obj", name)
  153. }
  154. if !structFieldValue.CanSet() {
  155. return fmt.Errorf("Cannot set %s field value", name)
  156. }
  157. structFieldType := structFieldValue.Type()
  158. val := reflect.ValueOf(value)
  159. if structFieldType != val.Type() {
  160. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  161. }
  162. structFieldValue.Set(val)
  163. return nil
  164. }
  165. type NodePrice struct {
  166. CPU string
  167. RAM string
  168. }
  169. type CustomProvider struct {
  170. Clientset *kubernetes.Clientset
  171. Pricing map[string]*NodePrice
  172. SpotLabel string
  173. SpotLabelValue string
  174. }
  175. func (*CustomProvider) GetConfig() (*CustomPricing, error) {
  176. return nil, nil
  177. }
  178. func (*CustomProvider) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  179. return nil, nil
  180. }
  181. func (*CustomProvider) ClusterName() ([]byte, error) {
  182. return nil, nil
  183. }
  184. func (*CustomProvider) AddServiceKey(url.Values) error {
  185. return nil
  186. }
  187. func (*CustomProvider) GetDisks() ([]byte, error) {
  188. return nil, nil
  189. }
  190. func (c *CustomProvider) AllNodePricing() (interface{}, error) {
  191. return c.Pricing, nil
  192. }
  193. func (c *CustomProvider) NodePricing(key Key) (*Node, error) {
  194. k := key.Features()
  195. if _, ok := c.Pricing[k]; !ok {
  196. k = "default"
  197. }
  198. return &Node{
  199. VCPUCost: c.Pricing[k].CPU,
  200. RAMCost: c.Pricing[k].RAM,
  201. }, nil
  202. }
  203. func (c *CustomProvider) DownloadPricingData() error {
  204. if c.Pricing == nil {
  205. m := make(map[string]*NodePrice)
  206. c.Pricing = m
  207. }
  208. p, err := GetDefaultPricingData("default.json")
  209. if err != nil {
  210. return err
  211. }
  212. c.Pricing["default"] = &NodePrice{
  213. CPU: p.CPU,
  214. RAM: p.RAM,
  215. }
  216. c.Pricing["default,spot"] = &NodePrice{
  217. CPU: p.SpotCPU,
  218. RAM: p.SpotRAM,
  219. }
  220. return nil
  221. }
  222. type customProviderKey struct {
  223. SpotLabel string
  224. SpotLabelValue string
  225. Labels map[string]string
  226. }
  227. func (c *customProviderKey) GPUType() string {
  228. return ""
  229. }
  230. func (c *customProviderKey) ID() string {
  231. return ""
  232. }
  233. func (c *customProviderKey) Features() string {
  234. if c.Labels[c.SpotLabel] != "" && c.Labels[c.SpotLabel] == c.SpotLabelValue {
  235. return "default,spot"
  236. }
  237. return "default" // TODO: multiple custom pricing support.
  238. }
  239. func (c *CustomProvider) GetKey(labels map[string]string) Key {
  240. return &customProviderKey{
  241. SpotLabel: c.SpotLabel,
  242. SpotLabelValue: c.SpotLabelValue,
  243. Labels: labels,
  244. }
  245. }
  246. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  247. // "start" and "end" are dates of the format YYYY-MM-DD
  248. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  249. func (*CustomProvider) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  250. return nil, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  251. }
  252. func (*CustomProvider) QuerySQL(query string) ([]byte, error) {
  253. return nil, nil
  254. }
  255. func (*CustomProvider) PVPricing(pvk PVKey) (*PV, error) {
  256. return nil, nil
  257. }
  258. func (*CustomProvider) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  259. return &awsPVKey{
  260. Labels: pv.Labels,
  261. StorageClassName: pv.Spec.StorageClassName,
  262. }
  263. }
  264. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  265. func NewProvider(clientset *kubernetes.Clientset, apiKey string) (Provider, error) {
  266. if metadata.OnGCE() {
  267. klog.V(3).Info("metadata reports we are in GCE")
  268. if apiKey == "" {
  269. return nil, errors.New("Supply a GCP Key to start getting data")
  270. }
  271. return &GCP{
  272. Clientset: clientset,
  273. APIKey: apiKey,
  274. }, nil
  275. }
  276. nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  277. if err != nil {
  278. return nil, err
  279. }
  280. provider := strings.ToLower(nodes.Items[0].Spec.ProviderID)
  281. if strings.HasPrefix(provider, "aws") {
  282. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  283. return &AWS{
  284. Clientset: clientset,
  285. }, nil
  286. } else if strings.HasPrefix(provider, "azure") {
  287. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  288. return &Azure{
  289. CustomProvider: &CustomProvider{
  290. Clientset: clientset,
  291. },
  292. }, nil
  293. } else {
  294. klog.V(2).Info("Unsupported provider, falling back to default")
  295. return &CustomProvider{
  296. Clientset: clientset,
  297. }, nil
  298. }
  299. }