provider.go 26 KB

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