provider.go 13 KB

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