provider.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. switch cp.provider {
  138. case kubecost.CSVProvider:
  139. log.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  140. return &CSVProvider{
  141. CSVLocation: env.GetCSVPath(),
  142. CustomProvider: &CustomProvider{
  143. Clientset: cache,
  144. ClusterRegion: cp.region,
  145. ClusterAccountID: cp.accountID,
  146. Config: NewProviderConfig(config, cp.configFileName),
  147. },
  148. }, nil
  149. case kubecost.GCPProvider:
  150. log.Info("Found ProviderID starting with \"gce\", using GCP Provider")
  151. if apiKey == "" {
  152. return nil, errors.New("Supply a GCP Key to start getting data")
  153. }
  154. return &gcp.GCP{
  155. Clientset: cache,
  156. APIKey: apiKey,
  157. Config: NewProviderConfig(config, cp.configFileName),
  158. ClusterRegion: cp.region,
  159. ClusterAccountID: cp.accountID,
  160. ClusterProjectID: cp.projectID,
  161. MetadataClient: metadata.NewClient(
  162. &http.Client{
  163. Transport: httputil.NewUserAgentTransport("kubecost", &http.Transport{
  164. Dial: (&net.Dialer{
  165. Timeout: 2 * time.Second,
  166. KeepAlive: 30 * time.Second,
  167. }).Dial,
  168. }),
  169. Timeout: 5 * time.Second,
  170. }),
  171. }, nil
  172. case kubecost.AWSProvider:
  173. log.Info("Found ProviderID starting with \"aws\", using AWS Provider")
  174. return &aws.AWS{
  175. Clientset: cache,
  176. Config: NewProviderConfig(config, cp.configFileName),
  177. ClusterRegion: cp.region,
  178. ClusterAccountID: cp.accountID,
  179. ServiceAccountChecks: models.NewServiceAccountChecks(),
  180. }, nil
  181. case kubecost.AzureProvider:
  182. log.Info("Found ProviderID starting with \"azure\", using Azure Provider")
  183. return &azure.Azure{
  184. Clientset: cache,
  185. Config: NewProviderConfig(config, cp.configFileName),
  186. ClusterRegion: cp.region,
  187. ClusterAccountID: cp.accountID,
  188. ServiceAccountChecks: models.NewServiceAccountChecks(),
  189. }, nil
  190. case kubecost.AlibabaProvider:
  191. log.Info("Found ProviderID starting with \"alibaba\", using Alibaba Cloud Provider")
  192. return &alibaba.Alibaba{
  193. Clientset: cache,
  194. Config: NewProviderConfig(config, cp.configFileName),
  195. ClusterRegion: cp.region,
  196. ClusterAccountId: cp.accountID,
  197. ServiceAccountChecks: models.NewServiceAccountChecks(),
  198. }, nil
  199. case kubecost.ScalewayProvider:
  200. log.Info("Found ProviderID starting with \"scaleway\", using Scaleway Provider")
  201. return &scaleway.Scaleway{
  202. Clientset: cache,
  203. ClusterRegion: cp.region,
  204. ClusterAccountID: cp.accountID,
  205. Config: NewProviderConfig(config, cp.configFileName),
  206. }, nil
  207. default:
  208. log.Info("Unsupported provider, falling back to default")
  209. return &CustomProvider{
  210. Clientset: cache,
  211. ClusterRegion: cp.region,
  212. ClusterAccountID: cp.accountID,
  213. Config: NewProviderConfig(config, cp.configFileName),
  214. }, nil
  215. }
  216. }
  217. type clusterProperties struct {
  218. provider string
  219. configFileName string
  220. region string
  221. accountID string
  222. projectID string
  223. }
  224. func getClusterProperties(node *v1.Node) clusterProperties {
  225. providerID := strings.ToLower(node.Spec.ProviderID)
  226. region, _ := util.GetRegion(node.Labels)
  227. cp := clusterProperties{
  228. provider: "DEFAULT",
  229. configFileName: "default.json",
  230. region: region,
  231. accountID: "",
  232. projectID: "",
  233. }
  234. // The second conditional is mainly if you're running opencost outside of GCE, say in a local environment.
  235. if metadata.OnGCE() || strings.HasPrefix(providerID, "gce") {
  236. cp.provider = kubecost.GCPProvider
  237. cp.configFileName = "gcp.json"
  238. cp.projectID = gcp.ParseGCPProjectID(providerID)
  239. } else if strings.HasPrefix(providerID, "aws") {
  240. cp.provider = kubecost.AWSProvider
  241. cp.configFileName = "aws.json"
  242. } else if strings.HasPrefix(providerID, "azure") {
  243. cp.provider = kubecost.AzureProvider
  244. cp.configFileName = "azure.json"
  245. cp.accountID = azure.ParseAzureSubscriptionID(providerID)
  246. } else if strings.HasPrefix(providerID, "scaleway") { // the scaleway provider ID looks like scaleway://instance/<instance_id>
  247. cp.provider = kubecost.ScalewayProvider
  248. cp.configFileName = "scaleway.json"
  249. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "aliyun") { // provider ID is not prefix with any distinct keyword like other providers
  250. cp.provider = kubecost.AlibabaProvider
  251. cp.configFileName = "alibaba.json"
  252. }
  253. if env.IsUseCSVProvider() {
  254. cp.provider = kubecost.CSVProvider
  255. }
  256. return cp
  257. }
  258. var (
  259. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  260. providerAWSRegex = regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  261. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  262. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  263. providerGCERegex = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  264. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  265. persistentVolumeAWSRegex = regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  266. // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  267. loadBalancerAWSRegex = regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$")
  268. )
  269. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  270. // returns the string as is if it cannot find a match
  271. func ParseID(id string) string {
  272. match := providerAWSRegex.FindStringSubmatch(id)
  273. if len(match) >= 2 {
  274. return match[1]
  275. }
  276. match = providerGCERegex.FindStringSubmatch(id)
  277. if len(match) >= 2 {
  278. return match[1]
  279. }
  280. // Return id for Azure Provider, CSV Provider and Custom Provider
  281. return id
  282. }
  283. // ParsePVID attempts to parse a PV ProviderId from a string based on formats from the various providers and
  284. // returns the string as is if it cannot find a match
  285. func ParsePVID(id string) string {
  286. match := persistentVolumeAWSRegex.FindStringSubmatch(id)
  287. if len(match) >= 2 {
  288. return match[1]
  289. }
  290. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  291. return id
  292. }
  293. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  294. // returns the string as is if it cannot find a match
  295. func ParseLBID(id string) string {
  296. match := loadBalancerAWSRegex.FindStringSubmatch(id)
  297. if len(match) >= 2 {
  298. return match[1]
  299. }
  300. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  301. return id
  302. }