provider.go 14 KB

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