provider.go 25 KB

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