provider.go 22 KB

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