provider.go 21 KB

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