provider.go 23 KB

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