provider.go 25 KB

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