provider.go 87 KB

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