provider.go 26 KB

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