provider.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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/scaleway"
  15. "github.com/opencost/opencost/pkg/kubecost"
  16. "github.com/opencost/opencost/pkg/util"
  17. "cloud.google.com/go/compute/metadata"
  18. "github.com/opencost/opencost/pkg/clustercache"
  19. "github.com/opencost/opencost/pkg/config"
  20. "github.com/opencost/opencost/pkg/env"
  21. "github.com/opencost/opencost/pkg/log"
  22. "github.com/opencost/opencost/pkg/util/httputil"
  23. "github.com/opencost/opencost/pkg/util/watcher"
  24. v1 "k8s.io/api/core/v1"
  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 kubecost.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 kubecost.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 kubecost.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 kubecost.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 kubecost.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 kubecost.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. default:
  214. log.Info("Unsupported provider, falling back to default")
  215. return &CustomProvider{
  216. Clientset: cache,
  217. ClusterRegion: cp.region,
  218. ClusterAccountID: cp.accountID,
  219. Config: NewProviderConfig(config, cp.configFileName),
  220. }, nil
  221. }
  222. }
  223. type clusterProperties struct {
  224. provider string
  225. configFileName string
  226. region string
  227. accountID string
  228. projectID string
  229. }
  230. func getClusterProperties(node *v1.Node) clusterProperties {
  231. providerID := strings.ToLower(node.Spec.ProviderID)
  232. region, _ := util.GetRegion(node.Labels)
  233. cp := clusterProperties{
  234. provider: "DEFAULT",
  235. configFileName: "default.json",
  236. region: region,
  237. accountID: "",
  238. projectID: "",
  239. }
  240. // The second conditional is mainly if you're running opencost outside of GCE, say in a local environment.
  241. if metadata.OnGCE() || strings.HasPrefix(providerID, "gce") {
  242. cp.provider = kubecost.GCPProvider
  243. cp.configFileName = "gcp.json"
  244. cp.projectID = gcp.ParseGCPProjectID(providerID)
  245. } else if strings.HasPrefix(providerID, "aws") {
  246. cp.provider = kubecost.AWSProvider
  247. cp.configFileName = "aws.json"
  248. } else if strings.HasPrefix(providerID, "azure") {
  249. cp.provider = kubecost.AzureProvider
  250. cp.configFileName = "azure.json"
  251. cp.accountID = azure.ParseAzureSubscriptionID(providerID)
  252. } else if strings.HasPrefix(providerID, "scaleway") { // the scaleway provider ID looks like scaleway://instance/<instance_id>
  253. cp.provider = kubecost.ScalewayProvider
  254. cp.configFileName = "scaleway.json"
  255. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "aliyun") { // provider ID is not prefix with any distinct keyword like other providers
  256. cp.provider = kubecost.AlibabaProvider
  257. cp.configFileName = "alibaba.json"
  258. }
  259. if env.IsUseCSVProvider() {
  260. cp.provider = kubecost.CSVProvider
  261. }
  262. return cp
  263. }
  264. var (
  265. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  266. providerAWSRegex = regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  267. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  268. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  269. providerGCERegex = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  270. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  271. persistentVolumeAWSRegex = regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  272. // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  273. loadBalancerAWSRegex = regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$")
  274. )
  275. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  276. // returns the string as is if it cannot find a match
  277. func ParseID(id string) string {
  278. match := providerAWSRegex.FindStringSubmatch(id)
  279. if len(match) >= 2 {
  280. return match[1]
  281. }
  282. match = providerGCERegex.FindStringSubmatch(id)
  283. if len(match) >= 2 {
  284. return match[1]
  285. }
  286. // Return id for Azure Provider, CSV Provider and Custom Provider
  287. return id
  288. }
  289. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  290. // returns the string as is if it cannot find a match
  291. func ParsePVID(id string) string {
  292. match := persistentVolumeAWSRegex.FindStringSubmatch(id)
  293. if len(match) >= 2 {
  294. return match[1]
  295. }
  296. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  297. return id
  298. }
  299. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  300. // returns the string as is if it cannot find a match
  301. func ParseLBID(id string) string {
  302. match := loadBalancerAWSRegex.FindStringSubmatch(id)
  303. if len(match) >= 2 {
  304. return match[1]
  305. }
  306. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  307. return id
  308. }