provider.go 26 KB

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