provider.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package provider
  2. import (
  3. "errors"
  4. "net"
  5. "net/http"
  6. "regexp"
  7. "strings"
  8. "time"
  9. "github.com/opencost/opencost/pkg/cloud/alibaba"
  10. "github.com/opencost/opencost/pkg/cloud/aws"
  11. "github.com/opencost/opencost/pkg/cloud/azure"
  12. "github.com/opencost/opencost/pkg/cloud/gcp"
  13. "github.com/opencost/opencost/pkg/cloud/models"
  14. "github.com/opencost/opencost/pkg/cloud/oracle"
  15. "github.com/opencost/opencost/pkg/cloud/scaleway"
  16. "github.com/opencost/opencost/core/pkg/opencost"
  17. "github.com/opencost/opencost/core/pkg/util"
  18. "cloud.google.com/go/compute/metadata"
  19. "github.com/opencost/opencost/core/pkg/log"
  20. "github.com/opencost/opencost/core/pkg/util/httputil"
  21. "github.com/opencost/opencost/core/pkg/util/watcher"
  22. "github.com/opencost/opencost/pkg/clustercache"
  23. "github.com/opencost/opencost/pkg/config"
  24. "github.com/opencost/opencost/pkg/env"
  25. )
  26. // ClusterName returns the name defined in cluster info, defaulting to the
  27. // CLUSTER_ID environment variable
  28. func ClusterName(p models.Provider) string {
  29. info, err := p.ClusterInfo()
  30. if err != nil {
  31. return env.GetClusterID()
  32. }
  33. name, ok := info["name"]
  34. if !ok {
  35. return env.GetClusterID()
  36. }
  37. return name
  38. }
  39. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  40. // indicating whether or not the cluster is using custom pricing.
  41. func CustomPricesEnabled(p models.Provider) bool {
  42. config, err := p.GetConfig()
  43. if err != nil {
  44. return false
  45. }
  46. // TODO:CLEANUP what is going on with this?
  47. if config.NegotiatedDiscount == "" {
  48. config.NegotiatedDiscount = "0%"
  49. }
  50. return config.CustomPricesEnabled == "true"
  51. }
  52. // ConfigWatcherFor returns a new ConfigWatcher instance which watches changes to the "pricing-configs"
  53. // configmap
  54. func ConfigWatcherFor(p models.Provider) *watcher.ConfigMapWatcher {
  55. return &watcher.ConfigMapWatcher{
  56. ConfigMapName: env.GetPricingConfigmapName(),
  57. WatchFunc: func(name string, data map[string]string) error {
  58. _, err := p.UpdateConfigFromConfigMap(data)
  59. return err
  60. },
  61. }
  62. }
  63. // AllocateIdleByDefault returns true if the application settings specify to allocate idle by default
  64. func AllocateIdleByDefault(p models.Provider) bool {
  65. config, err := p.GetConfig()
  66. if err != nil {
  67. return false
  68. }
  69. return config.DefaultIdle == "true"
  70. }
  71. // SharedNamespace returns a list of names of shared namespaces, as defined in the application settings
  72. func SharedNamespaces(p models.Provider) []string {
  73. namespaces := []string{}
  74. config, err := p.GetConfig()
  75. if err != nil {
  76. return namespaces
  77. }
  78. if config.SharedNamespaces == "" {
  79. return namespaces
  80. }
  81. // trim spaces so that "kube-system, kubecost" is equivalent to "kube-system,kubecost"
  82. for _, ns := range strings.Split(config.SharedNamespaces, ",") {
  83. namespaces = append(namespaces, strings.Trim(ns, " "))
  84. }
  85. return namespaces
  86. }
  87. // SharedLabel returns the configured set of shared labels as a parallel tuple of keys to values; e.g.
  88. // for app:kubecost,type:staging this returns (["app", "type"], ["kubecost", "staging"]) in order to
  89. // match the signature of the NewSharedResourceInfo
  90. func SharedLabels(p models.Provider) ([]string, []string) {
  91. names := []string{}
  92. values := []string{}
  93. config, err := p.GetConfig()
  94. if err != nil {
  95. return names, values
  96. }
  97. if config.SharedLabelNames == "" || config.SharedLabelValues == "" {
  98. return names, values
  99. }
  100. ks := strings.Split(config.SharedLabelNames, ",")
  101. vs := strings.Split(config.SharedLabelValues, ",")
  102. if len(ks) != len(vs) {
  103. log.Warnf("Shared labels have mis-matched lengths: %d names, %d values", len(ks), len(vs))
  104. return names, values
  105. }
  106. for i := range ks {
  107. names = append(names, strings.Trim(ks[i], " "))
  108. values = append(values, strings.Trim(vs[i], " "))
  109. }
  110. return names, values
  111. }
  112. // ShareTenancyCosts returns true if the application settings specify to share
  113. // tenancy costs by default.
  114. func ShareTenancyCosts(p models.Provider) bool {
  115. config, err := p.GetConfig()
  116. if err != nil {
  117. return false
  118. }
  119. return config.ShareTenancyCosts == "true"
  120. }
  121. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  122. func NewProvider(cache clustercache.ClusterCache, apiKey string, config *config.ConfigFileManager) (models.Provider, error) {
  123. nodes := cache.GetAllNodes()
  124. if len(nodes) == 0 {
  125. log.Infof("Could not locate any nodes for cluster.") // valid in ETL readonly mode
  126. return &CustomProvider{
  127. Clientset: cache,
  128. Config: NewProviderConfig(config, "default.json"),
  129. }, nil
  130. }
  131. cp := getClusterProperties(nodes[0])
  132. providerConfig := NewProviderConfig(config, cp.configFileName)
  133. // If ClusterAccount is set apply it to the cluster properties
  134. if providerConfig.customPricing != nil && providerConfig.customPricing.ClusterAccountID != "" {
  135. cp.accountID = providerConfig.customPricing.ClusterAccountID
  136. }
  137. providerConfig.Update(func(cp *models.CustomPricing) error {
  138. if cp.ServiceKeyName == "AKIXXX" {
  139. cp.ServiceKeyName = ""
  140. }
  141. return nil
  142. })
  143. switch cp.provider {
  144. case opencost.CSVProvider:
  145. log.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  146. return &CSVProvider{
  147. CSVLocation: env.GetCSVPath(),
  148. CustomProvider: &CustomProvider{
  149. Clientset: cache,
  150. ClusterRegion: cp.region,
  151. ClusterAccountID: cp.accountID,
  152. Config: NewProviderConfig(config, cp.configFileName),
  153. },
  154. }, nil
  155. case opencost.GCPProvider:
  156. log.Info("Found ProviderID starting with \"gce\", using GCP Provider")
  157. if apiKey == "" {
  158. return nil, errors.New("Supply a GCP Key to start getting data")
  159. }
  160. return &gcp.GCP{
  161. Clientset: cache,
  162. APIKey: apiKey,
  163. Config: NewProviderConfig(config, cp.configFileName),
  164. ClusterRegion: cp.region,
  165. ClusterAccountID: cp.accountID,
  166. ClusterProjectID: cp.projectID,
  167. MetadataClient: metadata.NewClient(
  168. &http.Client{
  169. Transport: httputil.NewUserAgentTransport("kubecost", &http.Transport{
  170. Dial: (&net.Dialer{
  171. Timeout: 2 * time.Second,
  172. KeepAlive: 30 * time.Second,
  173. }).Dial,
  174. }),
  175. Timeout: 5 * time.Second,
  176. }),
  177. }, nil
  178. case opencost.AWSProvider:
  179. log.Info("Found ProviderID starting with \"aws\", using AWS Provider")
  180. return &aws.AWS{
  181. Clientset: cache,
  182. Config: NewProviderConfig(config, cp.configFileName),
  183. ClusterRegion: cp.region,
  184. ClusterAccountID: cp.accountID,
  185. ServiceAccountChecks: models.NewServiceAccountChecks(),
  186. }, nil
  187. case opencost.AzureProvider:
  188. log.Info("Found ProviderID starting with \"azure\", using Azure Provider")
  189. return &azure.Azure{
  190. Clientset: cache,
  191. Config: NewProviderConfig(config, cp.configFileName),
  192. ClusterRegion: cp.region,
  193. ClusterAccountID: cp.accountID,
  194. ServiceAccountChecks: models.NewServiceAccountChecks(),
  195. }, nil
  196. case opencost.AlibabaProvider:
  197. log.Info("Found ProviderID starting with \"alibaba\", using Alibaba Cloud Provider")
  198. return &alibaba.Alibaba{
  199. Clientset: cache,
  200. Config: NewProviderConfig(config, cp.configFileName),
  201. ClusterRegion: cp.region,
  202. ClusterAccountId: cp.accountID,
  203. ServiceAccountChecks: models.NewServiceAccountChecks(),
  204. }, nil
  205. case opencost.ScalewayProvider:
  206. log.Info("Found ProviderID starting with \"scaleway\", using Scaleway Provider")
  207. return &scaleway.Scaleway{
  208. Clientset: cache,
  209. ClusterRegion: cp.region,
  210. ClusterAccountID: cp.accountID,
  211. Config: NewProviderConfig(config, cp.configFileName),
  212. }, nil
  213. case opencost.OracleProvider:
  214. log.Info("Found ProviderID starting with \"oracle\", using Oracle Provider")
  215. return &oracle.Oracle{
  216. Clientset: cache,
  217. Config: NewProviderConfig(config, cp.configFileName),
  218. ClusterRegion: cp.region,
  219. ClusterAccountID: cp.accountID,
  220. ServiceAccountChecks: models.NewServiceAccountChecks(),
  221. }, nil
  222. default:
  223. log.Info("Unsupported provider, falling back to default")
  224. return &CustomProvider{
  225. Clientset: cache,
  226. ClusterRegion: cp.region,
  227. ClusterAccountID: cp.accountID,
  228. Config: NewProviderConfig(config, cp.configFileName),
  229. }, nil
  230. }
  231. }
  232. type clusterProperties struct {
  233. provider string
  234. configFileName string
  235. region string
  236. accountID string
  237. projectID string
  238. }
  239. func getClusterProperties(node *clustercache.Node) clusterProperties {
  240. providerID := strings.ToLower(node.SpecProviderID)
  241. region, _ := util.GetRegion(node.Labels)
  242. cp := clusterProperties{
  243. provider: "DEFAULT",
  244. configFileName: "default.json",
  245. region: region,
  246. accountID: "",
  247. projectID: "",
  248. }
  249. // The second conditional is mainly if you're running opencost outside of GCE, say in a local environment.
  250. if metadata.OnGCE() || strings.HasPrefix(providerID, "gce") {
  251. cp.provider = opencost.GCPProvider
  252. cp.configFileName = "gcp.json"
  253. cp.projectID = gcp.ParseGCPProjectID(providerID)
  254. } else if strings.HasPrefix(providerID, "aws") {
  255. cp.provider = opencost.AWSProvider
  256. cp.configFileName = "aws.json"
  257. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "eks") { // Additional check for EKS, via kubelet check
  258. cp.provider = opencost.AWSProvider
  259. cp.configFileName = "aws.json"
  260. } else if strings.HasPrefix(providerID, "azure") {
  261. cp.provider = opencost.AzureProvider
  262. cp.configFileName = "azure.json"
  263. cp.accountID = azure.ParseAzureSubscriptionID(providerID)
  264. } else if strings.HasPrefix(providerID, "scaleway") { // the scaleway provider ID looks like scaleway://instance/<instance_id>
  265. cp.provider = opencost.ScalewayProvider
  266. cp.configFileName = "scaleway.json"
  267. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "aliyun") { // provider ID is not prefix with any distinct keyword like other providers
  268. cp.provider = opencost.AlibabaProvider
  269. cp.configFileName = "alibaba.json"
  270. } else if strings.HasPrefix(providerID, "ocid") {
  271. cp.provider = opencost.OracleProvider
  272. cp.configFileName = "oracle.json"
  273. }
  274. if env.IsUseCSVProvider() {
  275. cp.provider = opencost.CSVProvider
  276. }
  277. return cp
  278. }
  279. var (
  280. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  281. providerAWSRegex = regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  282. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  283. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  284. providerGCERegex = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  285. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  286. persistentVolumeAWSRegex = regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  287. // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  288. loadBalancerAWSRegex = regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$")
  289. )
  290. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  291. // returns the string as is if it cannot find a match
  292. func ParseID(id string) string {
  293. match := providerAWSRegex.FindStringSubmatch(id)
  294. if len(match) >= 2 {
  295. return match[1]
  296. }
  297. match = providerGCERegex.FindStringSubmatch(id)
  298. if len(match) >= 2 {
  299. return match[1]
  300. }
  301. // Return id for Azure Provider, CSV Provider and Custom Provider
  302. return id
  303. }
  304. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  305. // returns the string as is if it cannot find a match
  306. func ParsePVID(id string) string {
  307. match := persistentVolumeAWSRegex.FindStringSubmatch(id)
  308. if len(match) >= 2 {
  309. return match[1]
  310. }
  311. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  312. return id
  313. }
  314. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  315. // returns the string as is if it cannot find a match
  316. func ParseLBID(id string) string {
  317. match := loadBalancerAWSRegex.FindStringSubmatch(id)
  318. if len(match) >= 2 {
  319. return match[1]
  320. }
  321. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  322. return id
  323. }