provider.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. package cloud
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "golang.org/x/text/cases"
  7. "golang.org/x/text/language"
  8. "io"
  9. "net/http"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/opencost/opencost/pkg/kubecost"
  16. "github.com/opencost/opencost/pkg/util"
  17. "cloud.google.com/go/compute/metadata"
  18. "github.com/opencost/opencost/pkg/clustercache"
  19. "github.com/opencost/opencost/pkg/config"
  20. "github.com/opencost/opencost/pkg/env"
  21. "github.com/opencost/opencost/pkg/log"
  22. "github.com/opencost/opencost/pkg/util/httputil"
  23. "github.com/opencost/opencost/pkg/util/watcher"
  24. v1 "k8s.io/api/core/v1"
  25. )
  26. const authSecretPath = "/var/secrets/service-key.json"
  27. const storageConfigSecretPath = "/var/azure-storage-config/azure-storage-config.json"
  28. const defaultShareTenancyCost = "true"
  29. const KarpenterCapacityTypeLabel = "karpenter.sh/capacity-type"
  30. const KarpenterCapacitySpotTypeValue = "spot"
  31. var toTitle = cases.Title(language.Und, cases.NoLower)
  32. var createTableStatements = []string{
  33. `CREATE TABLE IF NOT EXISTS names (
  34. cluster_id VARCHAR(255) NOT NULL,
  35. cluster_name VARCHAR(255) NULL,
  36. PRIMARY KEY (cluster_id)
  37. );`,
  38. }
  39. // ReservedInstanceData keeps record of resources on a node should be
  40. // priced at reserved rates
  41. type ReservedInstanceData struct {
  42. ReservedCPU int64 `json:"reservedCPU"`
  43. ReservedRAM int64 `json:"reservedRAM"`
  44. CPUCost float64 `json:"CPUHourlyCost"`
  45. RAMCost float64 `json:"RAMHourlyCost"`
  46. }
  47. // Node is the interface by which the provider and cost model communicate Node prices.
  48. // The provider will best-effort try to fill out this struct.
  49. type Node struct {
  50. Cost string `json:"hourlyCost"`
  51. VCPU string `json:"CPU"`
  52. VCPUCost string `json:"CPUHourlyCost"`
  53. RAM string `json:"RAM"`
  54. RAMBytes string `json:"RAMBytes"`
  55. RAMCost string `json:"RAMGBHourlyCost"`
  56. Storage string `json:"storage"`
  57. StorageCost string `json:"storageHourlyCost"`
  58. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  59. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  60. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  61. BaseGPUPrice string `json:"baseGPUPrice"`
  62. UsageType string `json:"usageType"`
  63. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  64. GPUName string `json:"gpuName"`
  65. GPUCost string `json:"gpuCost"`
  66. InstanceType string `json:"instanceType,omitempty"`
  67. Region string `json:"region,omitempty"`
  68. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  69. ProviderID string `json:"providerID,omitempty"`
  70. PricingType PricingType `json:"pricingType,omitempty"`
  71. }
  72. // IsSpot determines whether or not a Node uses spot by usage type
  73. func (n *Node) IsSpot() bool {
  74. if n != nil {
  75. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  76. } else {
  77. return false
  78. }
  79. }
  80. // LoadBalancer is the interface by which the provider and cost model communicate LoadBalancer prices.
  81. // The provider will best-effort try to fill out this struct.
  82. type LoadBalancer struct {
  83. IngressIPAddresses []string `json:"IngressIPAddresses"`
  84. Cost float64 `json:"hourlyCost"`
  85. }
  86. // TODO: used for dynamic cloud provider price fetching.
  87. // determine what identifies a load balancer in the json returned from the cloud provider pricing API call
  88. // type LBKey interface {
  89. // }
  90. // Network is the interface by which the provider and cost model communicate network egress prices.
  91. // The provider will best-effort try to fill out this struct.
  92. type Network struct {
  93. ZoneNetworkEgressCost float64
  94. RegionNetworkEgressCost float64
  95. InternetNetworkEgressCost float64
  96. }
  97. type OrphanedResource struct {
  98. Kind string `json:"resourceKind"`
  99. Region string `json:"region"`
  100. Description map[string]string `json:"description"`
  101. Size *int64 `json:"diskSizeInGB,omitempty"`
  102. DiskName string `json:"diskName,omitempty"`
  103. Url string `json:"url"`
  104. Address string `json:"ipAddress,omitempty"`
  105. MonthlyCost *float64 `json:"monthlyCost"`
  106. }
  107. // PV is the interface by which the provider and cost model communicate PV prices.
  108. // The provider will best-effort try to fill out this struct.
  109. type PV struct {
  110. Cost string `json:"hourlyCost"`
  111. CostPerIO string `json:"costPerIOOperation"`
  112. Class string `json:"storageClass"`
  113. Size string `json:"size"`
  114. Region string `json:"region"`
  115. ProviderID string `json:"providerID,omitempty"`
  116. Parameters map[string]string `json:"parameters"`
  117. }
  118. // Key represents a way for nodes to match between the k8s API and a pricing API
  119. type Key interface {
  120. ID() string // ID represents an exact match
  121. Features() string // Features are a comma separated string of node metadata that could match pricing
  122. GPUType() string // GPUType returns "" if no GPU exists or GPUs, but the name of the GPU otherwise
  123. GPUCount() int // GPUCount returns 0 if no GPU exists or GPUs, but the number of attached GPUs otherwise
  124. }
  125. type PVKey interface {
  126. Features() string
  127. GetStorageClass() string
  128. ID() string
  129. }
  130. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  131. type OutOfClusterAllocation struct {
  132. Aggregator string `json:"aggregator"`
  133. Environment string `json:"environment"`
  134. Service string `json:"service"`
  135. Cost float64 `json:"cost"`
  136. Cluster string `json:"cluster"`
  137. }
  138. type CustomPricing struct {
  139. Provider string `json:"provider"`
  140. Description string `json:"description"`
  141. CPU string `json:"CPU"`
  142. SpotCPU string `json:"spotCPU"`
  143. RAM string `json:"RAM"`
  144. SpotRAM string `json:"spotRAM"`
  145. GPU string `json:"GPU"`
  146. SpotGPU string `json:"spotGPU"`
  147. Storage string `json:"storage"`
  148. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  149. RegionNetworkEgress string `json:"regionNetworkEgress"`
  150. InternetNetworkEgress string `json:"internetNetworkEgress"`
  151. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  152. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  153. LBIngressDataCost string `json:"LBIngressDataCost"`
  154. SpotLabel string `json:"spotLabel,omitempty"`
  155. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  156. GpuLabel string `json:"gpuLabel,omitempty"`
  157. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  158. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  159. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  160. AlibabaServiceKeyName string `json:"alibabaServiceKeyName,omitempty"`
  161. AlibabaServiceKeySecret string `json:"alibabaServiceKeySecret,omitempty"`
  162. AlibabaClusterRegion string `json:"alibabaClusterRegion,omitempty"`
  163. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  164. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  165. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  166. ProjectID string `json:"projectID,omitempty"`
  167. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  168. AthenaBucketName string `json:"athenaBucketName"`
  169. AthenaRegion string `json:"athenaRegion"`
  170. AthenaDatabase string `json:"athenaDatabase"`
  171. AthenaTable string `json:"athenaTable"`
  172. AthenaWorkgroup string `json:"athenaWorkgroup"`
  173. MasterPayerARN string `json:"masterPayerARN"`
  174. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  175. CustomPricesEnabled string `json:"customPricesEnabled"`
  176. DefaultIdle string `json:"defaultIdle"`
  177. AzureSubscriptionID string `json:"azureSubscriptionID"`
  178. AzureClientID string `json:"azureClientID"`
  179. AzureClientSecret string `json:"azureClientSecret"`
  180. AzureTenantID string `json:"azureTenantID"`
  181. AzureBillingRegion string `json:"azureBillingRegion"`
  182. AzureOfferDurableID string `json:"azureOfferDurableID"`
  183. AzureStorageSubscriptionID string `json:"azureStorageSubscriptionID"`
  184. AzureStorageAccount string `json:"azureStorageAccount"`
  185. AzureStorageAccessKey string `json:"azureStorageAccessKey"`
  186. AzureStorageContainer string `json:"azureStorageContainer"`
  187. AzureContainerPath string `json:"azureContainerPath"`
  188. AzureCloud string `json:"azureCloud"`
  189. CurrencyCode string `json:"currencyCode"`
  190. Discount string `json:"discount"`
  191. NegotiatedDiscount string `json:"negotiatedDiscount"`
  192. SharedOverhead string `json:"sharedOverhead"`
  193. ClusterName string `json:"clusterName"`
  194. SharedNamespaces string `json:"sharedNamespaces"`
  195. SharedLabelNames string `json:"sharedLabelNames"`
  196. SharedLabelValues string `json:"sharedLabelValues"`
  197. ShareTenancyCosts string `json:"shareTenancyCosts"` // TODO clean up configuration so we can use a type other that string (this should be a bool, but the app panics if it's not a string)
  198. ReadOnly string `json:"readOnly"`
  199. EditorAccess string `json:"editorAccess"`
  200. KubecostToken string `json:"kubecostToken"`
  201. GoogleAnalyticsTag string `json:"googleAnalyticsTag"`
  202. ExcludeProviderID string `json:"excludeProviderID"`
  203. }
  204. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  205. // of the configured monthly shared overhead cost. If the string version cannot
  206. // be parsed into a float, an error is logged and 0.0 is returned.
  207. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  208. // Empty string should be interpreted as "no cost", i.e. 0.0
  209. if cp.SharedOverhead == "" {
  210. return 0.0
  211. }
  212. // Attempt to parse, but log and return 0.0 if that fails.
  213. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  214. if err != nil {
  215. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  216. return 0.0
  217. }
  218. return sharedCostPerMonth
  219. }
  220. type ServiceAccountStatus struct {
  221. Checks []*ServiceAccountCheck `json:"checks"`
  222. }
  223. // ServiceAccountChecks is a thread safe map for holding ServiceAccountCheck objects
  224. type ServiceAccountChecks struct {
  225. sync.RWMutex
  226. serviceAccountChecks map[string]*ServiceAccountCheck
  227. }
  228. // NewServiceAccountChecks initialize ServiceAccountChecks
  229. func NewServiceAccountChecks() *ServiceAccountChecks {
  230. return &ServiceAccountChecks{
  231. serviceAccountChecks: make(map[string]*ServiceAccountCheck),
  232. }
  233. }
  234. func (sac *ServiceAccountChecks) set(key string, check *ServiceAccountCheck) {
  235. sac.Lock()
  236. defer sac.Unlock()
  237. sac.serviceAccountChecks[key] = check
  238. }
  239. // getStatus extracts ServiceAccountCheck objects into a slice and returns them in a ServiceAccountStatus
  240. func (sac *ServiceAccountChecks) getStatus() *ServiceAccountStatus {
  241. sac.Lock()
  242. defer sac.Unlock()
  243. checks := []*ServiceAccountCheck{}
  244. for _, v := range sac.serviceAccountChecks {
  245. checks = append(checks, v)
  246. }
  247. return &ServiceAccountStatus{
  248. Checks: checks,
  249. }
  250. }
  251. type ServiceAccountCheck struct {
  252. Message string `json:"message"`
  253. Status bool `json:"status"`
  254. AdditionalInfo string `json:"additionalInfo"`
  255. }
  256. type PricingSources struct {
  257. PricingSources map[string]*PricingSource
  258. }
  259. type PricingSource struct {
  260. Name string `json:"name"`
  261. Enabled bool `json:"enabled"`
  262. Available bool `json:"available"`
  263. Error string `json:"error"`
  264. }
  265. type PricingType string
  266. const (
  267. Api PricingType = "api"
  268. Spot PricingType = "spot"
  269. Reserved PricingType = "reserved"
  270. SavingsPlan PricingType = "savingsPlan"
  271. CsvExact PricingType = "csvExact"
  272. CsvClass PricingType = "csvClass"
  273. DefaultPrices PricingType = "defaultPrices"
  274. )
  275. type PricingMatchMetadata struct {
  276. TotalNodes int `json:"TotalNodes"`
  277. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  278. }
  279. // Provider represents a k8s provider.
  280. type Provider interface {
  281. ClusterInfo() (map[string]string, error)
  282. GetAddresses() ([]byte, error)
  283. GetDisks() ([]byte, error)
  284. GetOrphanedResources() ([]OrphanedResource, error)
  285. NodePricing(Key) (*Node, error)
  286. PVPricing(PVKey) (*PV, error)
  287. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  288. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  289. AllNodePricing() (interface{}, error)
  290. DownloadPricingData() error
  291. GetKey(map[string]string, *v1.Node) Key
  292. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  293. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  294. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  295. GetConfig() (*CustomPricing, error)
  296. GetManagementPlatform() (string, error)
  297. GetLocalStorageQuery(time.Duration, time.Duration, bool, bool) string
  298. ApplyReservedInstancePricing(map[string]*Node)
  299. ServiceAccountStatus() *ServiceAccountStatus
  300. PricingSourceStatus() map[string]*PricingSource
  301. ClusterManagementPricing() (string, float64, error)
  302. CombinedDiscountForNode(string, bool, float64, float64) float64
  303. Regions() []string
  304. }
  305. // ClusterName returns the name defined in cluster info, defaulting to the
  306. // CLUSTER_ID environment variable
  307. func ClusterName(p Provider) string {
  308. info, err := p.ClusterInfo()
  309. if err != nil {
  310. return env.GetClusterID()
  311. }
  312. name, ok := info["name"]
  313. if !ok {
  314. return env.GetClusterID()
  315. }
  316. return name
  317. }
  318. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  319. // indicating whether or not the cluster is using custom pricing.
  320. func CustomPricesEnabled(p Provider) bool {
  321. config, err := p.GetConfig()
  322. if err != nil {
  323. return false
  324. }
  325. // TODO:CLEANUP what is going on with this?
  326. if config.NegotiatedDiscount == "" {
  327. config.NegotiatedDiscount = "0%"
  328. }
  329. return config.CustomPricesEnabled == "true"
  330. }
  331. // ConfigWatcherFor returns a new ConfigWatcher instance which watches changes to the "pricing-configs"
  332. // configmap
  333. func ConfigWatcherFor(p Provider) *watcher.ConfigMapWatcher {
  334. return &watcher.ConfigMapWatcher{
  335. ConfigMapName: env.GetPricingConfigmapName(),
  336. WatchFunc: func(name string, data map[string]string) error {
  337. _, err := p.UpdateConfigFromConfigMap(data)
  338. return err
  339. },
  340. }
  341. }
  342. // AllocateIdleByDefault returns true if the application settings specify to allocate idle by default
  343. func AllocateIdleByDefault(p Provider) bool {
  344. config, err := p.GetConfig()
  345. if err != nil {
  346. return false
  347. }
  348. return config.DefaultIdle == "true"
  349. }
  350. // SharedNamespace returns a list of names of shared namespaces, as defined in the application settings
  351. func SharedNamespaces(p Provider) []string {
  352. namespaces := []string{}
  353. config, err := p.GetConfig()
  354. if err != nil {
  355. return namespaces
  356. }
  357. if config.SharedNamespaces == "" {
  358. return namespaces
  359. }
  360. // trim spaces so that "kube-system, kubecost" is equivalent to "kube-system,kubecost"
  361. for _, ns := range strings.Split(config.SharedNamespaces, ",") {
  362. namespaces = append(namespaces, strings.Trim(ns, " "))
  363. }
  364. return namespaces
  365. }
  366. // SharedLabel returns the configured set of shared labels as a parallel tuple of keys to values; e.g.
  367. // for app:kubecost,type:staging this returns (["app", "type"], ["kubecost", "staging"]) in order to
  368. // match the signature of the NewSharedResourceInfo
  369. func SharedLabels(p Provider) ([]string, []string) {
  370. names := []string{}
  371. values := []string{}
  372. config, err := p.GetConfig()
  373. if err != nil {
  374. return names, values
  375. }
  376. if config.SharedLabelNames == "" || config.SharedLabelValues == "" {
  377. return names, values
  378. }
  379. ks := strings.Split(config.SharedLabelNames, ",")
  380. vs := strings.Split(config.SharedLabelValues, ",")
  381. if len(ks) != len(vs) {
  382. log.Warnf("Shared labels have mis-matched lengths: %d names, %d values", len(ks), len(vs))
  383. return names, values
  384. }
  385. for i := range ks {
  386. names = append(names, strings.Trim(ks[i], " "))
  387. values = append(values, strings.Trim(vs[i], " "))
  388. }
  389. return names, values
  390. }
  391. // ShareTenancyCosts returns true if the application settings specify to share
  392. // tenancy costs by default.
  393. func ShareTenancyCosts(p Provider) bool {
  394. config, err := p.GetConfig()
  395. if err != nil {
  396. return false
  397. }
  398. return config.ShareTenancyCosts == "true"
  399. }
  400. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  401. func NewProvider(cache clustercache.ClusterCache, apiKey string, config *config.ConfigFileManager) (Provider, error) {
  402. nodes := cache.GetAllNodes()
  403. if len(nodes) == 0 {
  404. log.Infof("Could not locate any nodes for cluster.") // valid in ETL readonly mode
  405. return &CustomProvider{
  406. Clientset: cache,
  407. Config: NewProviderConfig(config, "default.json"),
  408. }, nil
  409. }
  410. cp := getClusterProperties(nodes[0])
  411. switch cp.provider {
  412. case kubecost.CSVProvider:
  413. log.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  414. return &CSVProvider{
  415. CSVLocation: env.GetCSVPath(),
  416. CustomProvider: &CustomProvider{
  417. Clientset: cache,
  418. Config: NewProviderConfig(config, cp.configFileName),
  419. },
  420. }, nil
  421. case kubecost.GCPProvider:
  422. log.Info("metadata reports we are in GCE")
  423. if apiKey == "" {
  424. return nil, errors.New("Supply a GCP Key to start getting data")
  425. }
  426. return &GCP{
  427. Clientset: cache,
  428. APIKey: apiKey,
  429. Config: NewProviderConfig(config, cp.configFileName),
  430. clusterRegion: cp.region,
  431. clusterProjectId: cp.projectID,
  432. metadataClient: metadata.NewClient(&http.Client{
  433. Transport: httputil.NewUserAgentTransport("kubecost", http.DefaultTransport),
  434. }),
  435. }, nil
  436. case kubecost.AWSProvider:
  437. log.Info("Found ProviderID starting with \"aws\", using AWS Provider")
  438. return &AWS{
  439. Clientset: cache,
  440. Config: NewProviderConfig(config, cp.configFileName),
  441. clusterRegion: cp.region,
  442. clusterAccountId: cp.accountID,
  443. serviceAccountChecks: NewServiceAccountChecks(),
  444. }, nil
  445. case kubecost.AzureProvider:
  446. log.Info("Found ProviderID starting with \"azure\", using Azure Provider")
  447. return &Azure{
  448. Clientset: cache,
  449. Config: NewProviderConfig(config, cp.configFileName),
  450. clusterRegion: cp.region,
  451. clusterAccountId: cp.accountID,
  452. serviceAccountChecks: NewServiceAccountChecks(),
  453. }, nil
  454. case kubecost.AlibabaProvider:
  455. log.Info("Found ProviderID starting with \"alibaba\", using Alibaba Cloud Provider")
  456. return &Alibaba{
  457. Clientset: cache,
  458. Config: NewProviderConfig(config, cp.configFileName),
  459. clusterRegion: cp.region,
  460. clusterAccountId: cp.accountID,
  461. serviceAccountChecks: NewServiceAccountChecks(),
  462. }, nil
  463. case kubecost.ScalewayProvider:
  464. log.Info("Found ProviderID starting with \"scaleway\", using Scaleway Provider")
  465. return &Scaleway{
  466. Clientset: cache,
  467. Config: NewProviderConfig(config, cp.configFileName),
  468. }, nil
  469. default:
  470. log.Info("Unsupported provider, falling back to default")
  471. return &CustomProvider{
  472. Clientset: cache,
  473. Config: NewProviderConfig(config, cp.configFileName),
  474. }, nil
  475. }
  476. }
  477. type clusterProperties struct {
  478. provider string
  479. configFileName string
  480. region string
  481. accountID string
  482. projectID string
  483. }
  484. func getClusterProperties(node *v1.Node) clusterProperties {
  485. providerID := strings.ToLower(node.Spec.ProviderID)
  486. region, _ := util.GetRegion(node.Labels)
  487. cp := clusterProperties{
  488. provider: "DEFAULT",
  489. configFileName: "default.json",
  490. region: region,
  491. accountID: "",
  492. projectID: "",
  493. }
  494. if metadata.OnGCE() {
  495. cp.provider = kubecost.GCPProvider
  496. cp.configFileName = "gcp.json"
  497. cp.projectID = parseGCPProjectID(providerID)
  498. } else if strings.HasPrefix(providerID, "aws") {
  499. cp.provider = kubecost.AWSProvider
  500. cp.configFileName = "aws.json"
  501. } else if strings.HasPrefix(providerID, "azure") {
  502. cp.provider = kubecost.AzureProvider
  503. cp.configFileName = "azure.json"
  504. cp.accountID = parseAzureSubscriptionID(providerID)
  505. } else if strings.HasPrefix(providerID, "scaleway") { // the scaleway provider ID looks like scaleway://instance/<instance_id>
  506. cp.provider = kubecost.ScalewayProvider
  507. cp.configFileName = "scaleway.json"
  508. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "aliyun") { // provider ID is not prefix with any distinct keyword like other providers
  509. cp.provider = kubecost.AlibabaProvider
  510. cp.configFileName = "alibaba.json"
  511. }
  512. if env.IsUseCSVProvider() {
  513. cp.provider = kubecost.CSVProvider
  514. }
  515. return cp
  516. }
  517. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  518. pw := env.GetRemotePW()
  519. address := env.GetSQLAddress()
  520. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  521. db, err := sql.Open("postgres", connStr)
  522. if err != nil {
  523. return err
  524. }
  525. defer db.Close()
  526. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  527. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  528. if err != nil {
  529. return err
  530. }
  531. return nil
  532. }
  533. func CreateClusterMeta(cluster_id, cluster_name string) error {
  534. pw := env.GetRemotePW()
  535. address := env.GetSQLAddress()
  536. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  537. db, err := sql.Open("postgres", connStr)
  538. if err != nil {
  539. return err
  540. }
  541. defer db.Close()
  542. for _, stmt := range createTableStatements {
  543. _, err := db.Exec(stmt)
  544. if err != nil {
  545. return err
  546. }
  547. }
  548. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  549. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  550. if err != nil {
  551. return err
  552. }
  553. return nil
  554. }
  555. func GetClusterMeta(cluster_id string) (string, string, error) {
  556. pw := env.GetRemotePW()
  557. address := env.GetSQLAddress()
  558. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  559. db, err := sql.Open("postgres", connStr)
  560. if err != nil {
  561. return "", "", err
  562. }
  563. defer db.Close()
  564. query := `SELECT cluster_id, cluster_name
  565. FROM names
  566. WHERE cluster_id = ?`
  567. rows, err := db.Query(query, cluster_id)
  568. if err != nil {
  569. return "", "", err
  570. }
  571. defer rows.Close()
  572. var (
  573. sql_cluster_id string
  574. cluster_name string
  575. )
  576. for rows.Next() {
  577. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  578. return "", "", err
  579. }
  580. }
  581. return sql_cluster_id, cluster_name, nil
  582. }
  583. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  584. id, name, err := GetClusterMeta(cluster_id)
  585. if err != nil {
  586. err := CreateClusterMeta(cluster_id, cluster_name)
  587. if err != nil {
  588. return "", "", err
  589. }
  590. }
  591. if id == "" {
  592. err := CreateClusterMeta(cluster_id, cluster_name)
  593. if err != nil {
  594. return "", "", err
  595. }
  596. }
  597. return id, name, nil
  598. }
  599. var (
  600. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  601. providerAWSRegex = regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  602. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  603. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  604. providerGCERegex = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  605. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  606. persistentVolumeAWSRegex = regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  607. // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  608. loadBalancerAWSRegex = regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$")
  609. )
  610. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  611. // returns the string as is if it cannot find a match
  612. func ParseID(id string) string {
  613. match := providerAWSRegex.FindStringSubmatch(id)
  614. if len(match) >= 2 {
  615. return match[1]
  616. }
  617. match = providerGCERegex.FindStringSubmatch(id)
  618. if len(match) >= 2 {
  619. return match[1]
  620. }
  621. // Return id for Azure Provider, CSV Provider and Custom Provider
  622. return id
  623. }
  624. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  625. // returns the string as is if it cannot find a match
  626. func ParsePVID(id string) string {
  627. match := persistentVolumeAWSRegex.FindStringSubmatch(id)
  628. if len(match) >= 2 {
  629. return match[1]
  630. }
  631. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  632. return id
  633. }
  634. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  635. // returns the string as is if it cannot find a match
  636. func ParseLBID(id string) string {
  637. match := loadBalancerAWSRegex.FindStringSubmatch(id)
  638. if len(match) >= 2 {
  639. return match[1]
  640. }
  641. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  642. return id
  643. }