provider.go 22 KB

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