provider.go 26 KB

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