provider.go 8.3 KB

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