provider.go 21 KB

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