provider.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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/cost-model/pkg/util"
  13. "k8s.io/klog"
  14. "cloud.google.com/go/compute/metadata"
  15. "github.com/kubecost/cost-model/pkg/clustercache"
  16. "github.com/kubecost/cost-model/pkg/config"
  17. "github.com/kubecost/cost-model/pkg/env"
  18. "github.com/kubecost/cost-model/pkg/log"
  19. "github.com/kubecost/cost-model/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. 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. KubecostToken string `json:"kubecostToken"`
  172. GoogleAnalyticsTag string `json:"googleAnalyticsTag"`
  173. }
  174. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  175. // of the configured monthly shared overhead cost. If the string version cannot
  176. // be parsed into a float, an error is logged and 0.0 is returned.
  177. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  178. // Empty string should be interpreted as "no cost", i.e. 0.0
  179. if cp.SharedOverhead == "" {
  180. return 0.0
  181. }
  182. // Attempt to parse, but log and return 0.0 if that fails.
  183. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  184. if err != nil {
  185. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  186. return 0.0
  187. }
  188. return sharedCostPerMonth
  189. }
  190. type ServiceAccountStatus struct {
  191. Checks []*ServiceAccountCheck `json:"checks"`
  192. }
  193. // ServiceAccountChecks is a thread safe map for holding ServiceAccountCheck objects
  194. type ServiceAccountChecks struct {
  195. sync.RWMutex
  196. serviceAccountChecks map[string]*ServiceAccountCheck
  197. }
  198. // NewServiceAccountChecks initialize ServiceAccountChecks
  199. func NewServiceAccountChecks() *ServiceAccountChecks {
  200. return &ServiceAccountChecks{
  201. serviceAccountChecks: make(map[string]*ServiceAccountCheck),
  202. }
  203. }
  204. func (sac *ServiceAccountChecks) set(key string, check *ServiceAccountCheck) {
  205. sac.Lock()
  206. defer sac.Unlock()
  207. sac.serviceAccountChecks[key] = check
  208. }
  209. // getStatus extracts ServiceAccountCheck objects into a slice and returns them in a ServiceAccountStatus
  210. func (sac *ServiceAccountChecks) getStatus() *ServiceAccountStatus {
  211. sac.Lock()
  212. defer sac.Unlock()
  213. checks := []*ServiceAccountCheck{}
  214. for _, v := range sac.serviceAccountChecks {
  215. checks = append(checks, v)
  216. }
  217. return &ServiceAccountStatus{
  218. Checks: checks,
  219. }
  220. }
  221. type ServiceAccountCheck struct {
  222. Message string `json:"message"`
  223. Status bool `json:"status"`
  224. AdditionalInfo string `json:"additionalInfo"`
  225. }
  226. type PricingSources struct {
  227. PricingSources map[string]*PricingSource
  228. }
  229. type PricingSource struct {
  230. Name string `json:"name"`
  231. Enabled bool `json:"enabled"`
  232. Available bool `json:"available"`
  233. Error string `json:"error"`
  234. }
  235. type PricingType string
  236. const (
  237. Api PricingType = "api"
  238. Spot PricingType = "spot"
  239. Reserved PricingType = "reserved"
  240. SavingsPlan PricingType = "savingsPlan"
  241. CsvExact PricingType = "csvExact"
  242. CsvClass PricingType = "csvClass"
  243. DefaultPrices PricingType = "defaultPrices"
  244. )
  245. type PricingMatchMetadata struct {
  246. TotalNodes int `json:"TotalNodes"`
  247. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  248. }
  249. // Provider represents a k8s provider.
  250. type Provider interface {
  251. ClusterInfo() (map[string]string, error)
  252. GetAddresses() ([]byte, error)
  253. GetDisks() ([]byte, error)
  254. NodePricing(Key) (*Node, error)
  255. PVPricing(PVKey) (*PV, error)
  256. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  257. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  258. AllNodePricing() (interface{}, error)
  259. DownloadPricingData() error
  260. GetKey(map[string]string, *v1.Node) Key
  261. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  262. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  263. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  264. GetConfig() (*CustomPricing, error)
  265. GetManagementPlatform() (string, error)
  266. GetLocalStorageQuery(time.Duration, time.Duration, bool, bool) string
  267. ApplyReservedInstancePricing(map[string]*Node)
  268. ServiceAccountStatus() *ServiceAccountStatus
  269. PricingSourceStatus() map[string]*PricingSource
  270. ClusterManagementPricing() (string, float64, error)
  271. CombinedDiscountForNode(string, bool, float64, float64) float64
  272. Regions() []string
  273. }
  274. // ClusterName returns the name defined in cluster info, defaulting to the
  275. // CLUSTER_ID environment variable
  276. func ClusterName(p Provider) string {
  277. info, err := p.ClusterInfo()
  278. if err != nil {
  279. return env.GetClusterID()
  280. }
  281. name, ok := info["name"]
  282. if !ok {
  283. return env.GetClusterID()
  284. }
  285. return name
  286. }
  287. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  288. // indicating whether or not the cluster is using custom pricing.
  289. func CustomPricesEnabled(p Provider) bool {
  290. config, err := p.GetConfig()
  291. if err != nil {
  292. return false
  293. }
  294. // TODO:CLEANUP what is going on with this?
  295. if config.NegotiatedDiscount == "" {
  296. config.NegotiatedDiscount = "0%"
  297. }
  298. return config.CustomPricesEnabled == "true"
  299. }
  300. // ConfigWatcherFor returns a new ConfigWatcher instance which watches changes to the "pricing-configs"
  301. // configmap
  302. func ConfigWatcherFor(p Provider) *watcher.ConfigMapWatcher {
  303. return &watcher.ConfigMapWatcher{
  304. ConfigMapName: env.GetPricingConfigmapName(),
  305. WatchFunc: func(name string, data map[string]string) error {
  306. _, err := p.UpdateConfigFromConfigMap(data)
  307. return err
  308. },
  309. }
  310. }
  311. // AllocateIdleByDefault returns true if the application settings specify to allocate idle by default
  312. func AllocateIdleByDefault(p Provider) bool {
  313. config, err := p.GetConfig()
  314. if err != nil {
  315. return false
  316. }
  317. return config.DefaultIdle == "true"
  318. }
  319. // SharedNamespace returns a list of names of shared namespaces, as defined in the application settings
  320. func SharedNamespaces(p Provider) []string {
  321. namespaces := []string{}
  322. config, err := p.GetConfig()
  323. if err != nil {
  324. return namespaces
  325. }
  326. if config.SharedNamespaces == "" {
  327. return namespaces
  328. }
  329. // trim spaces so that "kube-system, kubecost" is equivalent to "kube-system,kubecost"
  330. for _, ns := range strings.Split(config.SharedNamespaces, ",") {
  331. namespaces = append(namespaces, strings.Trim(ns, " "))
  332. }
  333. return namespaces
  334. }
  335. // SharedLabel returns the configured set of shared labels as a parallel tuple of keys to values; e.g.
  336. // for app:kubecost,type:staging this returns (["app", "type"], ["kubecost", "staging"]) in order to
  337. // match the signature of the NewSharedResourceInfo
  338. func SharedLabels(p Provider) ([]string, []string) {
  339. names := []string{}
  340. values := []string{}
  341. config, err := p.GetConfig()
  342. if err != nil {
  343. return names, values
  344. }
  345. if config.SharedLabelNames == "" || config.SharedLabelValues == "" {
  346. return names, values
  347. }
  348. ks := strings.Split(config.SharedLabelNames, ",")
  349. vs := strings.Split(config.SharedLabelValues, ",")
  350. if len(ks) != len(vs) {
  351. klog.V(2).Infof("[Warning] shared labels have mis-matched lengths: %d names, %d values", len(ks), len(vs))
  352. return names, values
  353. }
  354. for i := range ks {
  355. names = append(names, strings.Trim(ks[i], " "))
  356. values = append(values, strings.Trim(vs[i], " "))
  357. }
  358. return names, values
  359. }
  360. // ShareTenancyCosts returns true if the application settings specify to share
  361. // tenancy costs by default.
  362. func ShareTenancyCosts(p Provider) bool {
  363. config, err := p.GetConfig()
  364. if err != nil {
  365. return false
  366. }
  367. return config.ShareTenancyCosts == "true"
  368. }
  369. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  370. func NewProvider(cache clustercache.ClusterCache, apiKey string, config *config.ConfigFileManager) (Provider, error) {
  371. nodes := cache.GetAllNodes()
  372. if len(nodes) == 0 {
  373. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  374. }
  375. cp := getClusterProperties(nodes[0])
  376. switch cp.provider {
  377. case "CSV":
  378. klog.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  379. return &CSVProvider{
  380. CSVLocation: env.GetCSVPath(),
  381. CustomProvider: &CustomProvider{
  382. Clientset: cache,
  383. Config: NewProviderConfig(config, cp.configFileName),
  384. },
  385. }, nil
  386. case "GCP":
  387. klog.V(3).Info("metadata reports we are in GCE")
  388. if apiKey == "" {
  389. return nil, errors.New("Supply a GCP Key to start getting data")
  390. }
  391. return &GCP{
  392. Clientset: cache,
  393. APIKey: apiKey,
  394. Config: NewProviderConfig(config, cp.configFileName),
  395. clusterRegion: cp.region,
  396. clusterProjectId: cp.projectID,
  397. }, nil
  398. case "AWS":
  399. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  400. return &AWS{
  401. Clientset: cache,
  402. Config: NewProviderConfig(config, cp.configFileName),
  403. clusterRegion: cp.region,
  404. clusterAccountId: cp.accountID,
  405. serviceAccountChecks: NewServiceAccountChecks(),
  406. }, nil
  407. case "AZURE":
  408. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  409. return &Azure{
  410. Clientset: cache,
  411. Config: NewProviderConfig(config, cp.configFileName),
  412. clusterRegion: cp.region,
  413. clusterAccountId: cp.accountID,
  414. serviceAccountChecks: NewServiceAccountChecks(),
  415. }, nil
  416. default:
  417. klog.V(2).Info("Unsupported provider, falling back to default")
  418. return &CustomProvider{
  419. Clientset: cache,
  420. Config: NewProviderConfig(config, cp.configFileName),
  421. }, nil
  422. }
  423. }
  424. type clusterProperties struct {
  425. provider string
  426. configFileName string
  427. region string
  428. accountID string
  429. projectID string
  430. }
  431. func getClusterProperties(node *v1.Node) clusterProperties {
  432. providerID := strings.ToLower(node.Spec.ProviderID)
  433. region, _ := util.GetRegion(node.Labels)
  434. cp := clusterProperties{
  435. provider: "DEFAULT",
  436. configFileName: "default.json",
  437. region: region,
  438. accountID: "",
  439. projectID: "",
  440. }
  441. if metadata.OnGCE() {
  442. cp.provider = "GCP"
  443. cp.configFileName = "gcp.json"
  444. cp.projectID = parseGCPProjectID(providerID)
  445. } else if strings.HasPrefix(providerID, "aws") {
  446. cp.provider = "AWS"
  447. cp.configFileName = "aws.json"
  448. } else if strings.HasPrefix(providerID, "azure") {
  449. cp.provider = "AZURE"
  450. cp.configFileName = "azure.json"
  451. cp.accountID = parseAzureSubscriptionID(providerID)
  452. }
  453. if env.IsUseCSVProvider() {
  454. cp.provider = "CSV"
  455. }
  456. return cp
  457. }
  458. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  459. pw := env.GetRemotePW()
  460. address := env.GetSQLAddress()
  461. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  462. db, err := sql.Open("postgres", connStr)
  463. if err != nil {
  464. return err
  465. }
  466. defer db.Close()
  467. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  468. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  469. if err != nil {
  470. return err
  471. }
  472. return nil
  473. }
  474. func CreateClusterMeta(cluster_id, cluster_name string) error {
  475. pw := env.GetRemotePW()
  476. address := env.GetSQLAddress()
  477. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  478. db, err := sql.Open("postgres", connStr)
  479. if err != nil {
  480. return err
  481. }
  482. defer db.Close()
  483. for _, stmt := range createTableStatements {
  484. _, err := db.Exec(stmt)
  485. if err != nil {
  486. return err
  487. }
  488. }
  489. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  490. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  491. if err != nil {
  492. return err
  493. }
  494. return nil
  495. }
  496. func GetClusterMeta(cluster_id string) (string, string, error) {
  497. pw := env.GetRemotePW()
  498. address := env.GetSQLAddress()
  499. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  500. db, err := sql.Open("postgres", connStr)
  501. defer db.Close()
  502. query := `SELECT cluster_id, cluster_name
  503. FROM names
  504. WHERE cluster_id = ?`
  505. rows, err := db.Query(query, cluster_id)
  506. if err != nil {
  507. return "", "", err
  508. }
  509. defer rows.Close()
  510. var (
  511. sql_cluster_id string
  512. cluster_name string
  513. )
  514. for rows.Next() {
  515. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  516. return "", "", err
  517. }
  518. }
  519. return sql_cluster_id, cluster_name, nil
  520. }
  521. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  522. id, name, err := GetClusterMeta(cluster_id)
  523. if err != nil {
  524. err := CreateClusterMeta(cluster_id, cluster_name)
  525. if err != nil {
  526. return "", "", err
  527. }
  528. }
  529. if id == "" {
  530. err := CreateClusterMeta(cluster_id, cluster_name)
  531. if err != nil {
  532. return "", "", err
  533. }
  534. }
  535. return id, name, nil
  536. }
  537. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  538. // returns the string as is if it cannot find a match
  539. func ParseID(id string) string {
  540. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  541. rx := regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  542. match := rx.FindStringSubmatch(id)
  543. if len(match) >= 2 {
  544. return match[1]
  545. }
  546. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  547. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  548. rx = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  549. match = rx.FindStringSubmatch(id)
  550. if len(match) >= 2 {
  551. return match[1]
  552. }
  553. // Return id for Azure Provider, CSV Provider and Custom Provider
  554. return id
  555. }
  556. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  557. // returns the string as is if it cannot find a match
  558. func ParsePVID(id string) string {
  559. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  560. rx := regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  561. match := rx.FindStringSubmatch(id)
  562. if len(match) >= 2 {
  563. return match[1]
  564. }
  565. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  566. return id
  567. }
  568. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  569. // returns the string as is if it cannot find a match
  570. func ParseLBID(id string) string {
  571. rx := regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$") // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  572. match := rx.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. }