provider.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. package cloud
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "k8s.io/klog"
  12. "cloud.google.com/go/compute/metadata"
  13. "github.com/kubecost/cost-model/pkg/clustercache"
  14. "github.com/kubecost/cost-model/pkg/config"
  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, config *config.ConfigFileManager, overrideConfigPath string, cache clustercache.ClusterCache) (Provider, error) {
  338. if ctype == "aws" {
  339. return &AWS{
  340. Clientset: cache,
  341. Config: NewProviderConfig(config, overrideConfigPath),
  342. }, nil
  343. } else if ctype == "gcp" {
  344. return &GCP{
  345. Clientset: cache,
  346. Config: NewProviderConfig(config, overrideConfigPath),
  347. }, nil
  348. } else if ctype == "azure" {
  349. return &Azure{
  350. Clientset: cache,
  351. Config: NewProviderConfig(config, overrideConfigPath),
  352. }, nil
  353. }
  354. return &CustomProvider{
  355. Clientset: cache,
  356. Config: NewProviderConfig(config, 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, config *config.ConfigFileManager) (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. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  366. if env.IsUseCSVProvider() {
  367. klog.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  368. configFileName := ""
  369. if metadata.OnGCE() {
  370. configFileName = "gcp.json"
  371. } else if strings.HasPrefix(provider, "aws") {
  372. configFileName = "aws.json"
  373. } else if strings.HasPrefix(provider, "azure") {
  374. configFileName = "azure.json"
  375. } else {
  376. configFileName = "default.json"
  377. }
  378. return &CSVProvider{
  379. CSVLocation: env.GetCSVPath(),
  380. CustomProvider: &CustomProvider{
  381. Clientset: cache,
  382. Config: NewProviderConfig(config, configFileName),
  383. },
  384. }, nil
  385. }
  386. if metadata.OnGCE() {
  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, "gcp.json"),
  395. }, nil
  396. }
  397. if strings.HasPrefix(provider, "aws") {
  398. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  399. return &AWS{
  400. Clientset: cache,
  401. Config: NewProviderConfig(config, "aws.json"),
  402. }, nil
  403. } else if strings.HasPrefix(provider, "azure") {
  404. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  405. return &Azure{
  406. Clientset: cache,
  407. Config: NewProviderConfig(config, "azure.json"),
  408. }, nil
  409. } else {
  410. klog.V(2).Info("Unsupported provider, falling back to default")
  411. return &CustomProvider{
  412. Clientset: cache,
  413. Config: NewProviderConfig(config, "default.json"),
  414. }, nil
  415. }
  416. }
  417. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  418. pw := env.GetRemotePW()
  419. address := env.GetSQLAddress()
  420. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  421. db, err := sql.Open("postgres", connStr)
  422. if err != nil {
  423. return err
  424. }
  425. defer db.Close()
  426. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  427. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  428. if err != nil {
  429. return err
  430. }
  431. return nil
  432. }
  433. func CreateClusterMeta(cluster_id, cluster_name string) error {
  434. pw := env.GetRemotePW()
  435. address := env.GetSQLAddress()
  436. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  437. db, err := sql.Open("postgres", connStr)
  438. if err != nil {
  439. return err
  440. }
  441. defer db.Close()
  442. for _, stmt := range createTableStatements {
  443. _, err := db.Exec(stmt)
  444. if err != nil {
  445. return err
  446. }
  447. }
  448. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  449. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  450. if err != nil {
  451. return err
  452. }
  453. return nil
  454. }
  455. func GetClusterMeta(cluster_id string) (string, string, error) {
  456. pw := env.GetRemotePW()
  457. address := env.GetSQLAddress()
  458. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  459. db, err := sql.Open("postgres", connStr)
  460. defer db.Close()
  461. query := `SELECT cluster_id, cluster_name
  462. FROM names
  463. WHERE cluster_id = ?`
  464. rows, err := db.Query(query, cluster_id)
  465. if err != nil {
  466. return "", "", err
  467. }
  468. defer rows.Close()
  469. var (
  470. sql_cluster_id string
  471. cluster_name string
  472. )
  473. for rows.Next() {
  474. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  475. return "", "", err
  476. }
  477. }
  478. return sql_cluster_id, cluster_name, nil
  479. }
  480. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  481. id, name, err := GetClusterMeta(cluster_id)
  482. if err != nil {
  483. err := CreateClusterMeta(cluster_id, cluster_name)
  484. if err != nil {
  485. return "", "", err
  486. }
  487. }
  488. if id == "" {
  489. err := CreateClusterMeta(cluster_id, cluster_name)
  490. if err != nil {
  491. return "", "", err
  492. }
  493. }
  494. return id, name, nil
  495. }
  496. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  497. // returns the string as is if it cannot find a match
  498. func ParseID(id string) string {
  499. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  500. rx := regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  501. match := rx.FindStringSubmatch(id)
  502. if len(match) >= 2 {
  503. return match[1]
  504. }
  505. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  506. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  507. rx = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  508. match = rx.FindStringSubmatch(id)
  509. if len(match) >= 2 {
  510. return match[1]
  511. }
  512. // Return id for Azure Provider, CSV Provider and Custom Provider
  513. return id
  514. }
  515. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  516. // returns the string as is if it cannot find a match
  517. func ParsePVID(id string) string {
  518. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  519. rx := regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  520. match := rx.FindStringSubmatch(id)
  521. if len(match) >= 2 {
  522. return match[1]
  523. }
  524. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  525. return id
  526. }
  527. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  528. // returns the string as is if it cannot find a match
  529. func ParseLBID(id string) string {
  530. rx := regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$") // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  531. match := rx.FindStringSubmatch(id)
  532. if len(match) >= 2 {
  533. return match[1]
  534. }
  535. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  536. return id
  537. }