provider.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. package cloud
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/url"
  10. "os"
  11. "reflect"
  12. "strings"
  13. "sync"
  14. "k8s.io/klog"
  15. "cloud.google.com/go/compute/metadata"
  16. "github.com/kubecost/cost-model/clustercache"
  17. v1 "k8s.io/api/core/v1"
  18. )
  19. const clusterIDKey = "CLUSTER_ID"
  20. const remoteEnabled = "REMOTE_WRITE_ENABLED"
  21. const remotePW = "REMOTE_WRITE_PASSWORD"
  22. const sqlAddress = "SQL_ADDRESS"
  23. var createTableStatements = []string{
  24. `CREATE TABLE IF NOT EXISTS names (
  25. cluster_id VARCHAR(255) NOT NULL,
  26. cluster_name VARCHAR(255) NULL,
  27. PRIMARY KEY (cluster_id)
  28. );`,
  29. }
  30. // This Mutex is used to control read/writes to our default config file
  31. var configLock sync.Mutex
  32. // ReservedInstanceData keeps record of resources on a node should be
  33. // priced at reserved rates
  34. type ReservedInstanceData struct {
  35. ReservedCPU int64 `json:"reservedCPU"`
  36. ReservedRAM int64 `json:"reservedRAM"`
  37. CPUCost float64 `json:"CPUHourlyCost"`
  38. RAMCost float64 `json:"RAMHourlyCost"`
  39. }
  40. // Node is the interface by which the provider and cost model communicate Node prices.
  41. // The provider will best-effort try to fill out this struct.
  42. type Node struct {
  43. Cost string `json:"hourlyCost"`
  44. VCPU string `json:"CPU"`
  45. VCPUCost string `json:"CPUHourlyCost"`
  46. RAM string `json:"RAM"`
  47. RAMBytes string `json:"RAMBytes"`
  48. RAMCost string `json:"RAMGBHourlyCost"`
  49. Storage string `json:"storage"`
  50. StorageCost string `json:"storageHourlyCost"`
  51. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  52. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  53. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  54. BaseGPUPrice string `json:"baseGPUPrice"`
  55. UsageType string `json:"usageType"`
  56. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  57. GPUName string `json:"gpuName"`
  58. GPUCost string `json:"gpuCost"`
  59. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  60. }
  61. // IsSpot determines whether or not a Node uses spot by usage type
  62. func (n *Node) IsSpot() bool {
  63. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  64. }
  65. // Network is the interface by which the provider and cost model communicate network egress prices.
  66. // The provider will best-effort try to fill out this struct.
  67. type Network struct {
  68. ZoneNetworkEgressCost float64
  69. RegionNetworkEgressCost float64
  70. InternetNetworkEgressCost float64
  71. }
  72. // PV is the interface by which the provider and cost model communicate PV prices.
  73. // The provider will best-effort try to fill out this struct.
  74. type PV struct {
  75. Cost string `json:"hourlyCost"`
  76. CostPerIO string `json:"costPerIOOperation"`
  77. Class string `json:"storageClass"`
  78. Size string `json:"size"`
  79. Region string `json:"region"`
  80. Parameters map[string]string `json:"parameters"`
  81. }
  82. // Key represents a way for nodes to match between the k8s API and a pricing API
  83. type Key interface {
  84. ID() string // ID represents an exact match
  85. Features() string // Features are a comma separated string of node metadata that could match pricing
  86. GPUType() string // GPUType returns "" if no GPU exists, but the name of the GPU otherwise
  87. }
  88. type PVKey interface {
  89. Features() string
  90. GetStorageClass() string
  91. }
  92. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  93. type OutOfClusterAllocation struct {
  94. Aggregator string `json:"aggregator"`
  95. Environment string `json:"environment"`
  96. Service string `json:"service"`
  97. Cost float64 `json:"cost"`
  98. Cluster string `json:"cluster"`
  99. }
  100. type CustomPricing struct {
  101. Provider string `json:"provider"`
  102. Description string `json:"description"`
  103. CPU string `json:"CPU"`
  104. SpotCPU string `json:"spotCPU"`
  105. RAM string `json:"RAM"`
  106. SpotRAM string `json:"spotRAM"`
  107. GPU string `json:"GPU"`
  108. SpotGPU string `json:"spotGPU"`
  109. Storage string `json:"storage"`
  110. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  111. RegionNetworkEgress string `json:"regionNetworkEgress"`
  112. InternetNetworkEgress string `json:"internetNetworkEgress"`
  113. SpotLabel string `json:"spotLabel,omitempty"`
  114. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  115. GpuLabel string `json:"gpuLabel,omitempty"`
  116. GpuLabelValue string `json:"gpuLabelValue,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. CustomPricesEnabled string `json:"customPricesEnabled"`
  129. DefaultIdle string `json:"defaultIdle"`
  130. AzureSubscriptionID string `json:"azureSubscriptionID"`
  131. AzureClientID string `json:"azureClientID"`
  132. AzureClientSecret string `json:"azureClientSecret"`
  133. AzureTenantID string `json:"azureTenantID"`
  134. AzureBillingRegion string `json:"azureBillingRegion"`
  135. CurrencyCode string `json:"currencyCode"`
  136. Discount string `json:"discount"`
  137. NegotiatedDiscount string `json:"negotiatedDiscount"`
  138. SharedCosts map[string]string `json:"sharedCost"`
  139. ClusterName string `json:"clusterName"`
  140. SharedNamespaces string `json:"sharedNamespaces"`
  141. SharedLabelNames string `json:"sharedLabelNames"`
  142. SharedLabelValues string `json:"sharedLabelValues"`
  143. ReadOnly string `json:"readOnly"`
  144. }
  145. // Provider represents a k8s provider.
  146. type Provider interface {
  147. ClusterInfo() (map[string]string, error)
  148. AddServiceKey(url.Values) error
  149. GetDisks() ([]byte, error)
  150. NodePricing(Key) (*Node, error)
  151. PVPricing(PVKey) (*PV, error)
  152. NetworkPricing() (*Network, error)
  153. AllNodePricing() (interface{}, error)
  154. DownloadPricingData() error
  155. GetKey(map[string]string) Key
  156. GetPVKey(*v1.PersistentVolume, map[string]string) PVKey
  157. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  158. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  159. GetConfig() (*CustomPricing, error)
  160. GetManagementPlatform() (string, error)
  161. GetLocalStorageQuery(offset string) (string, error)
  162. ExternalAllocations(string, string, string, string, string) ([]*OutOfClusterAllocation, error)
  163. ApplyReservedInstancePricing(map[string]*Node)
  164. }
  165. // ClusterName returns the name defined in cluster info, defaulting to the
  166. // CLUSTER_ID environment variable
  167. func ClusterName(p Provider) string {
  168. info, err := p.ClusterInfo()
  169. if err != nil {
  170. return os.Getenv(clusterIDKey)
  171. }
  172. name, ok := info["name"]
  173. if !ok {
  174. return os.Getenv(clusterIDKey)
  175. }
  176. return name
  177. }
  178. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  179. // indicating whether or not the cluster is using custom pricing.
  180. func CustomPricesEnabled(p Provider) bool {
  181. config, err := p.GetConfig()
  182. if err != nil {
  183. return false
  184. }
  185. if config.NegotiatedDiscount == "" {
  186. config.NegotiatedDiscount = "0%"
  187. }
  188. return config.CustomPricesEnabled == "true"
  189. }
  190. // GetDefaultPricingData will search for a json file representing pricing data in /models/ and use it for base pricing info.
  191. func GetDefaultPricingData(fname string) (*CustomPricing, error) {
  192. configLock.Lock()
  193. defer configLock.Unlock()
  194. path := os.Getenv("CONFIG_PATH")
  195. if path == "" {
  196. path = "/models/"
  197. }
  198. path += fname
  199. if _, err := os.Stat(path); err == nil {
  200. jsonFile, err := os.Open(path)
  201. if err != nil {
  202. return nil, err
  203. }
  204. defer jsonFile.Close()
  205. byteValue, err := ioutil.ReadAll(jsonFile)
  206. if err != nil {
  207. return nil, err
  208. }
  209. var customPricing = &CustomPricing{}
  210. err = json.Unmarshal([]byte(byteValue), customPricing)
  211. if err != nil {
  212. return nil, err
  213. }
  214. return customPricing, nil
  215. } else if os.IsNotExist(err) {
  216. c := &CustomPricing{
  217. Provider: fname,
  218. Description: "Default prices based on GCP us-central1",
  219. CPU: "0.031611",
  220. SpotCPU: "0.006655",
  221. RAM: "0.004237",
  222. SpotRAM: "0.000892",
  223. GPU: "0.95",
  224. Storage: "0.00005479452",
  225. ZoneNetworkEgress: "0.01",
  226. RegionNetworkEgress: "0.01",
  227. InternetNetworkEgress: "0.12",
  228. CustomPricesEnabled: "false",
  229. }
  230. cj, err := json.Marshal(c)
  231. if err != nil {
  232. return nil, err
  233. }
  234. err = ioutil.WriteFile(path, cj, 0644)
  235. if err != nil {
  236. return nil, err
  237. }
  238. return c, nil
  239. } else {
  240. return nil, err
  241. }
  242. }
  243. func configmapUpdate(c *CustomPricing, path string, a map[string]string) (*CustomPricing, error) {
  244. for k, v := range a {
  245. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  246. err := SetCustomPricingField(c, kUpper, v)
  247. if err != nil {
  248. return nil, err
  249. }
  250. }
  251. configLock.Lock()
  252. defer configLock.Unlock()
  253. cj, err := json.Marshal(c)
  254. if err != nil {
  255. return nil, err
  256. }
  257. err = ioutil.WriteFile(path, cj, 0644)
  258. if err != nil {
  259. return nil, err
  260. }
  261. return c, nil
  262. }
  263. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  264. structValue := reflect.ValueOf(obj).Elem()
  265. structFieldValue := structValue.FieldByName(name)
  266. if !structFieldValue.IsValid() {
  267. return fmt.Errorf("No such field: %s in obj", name)
  268. }
  269. if !structFieldValue.CanSet() {
  270. return fmt.Errorf("Cannot set %s field value", name)
  271. }
  272. structFieldType := structFieldValue.Type()
  273. val := reflect.ValueOf(value)
  274. if structFieldType != val.Type() {
  275. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  276. }
  277. structFieldValue.Set(val)
  278. return nil
  279. }
  280. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  281. func NewProvider(cache clustercache.ClusterCache, apiKey string) (Provider, error) {
  282. if metadata.OnGCE() {
  283. klog.V(3).Info("metadata reports we are in GCE")
  284. if apiKey == "" {
  285. return nil, errors.New("Supply a GCP Key to start getting data")
  286. }
  287. return &GCP{
  288. Clientset: cache,
  289. APIKey: apiKey,
  290. }, nil
  291. }
  292. nodes := cache.GetAllNodes()
  293. if len(nodes) == 0 {
  294. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  295. }
  296. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  297. if strings.HasPrefix(provider, "aws") {
  298. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  299. return &AWS{
  300. Clientset: cache,
  301. }, nil
  302. } else if strings.HasPrefix(provider, "azure") {
  303. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  304. return &Azure{
  305. Clientset: cache,
  306. }, nil
  307. } else {
  308. klog.V(2).Info("Unsupported provider, falling back to default")
  309. return &CustomProvider{
  310. Clientset: cache,
  311. }, nil
  312. }
  313. }
  314. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  315. pw := os.Getenv(remotePW)
  316. address := os.Getenv(sqlAddress)
  317. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  318. db, err := sql.Open("postgres", connStr)
  319. if err != nil {
  320. return err
  321. }
  322. defer db.Close()
  323. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  324. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  325. if err != nil {
  326. return err
  327. }
  328. return nil
  329. }
  330. func CreateClusterMeta(cluster_id, cluster_name string) error {
  331. pw := os.Getenv(remotePW)
  332. address := os.Getenv(sqlAddress)
  333. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  334. db, err := sql.Open("postgres", connStr)
  335. if err != nil {
  336. return err
  337. }
  338. defer db.Close()
  339. for _, stmt := range createTableStatements {
  340. _, err := db.Exec(stmt)
  341. if err != nil {
  342. return err
  343. }
  344. }
  345. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  346. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  347. if err != nil {
  348. return err
  349. }
  350. return nil
  351. }
  352. func GetClusterMeta(cluster_id string) (string, string, error) {
  353. pw := os.Getenv(remotePW)
  354. address := os.Getenv(sqlAddress)
  355. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  356. db, err := sql.Open("postgres", connStr)
  357. defer db.Close()
  358. query := `SELECT cluster_id, cluster_name
  359. FROM names
  360. WHERE cluster_id = ?`
  361. rows, err := db.Query(query, cluster_id)
  362. if err != nil {
  363. return "", "", err
  364. }
  365. defer rows.Close()
  366. var (
  367. sql_cluster_id string
  368. cluster_name string
  369. )
  370. for rows.Next() {
  371. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  372. return "", "", err
  373. }
  374. }
  375. return sql_cluster_id, cluster_name, nil
  376. }
  377. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  378. id, name, err := GetClusterMeta(cluster_id)
  379. if err != nil {
  380. err := CreateClusterMeta(cluster_id, cluster_name)
  381. if err != nil {
  382. return "", "", err
  383. }
  384. }
  385. if id == "" {
  386. err := CreateClusterMeta(cluster_id, cluster_name)
  387. if err != nil {
  388. return "", "", err
  389. }
  390. }
  391. return id, name, nil
  392. }