provider.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. ReadOnly string `json:"readOnly"`
  142. }
  143. // Provider represents a k8s provider.
  144. type Provider interface {
  145. ClusterInfo() (map[string]string, error)
  146. AddServiceKey(url.Values) error
  147. GetDisks() ([]byte, error)
  148. NodePricing(Key) (*Node, error)
  149. PVPricing(PVKey) (*PV, error)
  150. NetworkPricing() (*Network, error)
  151. AllNodePricing() (interface{}, error)
  152. DownloadPricingData() error
  153. GetKey(map[string]string) Key
  154. GetPVKey(*v1.PersistentVolume, map[string]string) PVKey
  155. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  156. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  157. GetConfig() (*CustomPricing, error)
  158. GetManagementPlatform() (string, error)
  159. GetLocalStorageQuery(offset string) (string, error)
  160. ExternalAllocations(string, string, string, string, string) ([]*OutOfClusterAllocation, error)
  161. ApplyReservedInstancePricing(map[string]*Node)
  162. }
  163. // ClusterName returns the name defined in cluster info, defaulting to the
  164. // CLUSTER_ID environment variable
  165. func ClusterName(p Provider) string {
  166. info, err := p.ClusterInfo()
  167. if err != nil {
  168. return os.Getenv(clusterIDKey)
  169. }
  170. name, ok := info["name"]
  171. if !ok {
  172. return os.Getenv(clusterIDKey)
  173. }
  174. return name
  175. }
  176. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  177. // indicating whether or not the cluster is using custom pricing.
  178. func CustomPricesEnabled(p Provider) bool {
  179. config, err := p.GetConfig()
  180. if err != nil {
  181. return false
  182. }
  183. if config.NegotiatedDiscount == "" {
  184. config.NegotiatedDiscount = "0%"
  185. }
  186. return config.CustomPricesEnabled == "true"
  187. }
  188. // GetDefaultPricingData will search for a json file representing pricing data in /models/ and use it for base pricing info.
  189. func GetDefaultPricingData(fname string) (*CustomPricing, error) {
  190. configLock.Lock()
  191. defer configLock.Unlock()
  192. path := os.Getenv("CONFIG_PATH")
  193. if path == "" {
  194. path = "/models/"
  195. }
  196. path += fname
  197. if _, err := os.Stat(path); err == nil {
  198. jsonFile, err := os.Open(path)
  199. if err != nil {
  200. return nil, err
  201. }
  202. defer jsonFile.Close()
  203. byteValue, err := ioutil.ReadAll(jsonFile)
  204. if err != nil {
  205. return nil, err
  206. }
  207. var customPricing = &CustomPricing{}
  208. err = json.Unmarshal([]byte(byteValue), customPricing)
  209. if err != nil {
  210. return nil, err
  211. }
  212. return customPricing, nil
  213. } else if os.IsNotExist(err) {
  214. c := &CustomPricing{
  215. Provider: fname,
  216. Description: "Default prices based on GCP us-central1",
  217. CPU: "0.031611",
  218. SpotCPU: "0.006655",
  219. RAM: "0.004237",
  220. SpotRAM: "0.000892",
  221. GPU: "0.95",
  222. Storage: "0.00005479452",
  223. ZoneNetworkEgress: "0.01",
  224. RegionNetworkEgress: "0.01",
  225. InternetNetworkEgress: "0.12",
  226. CustomPricesEnabled: "false",
  227. }
  228. cj, err := json.Marshal(c)
  229. if err != nil {
  230. return nil, err
  231. }
  232. err = ioutil.WriteFile(path, cj, 0644)
  233. if err != nil {
  234. return nil, err
  235. }
  236. return c, nil
  237. } else {
  238. return nil, err
  239. }
  240. }
  241. func configmapUpdate(c *CustomPricing, path string, a map[string]string) (*CustomPricing, error) {
  242. for k, v := range a {
  243. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  244. err := SetCustomPricingField(c, kUpper, v)
  245. if err != nil {
  246. return nil, err
  247. }
  248. }
  249. configLock.Lock()
  250. defer configLock.Unlock()
  251. cj, err := json.Marshal(c)
  252. if err != nil {
  253. return nil, err
  254. }
  255. err = ioutil.WriteFile(path, cj, 0644)
  256. if err != nil {
  257. return nil, err
  258. }
  259. return c, nil
  260. }
  261. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  262. structValue := reflect.ValueOf(obj).Elem()
  263. structFieldValue := structValue.FieldByName(name)
  264. if !structFieldValue.IsValid() {
  265. return fmt.Errorf("No such field: %s in obj", name)
  266. }
  267. if !structFieldValue.CanSet() {
  268. return fmt.Errorf("Cannot set %s field value", name)
  269. }
  270. structFieldType := structFieldValue.Type()
  271. val := reflect.ValueOf(value)
  272. if structFieldType != val.Type() {
  273. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  274. }
  275. structFieldValue.Set(val)
  276. return nil
  277. }
  278. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  279. func NewProvider(cache clustercache.ClusterCache, apiKey string) (Provider, error) {
  280. if metadata.OnGCE() {
  281. klog.V(3).Info("metadata reports we are in GCE")
  282. if apiKey == "" {
  283. return nil, errors.New("Supply a GCP Key to start getting data")
  284. }
  285. return &GCP{
  286. Clientset: cache,
  287. APIKey: apiKey,
  288. }, nil
  289. }
  290. nodes := cache.GetAllNodes()
  291. if len(nodes) == 0 {
  292. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  293. }
  294. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  295. if strings.HasPrefix(provider, "aws") {
  296. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  297. return &AWS{
  298. Clientset: cache,
  299. }, nil
  300. } else if strings.HasPrefix(provider, "azure") {
  301. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  302. return &Azure{
  303. Clientset: cache,
  304. }, nil
  305. } else {
  306. klog.V(2).Info("Unsupported provider, falling back to default")
  307. return &CustomProvider{
  308. Clientset: cache,
  309. }, nil
  310. }
  311. }
  312. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  313. pw := os.Getenv(remotePW)
  314. address := os.Getenv(sqlAddress)
  315. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  316. db, err := sql.Open("postgres", connStr)
  317. if err != nil {
  318. return err
  319. }
  320. defer db.Close()
  321. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  322. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  323. if err != nil {
  324. return err
  325. }
  326. return nil
  327. }
  328. func CreateClusterMeta(cluster_id, cluster_name string) error {
  329. pw := os.Getenv(remotePW)
  330. address := os.Getenv(sqlAddress)
  331. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  332. db, err := sql.Open("postgres", connStr)
  333. if err != nil {
  334. return err
  335. }
  336. defer db.Close()
  337. for _, stmt := range createTableStatements {
  338. _, err := db.Exec(stmt)
  339. if err != nil {
  340. return err
  341. }
  342. }
  343. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  344. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  345. if err != nil {
  346. return err
  347. }
  348. return nil
  349. }
  350. func GetClusterMeta(cluster_id string) (string, string, error) {
  351. pw := os.Getenv(remotePW)
  352. address := os.Getenv(sqlAddress)
  353. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  354. db, err := sql.Open("postgres", connStr)
  355. defer db.Close()
  356. query := `SELECT cluster_id, cluster_name
  357. FROM names
  358. WHERE cluster_id = ?`
  359. rows, err := db.Query(query, cluster_id)
  360. if err != nil {
  361. return "", "", err
  362. }
  363. defer rows.Close()
  364. var (
  365. sql_cluster_id string
  366. cluster_name string
  367. )
  368. for rows.Next() {
  369. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  370. return "", "", err
  371. }
  372. }
  373. return sql_cluster_id, cluster_name, nil
  374. }
  375. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  376. id, name, err := GetClusterMeta(cluster_id)
  377. if err != nil {
  378. err := CreateClusterMeta(cluster_id, cluster_name)
  379. if err != nil {
  380. return "", "", err
  381. }
  382. }
  383. if id == "" {
  384. err := CreateClusterMeta(cluster_id, cluster_name)
  385. if err != nil {
  386. return "", "", err
  387. }
  388. }
  389. return id, name, nil
  390. }