provider.go 13 KB

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