provider.go 22 KB

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