provider.go 11 KB

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