provider.go 14 KB

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