provider.go 25 KB

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