provider.go 26 KB

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