provider.go 14 KB

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