provider.go 20 KB

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