provider.go 25 KB

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