provider.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. CurrencyCode string `json:"currencyCode"`
  160. Discount string `json:"discount"`
  161. NegotiatedDiscount string `json:"negotiatedDiscount"`
  162. SharedOverhead string `json:"sharedOverhead"`
  163. ClusterName string `json:"clusterName"`
  164. SharedNamespaces string `json:"sharedNamespaces"`
  165. SharedLabelNames string `json:"sharedLabelNames"`
  166. SharedLabelValues string `json:"sharedLabelValues"`
  167. 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)
  168. ReadOnly string `json:"readOnly"`
  169. KubecostToken string `json:"kubecostToken"`
  170. }
  171. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  172. // of the configured monthly shared overhead cost. If the string version cannot
  173. // be parsed into a float, an error is logged and 0.0 is returned.
  174. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  175. // Empty string should be interpreted as "no cost", i.e. 0.0
  176. if cp.SharedOverhead == "" {
  177. return 0.0
  178. }
  179. // Attempt to parse, but log and return 0.0 if that fails.
  180. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  181. if err != nil {
  182. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  183. return 0.0
  184. }
  185. return sharedCostPerMonth
  186. }
  187. type ServiceAccountStatus struct {
  188. Checks []*ServiceAccountCheck `json:"checks"`
  189. }
  190. type ServiceAccountCheck struct {
  191. Message string `json:"message"`
  192. Status bool `json:"status"`
  193. AdditionalInfo string `json:"additionalInfo"`
  194. }
  195. type PricingSources struct {
  196. PricingSources map[string]*PricingSource
  197. }
  198. type PricingSource struct {
  199. Name string `json:"name"`
  200. Available bool `json:"available"`
  201. Error string `json:"error"`
  202. }
  203. type PricingType string
  204. const (
  205. Api PricingType = "api"
  206. Spot PricingType = "spot"
  207. Reserved PricingType = "reserved"
  208. SavingsPlan PricingType = "savingsPlan"
  209. CsvExact PricingType = "csvExact"
  210. CsvClass PricingType = "csvClass"
  211. DefaultPrices PricingType = "defaultPrices"
  212. )
  213. type PricingMatchMetadata struct {
  214. TotalNodes int `json:"TotalNodes"`
  215. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  216. }
  217. // Provider represents a k8s provider.
  218. type Provider interface {
  219. ClusterInfo() (map[string]string, error)
  220. GetAddresses() ([]byte, error)
  221. GetDisks() ([]byte, error)
  222. NodePricing(Key) (*Node, error)
  223. PVPricing(PVKey) (*PV, error)
  224. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  225. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  226. AllNodePricing() (interface{}, error)
  227. DownloadPricingData() error
  228. GetKey(map[string]string, *v1.Node) Key
  229. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  230. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  231. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  232. GetConfig() (*CustomPricing, error)
  233. GetManagementPlatform() (string, error)
  234. GetLocalStorageQuery(time.Duration, time.Duration, bool, bool) string
  235. ExternalAllocations(string, string, []string, string, string, bool) ([]*OutOfClusterAllocation, error)
  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. func NewCrossClusterProvider(ctype string, config *config.ConfigFileManager, overrideConfigPath string, cache clustercache.ClusterCache) (Provider, error) {
  339. if ctype == "aws" {
  340. return &AWS{
  341. Clientset: cache,
  342. Config: NewProviderConfig(config, overrideConfigPath),
  343. }, nil
  344. } else if ctype == "gcp" {
  345. return &GCP{
  346. Clientset: cache,
  347. Config: NewProviderConfig(config, overrideConfigPath),
  348. }, nil
  349. } else if ctype == "azure" {
  350. return &Azure{
  351. Clientset: cache,
  352. Config: NewProviderConfig(config, overrideConfigPath),
  353. }, nil
  354. }
  355. return &CustomProvider{
  356. Clientset: cache,
  357. Config: NewProviderConfig(config, overrideConfigPath),
  358. }, nil
  359. }
  360. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  361. func NewProvider(cache clustercache.ClusterCache, apiKey string, config *config.ConfigFileManager) (Provider, error) {
  362. nodes := cache.GetAllNodes()
  363. if len(nodes) == 0 {
  364. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  365. }
  366. cp := getClusterProperties(nodes[0])
  367. switch cp.provider {
  368. case "CSV":
  369. klog.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  370. return &CSVProvider{
  371. CSVLocation: env.GetCSVPath(),
  372. CustomProvider: &CustomProvider{
  373. Clientset: cache,
  374. Config: NewProviderConfig(config, cp.configFileName),
  375. },
  376. }, nil
  377. case "GCP":
  378. klog.V(3).Info("metadata reports we are in GCE")
  379. if apiKey == "" {
  380. return nil, errors.New("Supply a GCP Key to start getting data")
  381. }
  382. return &GCP{
  383. Clientset: cache,
  384. APIKey: apiKey,
  385. Config: NewProviderConfig(config, cp.configFileName),
  386. clusterRegion: cp.region,
  387. clusterProjectId: cp.projectID,
  388. }, nil
  389. case "AWS":
  390. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  391. return &AWS{
  392. Clientset: cache,
  393. Config: NewProviderConfig(config, cp.configFileName),
  394. clusterRegion: cp.region,
  395. clusterAccountId: cp.accountID,
  396. }, nil
  397. case "AZURE":
  398. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  399. return &Azure{
  400. Clientset: cache,
  401. Config: NewProviderConfig(config, cp.configFileName),
  402. clusterRegion: cp.region,
  403. clusterAccountId: cp.accountID,
  404. }, nil
  405. default:
  406. klog.V(2).Info("Unsupported provider, falling back to default")
  407. return &CustomProvider{
  408. Clientset: cache,
  409. Config: NewProviderConfig(config, cp.configFileName),
  410. }, nil
  411. }
  412. }
  413. type clusterProperties struct {
  414. provider string
  415. configFileName string
  416. region string
  417. accountID string
  418. projectID string
  419. }
  420. func getClusterProperties(node *v1.Node) clusterProperties {
  421. providerID := strings.ToLower(node.Spec.ProviderID)
  422. region, _ := util.GetRegion(node.Labels)
  423. cp := clusterProperties{
  424. provider: "DEFAULT",
  425. configFileName: "default.json",
  426. region: region,
  427. accountID: "",
  428. projectID: "",
  429. }
  430. if metadata.OnGCE() {
  431. cp.provider = "GCP"
  432. cp.configFileName = "gcp.json"
  433. cp.projectID = parseGCPProjectID(providerID)
  434. } else if strings.HasPrefix(providerID, "aws") {
  435. cp.provider = "AWS"
  436. cp.configFileName = "aws.json"
  437. } else if strings.HasPrefix(providerID, "azure") {
  438. cp.provider = "AZURE"
  439. cp.configFileName = "azure.json"
  440. cp.accountID = parseAzureSubscriptionID(providerID)
  441. }
  442. if env.IsUseCSVProvider() {
  443. cp.provider = "CSV"
  444. }
  445. return cp
  446. }
  447. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  448. pw := env.GetRemotePW()
  449. address := env.GetSQLAddress()
  450. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  451. db, err := sql.Open("postgres", connStr)
  452. if err != nil {
  453. return err
  454. }
  455. defer db.Close()
  456. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  457. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  458. if err != nil {
  459. return err
  460. }
  461. return nil
  462. }
  463. func CreateClusterMeta(cluster_id, cluster_name 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. if err != nil {
  469. return err
  470. }
  471. defer db.Close()
  472. for _, stmt := range createTableStatements {
  473. _, err := db.Exec(stmt)
  474. if err != nil {
  475. return err
  476. }
  477. }
  478. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  479. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  480. if err != nil {
  481. return err
  482. }
  483. return nil
  484. }
  485. func GetClusterMeta(cluster_id string) (string, string, error) {
  486. pw := env.GetRemotePW()
  487. address := env.GetSQLAddress()
  488. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  489. db, err := sql.Open("postgres", connStr)
  490. defer db.Close()
  491. query := `SELECT cluster_id, cluster_name
  492. FROM names
  493. WHERE cluster_id = ?`
  494. rows, err := db.Query(query, cluster_id)
  495. if err != nil {
  496. return "", "", err
  497. }
  498. defer rows.Close()
  499. var (
  500. sql_cluster_id string
  501. cluster_name string
  502. )
  503. for rows.Next() {
  504. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  505. return "", "", err
  506. }
  507. }
  508. return sql_cluster_id, cluster_name, nil
  509. }
  510. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  511. id, name, err := GetClusterMeta(cluster_id)
  512. if err != nil {
  513. err := CreateClusterMeta(cluster_id, cluster_name)
  514. if err != nil {
  515. return "", "", err
  516. }
  517. }
  518. if id == "" {
  519. err := CreateClusterMeta(cluster_id, cluster_name)
  520. if err != nil {
  521. return "", "", err
  522. }
  523. }
  524. return id, name, nil
  525. }
  526. // ParseID attempts to parse a 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 ParseID(id string) string {
  529. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  530. rx := regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  531. match := rx.FindStringSubmatch(id)
  532. if len(match) >= 2 {
  533. return match[1]
  534. }
  535. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  536. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  537. rx = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  538. match = rx.FindStringSubmatch(id)
  539. if len(match) >= 2 {
  540. return match[1]
  541. }
  542. // Return id for Azure Provider, CSV Provider and Custom Provider
  543. return id
  544. }
  545. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  546. // returns the string as is if it cannot find a match
  547. func ParsePVID(id string) string {
  548. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  549. rx := regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  550. match := rx.FindStringSubmatch(id)
  551. if len(match) >= 2 {
  552. return match[1]
  553. }
  554. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  555. return id
  556. }
  557. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  558. // returns the string as is if it cannot find a match
  559. func ParseLBID(id string) string {
  560. rx := regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$") // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  561. match := rx.FindStringSubmatch(id)
  562. if len(match) >= 2 {
  563. return match[1]
  564. }
  565. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  566. return id
  567. }