provider.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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. }
  313. // ClusterName returns the name defined in cluster info, defaulting to the
  314. // CLUSTER_ID environment variable
  315. func ClusterName(p Provider) string {
  316. info, err := p.ClusterInfo()
  317. if err != nil {
  318. return env.GetClusterID()
  319. }
  320. name, ok := info["name"]
  321. if !ok {
  322. return env.GetClusterID()
  323. }
  324. return name
  325. }
  326. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  327. // indicating whether or not the cluster is using custom pricing.
  328. func CustomPricesEnabled(p Provider) bool {
  329. config, err := p.GetConfig()
  330. if err != nil {
  331. return false
  332. }
  333. // TODO:CLEANUP what is going on with this?
  334. if config.NegotiatedDiscount == "" {
  335. config.NegotiatedDiscount = "0%"
  336. }
  337. return config.CustomPricesEnabled == "true"
  338. }
  339. // ConfigWatcherFor returns a new ConfigWatcher instance which watches changes to the "pricing-configs"
  340. // configmap
  341. func ConfigWatcherFor(p Provider) *watcher.ConfigMapWatcher {
  342. return &watcher.ConfigMapWatcher{
  343. ConfigMapName: env.GetPricingConfigmapName(),
  344. WatchFunc: func(name string, data map[string]string) error {
  345. _, err := p.UpdateConfigFromConfigMap(data)
  346. return err
  347. },
  348. }
  349. }
  350. // AllocateIdleByDefault returns true if the application settings specify to allocate idle by default
  351. func AllocateIdleByDefault(p Provider) bool {
  352. config, err := p.GetConfig()
  353. if err != nil {
  354. return false
  355. }
  356. return config.DefaultIdle == "true"
  357. }
  358. // SharedNamespace returns a list of names of shared namespaces, as defined in the application settings
  359. func SharedNamespaces(p Provider) []string {
  360. namespaces := []string{}
  361. config, err := p.GetConfig()
  362. if err != nil {
  363. return namespaces
  364. }
  365. if config.SharedNamespaces == "" {
  366. return namespaces
  367. }
  368. // trim spaces so that "kube-system, kubecost" is equivalent to "kube-system,kubecost"
  369. for _, ns := range strings.Split(config.SharedNamespaces, ",") {
  370. namespaces = append(namespaces, strings.Trim(ns, " "))
  371. }
  372. return namespaces
  373. }
  374. // SharedLabel returns the configured set of shared labels as a parallel tuple of keys to values; e.g.
  375. // for app:kubecost,type:staging this returns (["app", "type"], ["kubecost", "staging"]) in order to
  376. // match the signature of the NewSharedResourceInfo
  377. func SharedLabels(p Provider) ([]string, []string) {
  378. names := []string{}
  379. values := []string{}
  380. config, err := p.GetConfig()
  381. if err != nil {
  382. return names, values
  383. }
  384. if config.SharedLabelNames == "" || config.SharedLabelValues == "" {
  385. return names, values
  386. }
  387. ks := strings.Split(config.SharedLabelNames, ",")
  388. vs := strings.Split(config.SharedLabelValues, ",")
  389. if len(ks) != len(vs) {
  390. log.Warnf("Shared labels have mis-matched lengths: %d names, %d values", len(ks), len(vs))
  391. return names, values
  392. }
  393. for i := range ks {
  394. names = append(names, strings.Trim(ks[i], " "))
  395. values = append(values, strings.Trim(vs[i], " "))
  396. }
  397. return names, values
  398. }
  399. // ShareTenancyCosts returns true if the application settings specify to share
  400. // tenancy costs by default.
  401. func ShareTenancyCosts(p Provider) bool {
  402. config, err := p.GetConfig()
  403. if err != nil {
  404. return false
  405. }
  406. return config.ShareTenancyCosts == "true"
  407. }
  408. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  409. func NewProvider(cache clustercache.ClusterCache, apiKey string, config *config.ConfigFileManager) (Provider, error) {
  410. nodes := cache.GetAllNodes()
  411. if len(nodes) == 0 {
  412. log.Infof("Could not locate any nodes for cluster.") // valid in ETL readonly mode
  413. return &CustomProvider{
  414. Clientset: cache,
  415. Config: NewProviderConfig(config, "default.json"),
  416. }, nil
  417. }
  418. cp := getClusterProperties(nodes[0])
  419. switch cp.provider {
  420. case kubecost.CSVProvider:
  421. log.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  422. return &CSVProvider{
  423. CSVLocation: env.GetCSVPath(),
  424. CustomProvider: &CustomProvider{
  425. Clientset: cache,
  426. Config: NewProviderConfig(config, cp.configFileName),
  427. },
  428. }, nil
  429. case kubecost.GCPProvider:
  430. log.Info("metadata reports we are in GCE")
  431. if apiKey == "" {
  432. return nil, errors.New("Supply a GCP Key to start getting data")
  433. }
  434. return &GCP{
  435. Clientset: cache,
  436. APIKey: apiKey,
  437. Config: NewProviderConfig(config, cp.configFileName),
  438. clusterRegion: cp.region,
  439. clusterProjectId: cp.projectID,
  440. metadataClient: metadata.NewClient(&http.Client{
  441. Transport: httputil.NewUserAgentTransport("kubecost", http.DefaultTransport),
  442. }),
  443. }, nil
  444. case kubecost.AWSProvider:
  445. log.Info("Found ProviderID starting with \"aws\", using AWS Provider")
  446. return &AWS{
  447. Clientset: cache,
  448. Config: NewProviderConfig(config, cp.configFileName),
  449. clusterRegion: cp.region,
  450. clusterAccountId: cp.accountID,
  451. serviceAccountChecks: NewServiceAccountChecks(),
  452. }, nil
  453. case kubecost.AzureProvider:
  454. log.Info("Found ProviderID starting with \"azure\", using Azure Provider")
  455. return &Azure{
  456. Clientset: cache,
  457. Config: NewProviderConfig(config, cp.configFileName),
  458. clusterRegion: cp.region,
  459. clusterAccountId: cp.accountID,
  460. serviceAccountChecks: NewServiceAccountChecks(),
  461. }, nil
  462. case kubecost.AlibabaProvider:
  463. log.Info("Found ProviderID starting with \"alibaba\", using Alibaba Cloud Provider")
  464. return &Alibaba{
  465. Clientset: cache,
  466. Config: NewProviderConfig(config, cp.configFileName),
  467. clusterRegion: cp.region,
  468. clusterAccountId: cp.accountID,
  469. serviceAccountChecks: NewServiceAccountChecks(),
  470. }, nil
  471. case kubecost.ScalewayProvider:
  472. log.Info("Found ProviderID starting with \"scaleway\", using Scaleway Provider")
  473. return &Scaleway{
  474. Clientset: cache,
  475. Config: NewProviderConfig(config, cp.configFileName),
  476. }, nil
  477. default:
  478. log.Info("Unsupported provider, falling back to default")
  479. return &CustomProvider{
  480. Clientset: cache,
  481. Config: NewProviderConfig(config, cp.configFileName),
  482. }, nil
  483. }
  484. }
  485. type clusterProperties struct {
  486. provider string
  487. configFileName string
  488. region string
  489. accountID string
  490. projectID string
  491. }
  492. func getClusterProperties(node *v1.Node) clusterProperties {
  493. providerID := strings.ToLower(node.Spec.ProviderID)
  494. region, _ := util.GetRegion(node.Labels)
  495. cp := clusterProperties{
  496. provider: "DEFAULT",
  497. configFileName: "default.json",
  498. region: region,
  499. accountID: "",
  500. projectID: "",
  501. }
  502. if metadata.OnGCE() {
  503. cp.provider = kubecost.GCPProvider
  504. cp.configFileName = "gcp.json"
  505. cp.projectID = parseGCPProjectID(providerID)
  506. } else if strings.HasPrefix(providerID, "aws") {
  507. cp.provider = kubecost.AWSProvider
  508. cp.configFileName = "aws.json"
  509. } else if strings.HasPrefix(providerID, "azure") {
  510. cp.provider = kubecost.AzureProvider
  511. cp.configFileName = "azure.json"
  512. cp.accountID = parseAzureSubscriptionID(providerID)
  513. } else if strings.HasPrefix(providerID, "scaleway") { // the scaleway provider ID looks like scaleway://instance/<instance_id>
  514. cp.provider = kubecost.ScalewayProvider
  515. cp.configFileName = "scaleway.json"
  516. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "aliyun") { // provider ID is not prefix with any distinct keyword like other providers
  517. cp.provider = kubecost.AlibabaProvider
  518. cp.configFileName = "alibaba.json"
  519. }
  520. if env.IsUseCSVProvider() {
  521. cp.provider = kubecost.CSVProvider
  522. }
  523. return cp
  524. }
  525. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  526. pw := env.GetRemotePW()
  527. address := env.GetSQLAddress()
  528. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  529. db, err := sql.Open("postgres", connStr)
  530. if err != nil {
  531. return err
  532. }
  533. defer db.Close()
  534. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  535. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  536. if err != nil {
  537. return err
  538. }
  539. return nil
  540. }
  541. func CreateClusterMeta(cluster_id, cluster_name string) error {
  542. pw := env.GetRemotePW()
  543. address := env.GetSQLAddress()
  544. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  545. db, err := sql.Open("postgres", connStr)
  546. if err != nil {
  547. return err
  548. }
  549. defer db.Close()
  550. for _, stmt := range createTableStatements {
  551. _, err := db.Exec(stmt)
  552. if err != nil {
  553. return err
  554. }
  555. }
  556. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  557. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  558. if err != nil {
  559. return err
  560. }
  561. return nil
  562. }
  563. func GetClusterMeta(cluster_id string) (string, string, error) {
  564. pw := env.GetRemotePW()
  565. address := env.GetSQLAddress()
  566. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  567. db, err := sql.Open("postgres", connStr)
  568. if err != nil {
  569. return "", "", err
  570. }
  571. defer db.Close()
  572. query := `SELECT cluster_id, cluster_name
  573. FROM names
  574. WHERE cluster_id = ?`
  575. rows, err := db.Query(query, cluster_id)
  576. if err != nil {
  577. return "", "", err
  578. }
  579. defer rows.Close()
  580. var (
  581. sql_cluster_id string
  582. cluster_name string
  583. )
  584. for rows.Next() {
  585. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  586. return "", "", err
  587. }
  588. }
  589. return sql_cluster_id, cluster_name, nil
  590. }
  591. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  592. id, name, err := GetClusterMeta(cluster_id)
  593. if err != nil {
  594. err := CreateClusterMeta(cluster_id, cluster_name)
  595. if err != nil {
  596. return "", "", err
  597. }
  598. }
  599. if id == "" {
  600. err := CreateClusterMeta(cluster_id, cluster_name)
  601. if err != nil {
  602. return "", "", err
  603. }
  604. }
  605. return id, name, nil
  606. }
  607. var (
  608. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  609. providerAWSRegex = regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  610. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  611. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  612. providerGCERegex = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  613. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  614. persistentVolumeAWSRegex = regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  615. // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  616. loadBalancerAWSRegex = regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$")
  617. )
  618. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  619. // returns the string as is if it cannot find a match
  620. func ParseID(id string) string {
  621. match := providerAWSRegex.FindStringSubmatch(id)
  622. if len(match) >= 2 {
  623. return match[1]
  624. }
  625. match = providerGCERegex.FindStringSubmatch(id)
  626. if len(match) >= 2 {
  627. return match[1]
  628. }
  629. // Return id for Azure Provider, CSV Provider and Custom Provider
  630. return id
  631. }
  632. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  633. // returns the string as is if it cannot find a match
  634. func ParsePVID(id string) string {
  635. match := persistentVolumeAWSRegex.FindStringSubmatch(id)
  636. if len(match) >= 2 {
  637. return match[1]
  638. }
  639. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  640. return id
  641. }
  642. // ParseLBID attempts to parse a LB 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 ParseLBID(id string) string {
  645. match := loadBalancerAWSRegex.FindStringSubmatch(id)
  646. if len(match) >= 2 {
  647. return match[1]
  648. }
  649. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  650. return id
  651. }