provider.go 13 KB

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