provider.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package provider
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/opencost/opencost/core/pkg/util/retry"
  13. "github.com/opencost/opencost/pkg/cloud/alibaba"
  14. "github.com/opencost/opencost/pkg/cloud/aws"
  15. "github.com/opencost/opencost/pkg/cloud/azure"
  16. "github.com/opencost/opencost/pkg/cloud/digitalocean"
  17. "github.com/opencost/opencost/pkg/cloud/gcp"
  18. "github.com/opencost/opencost/pkg/cloud/models"
  19. "github.com/opencost/opencost/pkg/cloud/oracle"
  20. "github.com/opencost/opencost/pkg/cloud/otc"
  21. "github.com/opencost/opencost/pkg/cloud/scaleway"
  22. "github.com/opencost/opencost/core/pkg/opencost"
  23. "github.com/opencost/opencost/core/pkg/util"
  24. "cloud.google.com/go/compute/metadata"
  25. "github.com/opencost/opencost/core/pkg/clustercache"
  26. "github.com/opencost/opencost/core/pkg/log"
  27. "github.com/opencost/opencost/core/pkg/util/httputil"
  28. "github.com/opencost/opencost/pkg/config"
  29. "github.com/opencost/opencost/pkg/env"
  30. "github.com/opencost/opencost/pkg/util/watcher"
  31. )
  32. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  33. // indicating whether or not the cluster is using custom pricing.
  34. func CustomPricesEnabled(p models.Provider) bool {
  35. config, err := p.GetConfig()
  36. if err != nil {
  37. return false
  38. }
  39. // TODO:CLEANUP what is going on with this?
  40. if config.NegotiatedDiscount == "" {
  41. config.NegotiatedDiscount = "0%"
  42. }
  43. return config.CustomPricesEnabled == "true"
  44. }
  45. // ConfigWatcherFor returns a new ConfigWatcher instance which watches changes to the "pricing-configs"
  46. // configmap
  47. func ConfigWatcherFor(p models.Provider) *watcher.ConfigMapWatcher {
  48. return &watcher.ConfigMapWatcher{
  49. ConfigMapName: env.GetPricingConfigmapName(),
  50. WatchFunc: func(name string, data map[string]string) error {
  51. _, err := p.UpdateConfigFromConfigMap(data)
  52. return err
  53. },
  54. }
  55. }
  56. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  57. func NewProvider(cache clustercache.ClusterCache, apiKey string, config *config.ConfigFileManager) (models.Provider, error) {
  58. getAllNodesFunc := func() ([]*clustercache.Node, error) {
  59. nodes := cache.GetAllNodes()
  60. if len(nodes) == 0 {
  61. return nil, fmt.Errorf("no nodes found in cluster cache")
  62. }
  63. return nodes, nil
  64. }
  65. var nodes []*clustercache.Node
  66. if env.HasKubernetesResourceAccess() {
  67. // the error can be ignored because getAllNodesFunc only errors if nodes is empty, a case which we explicitly
  68. // handle by checking the length of nodes below
  69. nodes, _ = retry.Retry(context.Background(), getAllNodesFunc, 10, time.Second)
  70. } else {
  71. nodes, _ = getAllNodesFunc()
  72. }
  73. if len(nodes) == 0 {
  74. log.Infof("Could not locate any nodes for cluster.")
  75. return &CustomProvider{
  76. Clientset: cache,
  77. Config: NewProviderConfig(config, "default.json"),
  78. }, nil
  79. }
  80. cp := getClusterProperties(nodes[0])
  81. // If provider is DEFAULT, check for explicitly set cloud provider from environment variable
  82. envProvider := env.GetCloudProvider()
  83. if cp.provider == "DEFAULT" && envProvider != "" {
  84. log.Infof("Using cloud provider from environment variable: %s", envProvider)
  85. cp.provider = envProvider
  86. switch envProvider {
  87. case opencost.AWSProvider:
  88. cp.configFileName = "aws.json"
  89. case opencost.AzureProvider:
  90. cp.configFileName = "azure.json"
  91. case opencost.GCPProvider:
  92. cp.configFileName = "gcp.json"
  93. case opencost.AlibabaProvider:
  94. cp.configFileName = "alibaba.json"
  95. case opencost.OracleProvider:
  96. cp.configFileName = "oracle.json"
  97. case opencost.ScalewayProvider:
  98. cp.configFileName = "scaleway.json"
  99. case opencost.OTCProvider:
  100. cp.configFileName = "otc.json"
  101. case opencost.CSVProvider:
  102. cp.configFileName = "default.json"
  103. }
  104. }
  105. providerConfig := NewProviderConfig(config, cp.configFileName)
  106. // If ClusterAccount is set apply it to the cluster properties
  107. if providerConfig.customPricing != nil && providerConfig.customPricing.ClusterAccountID != "" {
  108. cp.accountID = providerConfig.customPricing.ClusterAccountID
  109. }
  110. switch cp.provider {
  111. case opencost.CSVProvider:
  112. log.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  113. return &CSVProvider{
  114. CSVLocation: env.GetCSVPath(),
  115. CustomProvider: &CustomProvider{
  116. Clientset: cache,
  117. ClusterRegion: cp.region,
  118. ClusterAccountID: cp.accountID,
  119. Config: NewProviderConfig(config, cp.configFileName),
  120. },
  121. }, nil
  122. case opencost.GCPProvider:
  123. log.Info("Found ProviderID starting with \"gce\", using GCP Provider")
  124. if apiKey == "" {
  125. return nil, errors.New("Supply a GCP Key to start getting data")
  126. }
  127. return &gcp.GCP{
  128. Clientset: cache,
  129. APIKey: apiKey,
  130. Config: NewProviderConfig(config, cp.configFileName),
  131. ClusterRegion: cp.region,
  132. ClusterAccountID: cp.accountID,
  133. ClusterProjectID: cp.projectID,
  134. MetadataClient: metadata.NewClient(
  135. &http.Client{
  136. Transport: httputil.NewUserAgentTransport("kubecost", &http.Transport{
  137. Dial: (&net.Dialer{
  138. Timeout: 2 * time.Second,
  139. KeepAlive: 30 * time.Second,
  140. }).Dial,
  141. }),
  142. Timeout: 5 * time.Second,
  143. }),
  144. }, nil
  145. case opencost.AWSProvider:
  146. log.Info("Found ProviderID starting with \"aws\", using AWS Provider")
  147. return &aws.AWS{
  148. Clientset: cache,
  149. Config: NewProviderConfig(config, cp.configFileName),
  150. ClusterRegion: cp.region,
  151. ClusterAccountID: cp.accountID,
  152. ServiceAccountChecks: models.NewServiceAccountChecks(),
  153. }, nil
  154. case opencost.AzureProvider:
  155. log.Info("Found ProviderID starting with \"azure\", using Azure Provider")
  156. return &azure.Azure{
  157. Clientset: cache,
  158. Config: NewProviderConfig(config, cp.configFileName),
  159. ClusterRegion: cp.region,
  160. ClusterAccountID: cp.accountID,
  161. ServiceAccountChecks: models.NewServiceAccountChecks(),
  162. }, nil
  163. case opencost.AlibabaProvider:
  164. log.Info("Found ProviderID starting with \"alibaba\", using Alibaba Cloud Provider")
  165. return &alibaba.Alibaba{
  166. Clientset: cache,
  167. Config: NewProviderConfig(config, cp.configFileName),
  168. ClusterRegion: cp.region,
  169. ClusterAccountId: cp.accountID,
  170. ServiceAccountChecks: models.NewServiceAccountChecks(),
  171. }, nil
  172. case opencost.ScalewayProvider:
  173. log.Info("Found ProviderID starting with \"scaleway\", using Scaleway Provider")
  174. return &scaleway.Scaleway{
  175. Clientset: cache,
  176. ClusterRegion: cp.region,
  177. ClusterAccountID: cp.accountID,
  178. Config: NewProviderConfig(config, cp.configFileName),
  179. }, nil
  180. case opencost.OracleProvider:
  181. log.Info("Found ProviderID starting with \"oracle\", using Oracle Provider")
  182. return &oracle.Oracle{
  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.OTCProvider:
  190. log.Info("Found node label \"cce.cloud.com/cce-nodepool\", using OTC Provider")
  191. return &otc.OTC{
  192. Clientset: cache,
  193. Config: NewProviderConfig(config, cp.configFileName),
  194. ClusterRegion: cp.region,
  195. }, nil
  196. case opencost.DigitalOceanProvider:
  197. log.Info("Detected DigitalOcean, using DOKS")
  198. return &digitalocean.DOKS{
  199. Config: NewProviderConfig(config, cp.configFileName),
  200. Cache: digitalocean.NewPricingCache(),
  201. Products: make(map[string][]digitalocean.DOProduct),
  202. Clientset: cache,
  203. ClusterManagementCost: 0.0,
  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 *clustercache.Node) clusterProperties {
  223. providerID := strings.ToLower(node.SpecProviderID)
  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. // Check for custom provider settings
  233. if env.IsUseCustomProvider() {
  234. // Use CSV provider if set
  235. if env.IsUseCSVProvider() {
  236. log.Debug("using custom CSV provider")
  237. cp.provider = opencost.CSVProvider
  238. }
  239. return cp
  240. }
  241. // The second conditional is mainly if you're running opencost outside of GCE, say in a local environment.
  242. if metadata.OnGCE() || strings.HasPrefix(providerID, "gce") {
  243. log.Debug("using GCP provider")
  244. cp.provider = opencost.GCPProvider
  245. cp.configFileName = "gcp.json"
  246. cp.projectID = gcp.ParseGCPProjectID(providerID)
  247. } else if strings.HasPrefix(providerID, "aws") {
  248. log.Debug("using AWS provider")
  249. cp.provider = opencost.AWSProvider
  250. cp.configFileName = "aws.json"
  251. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "eks") { // Additional check for EKS, via kubelet check
  252. log.Debug("using AWS provider from EKS")
  253. cp.provider = opencost.AWSProvider
  254. cp.configFileName = "aws.json"
  255. } else if strings.HasPrefix(providerID, "azure") {
  256. log.Debug("using Azure provider")
  257. cp.provider = opencost.AzureProvider
  258. cp.configFileName = "azure.json"
  259. cp.accountID = azure.ParseAzureSubscriptionID(providerID)
  260. } else if strings.HasPrefix(providerID, "scaleway") { // the scaleway provider ID looks like scaleway://instance/<instance_id>
  261. log.Debug("using Scaleway provider")
  262. cp.provider = opencost.ScalewayProvider
  263. cp.configFileName = "scaleway.json"
  264. } else if strings.Contains(node.Status.NodeInfo.KubeletVersion, "aliyun") { // provider ID is not prefix with any distinct keyword like other providers
  265. log.Debug("using Alibaba provider")
  266. cp.provider = opencost.AlibabaProvider
  267. cp.configFileName = "alibaba.json"
  268. } else if strings.HasPrefix(providerID, "ocid") {
  269. log.Debug("using Oracle provider")
  270. cp.provider = opencost.OracleProvider
  271. cp.configFileName = "oracle.json"
  272. } else if _, ok := node.Labels["cce.cloud.com/cce-nodepool"]; ok { // The node label "cce.cloud.com/cce-nodepool" exists
  273. log.Debug("using OTC provider")
  274. cp.provider = opencost.OTCProvider
  275. cp.configFileName = "otc.json"
  276. } else if strings.HasPrefix(providerID, "digitalocean") {
  277. log.Debug("using DigitalOcean provider")
  278. cp.provider = opencost.DigitalOceanProvider
  279. cp.configFileName = "digitalocean.json"
  280. }
  281. // Override provider to CSV if CSVProvider is used and custom provider is not set
  282. if env.IsUseCSVProvider() {
  283. log.Debug("using CSV provider")
  284. cp.provider = opencost.CSVProvider
  285. }
  286. return cp
  287. }
  288. var (
  289. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  290. providerAWSRegex = regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  291. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  292. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  293. providerGCERegex = regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  294. // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  295. persistentVolumeAWSRegex = regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)")
  296. // Capture "ad9d88195b52a47c89b5055120f28c58" from "ad9d88195b52a47c89b5055120f28c58-1037804914.us-east-2.elb.amazonaws.com"
  297. loadBalancerAWSRegex = regexp.MustCompile("^([^-]+)-.+amazonaws\\.com$")
  298. )
  299. // ParseID attempts to parse a ProviderId from a string based on formats from the various providers and
  300. // returns the string as is if it cannot find a match
  301. func ParseID(id string) string {
  302. match := providerAWSRegex.FindStringSubmatch(id)
  303. if len(match) >= 2 {
  304. return match[1]
  305. }
  306. match = providerGCERegex.FindStringSubmatch(id)
  307. if len(match) >= 2 {
  308. return match[1]
  309. }
  310. // Return id for Azure Provider, CSV Provider and Custom Provider
  311. return id
  312. }
  313. // ParsePVID attempts to parse a PV 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 ParsePVID(id string) string {
  316. match := persistentVolumeAWSRegex.FindStringSubmatch(id)
  317. if len(match) >= 2 {
  318. return match[1]
  319. }
  320. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  321. return id
  322. }
  323. // ParseLBID attempts to parse a LB ProviderId from a string based on formats from the various providers and
  324. // returns the string as is if it cannot find a match
  325. func ParseLBID(id string) string {
  326. match := loadBalancerAWSRegex.FindStringSubmatch(id)
  327. if len(match) >= 2 {
  328. return match[1]
  329. }
  330. // Return id for GCP Provider, Azure Provider, CSV Provider and Custom Provider
  331. return id
  332. }
  333. // ParseLocalDiskID attempts to parse a ProviderID from the ProviderID of the node that the local disk is running on
  334. func ParseLocalDiskID(id string) string {
  335. // Parse like node
  336. id = ParseID(id)
  337. if strings.HasPrefix(id, "azure://") {
  338. // 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
  339. if strings.Contains(id, "virtualMachineScaleSets") {
  340. split := strings.Split(id, "/virtualMachineScaleSets/")
  341. // combine vmss name and number into a single string ending in a 6 character base 32 number
  342. vmSplit := strings.Split(split[1], "/")
  343. if len(vmSplit) != 3 {
  344. return id
  345. }
  346. vmNum, err := strconv.ParseInt(vmSplit[2], 10, 64)
  347. if err != nil {
  348. return id
  349. }
  350. id = fmt.Sprintf("%s/disks/%s%06s", split[0], vmSplit[0], strconv.FormatInt(vmNum, 32))
  351. }
  352. id = strings.Replace(id, "/virtualMachines/", "/disks/", -1)
  353. id = strings.ToLower(id)
  354. return fmt.Sprintf("%s_osdisk", id)
  355. }
  356. return id
  357. }