provider.go 25 KB

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