provider.go 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803
  1. package aws
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "context"
  6. "encoding/csv"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/aws/smithy-go"
  18. "github.com/opencost/opencost/pkg/cloud/httputil"
  19. "github.com/opencost/opencost/pkg/cloud/models"
  20. "github.com/opencost/opencost/pkg/cloud/utils"
  21. "github.com/opencost/opencost/core/pkg/clustercache"
  22. coreenv "github.com/opencost/opencost/core/pkg/env"
  23. errs "github.com/opencost/opencost/core/pkg/errors"
  24. "github.com/opencost/opencost/core/pkg/log"
  25. "github.com/opencost/opencost/core/pkg/opencost"
  26. "github.com/opencost/opencost/core/pkg/util"
  27. "github.com/opencost/opencost/core/pkg/util/fileutil"
  28. "github.com/opencost/opencost/core/pkg/util/json"
  29. "github.com/opencost/opencost/core/pkg/util/timeutil"
  30. "github.com/opencost/opencost/pkg/env"
  31. awsSDK "github.com/aws/aws-sdk-go-v2/aws"
  32. "github.com/aws/aws-sdk-go-v2/config"
  33. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  34. "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
  35. "github.com/aws/aws-sdk-go-v2/service/athena"
  36. athenaTypes "github.com/aws/aws-sdk-go-v2/service/athena/types"
  37. "github.com/aws/aws-sdk-go-v2/service/ec2"
  38. ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
  39. "github.com/aws/aws-sdk-go-v2/service/s3"
  40. "github.com/aws/aws-sdk-go-v2/service/sts"
  41. "github.com/jszwec/csvutil"
  42. )
  43. const (
  44. supportedSpotFeedVersion = "1"
  45. SpotInfoUpdateType = "spotinfo"
  46. AthenaInfoUpdateType = "athenainfo"
  47. PreemptibleType = "preemptible"
  48. APIPricingSource = "Public API"
  49. SpotPricingSource = "Spot Data Feed"
  50. SpotPriceHistorySource = "Spot Price History"
  51. ReservedInstancePricingSource = "Savings Plan, Reserved Instance, and Out-Of-Cluster"
  52. FargatePricingSource = "Fargate"
  53. InUseState = "in-use"
  54. AttachedState = "attached"
  55. AWSHourlyPublicIPCost = 0.005
  56. EKSCapacityTypeLabel = "eks.amazonaws.com/capacityType"
  57. EKSCapacitySpotTypeValue = "SPOT"
  58. // relevant to pricing url
  59. awsPricingBaseURL = "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/"
  60. awsChinaPricingBaseURL = "https://pricing.cn-north-1.amazonaws.com.cn/offers/v1.0/cn/"
  61. pricingCurrentPath = "/current/"
  62. pricingIndexFile = "index.json"
  63. chinaRegionPrefix = "cn-"
  64. )
  65. var (
  66. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  67. provIdRx = regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  68. usageTypeRegx = regexp.MustCompile(".*(-|^)(EBS.+)")
  69. versionRx = regexp.MustCompile(`^#Version: (\\d+)\\.\\d+$`)
  70. regionRx = regexp.MustCompile("([a-z]+-[a-z]+-[0-9])")
  71. ErrNoAthenaBucket = errors.New("No Athena Bucket configured")
  72. // StorageClassProvisionerDefaults specifies the default storage class types depending upon the provisioner
  73. StorageClassProvisionerDefaults = map[string]string{
  74. "kubernetes.io/aws-ebs": "gp2",
  75. "ebs.csi.aws.com": "gp3",
  76. // TODO: add efs provisioner
  77. }
  78. )
  79. func (aws *AWS) PricingSourceStatus() map[string]*models.PricingSource {
  80. sources := make(map[string]*models.PricingSource)
  81. sps := &models.PricingSource{
  82. Name: SpotPricingSource,
  83. Enabled: true,
  84. }
  85. if aws.SpotFeedRefreshEnabled() {
  86. sps.Error = ""
  87. if aws.SpotPricingError != nil {
  88. sps.Error = aws.SpotPricingError.Error()
  89. }
  90. if sps.Error != "" {
  91. sps.Available = false
  92. } else if len(aws.SpotPricingByInstanceID) > 0 {
  93. sps.Available = true
  94. } else {
  95. sps.Error = "No spot instances detected"
  96. }
  97. } else {
  98. sps.Available = false
  99. sps.Error = "Spot instances not set up"
  100. sps.Enabled = false
  101. }
  102. sources[SpotPricingSource] = sps
  103. sphs := &models.PricingSource{
  104. Name: SpotPriceHistorySource,
  105. Enabled: true,
  106. }
  107. if aws.SpotPriceHistoryError != nil {
  108. sphs.Error = aws.SpotPriceHistoryError.Error()
  109. sphs.Available = false
  110. } else if aws.SpotPriceHistoryCache == nil {
  111. sphs.Error = "Not yet initialized"
  112. sphs.Available = false
  113. } else {
  114. sphs.Available = true
  115. }
  116. sources[SpotPriceHistorySource] = sphs
  117. rps := &models.PricingSource{
  118. Name: ReservedInstancePricingSource,
  119. Enabled: true,
  120. }
  121. rps.Error = ""
  122. if aws.RIPricingError != nil {
  123. rps.Error = aws.RIPricingError.Error()
  124. }
  125. if rps.Error != "" {
  126. rps.Available = false
  127. } else {
  128. rps.Available = true
  129. }
  130. sources[ReservedInstancePricingSource] = rps
  131. fs := &models.PricingSource{
  132. Name: FargatePricingSource,
  133. Enabled: true,
  134. Available: true,
  135. }
  136. if aws.FargatePricingError != nil {
  137. fs.Error = aws.FargatePricingError.Error()
  138. fs.Available = false
  139. }
  140. sources[FargatePricingSource] = fs
  141. return sources
  142. }
  143. // SpotRefreshDuration represents how much time must pass before we refresh
  144. const SpotRefreshDuration = 15 * time.Minute
  145. var awsRegions = []string{
  146. "us-east-2",
  147. "us-east-1",
  148. "us-west-1",
  149. "us-west-2",
  150. "ap-east-1",
  151. "ap-south-1",
  152. "ap-northeast-3",
  153. "ap-northeast-2",
  154. "ap-southeast-1",
  155. "ap-southeast-2",
  156. "ap-northeast-1",
  157. "ap-southeast-3",
  158. "ca-central-1",
  159. "cn-north-1",
  160. "cn-northwest-1",
  161. "eu-central-1",
  162. "eu-west-1",
  163. "eu-west-2",
  164. "eu-west-3",
  165. "eu-north-1",
  166. "eu-south-1",
  167. "me-south-1",
  168. "sa-east-1",
  169. "af-south-1",
  170. "us-gov-east-1",
  171. "us-gov-west-1",
  172. "me-central-1",
  173. }
  174. // AWS represents an Amazon Provider
  175. type AWS struct {
  176. Pricing map[string]*AWSProductTerms
  177. SpotPricingByInstanceID map[string]*spotInfo
  178. SpotPricingUpdatedAt *time.Time
  179. SpotRefreshRunning bool
  180. SpotPricingLock sync.RWMutex
  181. SpotPricingError error
  182. SpotPriceHistoryCache *SpotPriceHistoryCache
  183. SpotPriceHistoryError error
  184. RIPricingByInstanceID map[string]*RIData
  185. RIPricingError error
  186. RIDataRunning bool
  187. RIDataLock sync.RWMutex
  188. SavingsPlanDataByInstanceID map[string]*SavingsPlanData
  189. SavingsPlanDataRunning bool
  190. SavingsPlanDataLock sync.RWMutex
  191. FargatePricing *FargatePricing
  192. FargatePricingError error
  193. ValidPricingKeys map[string]bool
  194. Clientset clustercache.ClusterCache
  195. BaseCPUPrice string
  196. BaseRAMPrice string
  197. BaseGPUPrice string
  198. BaseSpotCPUPrice string
  199. BaseSpotRAMPrice string
  200. BaseSpotGPUPrice string
  201. SpotLabelName string
  202. SpotLabelValue string
  203. SpotDataRegion string
  204. SpotDataBucket string
  205. SpotDataPrefix string
  206. ProjectID string
  207. DownloadPricingDataLock sync.RWMutex
  208. Config models.ProviderConfig
  209. ServiceAccountChecks *models.ServiceAccountChecks
  210. clusterManagementPrice float64
  211. ClusterRegion string
  212. ClusterAccountID string
  213. clusterProvisioner string
  214. }
  215. // AWSAccessKey holds AWS credentials and fulfils the awsV2.CredentialsProvider interface
  216. // Deprecated: v1.104 Use AccessKey instead
  217. type AWSAccessKey struct {
  218. AccessKeyID string `json:"aws_access_key_id"`
  219. SecretAccessKey string `json:"aws_secret_access_key"`
  220. }
  221. // Retrieve returns a set of awsV2 credentials using the AWSAccessKey's key and secret.
  222. // This fulfils the awsV2.CredentialsProvider interface contract.
  223. func (accessKey AWSAccessKey) Retrieve(ctx context.Context) (awsSDK.Credentials, error) {
  224. return awsSDK.Credentials{
  225. AccessKeyID: accessKey.AccessKeyID,
  226. SecretAccessKey: accessKey.SecretAccessKey,
  227. }, nil
  228. }
  229. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains for the provided region
  230. func (accessKey AWSAccessKey) CreateConfig(region string) (awsSDK.Config, error) {
  231. var cfg awsSDK.Config
  232. var err error
  233. // If accessKey values have not been provided, attempt to load cfg from service key annotations
  234. if accessKey.AccessKeyID == "" && accessKey.SecretAccessKey == "" {
  235. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
  236. if err != nil {
  237. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region from annotation %s: %s", region, err)
  238. }
  239. } else {
  240. // The AWS SDK v2 requires an object fulfilling the CredentialsProvider interface, which cloud.AWSAccessKey does
  241. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(accessKey), config.WithRegion(region))
  242. if err != nil {
  243. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region %s: %s", region, err)
  244. }
  245. }
  246. return cfg, nil
  247. }
  248. // AWSPricing maps a k8s node to an AWS Pricing "product"
  249. type AWSPricing struct {
  250. Products map[string]*AWSProduct `json:"products"`
  251. Terms AWSPricingTerms `json:"terms"`
  252. }
  253. // AWSProduct represents a purchased SKU
  254. type AWSProduct struct {
  255. Sku string `json:"sku"`
  256. Attributes AWSProductAttributes `json:"attributes"`
  257. }
  258. // AWSProductAttributes represents metadata about the product used to map to a node.
  259. type AWSProductAttributes struct {
  260. Location string `json:"location"`
  261. RegionCode string `json:"regionCode"`
  262. Operation string `json:"operation"`
  263. InstanceType string `json:"instanceType"`
  264. Memory string `json:"memory"`
  265. Storage string `json:"storage"`
  266. VCpu string `json:"vcpu"`
  267. UsageType string `json:"usagetype"`
  268. OperatingSystem string `json:"operatingSystem"`
  269. PreInstalledSw string `json:"preInstalledSw"`
  270. InstanceFamily string `json:"instanceFamily"`
  271. CapacityStatus string `json:"capacitystatus"`
  272. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  273. MarketOption string `json:"marketOption"`
  274. }
  275. // AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
  276. type AWSPricingTerms struct {
  277. OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
  278. Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
  279. }
  280. // AWSOfferTerm is a sku extension used to pay for the node.
  281. type AWSOfferTerm struct {
  282. Sku string `json:"sku"`
  283. OfferTermCode string `json:"offerTermCode"`
  284. PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
  285. }
  286. func (ot *AWSOfferTerm) String() string {
  287. var strs []string
  288. for k, rc := range ot.PriceDimensions {
  289. strs = append(strs, fmt.Sprintf("%s:%s", k, rc.String()))
  290. }
  291. return fmt.Sprintf("%s:%s", ot.Sku, strings.Join(strs, ","))
  292. }
  293. // AWSRateCode encodes data about the price of a product
  294. type AWSRateCode struct {
  295. Unit string `json:"unit"`
  296. PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
  297. }
  298. func (rc *AWSRateCode) String() string {
  299. return fmt.Sprintf("{unit: %s, pricePerUnit: %v", rc.Unit, rc.PricePerUnit)
  300. }
  301. // AWSCurrencyCode is the localized currency. (TODO: support non-USD)
  302. type AWSCurrencyCode struct {
  303. USD string `json:"USD,omitempty"`
  304. CNY string `json:"CNY,omitempty"`
  305. }
  306. // AWSProductTerms represents the full terms of the product
  307. type AWSProductTerms struct {
  308. Sku string `json:"sku"`
  309. OnDemand *AWSOfferTerm `json:"OnDemand"`
  310. Reserved *AWSOfferTerm `json:"Reserved"`
  311. Memory string `json:"memory"`
  312. Storage string `json:"storage"`
  313. VCpu string `json:"vcpu"`
  314. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  315. PV *models.PV `json:"pv"`
  316. LoadBalancer *models.LoadBalancer `json:"load_balancer"`
  317. }
  318. // ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
  319. const ClusterIdEnvVar = "AWS_CLUSTER_ID"
  320. // OnDemandRateCodes is are sets of identifiers for offerTermCodes matching 'On Demand' rates
  321. var OnDemandRateCodes = map[string]struct{}{
  322. "JRTCKXETXF": {},
  323. }
  324. var OnDemandRateCodesCn = map[string]struct{}{
  325. "99YE2YK9UR": {},
  326. "5Y9WH78GDR": {},
  327. "KW44MY7SZN": {},
  328. }
  329. // HourlyRateCode is appended to a node sku
  330. const (
  331. HourlyRateCode = "6YS6EN2CT7"
  332. HourlyRateCodeCn = "Q7UJUT2CE6"
  333. )
  334. // volTypes are used to map between AWS UsageTypes and
  335. // EBS volume types, as they would appear in K8s storage class
  336. // name and the EC2 API.
  337. var volTypes = map[string]string{
  338. "EBS:VolumeUsage.gp2": "gp2",
  339. "EBS:VolumeUsage.gp3": "gp3",
  340. "EBS:VolumeUsage": "standard",
  341. "EBS:VolumeUsage.sc1": "sc1",
  342. "EBS:VolumeP-IOPS.piops": "io1",
  343. "EBS:VolumeUsage.st1": "st1",
  344. "EBS:VolumeUsage.piops": "io1",
  345. "EBS:VolumeUsage.io2": "io2",
  346. "gp2": "EBS:VolumeUsage.gp2",
  347. "gp3": "EBS:VolumeUsage.gp3",
  348. "standard": "EBS:VolumeUsage",
  349. "sc1": "EBS:VolumeUsage.sc1",
  350. "io1": "EBS:VolumeUsage.piops",
  351. "st1": "EBS:VolumeUsage.st1",
  352. "io2": "EBS:VolumeUsage.io2",
  353. }
  354. var (
  355. loadedAWSSecret bool = false
  356. awsSecret *AWSAccessKey = nil
  357. )
  358. // KubeAttrConversion maps the k8s labels for region to an AWS key
  359. func (aws *AWS) KubeAttrConversion(region, instanceType, operatingSystem string) string {
  360. operatingSystem = strings.ToLower(operatingSystem)
  361. return region + "," + instanceType + "," + operatingSystem
  362. }
  363. // AwsSpotFeedInfo contains configuration for spot feed integration
  364. type AwsSpotFeedInfo struct {
  365. BucketName string `json:"bucketName"`
  366. Prefix string `json:"prefix"`
  367. Region string `json:"region"`
  368. AccountID string `json:"projectID"`
  369. ServiceKeyName string `json:"serviceKeyName"`
  370. ServiceKeySecret string `json:"serviceKeySecret"`
  371. SpotLabel string `json:"spotLabel"`
  372. SpotLabelValue string `json:"spotLabelValue"`
  373. }
  374. // AwsAthenaInfo contains configuration for CUR integration
  375. // Deprecated: v1.104 Use AthenaConfiguration instead
  376. type AwsAthenaInfo struct {
  377. AthenaBucketName string `json:"athenaBucketName"`
  378. AthenaRegion string `json:"athenaRegion"`
  379. AthenaDatabase string `json:"athenaDatabase"`
  380. AthenaCatalog string `json:"athenaCatalog"`
  381. AthenaTable string `json:"athenaTable"`
  382. AthenaWorkgroup string `json:"athenaWorkgroup"`
  383. ServiceKeyName string `json:"serviceKeyName"`
  384. ServiceKeySecret string `json:"serviceKeySecret"`
  385. AccountID string `json:"projectID"`
  386. MasterPayerARN string `json:"masterPayerARN"`
  387. }
  388. // IsEmpty returns true if all fields in config are empty, false if not.
  389. func (aai *AwsAthenaInfo) IsEmpty() bool {
  390. return aai.AthenaBucketName == "" &&
  391. aai.AthenaRegion == "" &&
  392. aai.AthenaDatabase == "" &&
  393. aai.AthenaCatalog == "" &&
  394. aai.AthenaTable == "" &&
  395. aai.AthenaWorkgroup == "" &&
  396. aai.ServiceKeyName == "" &&
  397. aai.ServiceKeySecret == "" &&
  398. aai.AccountID == "" &&
  399. aai.MasterPayerARN == ""
  400. }
  401. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains
  402. func (aai *AwsAthenaInfo) CreateConfig() (awsSDK.Config, error) {
  403. keyProvider := AWSAccessKey{AccessKeyID: aai.ServiceKeyName, SecretAccessKey: aai.ServiceKeySecret}
  404. cfg, err := keyProvider.CreateConfig(aai.AthenaRegion)
  405. if err != nil {
  406. return cfg, err
  407. }
  408. if aai.MasterPayerARN != "" {
  409. // Create the credentials from AssumeRoleProvider to assume the role
  410. // referenced by the roleARN.
  411. stsSvc := sts.NewFromConfig(cfg)
  412. creds := stscreds.NewAssumeRoleProvider(stsSvc, aai.MasterPayerARN)
  413. cfg.Credentials = awsSDK.NewCredentialsCache(creds)
  414. }
  415. return cfg, nil
  416. }
  417. func (aws *AWS) GetManagementPlatform() (string, error) {
  418. nodes := aws.Clientset.GetAllNodes()
  419. if len(nodes) > 0 {
  420. n := nodes[0]
  421. version := n.Status.NodeInfo.KubeletVersion
  422. if strings.Contains(version, "eks") {
  423. return "eks", nil
  424. }
  425. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  426. return "kops", nil
  427. }
  428. }
  429. return "", nil
  430. }
  431. func (aws *AWS) GetConfig() (*models.CustomPricing, error) {
  432. c, err := aws.Config.GetCustomPricingData()
  433. if err != nil {
  434. return nil, err
  435. }
  436. if c.Discount == "" {
  437. c.Discount = "0%"
  438. }
  439. if c.NegotiatedDiscount == "" {
  440. c.NegotiatedDiscount = "0%"
  441. }
  442. return c, nil
  443. }
  444. // GetAWSAccessKey generate an AWSAccessKey object from the config
  445. func (aws *AWS) GetAWSAccessKey() (*AWSAccessKey, error) {
  446. config, err := aws.GetConfig()
  447. if err != nil {
  448. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  449. }
  450. err = aws.ConfigureAuthWith(config)
  451. if err != nil {
  452. return nil, fmt.Errorf("error configuring Cloud Provider %s", err)
  453. }
  454. // Look for service key values in env if not present in config
  455. if config.AwsServiceKeyName == "" {
  456. config.AwsServiceKeyName = env.GetAWSAccessKeyID()
  457. }
  458. if config.AwsServiceKeySecret == "" {
  459. config.AwsServiceKeySecret = env.GetAWSAccessKeySecret()
  460. }
  461. if config.AwsServiceKeyName == "" && config.AwsServiceKeySecret == "" {
  462. log.DedupedInfof(1, "missing service key values for AWS cloud integration attempting to use service account integration")
  463. }
  464. return &AWSAccessKey{AccessKeyID: config.AwsServiceKeyName, SecretAccessKey: config.AwsServiceKeySecret}, nil
  465. }
  466. // GetAWSAthenaInfo generate an AWSAthenaInfo object from the config
  467. func (aws *AWS) GetAWSAthenaInfo() (*AwsAthenaInfo, error) {
  468. config, err := aws.GetConfig()
  469. if err != nil {
  470. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  471. }
  472. aak, err := aws.GetAWSAccessKey()
  473. if err != nil {
  474. return nil, err
  475. }
  476. return &AwsAthenaInfo{
  477. AthenaBucketName: config.AthenaBucketName,
  478. AthenaRegion: config.AthenaRegion,
  479. AthenaDatabase: config.AthenaDatabase,
  480. AthenaCatalog: config.AthenaCatalog,
  481. AthenaTable: config.AthenaTable,
  482. AthenaWorkgroup: config.AthenaWorkgroup,
  483. ServiceKeyName: aak.AccessKeyID,
  484. ServiceKeySecret: aak.SecretAccessKey,
  485. AccountID: config.AthenaProjectID,
  486. MasterPayerARN: config.MasterPayerARN,
  487. }, nil
  488. }
  489. func (aws *AWS) UpdateConfigFromConfigMap(cm map[string]string) (*models.CustomPricing, error) {
  490. return aws.Config.UpdateFromMap(cm)
  491. }
  492. func configUpdaterWithReaderAndType(r io.Reader, updateType string) func(c *models.CustomPricing) error {
  493. return func(c *models.CustomPricing) error {
  494. switch updateType {
  495. case SpotInfoUpdateType:
  496. asfi := AwsSpotFeedInfo{}
  497. err := json.NewDecoder(r).Decode(&asfi)
  498. if err != nil {
  499. return err
  500. }
  501. c.AwsServiceKeyName = asfi.ServiceKeyName
  502. if asfi.ServiceKeySecret != "" {
  503. c.AwsServiceKeySecret = asfi.ServiceKeySecret
  504. }
  505. c.AwsSpotDataPrefix = asfi.Prefix
  506. c.AwsSpotDataBucket = asfi.BucketName
  507. c.ProjectID = asfi.AccountID
  508. c.AwsSpotDataRegion = asfi.Region
  509. c.SpotLabel = asfi.SpotLabel
  510. c.SpotLabelValue = asfi.SpotLabelValue
  511. case AthenaInfoUpdateType:
  512. aai := AwsAthenaInfo{}
  513. err := json.NewDecoder(r).Decode(&aai)
  514. if err != nil {
  515. return err
  516. }
  517. c.AthenaBucketName = aai.AthenaBucketName
  518. c.AthenaRegion = aai.AthenaRegion
  519. c.AthenaDatabase = aai.AthenaDatabase
  520. c.AthenaCatalog = aai.AthenaCatalog
  521. c.AthenaTable = aai.AthenaTable
  522. c.AthenaWorkgroup = aai.AthenaWorkgroup
  523. c.AwsServiceKeyName = aai.ServiceKeyName
  524. if aai.ServiceKeySecret != "" {
  525. c.AwsServiceKeySecret = aai.ServiceKeySecret
  526. }
  527. if aai.MasterPayerARN != "" {
  528. c.MasterPayerARN = aai.MasterPayerARN
  529. }
  530. c.AthenaProjectID = aai.AccountID
  531. default:
  532. a := make(map[string]any)
  533. err := json.NewDecoder(r).Decode(&a)
  534. if err != nil {
  535. return err
  536. }
  537. for k, v := range a {
  538. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  539. vstr, ok := v.(string)
  540. if ok {
  541. err := models.SetCustomPricingField(c, kUpper, vstr)
  542. if err != nil {
  543. return fmt.Errorf("error setting custom pricing field: %w", err)
  544. }
  545. } else {
  546. return fmt.Errorf("type error while updating config for %s", kUpper)
  547. }
  548. }
  549. }
  550. if env.IsRemoteEnabled() {
  551. err := utils.UpdateClusterMeta(coreenv.GetClusterID(), c.ClusterName)
  552. if err != nil {
  553. return err
  554. }
  555. }
  556. return nil
  557. }
  558. }
  559. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  560. return aws.Config.Update(configUpdaterWithReaderAndType(r, updateType))
  561. }
  562. type awsKey struct {
  563. Name string
  564. SpotLabelName string
  565. SpotLabelValue string
  566. Labels map[string]string
  567. ProviderID string
  568. }
  569. func (k *awsKey) GPUCount() int {
  570. return 0
  571. }
  572. func (k *awsKey) GPUType() string {
  573. return ""
  574. }
  575. func (k *awsKey) ID() string {
  576. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  577. if matchNum == 2 {
  578. return group
  579. }
  580. }
  581. log.Warnf("Could not find instance ID in \"%s\"", k.ProviderID)
  582. return ""
  583. }
  584. // Features will return a comma separated list of features for the given node
  585. // If the node has a spot label, it will be included in the list
  586. // Otherwise, the list include instance type, operating system, and the region
  587. func (k *awsKey) Features() string {
  588. instanceType, _ := util.GetInstanceType(k.Labels)
  589. operatingSystem, _ := util.GetOperatingSystem(k.Labels)
  590. region, _ := util.GetRegion(k.Labels)
  591. key := region + "," + instanceType + "," + operatingSystem
  592. usageType := k.getUsageType(k.Labels)
  593. spotKey := key + "," + usageType
  594. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  595. return spotKey
  596. }
  597. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  598. return spotKey
  599. }
  600. if usageType == PreemptibleType {
  601. return spotKey
  602. }
  603. return key
  604. }
  605. const eksComputeTypeLabel = "eks.amazonaws.com/compute-type"
  606. func (k *awsKey) isFargateNode() bool {
  607. v := k.Labels[eksComputeTypeLabel]
  608. if v == "fargate" {
  609. return true
  610. }
  611. return false
  612. }
  613. // getUsageType returns the usage type of the instance
  614. // If the instance is a spot instance, it will return PreemptibleType
  615. // Otherwise returns an empty string
  616. func (k *awsKey) getUsageType(labels map[string]string) string {
  617. if kLabel, ok := labels[k.SpotLabelName]; ok && kLabel == k.SpotLabelValue {
  618. return PreemptibleType
  619. }
  620. if eksLabel, ok := labels[EKSCapacityTypeLabel]; ok && eksLabel == EKSCapacitySpotTypeValue {
  621. // We currently write out spot instances as "preemptible" in the pricing data, so these need to match
  622. return PreemptibleType
  623. }
  624. if kLabel, ok := labels[models.KarpenterCapacityTypeLabel]; ok && kLabel == models.KarpenterCapacitySpotTypeValue {
  625. return PreemptibleType
  626. }
  627. return ""
  628. }
  629. func (awsProvider *AWS) GpuPricing(nodeLabels map[string]string) (string, error) {
  630. return "", nil
  631. }
  632. func (aws *AWS) PVPricing(pvk models.PVKey) (*models.PV, error) {
  633. pricing, ok := aws.Pricing[pvk.Features()]
  634. if !ok {
  635. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  636. return &models.PV{}, nil
  637. }
  638. return pricing.PV, nil
  639. }
  640. type awsPVKey struct {
  641. Labels map[string]string
  642. StorageClassParameters map[string]string
  643. StorageClassName string
  644. Name string
  645. DefaultRegion string
  646. ProviderID string
  647. }
  648. func (aws *AWS) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  649. providerID := ""
  650. if pv.Spec.AWSElasticBlockStore != nil {
  651. providerID = pv.Spec.AWSElasticBlockStore.VolumeID
  652. } else if pv.Spec.CSI != nil {
  653. providerID = pv.Spec.CSI.VolumeHandle
  654. }
  655. return &awsPVKey{
  656. Labels: pv.Labels,
  657. StorageClassName: pv.Spec.StorageClassName,
  658. StorageClassParameters: parameters,
  659. Name: pv.Name,
  660. DefaultRegion: defaultRegion,
  661. ProviderID: providerID,
  662. }
  663. }
  664. func (key *awsPVKey) ID() string {
  665. return key.ProviderID
  666. }
  667. func (key *awsPVKey) GetStorageClass() string {
  668. return key.StorageClassName
  669. }
  670. func (key *awsPVKey) Features() string {
  671. storageClass, ok := key.StorageClassParameters["type"]
  672. if !ok {
  673. log.Debugf("storage class %s doesn't have a 'type' parameter", key.Name)
  674. storageClass = getStorageClassTypeFrom(key.StorageClassParameters["provisioner"])
  675. }
  676. if storageClass == "standard" {
  677. storageClass = "gp2"
  678. }
  679. // Storage class names are generally EBS volume types (gp2)
  680. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  681. // Converts between the 2
  682. region, ok := util.GetRegion(key.Labels)
  683. if !ok {
  684. region = key.DefaultRegion
  685. }
  686. class, ok := volTypes[storageClass]
  687. if !ok {
  688. log.Debugf("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  689. }
  690. return region + "," + class
  691. }
  692. // getStorageClassTypeFrom returns the default ebs volume type for a provider provisioner
  693. func getStorageClassTypeFrom(provisioner string) string {
  694. // if there isn't any provided provisioner, return empty volume type
  695. if provisioner == "" {
  696. return ""
  697. }
  698. scType, ok := StorageClassProvisionerDefaults[provisioner]
  699. if ok {
  700. log.Debugf("using default voltype %s for provisioner %s", scType, provisioner)
  701. return scType
  702. }
  703. return ""
  704. }
  705. // GetKey maps node labels to information needed to retrieve pricing data
  706. func (aws *AWS) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  707. return &awsKey{
  708. Name: n.Name,
  709. SpotLabelName: aws.SpotLabelName,
  710. SpotLabelValue: aws.SpotLabelValue,
  711. Labels: labels,
  712. ProviderID: labels["providerID"],
  713. }
  714. }
  715. func (aws *AWS) isPreemptible(key string) bool {
  716. s := strings.Split(key, ",")
  717. if len(s) == 4 && s[3] == PreemptibleType {
  718. return true
  719. }
  720. return false
  721. }
  722. func (aws *AWS) ClusterManagementPricing() (string, float64, error) {
  723. return aws.clusterProvisioner, aws.clusterManagementPrice, nil
  724. }
  725. func getPricingListURL(serviceCode string, nodeList []*clustercache.Node) string {
  726. // See https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/using-the-aws-price-list-bulk-api-fetching-price-list-files-manually.html
  727. region := ""
  728. multiregion := false
  729. isChina := false
  730. for _, n := range nodeList {
  731. r, ok := util.GetRegion(n.Labels)
  732. if !ok {
  733. multiregion = true
  734. break
  735. }
  736. if strings.HasPrefix(r, chinaRegionPrefix) {
  737. isChina = true
  738. }
  739. if region == "" {
  740. region = r
  741. } else if r != region {
  742. multiregion = true
  743. break
  744. }
  745. }
  746. baseURL := awsPricingBaseURL + serviceCode + pricingCurrentPath
  747. if isChina {
  748. // Chinese regions are isolated and use a different pricing endpoint
  749. baseURL = awsChinaPricingBaseURL + serviceCode + pricingCurrentPath
  750. }
  751. if region != "" && !multiregion {
  752. baseURL += region + "/"
  753. }
  754. return baseURL + pricingIndexFile
  755. }
  756. // Use the pricing data from the current region. Fall back to using all region data if needed.
  757. func (aws *AWS) getRegionPricing(nodeList []*clustercache.Node) (*http.Response, string, error) {
  758. var pricingURL string
  759. if env.GetAWSPricingURL() != "" { // Allow override of pricing URL
  760. pricingURL = env.GetAWSPricingURL()
  761. } else {
  762. pricingURL = getPricingListURL("AmazonEC2", nodeList)
  763. }
  764. log.Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  765. // This file is large and can take a while to stream, so the streaming client
  766. // bounds connect/TLS/response-header time but not the total body read - enough
  767. // to bail on a hung endpoint without truncating a legitimate slow download.
  768. resp, err := httputil.StreamingGet(context.Background(), pricingURL)
  769. if err != nil {
  770. log.Errorf("Bogus fetch of \"%s\": %v", pricingURL, err)
  771. return nil, pricingURL, err
  772. }
  773. return resp, pricingURL, err
  774. }
  775. // SpotFeedRefreshEnabled determines whether the required configs to run the spot feed query have been set up
  776. func (aws *AWS) SpotFeedRefreshEnabled() bool {
  777. // Guard against nil receiver
  778. if aws == nil {
  779. return false
  780. }
  781. // Fallback if config is not initialized
  782. if aws.Config == nil {
  783. return len(aws.SpotDataBucket) != 0 ||
  784. len(aws.SpotDataRegion) != 0 ||
  785. len(aws.ProjectID) != 0
  786. }
  787. // Check if spot data feed is explicitly disabled via config
  788. c, err := aws.Config.GetCustomPricingData()
  789. if err == nil && c.SpotDataFeedEnabled == "false" {
  790. return false
  791. }
  792. // Default behavior
  793. return len(aws.SpotDataBucket) != 0 ||
  794. len(aws.SpotDataRegion) != 0 ||
  795. len(aws.ProjectID) != 0
  796. }
  797. // DownloadPricingData fetches data from the AWS Pricing API
  798. func (aws *AWS) DownloadPricingData() error {
  799. aws.DownloadPricingDataLock.Lock()
  800. defer aws.DownloadPricingDataLock.Unlock()
  801. c, err := aws.Config.GetCustomPricingData()
  802. if err != nil {
  803. log.Errorf("Error downloading default pricing data: %s", err.Error())
  804. }
  805. aws.BaseCPUPrice = c.CPU
  806. aws.BaseRAMPrice = c.RAM
  807. aws.BaseGPUPrice = c.GPU
  808. aws.BaseSpotCPUPrice = c.SpotCPU
  809. aws.BaseSpotRAMPrice = c.SpotRAM
  810. aws.BaseSpotGPUPrice = c.SpotGPU
  811. aws.SpotLabelName = c.SpotLabel
  812. aws.SpotLabelValue = c.SpotLabelValue
  813. aws.SpotDataBucket = c.AwsSpotDataBucket
  814. aws.SpotDataPrefix = c.AwsSpotDataPrefix
  815. aws.ProjectID = c.ProjectID
  816. aws.SpotDataRegion = c.AwsSpotDataRegion
  817. aws.ConfigureAuthWith(c) // load aws authentication from configuration or secret
  818. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  819. log.Warnf("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  820. }
  821. nodeList := aws.Clientset.GetAllNodes()
  822. inputkeys := make(map[string]bool)
  823. for _, n := range nodeList {
  824. if _, ok := n.Labels["eks.amazonaws.com/nodegroup"]; ok {
  825. aws.clusterManagementPrice = 0.10
  826. aws.clusterProvisioner = "EKS"
  827. } else if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  828. aws.clusterProvisioner = "KOPS"
  829. }
  830. labels := n.Labels
  831. key := aws.GetKey(labels, n)
  832. inputkeys[key.Features()] = true
  833. }
  834. pvList := aws.Clientset.GetAllPersistentVolumes()
  835. storageClasses := aws.Clientset.GetAllStorageClasses()
  836. storageClassMap := make(map[string]map[string]string)
  837. for _, storageClass := range storageClasses {
  838. params := storageClass.Parameters
  839. if params != nil {
  840. params["provisioner"] = storageClass.Provisioner
  841. }
  842. storageClassMap[storageClass.Name] = params
  843. if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  844. storageClassMap["default"] = params
  845. storageClassMap[""] = params
  846. }
  847. }
  848. pvkeys := make(map[string]models.PVKey)
  849. for _, pv := range pvList {
  850. params, ok := storageClassMap[pv.Spec.StorageClassName]
  851. if !ok {
  852. log.Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  853. continue
  854. }
  855. key := aws.GetPVKey(pv, params, "")
  856. pvkeys[key.Features()] = key
  857. }
  858. // RIDataRunning establishes the existence of the goroutine. Since it's possible we
  859. // run multiple downloads, we don't want to create multiple go routines if one already exists
  860. //
  861. // If athenaBucketName is unconfigured, the ReservedInstanceData and SavingsPlanData watchers
  862. // are skipped. Note: These watchers are less commonly used. It is recommended to use the full
  863. // CloudCosts feature via athenaintegration.go.
  864. if !aws.RIDataRunning {
  865. err = aws.GetReservationDataFromAthena() // Block until one run has completed.
  866. if err != nil {
  867. if errors.Is(err, ErrNoAthenaBucket) {
  868. log.Debugf("No \"athenaBucketName\" configured, ReservedInstanceData watcher will not run")
  869. } else {
  870. log.Warnf("Failed to lookup reserved instance data: %s", err.Error())
  871. }
  872. } else { // If we make one successful run, check on new reservation data every hour
  873. go func() {
  874. defer errs.HandlePanic()
  875. aws.RIDataRunning = true
  876. for {
  877. log.Infof("Reserved Instance watcher running... next update in 1h")
  878. time.Sleep(time.Hour)
  879. err := aws.GetReservationDataFromAthena()
  880. if err != nil {
  881. log.Infof("Error updating RI data: %s", err.Error())
  882. }
  883. }
  884. }()
  885. }
  886. }
  887. if !aws.SavingsPlanDataRunning {
  888. err = aws.GetSavingsPlanDataFromAthena()
  889. if err != nil {
  890. if errors.Is(err, ErrNoAthenaBucket) {
  891. log.Debugf("No \"athenaBucketName\" configured, SavingsPlanData watcher will not run")
  892. } else {
  893. log.Errorf("Failed to lookup savings plan data: %s", err.Error())
  894. }
  895. } else {
  896. go func() {
  897. defer errs.HandlePanic()
  898. aws.SavingsPlanDataRunning = true
  899. for {
  900. log.Infof("Savings Plan watcher running... next update in 1h")
  901. time.Sleep(time.Hour)
  902. err := aws.GetSavingsPlanDataFromAthena()
  903. if err != nil {
  904. log.Infof("Error updating Savings Plan data: %s", err.Error())
  905. }
  906. }
  907. }()
  908. }
  909. }
  910. // Initialize fargate pricing if it's not initialized yet
  911. if aws.FargatePricing == nil {
  912. aws.FargatePricing = NewFargatePricing()
  913. aws.FargatePricingError = aws.FargatePricing.Initialize(nodeList)
  914. if aws.FargatePricingError != nil {
  915. log.Errorf("Failed to initialize fargate pricing: %s", aws.FargatePricingError.Error())
  916. }
  917. }
  918. aws.ValidPricingKeys = make(map[string]bool)
  919. resp, pricingURL, err := aws.getRegionPricing(nodeList)
  920. if err != nil {
  921. return err
  922. }
  923. err = aws.populatePricing(resp, inputkeys)
  924. if err != nil {
  925. return err
  926. }
  927. log.Infof("Finished downloading \"%s\"", pricingURL)
  928. // Initialize a spot price history cache if not already initialized.
  929. // Reset error to allow retrying on subsequent DownloadPricingData calls.
  930. if aws.SpotPriceHistoryCache == nil {
  931. aws.SpotPriceHistoryError = nil
  932. aws.SpotPriceHistoryCache, aws.SpotPriceHistoryError = aws.initializeSpotPriceHistoryCache()
  933. if aws.SpotPriceHistoryError != nil {
  934. log.Errorf("Failed to initialize spot price history manager: %v", aws.SpotPriceHistoryError)
  935. }
  936. }
  937. if aws.SpotFeedRefreshEnabled() {
  938. // Always run spot pricing refresh when performing download
  939. aws.refreshSpotPricing(true)
  940. // Only start a single refresh goroutine
  941. if !aws.SpotRefreshRunning {
  942. aws.SpotRefreshRunning = true
  943. go func() {
  944. defer errs.HandlePanic()
  945. for {
  946. log.Infof("Spot Pricing Refresh scheduled in %.2f minutes.", SpotRefreshDuration.Minutes())
  947. time.Sleep(SpotRefreshDuration)
  948. // Reoccurring refresh checks update times
  949. aws.refreshSpotPricing(false)
  950. }
  951. }()
  952. }
  953. }
  954. return nil
  955. }
  956. // populatePricing parses AWS pricing JSON response and populates the pricing map.
  957. //
  958. // AWS Pricing JSON Structure:
  959. //
  960. // {
  961. // "products": {
  962. // "<SKU>": {
  963. // "sku": "<SKU>",
  964. // "attributes": { "instanceType": "...", "regionCode": "...", ... }
  965. // },
  966. // ...
  967. // },
  968. // "terms": {
  969. // "OnDemand": {
  970. // "<SKU>": {
  971. // "<SKU>.<OfferTermCode>": {
  972. // "offerTermCode": "...",
  973. // "priceDimensions": {
  974. // "<SKU>.<OfferTermCode>.<RateCode>": {
  975. // "unit": "Hrs",
  976. // "pricePerUnit": { "USD": "..." },
  977. // "description": "..."
  978. // }
  979. // }
  980. // }
  981. // }
  982. // }
  983. // }
  984. // }
  985. //
  986. // This function uses streaming JSON parsing to handle large pricing files efficiently:
  987. // 1. Parse "products" section: Extract SKUs and attributes for EC2 instances, EBS volumes, and load balancers
  988. // 2. Parse "terms" section: Extract on-demand pricing for each SKU. Note: only the
  989. // first term-type key is read and processed if it equals "OnDemand", so this
  990. // assumes "OnDemand" precedes any "Reserved" terms.
  991. // 3. Match SKUs to pricing keys and populate the pricing map
  992. func (aws *AWS) populatePricing(resp *http.Response, inputkeys map[string]bool) error {
  993. aws.Pricing = make(map[string]*AWSProductTerms)
  994. skuToPricingKeyMap := make(map[string]string)
  995. dec := json.NewDecoder(resp.Body)
  996. // Stream through the JSON response token by token
  997. for {
  998. token, err := dec.Token()
  999. if err == io.EOF {
  1000. log.Debugf("Finished parsing pricing data from \"%s\"", resp.Request.URL.String())
  1001. break
  1002. } else if err != nil {
  1003. // Keep pricing parsed so far rather than discarding the whole region.
  1004. log.Errorf("Error parsing pricing JSON response from \"%s\": %v", resp.Request.URL.String(), err)
  1005. break
  1006. }
  1007. // Parse "products" section: Extract product metadata (SKU, instance type, region, etc.)
  1008. if token == "products" {
  1009. _, err := dec.Token() // opening "{"
  1010. if err != nil {
  1011. return err
  1012. }
  1013. for dec.More() {
  1014. _, err := dec.Token() // SKU key
  1015. if err != nil {
  1016. return err
  1017. }
  1018. product := &AWSProduct{}
  1019. err = dec.Decode(&product)
  1020. if err != nil {
  1021. // Fall through to terms so registered SKUs still get a non-nil OnDemand.
  1022. log.Errorf("Error decoding product from \"%s\": %v", resp.Request.URL.String(), err)
  1023. break
  1024. }
  1025. // Filter for EC2 compute instances (on-demand, no pre-installed software)
  1026. if product.Attributes.PreInstalledSw == "NA" &&
  1027. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) &&
  1028. product.Attributes.CapacityStatus == "Used" &&
  1029. product.Attributes.MarketOption == "OnDemand" {
  1030. key := aws.KubeAttrConversion(product.Attributes.RegionCode, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  1031. spotKey := key + ",preemptible"
  1032. // Only store pricing for instances we actually have in the cluster
  1033. if inputkeys[key] || inputkeys[spotKey] {
  1034. productTerms := &AWSProductTerms{
  1035. Sku: product.Sku,
  1036. Memory: product.Attributes.Memory,
  1037. Storage: product.Attributes.Storage,
  1038. VCpu: product.Attributes.VCpu,
  1039. GPU: product.Attributes.GPU,
  1040. }
  1041. aws.Pricing[key] = productTerms
  1042. aws.Pricing[spotKey] = productTerms
  1043. skuToPricingKeyMap[product.Sku] = key
  1044. }
  1045. aws.ValidPricingKeys[key] = true
  1046. aws.ValidPricingKeys[spotKey] = true
  1047. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  1048. // Parse EBS volume pricing (storage)
  1049. // UsageTypes may be prefixed with a region code - strip it for generic lookups
  1050. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  1051. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  1052. key := product.Attributes.RegionCode + "," + usageTypeNoRegion
  1053. spotKey := key + ",preemptible"
  1054. pv := &models.PV{
  1055. Class: volTypes[usageTypeNoRegion],
  1056. Region: product.Attributes.RegionCode,
  1057. }
  1058. productTerms := &AWSProductTerms{
  1059. Sku: product.Sku,
  1060. PV: pv,
  1061. }
  1062. aws.Pricing[key] = productTerms
  1063. aws.Pricing[spotKey] = productTerms
  1064. skuToPricingKeyMap[product.Sku] = key
  1065. aws.ValidPricingKeys[key] = true
  1066. aws.ValidPricingKeys[spotKey] = true
  1067. } else if strings.Contains(product.Attributes.UsageType, "LoadBalancerUsage") && product.Attributes.Operation == "LoadBalancing:Network" {
  1068. // Parse Network Load Balancer pricing
  1069. // Note: Only NLBs are tracked since costmodel uses LoadBalancer services,
  1070. // not ingresses controlled by AWS load balancer controller
  1071. productTerms := &AWSProductTerms{
  1072. Sku: product.Sku,
  1073. LoadBalancer: &models.LoadBalancer{},
  1074. }
  1075. key := product.Attributes.RegionCode + ",LoadBalancerUsage"
  1076. aws.Pricing[key] = productTerms
  1077. skuToPricingKeyMap[product.Sku] = key
  1078. aws.ValidPricingKeys[key] = true
  1079. }
  1080. }
  1081. }
  1082. // Parse "terms" section: Extract on-demand pricing for each SKU
  1083. if token == "terms" {
  1084. _, err := dec.Token() // opening "{"
  1085. if err != nil {
  1086. return err
  1087. }
  1088. termType, err := dec.Token()
  1089. if err != nil {
  1090. return err
  1091. }
  1092. if termType == "OnDemand" {
  1093. _, err := dec.Token() // opening "{"
  1094. if err != nil {
  1095. return err
  1096. }
  1097. for dec.More() {
  1098. sku, err := dec.Token()
  1099. if err != nil {
  1100. return err
  1101. }
  1102. skuStr, ok := sku.(string)
  1103. if !ok {
  1104. return fmt.Errorf("failed to parse %s pricing from %s: expected SKU to be a string, got %T", termType, resp.Request.URL.String(), sku)
  1105. }
  1106. _, err = dec.Token() // opening "{"
  1107. if err != nil {
  1108. return err
  1109. }
  1110. _, err = dec.Token() // SKU.OfferTermCode key
  1111. if err != nil {
  1112. return err
  1113. }
  1114. offerTerm := &AWSOfferTerm{}
  1115. err = dec.Decode(&offerTerm)
  1116. if err != nil {
  1117. log.Errorf("Error decoding AWS Offer Term for SKU %s: %v", skuStr, err)
  1118. }
  1119. key, ok := skuToPricingKeyMap[skuStr]
  1120. if ok {
  1121. spotKey := key + ",preemptible"
  1122. aws.Pricing[key].OnDemand = offerTerm
  1123. if _, ok := aws.Pricing[spotKey]; ok {
  1124. aws.Pricing[spotKey].OnDemand = offerTerm
  1125. }
  1126. // Extract hourly cost from price dimensions
  1127. // Price dimension key format: <SKU>.<OfferTermCode>.<RateCode>
  1128. var cost string
  1129. if _, isMatch := OnDemandRateCodes[offerTerm.OfferTermCode]; isMatch {
  1130. // USD pricing path
  1131. priceDimensionKey := strings.Join([]string{skuStr, offerTerm.OfferTermCode, HourlyRateCode}, ".")
  1132. dimension, ok := offerTerm.PriceDimensions[priceDimensionKey]
  1133. if ok {
  1134. // Expected dimension found - use it directly
  1135. cost = dimension.PricePerUnit.USD
  1136. } else {
  1137. // Expected dimension missing - fallback. If there is only one
  1138. // dimension, use it even if the key doesn't match exactly
  1139. dimensionCount := len(offerTerm.PriceDimensions)
  1140. if dimensionCount == 1 {
  1141. for dimensionKey, backupDimension := range offerTerm.PriceDimensions {
  1142. cost = backupDimension.PricePerUnit.USD
  1143. log.DedupedWarningf(5, "using:%v for a price dimension instead of missing dimension: %s", offerTerm.PriceDimensions[dimensionKey], priceDimensionKey)
  1144. break
  1145. }
  1146. } else if dimensionCount == 0 {
  1147. log.DedupedWarningf(5, "populatePricing: no pricing dimension available for: %s.", priceDimensionKey)
  1148. } else {
  1149. log.DedupedWarningf(5, "populatePricing: no assumable pricing dimension available for: %s.", priceDimensionKey)
  1150. }
  1151. }
  1152. } else if _, isMatch := OnDemandRateCodesCn[offerTerm.OfferTermCode]; isMatch {
  1153. // CNY pricing path (China regions)
  1154. priceDimensionKey := strings.Join([]string{skuStr, offerTerm.OfferTermCode, HourlyRateCodeCn}, ".")
  1155. dimension, ok := offerTerm.PriceDimensions[priceDimensionKey]
  1156. if ok {
  1157. cost = dimension.PricePerUnit.CNY
  1158. } else {
  1159. dimensionCount := len(offerTerm.PriceDimensions)
  1160. if dimensionCount == 1 {
  1161. for dimensionKey, backupDimension := range offerTerm.PriceDimensions {
  1162. cost = backupDimension.PricePerUnit.CNY
  1163. log.DedupedWarningf(5, "using:%v for a price dimension instead of missing dimension: %s", offerTerm.PriceDimensions[dimensionKey], priceDimensionKey)
  1164. break
  1165. }
  1166. } else if dimensionCount == 0 {
  1167. log.DedupedWarningf(5, "populatePricing: no pricing dimension available for: %s.", priceDimensionKey)
  1168. } else {
  1169. log.DedupedWarningf(5, "populatePricing: no assumable pricing dimension available for: %s.", priceDimensionKey)
  1170. }
  1171. }
  1172. }
  1173. // Apply cost to the appropriate resource type
  1174. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  1175. // If the specific UsageType is the per IO cost used on io1 volumes
  1176. // we need to add the per IO cost to the io1 PV cost
  1177. // Add the per IO cost to the PV object for the io1 volume type
  1178. aws.Pricing[key].PV.CostPerIO = cost
  1179. } else if strings.Contains(key, "EBS:Volume") {
  1180. // EBS volumes: convert monthly cost to hourly (730 hours/month)
  1181. costFloat, err := strconv.ParseFloat(cost, 64)
  1182. if err != nil {
  1183. log.Debugf("Error parsing EBS volume cost for %s: %v", key, err)
  1184. // Preserve prior behavior: always leave a valid numeric
  1185. // string so downstream ParseFloat (e.g. findCostForDisk)
  1186. // doesn't fail on an empty value.
  1187. aws.Pricing[key].PV.Cost = "0"
  1188. } else {
  1189. hourlyPrice := costFloat / timeutil.HoursPerMonth
  1190. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  1191. }
  1192. } else if strings.Contains(key, "LoadBalancerUsage") {
  1193. // On an unparseable cost, rely on the default rather than
  1194. // discarding all pricing (mirrors the EBS handling above).
  1195. costFloat, err := strconv.ParseFloat(cost, 64)
  1196. if err != nil {
  1197. log.Debugf("Error parsing load balancer cost for %s: %v", key, err)
  1198. } else {
  1199. aws.Pricing[key].LoadBalancer.Cost = costFloat
  1200. }
  1201. }
  1202. }
  1203. _, err = dec.Token() // closing "}"
  1204. if err != nil {
  1205. return err
  1206. }
  1207. }
  1208. _, err = dec.Token() // closing "}"
  1209. if err != nil {
  1210. return err
  1211. }
  1212. }
  1213. }
  1214. }
  1215. return nil
  1216. }
  1217. func (aws *AWS) refreshSpotPricing(force bool) {
  1218. aws.SpotPricingLock.Lock()
  1219. defer aws.SpotPricingLock.Unlock()
  1220. now := time.Now().UTC()
  1221. updateTime := now.Add(-SpotRefreshDuration)
  1222. // Return if there was an update time set and an hour hasn't elapsed
  1223. if !force && aws.SpotPricingUpdatedAt != nil && aws.SpotPricingUpdatedAt.After(updateTime) {
  1224. return
  1225. }
  1226. sp, err := aws.parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion)
  1227. if err != nil {
  1228. log.Warnf("Skipping AWS spot data download: %s", err.Error())
  1229. aws.SpotPricingError = err
  1230. return
  1231. }
  1232. aws.SpotPricingError = nil
  1233. // update time last updated
  1234. aws.SpotPricingUpdatedAt = &now
  1235. aws.SpotPricingByInstanceID = sp
  1236. }
  1237. func (aws *AWS) initializeSpotPriceHistoryCache() (*SpotPriceHistoryCache, error) {
  1238. log.Info("Initializing AWS Spot Price History Manager")
  1239. // Get AWS access key for creating config
  1240. accessKey, err := aws.GetAWSAccessKey()
  1241. if err != nil {
  1242. return nil, fmt.Errorf("getting AWS access key for spot price history: %w", err)
  1243. }
  1244. // Use the cluster region to create the initial AWS config and credentials.
  1245. // The SpotPriceHistoryFetcher itself can query multiple regions by creating
  1246. // region-specific EC2 clients as needed.
  1247. if aws.ClusterRegion == "" {
  1248. return nil, fmt.Errorf("no cluster region configured")
  1249. }
  1250. // Create config for the cluster region
  1251. awsConfig, err := accessKey.CreateConfig(aws.ClusterRegion)
  1252. if err != nil {
  1253. return nil, fmt.Errorf("creating AWS config for spot price history: %w", err)
  1254. }
  1255. return NewSpotPriceHistoryCache(NewAWSSpotPriceHistoryFetcher(awsConfig)), nil
  1256. }
  1257. func (aws *AWS) spotPricingFromHistory(k models.Key) (*SpotPriceHistoryEntry, bool) {
  1258. if aws.SpotPriceHistoryCache == nil {
  1259. return nil, false
  1260. }
  1261. // Extract region, instance type, and availability zone from the key
  1262. awsKey, ok := k.(*awsKey)
  1263. if !ok {
  1264. log.DedupedWarningf(10, "Failed to cast key to awsKey for spot price history lookup: %s", k.ID())
  1265. return nil, false
  1266. }
  1267. region, regionOk := util.GetRegion(awsKey.Labels)
  1268. instanceType, instanceTypeOk := util.GetInstanceType(awsKey.Labels)
  1269. availabilityZone, availabilityZoneOk := util.GetZone(awsKey.Labels)
  1270. // Skip lookup if any required information is missing
  1271. if !regionOk || !instanceTypeOk || !availabilityZoneOk {
  1272. log.DedupedWarningf(10, "Missing required info for spot price history lookup (region: %s, instanceType: %s, zone: %s): %s", region, instanceType, availabilityZone, k.ID())
  1273. return nil, false
  1274. }
  1275. price, err := aws.SpotPriceHistoryCache.GetSpotPrice(region, instanceType, availabilityZone)
  1276. if err != nil {
  1277. log.Debugf("Failed to get spot price history for instance %s: %s", k.ID(), err.Error())
  1278. return nil, false
  1279. }
  1280. return price, true
  1281. }
  1282. // Stubbed NetworkPricing for AWS. Pull directly from aws.json for now
  1283. func (aws *AWS) NetworkPricing() (*models.Network, error) {
  1284. cpricing, err := aws.Config.GetCustomPricingData()
  1285. if err != nil {
  1286. return nil, err
  1287. }
  1288. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1289. if err != nil {
  1290. return nil, err
  1291. }
  1292. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1293. if err != nil {
  1294. return nil, err
  1295. }
  1296. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1297. if err != nil {
  1298. return nil, err
  1299. }
  1300. nge, err := strconv.ParseFloat(cpricing.NatGatewayEgress, 64)
  1301. if err != nil {
  1302. return nil, err
  1303. }
  1304. ngi, err := strconv.ParseFloat(cpricing.NatGatewayIngress, 64)
  1305. if err != nil {
  1306. return nil, err
  1307. }
  1308. return &models.Network{
  1309. ZoneNetworkEgressCost: znec,
  1310. RegionNetworkEgressCost: rnec,
  1311. InternetNetworkEgressCost: inec,
  1312. NatGatewayEgressCost: nge,
  1313. NatGatewayIngressCost: ngi,
  1314. }, nil
  1315. }
  1316. func (aws *AWS) LoadBalancerPricing() (*models.LoadBalancer, error) {
  1317. // TODO: determine key based on function arguments
  1318. // this is something that should be changed in the Provider interface
  1319. key := aws.ClusterRegion + ",LoadBalancerUsage"
  1320. // set default price
  1321. hourlyCost := 0.025
  1322. // use price index when available
  1323. if terms, ok := aws.Pricing[key]; ok {
  1324. hourlyCost = terms.LoadBalancer.Cost
  1325. }
  1326. return &models.LoadBalancer{
  1327. Cost: hourlyCost,
  1328. }, nil
  1329. }
  1330. // AllNodePricing returns all the billing data fetched.
  1331. func (aws *AWS) AllNodePricing() (interface{}, error) {
  1332. aws.DownloadPricingDataLock.RLock()
  1333. defer aws.DownloadPricingDataLock.RUnlock()
  1334. return aws.Pricing, nil
  1335. }
  1336. func (aws *AWS) spotPricing(instanceID string) (*spotInfo, bool) {
  1337. aws.SpotPricingLock.RLock()
  1338. defer aws.SpotPricingLock.RUnlock()
  1339. info, ok := aws.SpotPricingByInstanceID[instanceID]
  1340. return info, ok
  1341. }
  1342. func (aws *AWS) reservedInstancePricing(instanceID string) (*RIData, bool) {
  1343. aws.RIDataLock.RLock()
  1344. defer aws.RIDataLock.RUnlock()
  1345. data, ok := aws.RIPricingByInstanceID[instanceID]
  1346. return data, ok
  1347. }
  1348. func (aws *AWS) savingsPlanPricing(instanceID string) (*SavingsPlanData, bool) {
  1349. aws.SavingsPlanDataLock.RLock()
  1350. defer aws.SavingsPlanDataLock.RUnlock()
  1351. data, ok := aws.SavingsPlanDataByInstanceID[instanceID]
  1352. return data, ok
  1353. }
  1354. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k models.Key) (*models.Node, models.PricingMetadata, error) {
  1355. key := k.Features()
  1356. meta := models.PricingMetadata{}
  1357. var cost string
  1358. publicPricingFound := true
  1359. c, ok := terms.OnDemand.PriceDimensions[strings.Join([]string{terms.Sku, terms.OnDemand.OfferTermCode, HourlyRateCode}, ".")]
  1360. if ok {
  1361. cost = c.PricePerUnit.USD
  1362. } else {
  1363. // Check for Chinese pricing
  1364. c, ok = terms.OnDemand.PriceDimensions[strings.Join([]string{terms.Sku, terms.OnDemand.OfferTermCode, HourlyRateCodeCn}, ".")]
  1365. if ok {
  1366. cost = c.PricePerUnit.CNY
  1367. } else {
  1368. publicPricingFound = false
  1369. }
  1370. }
  1371. if spotInfo, ok := aws.spotPricing(k.ID()); ok {
  1372. var spotcost string
  1373. log.DedupedInfof(5, "Looking up spot data from feed for node %s", k.ID())
  1374. arr := strings.Split(spotInfo.Charge, " ")
  1375. if len(arr) == 2 {
  1376. spotcost = arr[0]
  1377. } else {
  1378. log.Infof("Spot data for node %s is missing", k.ID())
  1379. }
  1380. return &models.Node{
  1381. Cost: spotcost,
  1382. VCPU: terms.VCpu,
  1383. RAM: terms.Memory,
  1384. GPU: terms.GPU,
  1385. Storage: terms.Storage,
  1386. BaseCPUPrice: aws.BaseCPUPrice,
  1387. BaseRAMPrice: aws.BaseRAMPrice,
  1388. BaseGPUPrice: aws.BaseGPUPrice,
  1389. UsageType: PreemptibleType,
  1390. }, meta, nil
  1391. } else if aws.isPreemptible(key) { // Preemptible but we don't have any data in the pricing report.
  1392. log.Debugf("Node %s marked preemptible but no spot feed data available; falling back to other pricing sources", k.ID())
  1393. // Try to get spot pricing from DescribeSpotPriceHistory API
  1394. if historyEntry, ok := aws.spotPricingFromHistory(k); ok {
  1395. log.DedupedInfof(5, "Using spot price history data for node %s: $%f", k.ID(), historyEntry.SpotPrice)
  1396. spotHistoryCost := fmt.Sprintf("%f", historyEntry.SpotPrice)
  1397. meta.Source = SpotPriceHistorySource
  1398. return &models.Node{
  1399. Cost: spotHistoryCost,
  1400. VCPU: terms.VCpu,
  1401. RAM: terms.Memory,
  1402. GPU: terms.GPU,
  1403. Storage: terms.Storage,
  1404. BaseCPUPrice: aws.BaseCPUPrice,
  1405. BaseRAMPrice: aws.BaseRAMPrice,
  1406. BaseGPUPrice: aws.BaseGPUPrice,
  1407. UsageType: PreemptibleType,
  1408. }, meta, nil
  1409. }
  1410. if publicPricingFound {
  1411. // return public price if found
  1412. log.Debugf("No spot price history available for %s, falling back to on-demand pricing", k.ID())
  1413. return &models.Node{
  1414. Cost: cost,
  1415. VCPU: terms.VCpu,
  1416. RAM: terms.Memory,
  1417. GPU: terms.GPU,
  1418. Storage: terms.Storage,
  1419. BaseCPUPrice: aws.BaseCPUPrice,
  1420. BaseRAMPrice: aws.BaseRAMPrice,
  1421. BaseGPUPrice: aws.BaseGPUPrice,
  1422. UsageType: PreemptibleType,
  1423. }, meta, nil
  1424. } else {
  1425. // return defaults if public pricing not found
  1426. log.DedupedWarningf(5, "Could not find Node %s's public pricing info, using default configured spot prices instead", k.ID())
  1427. return &models.Node{
  1428. VCPU: terms.VCpu,
  1429. VCPUCost: aws.BaseSpotCPUPrice,
  1430. RAMCost: aws.BaseSpotRAMPrice,
  1431. RAM: terms.Memory,
  1432. GPU: terms.GPU,
  1433. Storage: terms.Storage,
  1434. BaseCPUPrice: aws.BaseCPUPrice,
  1435. BaseRAMPrice: aws.BaseRAMPrice,
  1436. BaseGPUPrice: aws.BaseGPUPrice,
  1437. UsageType: PreemptibleType,
  1438. }, meta, nil
  1439. }
  1440. } else if sp, ok := aws.savingsPlanPricing(k.ID()); ok {
  1441. strCost := fmt.Sprintf("%f", sp.EffectiveCost)
  1442. return &models.Node{
  1443. Cost: strCost,
  1444. VCPU: terms.VCpu,
  1445. RAM: terms.Memory,
  1446. GPU: terms.GPU,
  1447. Storage: terms.Storage,
  1448. BaseCPUPrice: aws.BaseCPUPrice,
  1449. BaseRAMPrice: aws.BaseRAMPrice,
  1450. BaseGPUPrice: aws.BaseGPUPrice,
  1451. UsageType: usageType,
  1452. }, meta, nil
  1453. } else if ri, ok := aws.reservedInstancePricing(k.ID()); ok {
  1454. strCost := fmt.Sprintf("%f", ri.EffectiveCost)
  1455. return &models.Node{
  1456. Cost: strCost,
  1457. VCPU: terms.VCpu,
  1458. RAM: terms.Memory,
  1459. GPU: terms.GPU,
  1460. Storage: terms.Storage,
  1461. BaseCPUPrice: aws.BaseCPUPrice,
  1462. BaseRAMPrice: aws.BaseRAMPrice,
  1463. BaseGPUPrice: aws.BaseGPUPrice,
  1464. UsageType: usageType,
  1465. }, meta, nil
  1466. }
  1467. // Throw error if public price is not found
  1468. if !publicPricingFound {
  1469. return nil, meta, fmt.Errorf("for node \"%s\", cannot find the following key in OnDemand pricing data \"%s\"", k.ID(), k.Features())
  1470. }
  1471. return &models.Node{
  1472. Cost: cost,
  1473. VCPU: terms.VCpu,
  1474. RAM: terms.Memory,
  1475. GPU: terms.GPU,
  1476. Storage: terms.Storage,
  1477. BaseCPUPrice: aws.BaseCPUPrice,
  1478. BaseRAMPrice: aws.BaseRAMPrice,
  1479. BaseGPUPrice: aws.BaseGPUPrice,
  1480. UsageType: usageType,
  1481. }, meta, nil
  1482. }
  1483. func (aws *AWS) getFargatePod(awsKey *awsKey) (*clustercache.Pod, bool) {
  1484. pods := aws.Clientset.GetAllPods()
  1485. for _, pod := range pods {
  1486. if pod.Spec.NodeName == awsKey.Name {
  1487. return pod, true
  1488. }
  1489. }
  1490. return nil, false
  1491. }
  1492. const (
  1493. nodeOSLabel = "kubernetes.io/os"
  1494. nodeArchLabel = "kubernetes.io/arch"
  1495. fargatePodCapacityAnnotation = "CapacityProvisioned"
  1496. )
  1497. // e.g. "0.25vCPU 0.5GB"
  1498. var fargatePodCapacityRegex = regexp.MustCompile("^([0-9.]+)vCPU ([0-9.]+)GB$")
  1499. func (aws *AWS) createFargateNode(awsKey *awsKey, usageType string) (*models.Node, models.PricingMetadata, error) {
  1500. if aws.FargatePricing == nil {
  1501. return nil, models.PricingMetadata{}, fmt.Errorf("fargate pricing not initialized")
  1502. }
  1503. pod, ok := aws.getFargatePod(awsKey)
  1504. if !ok {
  1505. return nil, models.PricingMetadata{}, fmt.Errorf("could not find pod for fargate node %s", awsKey.Name)
  1506. }
  1507. capacity := pod.Annotations[fargatePodCapacityAnnotation]
  1508. match := fargatePodCapacityRegex.FindStringSubmatch(capacity)
  1509. if len(match) == 0 {
  1510. return nil, models.PricingMetadata{}, fmt.Errorf("could not parse pod capacity for fargate node %s", awsKey.Name)
  1511. }
  1512. vCPU, err := strconv.ParseFloat(match[1], 64)
  1513. if err != nil {
  1514. return nil, models.PricingMetadata{}, fmt.Errorf("could not parse vCPU capacity for fargate node %s: %v", awsKey.Name, err)
  1515. }
  1516. memory, err := strconv.ParseFloat(match[2], 64)
  1517. if err != nil {
  1518. return nil, models.PricingMetadata{}, fmt.Errorf("could not parse memory capacity for fargate node %s: %v", awsKey.Name, err)
  1519. }
  1520. region, ok := util.GetRegion(awsKey.Labels)
  1521. if !ok {
  1522. return nil, models.PricingMetadata{}, fmt.Errorf("could not get region for fargate node %s", awsKey.Name)
  1523. }
  1524. nodeOS := awsKey.Labels[nodeOSLabel]
  1525. nodeArch := awsKey.Labels[nodeArchLabel]
  1526. hourlyCPU, hourlyRAM, err := aws.FargatePricing.GetHourlyPricing(region, nodeOS, nodeArch)
  1527. if err != nil {
  1528. return nil, models.PricingMetadata{}, fmt.Errorf("could not get hourly pricing for fargate node %s: %v", awsKey.Name, err)
  1529. }
  1530. cost := hourlyCPU*vCPU + hourlyRAM*memory
  1531. return &models.Node{
  1532. Cost: strconv.FormatFloat(cost, 'f', -1, 64),
  1533. VCPU: strconv.FormatFloat(vCPU, 'f', -1, 64),
  1534. RAM: strconv.FormatFloat(memory, 'f', -1, 64),
  1535. RAMBytes: strconv.FormatFloat(memory*1024*1024*1024, 'f', -1, 64),
  1536. VCPUCost: strconv.FormatFloat(hourlyCPU, 'f', -1, 64),
  1537. RAMCost: strconv.FormatFloat(hourlyRAM, 'f', -1, 64),
  1538. BaseCPUPrice: aws.BaseCPUPrice,
  1539. BaseRAMPrice: aws.BaseRAMPrice,
  1540. BaseGPUPrice: aws.BaseGPUPrice,
  1541. UsageType: usageType,
  1542. }, models.PricingMetadata{}, nil
  1543. }
  1544. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  1545. func (aws *AWS) NodePricing(k models.Key) (*models.Node, models.PricingMetadata, error) {
  1546. aws.DownloadPricingDataLock.RLock()
  1547. defer aws.DownloadPricingDataLock.RUnlock()
  1548. key := k.Features()
  1549. usageType := "ondemand"
  1550. if aws.isPreemptible(key) {
  1551. usageType = PreemptibleType
  1552. }
  1553. meta := models.PricingMetadata{}
  1554. terms, ok := aws.Pricing[key]
  1555. if termsStr, err := json.Marshal(terms); err == nil {
  1556. log.Debugf("NodePricing: for key \"%s\" found the following OnDemand data: %s", key, string(termsStr))
  1557. }
  1558. if ok {
  1559. return aws.createNode(terms, usageType, k)
  1560. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  1561. aws.DownloadPricingDataLock.RUnlock()
  1562. err := aws.DownloadPricingData()
  1563. aws.DownloadPricingDataLock.RLock()
  1564. if err != nil {
  1565. return &models.Node{
  1566. Cost: aws.BaseCPUPrice,
  1567. BaseCPUPrice: aws.BaseCPUPrice,
  1568. BaseRAMPrice: aws.BaseRAMPrice,
  1569. BaseGPUPrice: aws.BaseGPUPrice,
  1570. UsageType: usageType,
  1571. UsesBaseCPUPrice: true,
  1572. }, meta, err
  1573. }
  1574. terms, termsOk := aws.Pricing[key]
  1575. if !termsOk {
  1576. return &models.Node{
  1577. Cost: aws.BaseCPUPrice,
  1578. BaseCPUPrice: aws.BaseCPUPrice,
  1579. BaseRAMPrice: aws.BaseRAMPrice,
  1580. BaseGPUPrice: aws.BaseGPUPrice,
  1581. UsageType: usageType,
  1582. UsesBaseCPUPrice: true,
  1583. }, meta, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  1584. }
  1585. return aws.createNode(terms, usageType, k)
  1586. } else if awsKey, ok := k.(*awsKey); ok && awsKey.isFargateNode() {
  1587. // Since Fargate pricing is listed at AmazonECS and is different from AmazonEC2, we handle it separately here
  1588. return aws.createFargateNode(awsKey, usageType)
  1589. } else { // Fall back to base pricing if we can't find the key. Base pricing is handled at the costmodel level.
  1590. // we seem to have an issue where this error gets thrown during app start.
  1591. // somehow the ValidPricingKeys map is being accessed before all the pricing data has been downloaded
  1592. return nil, meta, fmt.Errorf("Invalid Pricing Key \"%s\"", key)
  1593. }
  1594. }
  1595. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  1596. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  1597. c, err := awsProvider.GetConfig()
  1598. if err != nil {
  1599. return nil, err
  1600. }
  1601. const defaultClusterName = "AWS Cluster #1"
  1602. // Determine cluster name
  1603. clusterName := c.ClusterName
  1604. if clusterName == "" {
  1605. if clusterName = env.GetAWSClusterID(); clusterName != "" {
  1606. log.DedupedWarningf(3, "%s will be deprecated in a future release. Use %s instead", env.AWSClusterIDEnvVar, coreenv.ClusterIDEnvVar)
  1607. } else if clusterName = coreenv.GetClusterID(); clusterName != "" {
  1608. log.DedupedDebugf(3, "Setting cluster name to %s from %s", clusterName, coreenv.ClusterIDEnvVar)
  1609. } else {
  1610. clusterName = defaultClusterName
  1611. log.DedupedWarningf(3, "Unable to detect cluster name - using default of %s. Set it through the configmap or the %s env var", defaultClusterName, coreenv.ClusterIDEnvVar)
  1612. }
  1613. }
  1614. // this value requires configuration but is unavailable else where
  1615. clusterAccountID := c.ClusterAccountID
  1616. // Use AthenaProjectID if Cluster Account is not set to support older configs
  1617. if clusterAccountID == "" {
  1618. clusterAccountID = c.AthenaProjectID
  1619. }
  1620. m := make(map[string]string)
  1621. m["name"] = clusterName
  1622. m["provider"] = opencost.AWSProvider
  1623. m["account"] = clusterAccountID
  1624. m["region"] = awsProvider.ClusterRegion
  1625. m["id"] = coreenv.GetClusterID()
  1626. m["remoteReadEnabled"] = strconv.FormatBool(env.IsRemoteEnabled())
  1627. m["provisioner"] = awsProvider.clusterProvisioner
  1628. return m, nil
  1629. }
  1630. // updates the authentication to the latest values (via config or secret)
  1631. func (aws *AWS) ConfigureAuth() error {
  1632. c, err := aws.Config.GetCustomPricingData()
  1633. if err != nil {
  1634. log.Errorf("Error downloading default pricing data: %s", err.Error())
  1635. }
  1636. return aws.ConfigureAuthWith(c)
  1637. }
  1638. // updates the authentication to the latest values (via config or secret)
  1639. func (aws *AWS) ConfigureAuthWith(config *models.CustomPricing) error {
  1640. accessKeyID, accessKeySecret := aws.getAWSAuth(false, config)
  1641. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1642. err := coreenv.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1643. if err != nil {
  1644. return err
  1645. }
  1646. err = coreenv.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1647. if err != nil {
  1648. return err
  1649. }
  1650. }
  1651. return nil
  1652. }
  1653. // Gets the aws key id and secret
  1654. func (aws *AWS) getAWSAuth(forceReload bool, cp *models.CustomPricing) (string, string) {
  1655. // 1. Check config values first (set from frontend UI)
  1656. if cp.AwsServiceKeyName != "" && cp.AwsServiceKeySecret != "" {
  1657. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1658. Message: "AWS ServiceKey exists",
  1659. Status: true,
  1660. })
  1661. return cp.AwsServiceKeyName, cp.AwsServiceKeySecret
  1662. }
  1663. // 2. Check for secret
  1664. s, _ := aws.loadAWSAuthSecret(forceReload)
  1665. if s != nil && s.AccessKeyID != "" && s.SecretAccessKey != "" {
  1666. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1667. Message: "AWS ServiceKey exists",
  1668. Status: true,
  1669. })
  1670. return s.AccessKeyID, s.SecretAccessKey
  1671. }
  1672. // 3. Fall back to env vars
  1673. if env.GetAWSAccessKeyID() == "" || env.GetAWSAccessKeySecret() == "" {
  1674. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1675. Message: "AWS ServiceKey exists",
  1676. Status: false,
  1677. })
  1678. } else {
  1679. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1680. Message: "AWS ServiceKey exists",
  1681. Status: true,
  1682. })
  1683. }
  1684. return env.GetAWSAccessKeyID(), env.GetAWSAccessKeySecret()
  1685. }
  1686. // Load once and cache the result (even on failure). This is an install time secret, so
  1687. // we don't expect the secret to change. If it does, however, we can force reload using
  1688. // the input parameter.
  1689. func (aws *AWS) loadAWSAuthSecret(force bool) (*AWSAccessKey, error) {
  1690. if !force && loadedAWSSecret {
  1691. return awsSecret, nil
  1692. }
  1693. loadedAWSSecret = true
  1694. exists, err := fileutil.FileExists(models.AuthSecretPath)
  1695. if !exists || err != nil {
  1696. return nil, fmt.Errorf("Failed to locate service account file: %s", models.AuthSecretPath)
  1697. }
  1698. result, err := os.ReadFile(models.AuthSecretPath)
  1699. if err != nil {
  1700. return nil, err
  1701. }
  1702. var ak AWSAccessKey
  1703. err = json.Unmarshal(result, &ak)
  1704. if err != nil {
  1705. return nil, err
  1706. }
  1707. awsSecret = &ak
  1708. return awsSecret, nil
  1709. }
  1710. func (aws *AWS) getAddressesForRegion(ctx context.Context, region string) (*ec2.DescribeAddressesOutput, error) {
  1711. aak, err := aws.GetAWSAccessKey()
  1712. if err != nil {
  1713. return nil, err
  1714. }
  1715. cfg, err := aak.CreateConfig(region)
  1716. if err != nil {
  1717. return nil, err
  1718. }
  1719. cli := ec2.NewFromConfig(cfg)
  1720. return cli.DescribeAddresses(ctx, &ec2.DescribeAddressesInput{})
  1721. }
  1722. func (aws *AWS) getAllAddresses() ([]*ec2Types.Address, error) {
  1723. aws.ConfigureAuth() // load authentication data into env vars
  1724. regions := aws.Regions()
  1725. addressCh := make(chan *ec2.DescribeAddressesOutput, len(regions))
  1726. errorCh := make(chan error, len(regions))
  1727. var wg sync.WaitGroup
  1728. wg.Add(len(regions))
  1729. // Get volumes from each AWS region
  1730. for _, r := range regions {
  1731. region := r // make a copy of r to avoid capturing loop variable
  1732. // Fetch IP address response and send results and errors to their
  1733. // respective channels
  1734. go func() {
  1735. defer wg.Done()
  1736. defer errs.HandlePanic()
  1737. // Query for first page of volume results
  1738. resp, err := aws.getAddressesForRegion(context.TODO(), region)
  1739. if err != nil {
  1740. var awsErr smithy.APIError
  1741. if errors.As(err, &awsErr) {
  1742. switch awsErr.ErrorCode() {
  1743. case "AuthFailure", "InvalidClientTokenId", "UnauthorizedOperation":
  1744. log.DedupedInfof(5, "Unable to get addresses for region %s due to AWS permissions, error message: %s", region, awsErr.ErrorMessage())
  1745. return
  1746. default:
  1747. errorCh <- err
  1748. return
  1749. }
  1750. } else {
  1751. errorCh <- err
  1752. return
  1753. }
  1754. }
  1755. addressCh <- resp
  1756. }()
  1757. }
  1758. // Close the result channels after everything has been sent
  1759. go func() {
  1760. defer errs.HandlePanic()
  1761. wg.Wait()
  1762. close(errorCh)
  1763. close(addressCh)
  1764. }()
  1765. var addresses []*ec2Types.Address
  1766. for adds := range addressCh {
  1767. for _, add := range adds.Addresses {
  1768. a := add // duplicate to avoid pointer to iterator
  1769. addresses = append(addresses, &a)
  1770. }
  1771. }
  1772. var errs []error
  1773. for err := range errorCh {
  1774. log.DedupedWarningf(5, "unable to get addresses: %s", err)
  1775. errs = append(errs, err)
  1776. }
  1777. // Return error if no addresses are returned
  1778. if len(errs) > 0 && len(addresses) == 0 {
  1779. return nil, fmt.Errorf("%d error(s) retrieving addresses: %v", len(errs), errs)
  1780. }
  1781. return addresses, nil
  1782. }
  1783. // GetAddresses retrieves EC2 addresses
  1784. func (aws *AWS) GetAddresses() ([]byte, error) {
  1785. addresses, err := aws.getAllAddresses()
  1786. if err != nil {
  1787. return nil, err
  1788. }
  1789. // Format the response this way to match the JSON-encoded formatting of a single response
  1790. // from DescribeAddresss, so that consumers can always expect AWS disk responses to have
  1791. // a "Addresss" key at the top level.
  1792. return json.Marshal(map[string][]*ec2Types.Address{
  1793. "Addresses": addresses,
  1794. })
  1795. }
  1796. func (aws *AWS) isAddressOrphaned(address *ec2Types.Address) bool {
  1797. if address.AssociationId != nil {
  1798. return false
  1799. }
  1800. return true
  1801. }
  1802. func (aws *AWS) getDisksForRegion(ctx context.Context, region string, maxResults int32, nextToken *string) (*ec2.DescribeVolumesOutput, error) {
  1803. aak, err := aws.GetAWSAccessKey()
  1804. if err != nil {
  1805. return nil, err
  1806. }
  1807. cfg, err := aak.CreateConfig(region)
  1808. if err != nil {
  1809. return nil, err
  1810. }
  1811. cli := ec2.NewFromConfig(cfg)
  1812. return cli.DescribeVolumes(ctx, &ec2.DescribeVolumesInput{
  1813. MaxResults: &maxResults,
  1814. NextToken: nextToken,
  1815. })
  1816. }
  1817. func (aws *AWS) getAllDisks() ([]*ec2Types.Volume, error) {
  1818. aws.ConfigureAuth() // load authentication data into env vars
  1819. regions := aws.Regions()
  1820. volumeCh := make(chan *ec2.DescribeVolumesOutput, len(regions))
  1821. errorCh := make(chan error, len(regions))
  1822. var wg sync.WaitGroup
  1823. wg.Add(len(regions))
  1824. // Get volumes from each AWS region
  1825. for _, r := range regions {
  1826. // Fetch volume response and send results and errors to their
  1827. // respective channels
  1828. go func(region string) {
  1829. defer wg.Done()
  1830. defer errs.HandlePanic()
  1831. // Query for first page of volume results
  1832. resp, err := aws.getDisksForRegion(context.TODO(), region, 1000, nil)
  1833. if err != nil {
  1834. var awsErr smithy.APIError
  1835. if errors.As(err, &awsErr) {
  1836. switch awsErr.ErrorCode() {
  1837. case "AuthFailure", "InvalidClientTokenId", "UnauthorizedOperation":
  1838. log.DedupedInfof(5, "Unable to get disks for region %s due to AWS permissions, error message: %s", region, awsErr.ErrorMessage())
  1839. return
  1840. default:
  1841. errorCh <- err
  1842. return
  1843. }
  1844. } else {
  1845. errorCh <- err
  1846. return
  1847. }
  1848. }
  1849. volumeCh <- resp
  1850. // A NextToken indicates more pages of results. Keep querying
  1851. // until all pages are retrieved.
  1852. for resp.NextToken != nil {
  1853. resp, err = aws.getDisksForRegion(context.TODO(), region, 100, resp.NextToken)
  1854. if err != nil {
  1855. errorCh <- err
  1856. return
  1857. }
  1858. volumeCh <- resp
  1859. }
  1860. }(r)
  1861. }
  1862. // Close the result channels after everything has been sent
  1863. go func() {
  1864. defer errs.HandlePanic()
  1865. wg.Wait()
  1866. close(errorCh)
  1867. close(volumeCh)
  1868. }()
  1869. var volumes []*ec2Types.Volume
  1870. for vols := range volumeCh {
  1871. for _, vol := range vols.Volumes {
  1872. v := vol // duplicate to avoid pointer to iterator
  1873. volumes = append(volumes, &v)
  1874. }
  1875. }
  1876. var errs []error
  1877. for err := range errorCh {
  1878. log.DedupedWarningf(5, "unable to get disks: %s", err)
  1879. errs = append(errs, err)
  1880. }
  1881. // Return error if no volumes are returned
  1882. if len(errs) > 0 && len(volumes) == 0 {
  1883. return nil, fmt.Errorf("%d error(s) retrieving volumes: %v", len(errs), errs)
  1884. }
  1885. return volumes, nil
  1886. }
  1887. // GetDisks returns the AWS disks backing PVs. Useful because sometimes k8s will not clean up PVs correctly. Requires a json config in /var/configs with key region.
  1888. func (aws *AWS) GetDisks() ([]byte, error) {
  1889. volumes, err := aws.getAllDisks()
  1890. if err != nil {
  1891. return nil, err
  1892. }
  1893. // Format the response this way to match the JSON-encoded formatting of a single response
  1894. // from DescribeVolumes, so that consumers can always expect AWS disk responses to have
  1895. // a "Volumes" key at the top level.
  1896. return json.Marshal(map[string][]*ec2Types.Volume{
  1897. "Volumes": volumes,
  1898. })
  1899. }
  1900. func (aws *AWS) isDiskOrphaned(vol *ec2Types.Volume) bool {
  1901. // Do not consider volume orphaned if in use
  1902. if vol.State == InUseState {
  1903. return false
  1904. }
  1905. // Do not consider volume orphaned if volume is attached to any attachments
  1906. if len(vol.Attachments) != 0 {
  1907. for _, attachment := range vol.Attachments {
  1908. if attachment.State == AttachedState {
  1909. return false
  1910. }
  1911. }
  1912. }
  1913. return true
  1914. }
  1915. func (aws *AWS) GetOrphanedResources() ([]models.OrphanedResource, error) {
  1916. volumes, volumesErr := aws.getAllDisks()
  1917. addresses, addressesErr := aws.getAllAddresses()
  1918. // If we have any orphaned resources - prioritize returning them over returning errors
  1919. if len(addresses) == 0 && len(volumes) == 0 {
  1920. if volumesErr != nil {
  1921. return nil, volumesErr
  1922. }
  1923. if addressesErr != nil {
  1924. return nil, addressesErr
  1925. }
  1926. }
  1927. var orphanedResources []models.OrphanedResource
  1928. for _, volume := range volumes {
  1929. if aws.isDiskOrphaned(volume) {
  1930. cost, err := aws.findCostForDisk(volume)
  1931. if err != nil {
  1932. return nil, err
  1933. }
  1934. var volumeSize int64
  1935. if volume.Size != nil {
  1936. volumeSize = int64(*volume.Size)
  1937. }
  1938. // This is turning us-east-1a into us-east-1
  1939. var zone string
  1940. if volume.AvailabilityZone != nil {
  1941. zone = *volume.AvailabilityZone
  1942. }
  1943. var region, url string
  1944. region = parseRegionFromAZ(zone)
  1945. if region != "" {
  1946. url = "https://console.aws.amazon.com/ec2/home?region=" + region + "#Volumes:sort=desc:createTime"
  1947. } else {
  1948. url = "https://console.aws.amazon.com/ec2/home?#Volumes:sort=desc:createTime"
  1949. }
  1950. // output tags as desc
  1951. tags := map[string]string{}
  1952. for _, tag := range volume.Tags {
  1953. tags[*tag.Key] = *tag.Value
  1954. }
  1955. or := models.OrphanedResource{
  1956. Kind: "disk",
  1957. Region: zone,
  1958. Size: &volumeSize,
  1959. DiskName: *volume.VolumeId,
  1960. Url: url,
  1961. MonthlyCost: cost,
  1962. Description: tags,
  1963. }
  1964. orphanedResources = append(orphanedResources, or)
  1965. }
  1966. }
  1967. for _, address := range addresses {
  1968. if aws.isAddressOrphaned(address) {
  1969. cost := AWSHourlyPublicIPCost * timeutil.HoursPerMonth
  1970. desc := map[string]string{}
  1971. for _, tag := range address.Tags {
  1972. if tag.Key == nil {
  1973. continue
  1974. }
  1975. if tag.Value == nil {
  1976. desc[*tag.Key] = ""
  1977. } else {
  1978. desc[*tag.Key] = *tag.Value
  1979. }
  1980. }
  1981. or := models.OrphanedResource{
  1982. Kind: "address",
  1983. Address: *address.PublicIp,
  1984. Description: desc,
  1985. Url: "http://console.aws.amazon.com/ec2/home?#Addresses",
  1986. MonthlyCost: &cost,
  1987. }
  1988. orphanedResources = append(orphanedResources, or)
  1989. }
  1990. }
  1991. return orphanedResources, nil
  1992. }
  1993. func (aws *AWS) findCostForDisk(disk *ec2Types.Volume) (*float64, error) {
  1994. if disk.AvailabilityZone == nil {
  1995. return nil, fmt.Errorf("nil AvailabilityZone")
  1996. }
  1997. if disk.Size == nil {
  1998. return nil, fmt.Errorf("nil disk size")
  1999. }
  2000. class := volTypes[string(disk.VolumeType)]
  2001. region := parseRegionFromAZ(*disk.AvailabilityZone)
  2002. key := region + "," + class
  2003. _, ok := aws.Pricing[key]
  2004. if region == "" || !ok {
  2005. // Fallback to ClusterRegion
  2006. key = aws.ClusterRegion + "," + class
  2007. }
  2008. pricing, ok := aws.Pricing[key]
  2009. if !ok {
  2010. return nil, fmt.Errorf("no pricing data for key '%s'", key)
  2011. }
  2012. if pricing == nil {
  2013. return nil, fmt.Errorf("nil pricing data for key '%s'", key)
  2014. }
  2015. if pricing.PV == nil {
  2016. return nil, fmt.Errorf("pricing for key '%s' has nil PV", key)
  2017. }
  2018. priceStr := pricing.PV.Cost
  2019. price, err := strconv.ParseFloat(priceStr, 64)
  2020. if err != nil {
  2021. return nil, err
  2022. }
  2023. cost := price * timeutil.HoursPerMonth * float64(*disk.Size)
  2024. return &cost, nil
  2025. }
  2026. // QueryAthenaPaginated executes athena query and processes results.
  2027. func (aws *AWS) QueryAthenaPaginated(ctx context.Context, query string, fn func(*athena.GetQueryResultsOutput) bool) error {
  2028. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  2029. if err != nil {
  2030. return err
  2031. }
  2032. if awsAthenaInfo.AthenaDatabase == "" || awsAthenaInfo.AthenaTable == "" || awsAthenaInfo.AthenaRegion == "" ||
  2033. awsAthenaInfo.AthenaBucketName == "" || awsAthenaInfo.AccountID == "" {
  2034. return fmt.Errorf("QueryAthenaPaginated: athena configuration incomplete")
  2035. }
  2036. queryExecutionCtx := &athenaTypes.QueryExecutionContext{
  2037. Database: awsSDK.String(awsAthenaInfo.AthenaDatabase),
  2038. }
  2039. if awsAthenaInfo.AthenaCatalog != "" {
  2040. queryExecutionCtx.Catalog = awsSDK.String(awsAthenaInfo.AthenaCatalog)
  2041. }
  2042. resultConfiguration := &athenaTypes.ResultConfiguration{
  2043. OutputLocation: awsSDK.String(awsAthenaInfo.AthenaBucketName),
  2044. }
  2045. startQueryExecutionInput := &athena.StartQueryExecutionInput{
  2046. QueryString: awsSDK.String(query),
  2047. QueryExecutionContext: queryExecutionCtx,
  2048. ResultConfiguration: resultConfiguration,
  2049. }
  2050. // Only set if there is a value, the default input is nil which defaults to the 'primary' workgroup
  2051. if awsAthenaInfo.AthenaWorkgroup != "" {
  2052. startQueryExecutionInput.WorkGroup = awsSDK.String(awsAthenaInfo.AthenaWorkgroup)
  2053. }
  2054. // Create Athena Client
  2055. cfg, err := awsAthenaInfo.CreateConfig()
  2056. if err != nil {
  2057. log.Errorf("Could not retrieve Athena Configuration: %s", err.Error())
  2058. }
  2059. cli := athena.NewFromConfig(cfg)
  2060. // Query Athena
  2061. startQueryExecutionOutput, err := cli.StartQueryExecution(ctx, startQueryExecutionInput)
  2062. if err != nil {
  2063. return fmt.Errorf("QueryAthenaPaginated: start query error: %s", err.Error())
  2064. }
  2065. err = waitForQueryToComplete(ctx, cli, startQueryExecutionOutput.QueryExecutionId)
  2066. if err != nil {
  2067. return fmt.Errorf("QueryAthenaPaginated: query execution error: %s", err.Error())
  2068. }
  2069. queryResultsInput := &athena.GetQueryResultsInput{
  2070. QueryExecutionId: startQueryExecutionOutput.QueryExecutionId,
  2071. }
  2072. getQueryResultsPaginator := athena.NewGetQueryResultsPaginator(cli, queryResultsInput)
  2073. for getQueryResultsPaginator.HasMorePages() {
  2074. pg, err := getQueryResultsPaginator.NextPage(ctx)
  2075. if err != nil {
  2076. log.Errorf("QueryAthenaPaginated: NextPage error: %s", err.Error())
  2077. continue
  2078. }
  2079. fn(pg)
  2080. }
  2081. return nil
  2082. }
  2083. type SavingsPlanData struct {
  2084. ResourceID string
  2085. EffectiveCost float64
  2086. SavingsPlanARN string
  2087. MostRecentDate string
  2088. }
  2089. func (aws *AWS) GetSavingsPlanDataFromAthena() error {
  2090. cfg, err := aws.GetConfig()
  2091. if err != nil {
  2092. aws.RIPricingError = err
  2093. return err
  2094. }
  2095. if cfg.AthenaBucketName == "" {
  2096. err = ErrNoAthenaBucket
  2097. aws.RIPricingError = err
  2098. return err
  2099. }
  2100. if aws.SavingsPlanDataByInstanceID == nil {
  2101. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData)
  2102. }
  2103. tNow := time.Now()
  2104. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  2105. start := tOneDayAgo.Format("2006-01-02")
  2106. end := tNow.Format("2006-01-02")
  2107. // Use Savings Plan Effective Rate as an estimation for cost, assuming the 1h most recent period got a fully loaded savings plan.
  2108. //
  2109. q := `SELECT
  2110. line_item_usage_start_date,
  2111. savings_plan_savings_plan_a_r_n,
  2112. line_item_resource_id,
  2113. savings_plan_savings_plan_rate
  2114. FROM %s as cost_data
  2115. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  2116. AND line_item_line_item_type = 'SavingsPlanCoveredUsage' ORDER BY
  2117. line_item_usage_start_date DESC`
  2118. page := 0
  2119. mostRecentDate := ""
  2120. processResults := func(op *athena.GetQueryResultsOutput) bool {
  2121. if op == nil {
  2122. log.Errorf("GetSavingsPlanDataFromAthena: Athena page is nil")
  2123. return false
  2124. } else if op.ResultSet == nil {
  2125. log.Errorf("GetSavingsPlanDataFromAthena: Athena page.ResultSet is nil")
  2126. return false
  2127. }
  2128. aws.SavingsPlanDataLock.Lock()
  2129. defer aws.SavingsPlanDataLock.Unlock()
  2130. if page == 0 {
  2131. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData) // Clean out the old data and only report a savingsplan price if its in the most recent run.
  2132. }
  2133. iter := op.ResultSet.Rows
  2134. if page == 0 && len(iter) > 0 {
  2135. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  2136. }
  2137. page++
  2138. for _, r := range iter {
  2139. d := *r.Data[0].VarCharValue
  2140. if mostRecentDate == "" {
  2141. mostRecentDate = d
  2142. } else if mostRecentDate != d { // Get all most recent assignments
  2143. break
  2144. }
  2145. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  2146. if err != nil {
  2147. log.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  2148. }
  2149. r := &SavingsPlanData{
  2150. ResourceID: *r.Data[2].VarCharValue,
  2151. EffectiveCost: cost,
  2152. SavingsPlanARN: *r.Data[1].VarCharValue,
  2153. MostRecentDate: d,
  2154. }
  2155. aws.SavingsPlanDataByInstanceID[r.ResourceID] = r
  2156. }
  2157. log.Debugf("Found %d savings plan applied instances", len(aws.SavingsPlanDataByInstanceID))
  2158. for k, r := range aws.SavingsPlanDataByInstanceID {
  2159. log.DedupedInfof(5, "Savings Plan Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  2160. }
  2161. return true
  2162. }
  2163. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  2164. log.Debugf("Running Query: %s", query)
  2165. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  2166. if err != nil {
  2167. aws.RIPricingError = err
  2168. return fmt.Errorf("Error fetching Savings Plan Data: %s", err)
  2169. }
  2170. return nil
  2171. }
  2172. type RIData struct {
  2173. ResourceID string
  2174. EffectiveCost float64
  2175. ReservationARN string
  2176. MostRecentDate string
  2177. }
  2178. func (aws *AWS) GetReservationDataFromAthena() error {
  2179. cfg, err := aws.GetConfig()
  2180. if err != nil {
  2181. aws.RIPricingError = err
  2182. return err
  2183. }
  2184. if cfg.AthenaBucketName == "" {
  2185. err = ErrNoAthenaBucket
  2186. aws.RIPricingError = err
  2187. return err
  2188. }
  2189. // Query for all column names in advance in order to validate configured
  2190. // label columns
  2191. columns, _ := aws.fetchColumns()
  2192. if !columns["reservation_reservation_a_r_n"] || !columns["reservation_effective_cost"] {
  2193. err = fmt.Errorf("no reservation data available in Athena")
  2194. aws.RIPricingError = err
  2195. return err
  2196. }
  2197. if aws.RIPricingByInstanceID == nil {
  2198. aws.RIPricingByInstanceID = make(map[string]*RIData)
  2199. }
  2200. tNow := time.Now()
  2201. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  2202. start := tOneDayAgo.Format("2006-01-02")
  2203. end := tNow.Format("2006-01-02")
  2204. q := `SELECT
  2205. line_item_usage_start_date,
  2206. reservation_reservation_a_r_n,
  2207. line_item_resource_id,
  2208. reservation_effective_cost
  2209. FROM %s as cost_data
  2210. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  2211. AND reservation_reservation_a_r_n <> '' ORDER BY
  2212. line_item_usage_start_date DESC`
  2213. page := 0
  2214. mostRecentDate := ""
  2215. processResults := func(op *athena.GetQueryResultsOutput) bool {
  2216. if op == nil {
  2217. log.Errorf("GetReservationDataFromAthena: Athena page is nil")
  2218. return false
  2219. } else if op.ResultSet == nil {
  2220. log.Errorf("GetReservationDataFromAthena: Athena page.ResultSet is nil")
  2221. return false
  2222. }
  2223. aws.RIDataLock.Lock()
  2224. defer aws.RIDataLock.Unlock()
  2225. if page == 0 {
  2226. aws.RIPricingByInstanceID = make(map[string]*RIData) // Clean out the old data and only report a RI price if its in the most recent run.
  2227. }
  2228. iter := op.ResultSet.Rows
  2229. if page == 0 && len(iter) > 0 {
  2230. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  2231. }
  2232. page++
  2233. for _, r := range iter {
  2234. d := *r.Data[0].VarCharValue
  2235. if mostRecentDate == "" {
  2236. mostRecentDate = d
  2237. } else if mostRecentDate != d { // Get all most recent assignments
  2238. break
  2239. }
  2240. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  2241. if err != nil {
  2242. log.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  2243. }
  2244. r := &RIData{
  2245. ResourceID: *r.Data[2].VarCharValue,
  2246. EffectiveCost: cost,
  2247. ReservationARN: *r.Data[1].VarCharValue,
  2248. MostRecentDate: d,
  2249. }
  2250. aws.RIPricingByInstanceID[r.ResourceID] = r
  2251. }
  2252. log.Debugf("Found %d reserved instances", len(aws.RIPricingByInstanceID))
  2253. for k, r := range aws.RIPricingByInstanceID {
  2254. log.DedupedInfof(5, "Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  2255. }
  2256. return true
  2257. }
  2258. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  2259. log.Debugf("Running Query: %s", query)
  2260. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  2261. if err != nil {
  2262. aws.RIPricingError = err
  2263. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  2264. }
  2265. aws.RIPricingError = nil
  2266. return nil
  2267. }
  2268. // fetchColumns returns a list of the names of all columns in the configured
  2269. // Athena tables
  2270. func (aws *AWS) fetchColumns() (map[string]bool, error) {
  2271. columnSet := map[string]bool{}
  2272. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  2273. if err != nil {
  2274. return nil, err
  2275. }
  2276. // This Query is supported by Athena tables and views
  2277. q := `SELECT column_name FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s'`
  2278. query := fmt.Sprintf(q, awsAthenaInfo.AthenaDatabase, awsAthenaInfo.AthenaTable)
  2279. pageNum := 0
  2280. athenaErr := aws.QueryAthenaPaginated(context.TODO(), query, func(page *athena.GetQueryResultsOutput) bool {
  2281. if page == nil {
  2282. log.Errorf("fetchColumns: Athena page is nil")
  2283. return false
  2284. } else if page.ResultSet == nil {
  2285. log.Errorf("fetchColumns: Athena page.ResultSet is nil")
  2286. return false
  2287. }
  2288. // remove header row 'column_name'
  2289. rows := page.ResultSet.Rows[1:]
  2290. for _, row := range rows {
  2291. columnSet[*row.Data[0].VarCharValue] = true
  2292. }
  2293. pageNum++
  2294. return true
  2295. })
  2296. if athenaErr != nil {
  2297. return columnSet, athenaErr
  2298. }
  2299. if len(columnSet) == 0 {
  2300. log.Infof("No columns retrieved from Athena")
  2301. }
  2302. return columnSet, nil
  2303. }
  2304. type spotInfo struct {
  2305. Timestamp string `csv:"Timestamp"`
  2306. UsageType string `csv:"UsageType"`
  2307. Operation string `csv:"Operation"`
  2308. InstanceID string `csv:"InstanceID"`
  2309. MyBidID string `csv:"MyBidID"`
  2310. MyMaxPrice string `csv:"MyMaxPrice"`
  2311. MarketPrice string `csv:"MarketPrice"`
  2312. Charge string `csv:"Charge"`
  2313. Version string `csv:"Version"`
  2314. }
  2315. func (aws *AWS) parseSpotData(bucket string, prefix string, projectID string, region string) (map[string]*spotInfo, error) {
  2316. aws.ConfigureAuth() // configure aws api authentication by setting env vars
  2317. s3Prefix := projectID
  2318. if len(prefix) != 0 {
  2319. s3Prefix = prefix + "/" + s3Prefix
  2320. }
  2321. aak, err := aws.GetAWSAccessKey()
  2322. if err != nil {
  2323. return nil, err
  2324. }
  2325. cfg, err := aak.CreateConfig(region)
  2326. if err != nil {
  2327. return nil, err
  2328. }
  2329. cli := s3.NewFromConfig(cfg)
  2330. downloader := manager.NewDownloader(cli)
  2331. tNow := time.Now()
  2332. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  2333. ls := &s3.ListObjectsInput{
  2334. Bucket: awsSDK.String(bucket),
  2335. Prefix: awsSDK.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  2336. }
  2337. ls2 := &s3.ListObjectsInput{
  2338. Bucket: awsSDK.String(bucket),
  2339. Prefix: awsSDK.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  2340. }
  2341. lso, err := cli.ListObjects(context.TODO(), ls)
  2342. if err != nil {
  2343. aws.ServiceAccountChecks.Set("bucketList", &models.ServiceAccountCheck{
  2344. Message: "Bucket List Permissions Available",
  2345. Status: false,
  2346. AdditionalInfo: err.Error(),
  2347. })
  2348. return nil, err
  2349. } else {
  2350. aws.ServiceAccountChecks.Set("bucketList", &models.ServiceAccountCheck{
  2351. Message: "Bucket List Permissions Available",
  2352. Status: true,
  2353. })
  2354. }
  2355. lsoLen := len(lso.Contents)
  2356. log.Debugf("Found %d spot data files from yesterday", lsoLen)
  2357. if lsoLen == 0 {
  2358. log.Debugf("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  2359. }
  2360. lso2, err := cli.ListObjects(context.TODO(), ls2)
  2361. if err != nil {
  2362. return nil, err
  2363. }
  2364. lso2Len := len(lso2.Contents)
  2365. log.Debugf("Found %d spot data files from today", lso2Len)
  2366. if lso2Len == 0 {
  2367. log.Debugf("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  2368. }
  2369. // TODO: Worth it to use LastModifiedDate to determine if we should reparse the spot data?
  2370. var keys []*string
  2371. for _, obj := range lso.Contents {
  2372. keys = append(keys, obj.Key)
  2373. }
  2374. for _, obj := range lso2.Contents {
  2375. keys = append(keys, obj.Key)
  2376. }
  2377. header, err := csvutil.Header(spotInfo{}, "csv")
  2378. if err != nil {
  2379. return nil, err
  2380. }
  2381. fieldsPerRecord := len(header)
  2382. spots := make(map[string]*spotInfo)
  2383. for _, key := range keys {
  2384. getObj := &s3.GetObjectInput{
  2385. Bucket: awsSDK.String(bucket),
  2386. Key: key,
  2387. }
  2388. buf := manager.NewWriteAtBuffer([]byte{})
  2389. _, err := downloader.Download(context.TODO(), buf, getObj)
  2390. if err != nil {
  2391. aws.ServiceAccountChecks.Set("objectList", &models.ServiceAccountCheck{
  2392. Message: "Object Get Permissions Available",
  2393. Status: false,
  2394. AdditionalInfo: err.Error(),
  2395. })
  2396. return nil, err
  2397. } else {
  2398. aws.ServiceAccountChecks.Set("objectList", &models.ServiceAccountCheck{
  2399. Message: "Object Get Permissions Available",
  2400. Status: true,
  2401. })
  2402. }
  2403. r := bytes.NewReader(buf.Bytes())
  2404. gr, err := gzip.NewReader(r)
  2405. if err != nil {
  2406. return nil, err
  2407. }
  2408. csvReader := csv.NewReader(gr)
  2409. csvReader.Comma = '\t'
  2410. csvReader.FieldsPerRecord = fieldsPerRecord
  2411. dec, err := csvutil.NewDecoder(csvReader, header...)
  2412. if err != nil {
  2413. return nil, err
  2414. }
  2415. var foundVersion string
  2416. for {
  2417. spot := spotInfo{}
  2418. err := dec.Decode(&spot)
  2419. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  2420. if err == io.EOF {
  2421. break
  2422. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  2423. rec := dec.Record()
  2424. // the first two "Record()" will be the comment lines
  2425. // and they show up as len() == 1
  2426. // the first of which is "#Version"
  2427. // the second of which is "#Fields: "
  2428. if len(rec) != 1 {
  2429. log.Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  2430. continue
  2431. }
  2432. if len(foundVersion) == 0 {
  2433. spotFeedVersion := rec[0]
  2434. log.Debugf("Spot feed version is \"%s\"", spotFeedVersion)
  2435. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  2436. if matches != nil {
  2437. foundVersion = matches[1]
  2438. if foundVersion != supportedSpotFeedVersion {
  2439. log.Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  2440. break
  2441. }
  2442. }
  2443. continue
  2444. } else if strings.Index(rec[0], "#") == 0 {
  2445. continue
  2446. } else {
  2447. log.Infof("skipping non-TSV line: %s", rec)
  2448. continue
  2449. }
  2450. } else if err != nil {
  2451. log.Warnf("Error during spot info decode: %+v", err)
  2452. continue
  2453. }
  2454. log.DedupedInfof(5, "Found spot info for: %s", spot.InstanceID)
  2455. spots[spot.InstanceID] = &spot
  2456. }
  2457. gr.Close()
  2458. }
  2459. return spots, nil
  2460. }
  2461. // ApplyReservedInstancePricing TODO
  2462. func (aws *AWS) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  2463. }
  2464. func (aws *AWS) ServiceAccountStatus() *models.ServiceAccountStatus {
  2465. return aws.ServiceAccountChecks.GetStatus()
  2466. }
  2467. func (aws *AWS) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  2468. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  2469. }
  2470. // Regions returns a predefined list of AWS regions
  2471. func (aws *AWS) Regions() []string {
  2472. regionOverrides := env.GetRegionOverrideList()
  2473. if len(regionOverrides) > 0 {
  2474. log.Debugf("Overriding AWS regions with configured region list: %+v", regionOverrides)
  2475. return regionOverrides
  2476. }
  2477. return awsRegions
  2478. }
  2479. // PricingSourceSummary returns the pricing source summary for the provider.
  2480. // The summary represents what was _parsed_ from the pricing source, not
  2481. // everything that was _available_ in the pricing source.
  2482. func (aws *AWS) PricingSourceSummary() interface{} {
  2483. // encode the pricing source summary as a JSON string
  2484. return aws.Pricing
  2485. }
  2486. func parseRegionFromAZ(zone string) string {
  2487. region := ""
  2488. for _, r := range awsRegions {
  2489. if strings.HasPrefix(zone, r) && len(r) > len(region) {
  2490. region = r
  2491. }
  2492. }
  2493. if region == "" {
  2494. region = regionRx.FindString(zone)
  2495. }
  2496. return region
  2497. }