provider.go 87 KB

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