2
0

provider.go 14 KB

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