provider.go 12 KB

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