awsprovider.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303
  1. package cloud
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "context"
  6. "encoding/csv"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/opencost/opencost/pkg/kubecost"
  17. "github.com/opencost/opencost/pkg/clustercache"
  18. "github.com/opencost/opencost/pkg/env"
  19. errs "github.com/opencost/opencost/pkg/errors"
  20. "github.com/opencost/opencost/pkg/log"
  21. "github.com/opencost/opencost/pkg/util"
  22. "github.com/opencost/opencost/pkg/util/fileutil"
  23. "github.com/opencost/opencost/pkg/util/json"
  24. "github.com/opencost/opencost/pkg/util/timeutil"
  25. awsSDK "github.com/aws/aws-sdk-go-v2/aws"
  26. "github.com/aws/aws-sdk-go-v2/config"
  27. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  28. "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
  29. "github.com/aws/aws-sdk-go-v2/service/athena"
  30. athenaTypes "github.com/aws/aws-sdk-go-v2/service/athena/types"
  31. "github.com/aws/aws-sdk-go-v2/service/ec2"
  32. ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
  33. "github.com/aws/aws-sdk-go-v2/service/s3"
  34. "github.com/aws/aws-sdk-go-v2/service/sts"
  35. "github.com/jszwec/csvutil"
  36. v1 "k8s.io/api/core/v1"
  37. )
  38. const (
  39. supportedSpotFeedVersion = "1"
  40. SpotInfoUpdateType = "spotinfo"
  41. AthenaInfoUpdateType = "athenainfo"
  42. PreemptibleType = "preemptible"
  43. APIPricingSource = "Public API"
  44. SpotPricingSource = "Spot Data Feed"
  45. ReservedInstancePricingSource = "Savings Plan, Reserved Instance, and Out-Of-Cluster"
  46. InUseState = "in-use"
  47. AttachedState = "attached"
  48. AWSHourlyPublicIPCost = 0.005
  49. EKSCapacityTypeLabel = "eks.amazonaws.com/capacityType"
  50. EKSCapacitySpotTypeValue = "SPOT"
  51. KarpenterCapacityTypeLabel = "karpenter.sh/capacity-type"
  52. KarpenterCapacitySpotTypeValue = "spot"
  53. )
  54. var (
  55. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  56. provIdRx = regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  57. usageTypeRegx = regexp.MustCompile(".*(-|^)(EBS.+)")
  58. versionRx = regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  59. regionRx = regexp.MustCompile("([a-z]+-[a-z]+-[0-9])")
  60. )
  61. func (aws *AWS) PricingSourceStatus() map[string]*PricingSource {
  62. sources := make(map[string]*PricingSource)
  63. sps := &PricingSource{
  64. Name: SpotPricingSource,
  65. Enabled: true,
  66. }
  67. if !aws.SpotRefreshEnabled() {
  68. sps.Available = false
  69. sps.Error = "Spot instances not set up"
  70. sps.Enabled = false
  71. } else {
  72. sps.Error = ""
  73. if aws.SpotPricingError != nil {
  74. sps.Error = aws.SpotPricingError.Error()
  75. }
  76. if sps.Error != "" {
  77. sps.Available = false
  78. } else if len(aws.SpotPricingByInstanceID) > 0 {
  79. sps.Available = true
  80. } else {
  81. sps.Error = "No spot instances detected"
  82. }
  83. }
  84. sources[SpotPricingSource] = sps
  85. rps := &PricingSource{
  86. Name: ReservedInstancePricingSource,
  87. Enabled: true,
  88. }
  89. rps.Error = ""
  90. if aws.RIPricingError != nil {
  91. rps.Error = aws.RIPricingError.Error()
  92. }
  93. if rps.Error != "" {
  94. rps.Available = false
  95. } else {
  96. rps.Available = true
  97. }
  98. sources[ReservedInstancePricingSource] = rps
  99. return sources
  100. }
  101. // How often spot data is refreshed
  102. const SpotRefreshDuration = 15 * time.Minute
  103. var awsRegions = []string{
  104. "us-east-2",
  105. "us-east-1",
  106. "us-west-1",
  107. "us-west-2",
  108. "ap-east-1",
  109. "ap-south-1",
  110. "ap-northeast-3",
  111. "ap-northeast-2",
  112. "ap-southeast-1",
  113. "ap-southeast-2",
  114. "ap-northeast-1",
  115. "ap-southeast-3",
  116. "ca-central-1",
  117. "cn-north-1",
  118. "cn-northwest-1",
  119. "eu-central-1",
  120. "eu-west-1",
  121. "eu-west-2",
  122. "eu-west-3",
  123. "eu-north-1",
  124. "eu-south-1",
  125. "me-south-1",
  126. "sa-east-1",
  127. "af-south-1",
  128. "us-gov-east-1",
  129. "us-gov-west-1",
  130. }
  131. // AWS represents an Amazon Provider
  132. type AWS struct {
  133. Pricing map[string]*AWSProductTerms
  134. SpotPricingByInstanceID map[string]*spotInfo
  135. SpotPricingUpdatedAt *time.Time
  136. SpotRefreshRunning bool
  137. SpotPricingLock sync.RWMutex
  138. SpotPricingError error
  139. RIPricingByInstanceID map[string]*RIData
  140. RIPricingError error
  141. RIDataRunning bool
  142. RIDataLock sync.RWMutex
  143. SavingsPlanDataByInstanceID map[string]*SavingsPlanData
  144. SavingsPlanDataRunning bool
  145. SavingsPlanDataLock sync.RWMutex
  146. ValidPricingKeys map[string]bool
  147. Clientset clustercache.ClusterCache
  148. BaseCPUPrice string
  149. BaseRAMPrice string
  150. BaseGPUPrice string
  151. BaseSpotCPUPrice string
  152. BaseSpotRAMPrice string
  153. BaseSpotGPUPrice string
  154. SpotLabelName string
  155. SpotLabelValue string
  156. SpotDataRegion string
  157. SpotDataBucket string
  158. SpotDataPrefix string
  159. ProjectID string
  160. DownloadPricingDataLock sync.RWMutex
  161. Config *ProviderConfig
  162. serviceAccountChecks *ServiceAccountChecks
  163. clusterManagementPrice float64
  164. clusterAccountId string
  165. clusterRegion string
  166. clusterProvisioner string
  167. *CustomProvider
  168. }
  169. // AWSAccessKey holds AWS credentials and fulfils the awsV2.CredentialsProvider interface
  170. type AWSAccessKey struct {
  171. AccessKeyID string `json:"aws_access_key_id"`
  172. SecretAccessKey string `json:"aws_secret_access_key"`
  173. }
  174. // Retrieve returns a set of awsV2 credentials using the AWSAccessKey's key and secret.
  175. // This fulfils the awsV2.CredentialsProvider interface contract.
  176. func (accessKey AWSAccessKey) Retrieve(ctx context.Context) (awsSDK.Credentials, error) {
  177. return awsSDK.Credentials{
  178. AccessKeyID: accessKey.AccessKeyID,
  179. SecretAccessKey: accessKey.SecretAccessKey,
  180. }, nil
  181. }
  182. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains for the provided region
  183. func (accessKey AWSAccessKey) CreateConfig(region string) (awsSDK.Config, error) {
  184. var cfg awsSDK.Config
  185. var err error
  186. // If accessKey values have not been provided, attempt to load cfg from service key annotations
  187. if accessKey.AccessKeyID == "" && accessKey.SecretAccessKey == "" {
  188. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
  189. if err != nil {
  190. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region from annotation %s: %s", region, err)
  191. }
  192. } else {
  193. // The AWS SDK v2 requires an object fulfilling the CredentialsProvider interface, which cloud.AWSAccessKey does
  194. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(accessKey), config.WithRegion(region))
  195. if err != nil {
  196. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region %s: %s", region, err)
  197. }
  198. }
  199. return cfg, nil
  200. }
  201. // AWSPricing maps a k8s node to an AWS Pricing "product"
  202. type AWSPricing struct {
  203. Products map[string]*AWSProduct `json:"products"`
  204. Terms AWSPricingTerms `json:"terms"`
  205. }
  206. // AWSProduct represents a purchased SKU
  207. type AWSProduct struct {
  208. Sku string `json:"sku"`
  209. Attributes AWSProductAttributes `json:"attributes"`
  210. }
  211. // AWSProductAttributes represents metadata about the product used to map to a node.
  212. type AWSProductAttributes struct {
  213. Location string `json:"location"`
  214. InstanceType string `json:"instanceType"`
  215. Memory string `json:"memory"`
  216. Storage string `json:"storage"`
  217. VCpu string `json:"vcpu"`
  218. UsageType string `json:"usagetype"`
  219. OperatingSystem string `json:"operatingSystem"`
  220. PreInstalledSw string `json:"preInstalledSw"`
  221. InstanceFamily string `json:"instanceFamily"`
  222. CapacityStatus string `json:"capacitystatus"`
  223. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  224. }
  225. // AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
  226. type AWSPricingTerms struct {
  227. OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
  228. Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
  229. }
  230. // AWSOfferTerm is a sku extension used to pay for the node.
  231. type AWSOfferTerm struct {
  232. Sku string `json:"sku"`
  233. PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
  234. }
  235. func (ot *AWSOfferTerm) String() string {
  236. var strs []string
  237. for k, rc := range ot.PriceDimensions {
  238. strs = append(strs, fmt.Sprintf("%s:%s", k, rc.String()))
  239. }
  240. return fmt.Sprintf("%s:%s", ot.Sku, strings.Join(strs, ","))
  241. }
  242. // AWSRateCode encodes data about the price of a product
  243. type AWSRateCode struct {
  244. Unit string `json:"unit"`
  245. PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
  246. }
  247. func (rc *AWSRateCode) String() string {
  248. return fmt.Sprintf("{unit: %s, pricePerUnit: %v", rc.Unit, rc.PricePerUnit)
  249. }
  250. // AWSCurrencyCode is the localized currency. (TODO: support non-USD)
  251. type AWSCurrencyCode struct {
  252. USD string `json:"USD,omitempty"`
  253. CNY string `json:"CNY,omitempty"`
  254. }
  255. // AWSProductTerms represents the full terms of the product
  256. type AWSProductTerms struct {
  257. Sku string `json:"sku"`
  258. OnDemand *AWSOfferTerm `json:"OnDemand"`
  259. Reserved *AWSOfferTerm `json:"Reserved"`
  260. Memory string `json:"memory"`
  261. Storage string `json:"storage"`
  262. VCpu string `json:"vcpu"`
  263. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  264. PV *PV `json:"pv"`
  265. }
  266. // ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
  267. const ClusterIdEnvVar = "AWS_CLUSTER_ID"
  268. // OnDemandRateCode is appended to an node sku
  269. const OnDemandRateCode = ".JRTCKXETXF"
  270. const OnDemandRateCodeCn = ".99YE2YK9UR"
  271. // ReservedRateCode is appended to a node sku
  272. const ReservedRateCode = ".38NPMPTW36"
  273. // HourlyRateCode is appended to a node sku
  274. const HourlyRateCode = ".6YS6EN2CT7"
  275. const HourlyRateCodeCn = ".Q7UJUT2CE6"
  276. // volTypes are used to map between AWS UsageTypes and
  277. // EBS volume types, as they would appear in K8s storage class
  278. // name and the EC2 API.
  279. var volTypes = map[string]string{
  280. "EBS:VolumeUsage.gp2": "gp2",
  281. "EBS:VolumeUsage.gp3": "gp3",
  282. "EBS:VolumeUsage": "standard",
  283. "EBS:VolumeUsage.sc1": "sc1",
  284. "EBS:VolumeP-IOPS.piops": "io1",
  285. "EBS:VolumeUsage.st1": "st1",
  286. "EBS:VolumeUsage.piops": "io1",
  287. "gp2": "EBS:VolumeUsage.gp2",
  288. "gp3": "EBS:VolumeUsage.gp3",
  289. "standard": "EBS:VolumeUsage",
  290. "sc1": "EBS:VolumeUsage.sc1",
  291. "io1": "EBS:VolumeUsage.piops",
  292. "st1": "EBS:VolumeUsage.st1",
  293. }
  294. // locationToRegion maps AWS region names (As they come from Billing)
  295. // to actual region identifiers
  296. var locationToRegion = map[string]string{
  297. "US East (Ohio)": "us-east-2",
  298. "US East (N. Virginia)": "us-east-1",
  299. "US West (N. California)": "us-west-1",
  300. "US West (Oregon)": "us-west-2",
  301. "Asia Pacific (Hong Kong)": "ap-east-1",
  302. "Asia Pacific (Mumbai)": "ap-south-1",
  303. "Asia Pacific (Osaka)": "ap-northeast-3",
  304. "Asia Pacific (Seoul)": "ap-northeast-2",
  305. "Asia Pacific (Singapore)": "ap-southeast-1",
  306. "Asia Pacific (Sydney)": "ap-southeast-2",
  307. "Asia Pacific (Tokyo)": "ap-northeast-1",
  308. "Asia Pacific (Jakarta)": "ap-southeast-3",
  309. "Canada (Central)": "ca-central-1",
  310. "China (Beijing)": "cn-north-1",
  311. "China (Ningxia)": "cn-northwest-1",
  312. "EU (Frankfurt)": "eu-central-1",
  313. "EU (Ireland)": "eu-west-1",
  314. "EU (London)": "eu-west-2",
  315. "EU (Paris)": "eu-west-3",
  316. "EU (Stockholm)": "eu-north-1",
  317. "EU (Milan)": "eu-south-1",
  318. "South America (Sao Paulo)": "sa-east-1",
  319. "Africa (Cape Town)": "af-south-1",
  320. "AWS GovCloud (US-East)": "us-gov-east-1",
  321. "AWS GovCloud (US-West)": "us-gov-west-1",
  322. }
  323. var regionToBillingRegionCode = map[string]string{
  324. "us-east-2": "USE2",
  325. "us-east-1": "",
  326. "us-west-1": "USW1",
  327. "us-west-2": "USW2",
  328. "ap-east-1": "APE1",
  329. "ap-south-1": "APS3",
  330. "ap-northeast-3": "APN3",
  331. "ap-northeast-2": "APN2",
  332. "ap-southeast-1": "APS1",
  333. "ap-southeast-2": "APS2",
  334. "ap-northeast-1": "APN1",
  335. "ap-southeast-3": "APS4",
  336. "ca-central-1": "CAN1",
  337. "cn-north-1": "",
  338. "cn-northwest-1": "",
  339. "eu-central-1": "EUC1",
  340. "eu-west-1": "EU",
  341. "eu-west-2": "EUW2",
  342. "eu-west-3": "EUW3",
  343. "eu-north-1": "EUN1",
  344. "eu-south-1": "EUS1",
  345. "sa-east-1": "SAE1",
  346. "af-south-1": "AFS1",
  347. "us-gov-east-1": "UGE1",
  348. "us-gov-west-1": "UGW1",
  349. }
  350. var loadedAWSSecret bool = false
  351. var awsSecret *AWSAccessKey = nil
  352. func (aws *AWS) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  353. return ""
  354. }
  355. // KubeAttrConversion maps the k8s labels for region to an aws region
  356. func (aws *AWS) KubeAttrConversion(location, instanceType, operatingSystem string) string {
  357. operatingSystem = strings.ToLower(operatingSystem)
  358. region := locationToRegion[location]
  359. return region + "," + instanceType + "," + operatingSystem
  360. }
  361. // AwsSpotFeedInfo contains configuration for spot feed integration
  362. type AwsSpotFeedInfo struct {
  363. BucketName string `json:"bucketName"`
  364. Prefix string `json:"prefix"`
  365. Region string `json:"region"`
  366. AccountID string `json:"projectID"`
  367. ServiceKeyName string `json:"serviceKeyName"`
  368. ServiceKeySecret string `json:"serviceKeySecret"`
  369. SpotLabel string `json:"spotLabel"`
  370. SpotLabelValue string `json:"spotLabelValue"`
  371. }
  372. // AwsAthenaInfo contains configuration for CUR integration
  373. type AwsAthenaInfo struct {
  374. AthenaBucketName string `json:"athenaBucketName"`
  375. AthenaRegion string `json:"athenaRegion"`
  376. AthenaDatabase string `json:"athenaDatabase"`
  377. AthenaTable string `json:"athenaTable"`
  378. AthenaWorkgroup string `json:"athenaWorkgroup"`
  379. ServiceKeyName string `json:"serviceKeyName"`
  380. ServiceKeySecret string `json:"serviceKeySecret"`
  381. AccountID string `json:"projectID"`
  382. MasterPayerARN string `json:"masterPayerARN"`
  383. }
  384. // IsEmpty returns true if all fields in config are empty, false if not.
  385. func (aai *AwsAthenaInfo) IsEmpty() bool {
  386. return aai.AthenaBucketName == "" &&
  387. aai.AthenaRegion == "" &&
  388. aai.AthenaDatabase == "" &&
  389. aai.AthenaTable == "" &&
  390. aai.AthenaWorkgroup == "" &&
  391. aai.ServiceKeyName == "" &&
  392. aai.ServiceKeySecret == "" &&
  393. aai.AccountID == "" &&
  394. aai.MasterPayerARN == ""
  395. }
  396. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains
  397. func (aai *AwsAthenaInfo) CreateConfig() (awsSDK.Config, error) {
  398. keyProvider := AWSAccessKey{AccessKeyID: aai.ServiceKeyName, SecretAccessKey: aai.ServiceKeySecret}
  399. cfg, err := keyProvider.CreateConfig(aai.AthenaRegion)
  400. if err != nil {
  401. return cfg, err
  402. }
  403. if aai.MasterPayerARN != "" {
  404. // Create the credentials from AssumeRoleProvider to assume the role
  405. // referenced by the roleARN.
  406. stsSvc := sts.NewFromConfig(cfg)
  407. creds := stscreds.NewAssumeRoleProvider(stsSvc, aai.MasterPayerARN)
  408. cfg.Credentials = awsSDK.NewCredentialsCache(creds)
  409. }
  410. return cfg, nil
  411. }
  412. func (aws *AWS) GetManagementPlatform() (string, error) {
  413. nodes := aws.Clientset.GetAllNodes()
  414. if len(nodes) > 0 {
  415. n := nodes[0]
  416. version := n.Status.NodeInfo.KubeletVersion
  417. if strings.Contains(version, "eks") {
  418. return "eks", nil
  419. }
  420. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  421. return "kops", nil
  422. }
  423. }
  424. return "", nil
  425. }
  426. func (aws *AWS) GetConfig() (*CustomPricing, error) {
  427. c, err := aws.Config.GetCustomPricingData()
  428. if err != nil {
  429. return nil, err
  430. }
  431. if c.Discount == "" {
  432. c.Discount = "0%"
  433. }
  434. if c.NegotiatedDiscount == "" {
  435. c.NegotiatedDiscount = "0%"
  436. }
  437. if c.ShareTenancyCosts == "" {
  438. c.ShareTenancyCosts = defaultShareTenancyCost
  439. }
  440. return c, nil
  441. }
  442. // GetAWSAccessKey generate an AWSAccessKey object from the config
  443. func (aws *AWS) GetAWSAccessKey() (*AWSAccessKey, error) {
  444. config, err := aws.GetConfig()
  445. if err != nil {
  446. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  447. }
  448. err = aws.ConfigureAuthWith(config)
  449. if err != nil {
  450. return nil, fmt.Errorf("error configuring Cloud Provider %s", err)
  451. }
  452. //Look for service key values in env if not present in config
  453. if config.ServiceKeyName == "" {
  454. config.ServiceKeyName = env.GetAWSAccessKeyID()
  455. }
  456. if config.ServiceKeySecret == "" {
  457. config.ServiceKeySecret = env.GetAWSAccessKeySecret()
  458. }
  459. if config.ServiceKeyName == "" && config.ServiceKeySecret == "" {
  460. log.DedupedInfof(1, "missing service key values for AWS cloud integration attempting to use service account integration")
  461. }
  462. return &AWSAccessKey{AccessKeyID: config.ServiceKeyName, SecretAccessKey: config.ServiceKeySecret}, nil
  463. }
  464. // GetAWSAthenaInfo generate an AWSAthenaInfo object from the config
  465. func (aws *AWS) GetAWSAthenaInfo() (*AwsAthenaInfo, error) {
  466. config, err := aws.GetConfig()
  467. if err != nil {
  468. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  469. }
  470. aak, err := aws.GetAWSAccessKey()
  471. if err != nil {
  472. return nil, err
  473. }
  474. return &AwsAthenaInfo{
  475. AthenaBucketName: config.AthenaBucketName,
  476. AthenaRegion: config.AthenaRegion,
  477. AthenaDatabase: config.AthenaDatabase,
  478. AthenaTable: config.AthenaTable,
  479. AthenaWorkgroup: config.AthenaWorkgroup,
  480. ServiceKeyName: aak.AccessKeyID,
  481. ServiceKeySecret: aak.SecretAccessKey,
  482. AccountID: config.AthenaProjectID,
  483. MasterPayerARN: config.MasterPayerARN,
  484. }, nil
  485. }
  486. func (aws *AWS) UpdateConfigFromConfigMap(cm map[string]string) (*CustomPricing, error) {
  487. return aws.Config.UpdateFromMap(cm)
  488. }
  489. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  490. return aws.Config.Update(func(c *CustomPricing) error {
  491. if updateType == SpotInfoUpdateType {
  492. asfi := AwsSpotFeedInfo{}
  493. err := json.NewDecoder(r).Decode(&asfi)
  494. if err != nil {
  495. return err
  496. }
  497. c.ServiceKeyName = asfi.ServiceKeyName
  498. if asfi.ServiceKeySecret != "" {
  499. c.ServiceKeySecret = asfi.ServiceKeySecret
  500. }
  501. c.SpotDataPrefix = asfi.Prefix
  502. c.SpotDataBucket = asfi.BucketName
  503. c.ProjectID = asfi.AccountID
  504. c.SpotDataRegion = asfi.Region
  505. c.SpotLabel = asfi.SpotLabel
  506. c.SpotLabelValue = asfi.SpotLabelValue
  507. } else if updateType == AthenaInfoUpdateType {
  508. aai := AwsAthenaInfo{}
  509. err := json.NewDecoder(r).Decode(&aai)
  510. if err != nil {
  511. return err
  512. }
  513. c.AthenaBucketName = aai.AthenaBucketName
  514. c.AthenaRegion = aai.AthenaRegion
  515. c.AthenaDatabase = aai.AthenaDatabase
  516. c.AthenaTable = aai.AthenaTable
  517. c.AthenaWorkgroup = aai.AthenaWorkgroup
  518. c.ServiceKeyName = aai.ServiceKeyName
  519. if aai.ServiceKeySecret != "" {
  520. c.ServiceKeySecret = aai.ServiceKeySecret
  521. }
  522. if aai.MasterPayerARN != "" {
  523. c.MasterPayerARN = aai.MasterPayerARN
  524. }
  525. c.AthenaProjectID = aai.AccountID
  526. } else {
  527. a := make(map[string]interface{})
  528. err := json.NewDecoder(r).Decode(&a)
  529. if err != nil {
  530. return err
  531. }
  532. for k, v := range a {
  533. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  534. vstr, ok := v.(string)
  535. if ok {
  536. err := SetCustomPricingField(c, kUpper, vstr)
  537. if err != nil {
  538. return err
  539. }
  540. } else {
  541. return fmt.Errorf("type error while updating config for %s", kUpper)
  542. }
  543. }
  544. }
  545. if env.IsRemoteEnabled() {
  546. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  547. if err != nil {
  548. return err
  549. }
  550. }
  551. return nil
  552. })
  553. }
  554. type awsKey struct {
  555. SpotLabelName string
  556. SpotLabelValue string
  557. Labels map[string]string
  558. ProviderID string
  559. }
  560. func (k *awsKey) GPUCount() int {
  561. return 0
  562. }
  563. func (k *awsKey) GPUType() string {
  564. return ""
  565. }
  566. func (k *awsKey) ID() string {
  567. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  568. if matchNum == 2 {
  569. return group
  570. }
  571. }
  572. log.Warnf("Could not find instance ID in \"%s\"", k.ProviderID)
  573. return ""
  574. }
  575. // Features will return a comma seperated list of features for the given node
  576. // If the node has a spot label, it will be included in the list
  577. // Otherwise, the list include instance type, operating system, and the region
  578. func (k *awsKey) Features() string {
  579. instanceType, _ := util.GetInstanceType(k.Labels)
  580. operatingSystem, _ := util.GetOperatingSystem(k.Labels)
  581. region, _ := util.GetRegion(k.Labels)
  582. key := region + "," + instanceType + "," + operatingSystem
  583. usageType := k.getUsageType(k.Labels)
  584. spotKey := key + "," + usageType
  585. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  586. return spotKey
  587. }
  588. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  589. return spotKey
  590. }
  591. if usageType == PreemptibleType {
  592. return spotKey
  593. }
  594. return key
  595. }
  596. // getUsageType returns the usage type of the instance
  597. // If the instance is a spot instance, it will return PreemptibleType
  598. // Otherwise returns an empty string
  599. func (k *awsKey) getUsageType(labels map[string]string) string {
  600. if eksLabel, ok := labels[EKSCapacityTypeLabel]; ok && eksLabel == EKSCapacitySpotTypeValue {
  601. // We currently write out spot instances as "preemptible" in the pricing data, so these need to match
  602. return PreemptibleType
  603. }
  604. if kLabel, ok := labels[KarpenterCapacityTypeLabel]; ok && kLabel == KarpenterCapacitySpotTypeValue {
  605. return PreemptibleType
  606. }
  607. return ""
  608. }
  609. func (aws *AWS) PVPricing(pvk PVKey) (*PV, error) {
  610. pricing, ok := aws.Pricing[pvk.Features()]
  611. if !ok {
  612. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  613. return &PV{}, nil
  614. }
  615. return pricing.PV, nil
  616. }
  617. type awsPVKey struct {
  618. Labels map[string]string
  619. StorageClassParameters map[string]string
  620. StorageClassName string
  621. Name string
  622. DefaultRegion string
  623. ProviderID string
  624. }
  625. func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  626. providerID := ""
  627. if pv.Spec.AWSElasticBlockStore != nil {
  628. providerID = pv.Spec.AWSElasticBlockStore.VolumeID
  629. } else if pv.Spec.CSI != nil {
  630. providerID = pv.Spec.CSI.VolumeHandle
  631. }
  632. return &awsPVKey{
  633. Labels: pv.Labels,
  634. StorageClassName: pv.Spec.StorageClassName,
  635. StorageClassParameters: parameters,
  636. Name: pv.Name,
  637. DefaultRegion: defaultRegion,
  638. ProviderID: providerID,
  639. }
  640. }
  641. func (key *awsPVKey) ID() string {
  642. return key.ProviderID
  643. }
  644. func (key *awsPVKey) GetStorageClass() string {
  645. return key.StorageClassName
  646. }
  647. func (key *awsPVKey) Features() string {
  648. storageClass := key.StorageClassParameters["type"]
  649. if storageClass == "standard" {
  650. storageClass = "gp2"
  651. }
  652. // Storage class names are generally EBS volume types (gp2)
  653. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  654. // Converts between the 2
  655. region, ok := util.GetRegion(key.Labels)
  656. if !ok {
  657. region = key.DefaultRegion
  658. }
  659. class, ok := volTypes[storageClass]
  660. if !ok {
  661. log.Debugf("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  662. }
  663. return region + "," + class
  664. }
  665. // GetKey maps node labels to information needed to retrieve pricing data
  666. func (aws *AWS) GetKey(labels map[string]string, n *v1.Node) Key {
  667. return &awsKey{
  668. SpotLabelName: aws.SpotLabelName,
  669. SpotLabelValue: aws.SpotLabelValue,
  670. Labels: labels,
  671. ProviderID: labels["providerID"],
  672. }
  673. }
  674. func (aws *AWS) isPreemptible(key string) bool {
  675. s := strings.Split(key, ",")
  676. if len(s) == 4 && s[3] == PreemptibleType {
  677. return true
  678. }
  679. return false
  680. }
  681. func (aws *AWS) ClusterManagementPricing() (string, float64, error) {
  682. return aws.clusterProvisioner, aws.clusterManagementPrice, nil
  683. }
  684. // Use the pricing data from the current region. Fall back to using all region data if needed.
  685. func (aws *AWS) getRegionPricing(nodeList []*v1.Node) (*http.Response, string, error) {
  686. pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/"
  687. region := ""
  688. multiregion := false
  689. for _, n := range nodeList {
  690. labels := n.GetLabels()
  691. currentNodeRegion := ""
  692. if r, ok := util.GetRegion(labels); ok {
  693. currentNodeRegion = r
  694. // Switch to Chinese endpoint for regions with the Chinese prefix
  695. if strings.HasPrefix(currentNodeRegion, "cn-") {
  696. pricingURL = "https://pricing.cn-north-1.amazonaws.com.cn/offers/v1.0/cn/AmazonEC2/current/"
  697. }
  698. } else {
  699. multiregion = true // We weren't able to detect the node's region, so pull all data.
  700. break
  701. }
  702. if region == "" { // We haven't set a region yet
  703. region = currentNodeRegion
  704. } else if region != "" && currentNodeRegion != region { // If two nodes have different regions here, we'll need to fetch all pricing data.
  705. multiregion = true
  706. break
  707. }
  708. }
  709. // Chinese multiregion endpoint only contains data for Chinese regions and Chinese regions are excluded from other endpoint
  710. if region != "" && !multiregion {
  711. pricingURL += region + "/"
  712. }
  713. pricingURL += "index.json"
  714. if env.GetAWSPricingURL() != "" { // Allow override of pricing URL
  715. pricingURL = env.GetAWSPricingURL()
  716. }
  717. log.Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  718. resp, err := http.Get(pricingURL)
  719. if err != nil {
  720. log.Errorf("Bogus fetch of \"%s\": %v", pricingURL, err)
  721. return nil, pricingURL, err
  722. }
  723. return resp, pricingURL, err
  724. }
  725. // SpotRefreshEnabled determines whether the required configs to run the spot feed query have been set up
  726. func (aws *AWS) SpotRefreshEnabled() bool {
  727. // Need a valid value for at least one of these fields to consider spot pricing as enabled
  728. return len(aws.SpotDataBucket) != 0 || len(aws.SpotDataRegion) != 0 || len(aws.ProjectID) != 0
  729. }
  730. // DownloadPricingData fetches data from the AWS Pricing API
  731. func (aws *AWS) DownloadPricingData() error {
  732. aws.DownloadPricingDataLock.Lock()
  733. defer aws.DownloadPricingDataLock.Unlock()
  734. c, err := aws.Config.GetCustomPricingData()
  735. if err != nil {
  736. log.Errorf("Error downloading default pricing data: %s", err.Error())
  737. }
  738. aws.BaseCPUPrice = c.CPU
  739. aws.BaseRAMPrice = c.RAM
  740. aws.BaseGPUPrice = c.GPU
  741. aws.BaseSpotCPUPrice = c.SpotCPU
  742. aws.BaseSpotRAMPrice = c.SpotRAM
  743. aws.BaseSpotGPUPrice = c.SpotGPU
  744. aws.SpotLabelName = c.SpotLabel
  745. aws.SpotLabelValue = c.SpotLabelValue
  746. aws.SpotDataBucket = c.SpotDataBucket
  747. aws.SpotDataPrefix = c.SpotDataPrefix
  748. aws.ProjectID = c.ProjectID
  749. aws.SpotDataRegion = c.SpotDataRegion
  750. aws.ConfigureAuthWith(c) // load aws authentication from configuration or secret
  751. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  752. log.Warnf("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  753. }
  754. nodeList := aws.Clientset.GetAllNodes()
  755. inputkeys := make(map[string]bool)
  756. for _, n := range nodeList {
  757. if _, ok := n.Labels["eks.amazonaws.com/nodegroup"]; ok {
  758. aws.clusterManagementPrice = 0.10
  759. aws.clusterProvisioner = "EKS"
  760. } else if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  761. aws.clusterProvisioner = "KOPS"
  762. }
  763. labels := n.GetObjectMeta().GetLabels()
  764. key := aws.GetKey(labels, n)
  765. inputkeys[key.Features()] = true
  766. }
  767. pvList := aws.Clientset.GetAllPersistentVolumes()
  768. storageClasses := aws.Clientset.GetAllStorageClasses()
  769. storageClassMap := make(map[string]map[string]string)
  770. for _, storageClass := range storageClasses {
  771. params := storageClass.Parameters
  772. storageClassMap[storageClass.ObjectMeta.Name] = params
  773. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  774. storageClassMap["default"] = params
  775. storageClassMap[""] = params
  776. }
  777. }
  778. pvkeys := make(map[string]PVKey)
  779. for _, pv := range pvList {
  780. params, ok := storageClassMap[pv.Spec.StorageClassName]
  781. if !ok {
  782. log.Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  783. continue
  784. }
  785. key := aws.GetPVKey(pv, params, "")
  786. pvkeys[key.Features()] = key
  787. }
  788. // RIDataRunning establishes the existence of the goroutine. Since it's possible we
  789. // run multiple downloads, we don't want to create multiple go routines if one already exists
  790. if !aws.RIDataRunning {
  791. err = aws.GetReservationDataFromAthena() // Block until one run has completed.
  792. if err != nil {
  793. log.Errorf("Failed to lookup reserved instance data: %s", err.Error())
  794. } else { // If we make one successful run, check on new reservation data every hour
  795. go func() {
  796. defer errs.HandlePanic()
  797. aws.RIDataRunning = true
  798. for {
  799. log.Infof("Reserved Instance watcher running... next update in 1h")
  800. time.Sleep(time.Hour)
  801. err := aws.GetReservationDataFromAthena()
  802. if err != nil {
  803. log.Infof("Error updating RI data: %s", err.Error())
  804. }
  805. }
  806. }()
  807. }
  808. }
  809. if !aws.SavingsPlanDataRunning {
  810. err = aws.GetSavingsPlanDataFromAthena()
  811. if err != nil {
  812. log.Errorf("Failed to lookup savings plan data: %s", err.Error())
  813. } else {
  814. go func() {
  815. defer errs.HandlePanic()
  816. aws.SavingsPlanDataRunning = true
  817. for {
  818. log.Infof("Savings Plan watcher running... next update in 1h")
  819. time.Sleep(time.Hour)
  820. err := aws.GetSavingsPlanDataFromAthena()
  821. if err != nil {
  822. log.Infof("Error updating Savings Plan data: %s", err.Error())
  823. }
  824. }
  825. }()
  826. }
  827. }
  828. aws.Pricing = make(map[string]*AWSProductTerms)
  829. aws.ValidPricingKeys = make(map[string]bool)
  830. skusToKeys := make(map[string]string)
  831. resp, pricingURL, err := aws.getRegionPricing(nodeList)
  832. if err != nil {
  833. return err
  834. }
  835. dec := json.NewDecoder(resp.Body)
  836. for {
  837. t, err := dec.Token()
  838. if err == io.EOF {
  839. log.Infof("done loading \"%s\"\n", pricingURL)
  840. break
  841. } else if err != nil {
  842. log.Errorf("error parsing response json %v", resp.Body)
  843. break
  844. }
  845. if t == "products" {
  846. _, err := dec.Token() // this should parse the opening "{""
  847. if err != nil {
  848. return err
  849. }
  850. for dec.More() {
  851. _, err := dec.Token() // the sku token
  852. if err != nil {
  853. return err
  854. }
  855. product := &AWSProduct{}
  856. err = dec.Decode(&product)
  857. if err != nil {
  858. log.Errorf("Error parsing response from \"%s\": %v", pricingURL, err.Error())
  859. break
  860. }
  861. if product.Attributes.PreInstalledSw == "NA" &&
  862. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) &&
  863. product.Attributes.CapacityStatus == "Used" {
  864. key := aws.KubeAttrConversion(product.Attributes.Location, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  865. spotKey := key + ",preemptible"
  866. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  867. productTerms := &AWSProductTerms{
  868. Sku: product.Sku,
  869. Memory: product.Attributes.Memory,
  870. Storage: product.Attributes.Storage,
  871. VCpu: product.Attributes.VCpu,
  872. GPU: product.Attributes.GPU,
  873. }
  874. aws.Pricing[key] = productTerms
  875. aws.Pricing[spotKey] = productTerms
  876. skusToKeys[product.Sku] = key
  877. }
  878. aws.ValidPricingKeys[key] = true
  879. aws.ValidPricingKeys[spotKey] = true
  880. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  881. // UsageTypes may be prefixed with a region code - we're removing this when using
  882. // volTypes to keep lookups generic
  883. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  884. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  885. key := locationToRegion[product.Attributes.Location] + "," + usageTypeNoRegion
  886. spotKey := key + ",preemptible"
  887. pv := &PV{
  888. Class: volTypes[usageTypeNoRegion],
  889. Region: locationToRegion[product.Attributes.Location],
  890. }
  891. productTerms := &AWSProductTerms{
  892. Sku: product.Sku,
  893. PV: pv,
  894. }
  895. aws.Pricing[key] = productTerms
  896. aws.Pricing[spotKey] = productTerms
  897. skusToKeys[product.Sku] = key
  898. aws.ValidPricingKeys[key] = true
  899. aws.ValidPricingKeys[spotKey] = true
  900. }
  901. }
  902. }
  903. if t == "terms" {
  904. _, err := dec.Token() // this should parse the opening "{""
  905. if err != nil {
  906. return err
  907. }
  908. termType, err := dec.Token()
  909. if err != nil {
  910. return err
  911. }
  912. if termType == "OnDemand" {
  913. _, err := dec.Token()
  914. if err != nil { // again, should parse an opening "{"
  915. return err
  916. }
  917. for dec.More() {
  918. sku, err := dec.Token()
  919. if err != nil {
  920. return err
  921. }
  922. _, err = dec.Token() // another opening "{"
  923. if err != nil {
  924. return err
  925. }
  926. skuOnDemand, err := dec.Token()
  927. if err != nil {
  928. return err
  929. }
  930. offerTerm := &AWSOfferTerm{}
  931. err = dec.Decode(&offerTerm)
  932. if err != nil {
  933. log.Errorf("Error decoding AWS Offer Term: " + err.Error())
  934. }
  935. key, ok := skusToKeys[sku.(string)]
  936. spotKey := key + ",preemptible"
  937. if ok {
  938. aws.Pricing[key].OnDemand = offerTerm
  939. aws.Pricing[spotKey].OnDemand = offerTerm
  940. var cost string
  941. if sku.(string)+OnDemandRateCode == skuOnDemand {
  942. cost = offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  943. } else if sku.(string)+OnDemandRateCodeCn == skuOnDemand {
  944. cost = offerTerm.PriceDimensions[sku.(string)+OnDemandRateCodeCn+HourlyRateCodeCn].PricePerUnit.CNY
  945. }
  946. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  947. // If the specific UsageType is the per IO cost used on io1 volumes
  948. // we need to add the per IO cost to the io1 PV cost
  949. // Add the per IO cost to the PV object for the io1 volume type
  950. aws.Pricing[key].PV.CostPerIO = cost
  951. } else if strings.Contains(key, "EBS:Volume") {
  952. // If volume, we need to get hourly cost and add it to the PV object
  953. costFloat, _ := strconv.ParseFloat(cost, 64)
  954. hourlyPrice := costFloat / 730
  955. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  956. }
  957. }
  958. _, err = dec.Token()
  959. if err != nil {
  960. return err
  961. }
  962. }
  963. _, err = dec.Token()
  964. if err != nil {
  965. return err
  966. }
  967. }
  968. }
  969. }
  970. log.Infof("Finished downloading \"%s\"", pricingURL)
  971. if !aws.SpotRefreshEnabled() {
  972. return nil
  973. }
  974. // Always run spot pricing refresh when performing download
  975. aws.refreshSpotPricing(true)
  976. // Only start a single refresh goroutine
  977. if !aws.SpotRefreshRunning {
  978. aws.SpotRefreshRunning = true
  979. go func() {
  980. defer errs.HandlePanic()
  981. for {
  982. log.Infof("Spot Pricing Refresh scheduled in %.2f minutes.", SpotRefreshDuration.Minutes())
  983. time.Sleep(SpotRefreshDuration)
  984. // Reoccurring refresh checks update times
  985. aws.refreshSpotPricing(false)
  986. }
  987. }()
  988. }
  989. return nil
  990. }
  991. func (aws *AWS) refreshSpotPricing(force bool) {
  992. aws.SpotPricingLock.Lock()
  993. defer aws.SpotPricingLock.Unlock()
  994. now := time.Now().UTC()
  995. updateTime := now.Add(-SpotRefreshDuration)
  996. // Return if there was an update time set and an hour hasn't elapsed
  997. if !force && aws.SpotPricingUpdatedAt != nil && aws.SpotPricingUpdatedAt.After(updateTime) {
  998. return
  999. }
  1000. sp, err := aws.parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion)
  1001. if err != nil {
  1002. log.Warnf("Skipping AWS spot data download: %s", err.Error())
  1003. aws.SpotPricingError = err
  1004. return
  1005. }
  1006. aws.SpotPricingError = nil
  1007. // update time last updated
  1008. aws.SpotPricingUpdatedAt = &now
  1009. aws.SpotPricingByInstanceID = sp
  1010. }
  1011. // Stubbed NetworkPricing for AWS. Pull directly from aws.json for now
  1012. func (aws *AWS) NetworkPricing() (*Network, error) {
  1013. cpricing, err := aws.Config.GetCustomPricingData()
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1018. if err != nil {
  1019. return nil, err
  1020. }
  1021. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1022. if err != nil {
  1023. return nil, err
  1024. }
  1025. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1026. if err != nil {
  1027. return nil, err
  1028. }
  1029. return &Network{
  1030. ZoneNetworkEgressCost: znec,
  1031. RegionNetworkEgressCost: rnec,
  1032. InternetNetworkEgressCost: inec,
  1033. }, nil
  1034. }
  1035. func (aws *AWS) LoadBalancerPricing() (*LoadBalancer, error) {
  1036. fffrc := 0.025
  1037. afrc := 0.010
  1038. lbidc := 0.008
  1039. numForwardingRules := 1.0
  1040. dataIngressGB := 0.0
  1041. var totalCost float64
  1042. if numForwardingRules < 5 {
  1043. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  1044. } else {
  1045. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  1046. }
  1047. return &LoadBalancer{
  1048. Cost: totalCost,
  1049. }, nil
  1050. }
  1051. // AllNodePricing returns all the billing data fetched.
  1052. func (aws *AWS) AllNodePricing() (interface{}, error) {
  1053. aws.DownloadPricingDataLock.RLock()
  1054. defer aws.DownloadPricingDataLock.RUnlock()
  1055. return aws.Pricing, nil
  1056. }
  1057. func (aws *AWS) spotPricing(instanceID string) (*spotInfo, bool) {
  1058. aws.SpotPricingLock.RLock()
  1059. defer aws.SpotPricingLock.RUnlock()
  1060. info, ok := aws.SpotPricingByInstanceID[instanceID]
  1061. return info, ok
  1062. }
  1063. func (aws *AWS) reservedInstancePricing(instanceID string) (*RIData, bool) {
  1064. aws.RIDataLock.RLock()
  1065. defer aws.RIDataLock.RUnlock()
  1066. data, ok := aws.RIPricingByInstanceID[instanceID]
  1067. return data, ok
  1068. }
  1069. func (aws *AWS) savingsPlanPricing(instanceID string) (*SavingsPlanData, bool) {
  1070. aws.SavingsPlanDataLock.RLock()
  1071. defer aws.SavingsPlanDataLock.RUnlock()
  1072. data, ok := aws.SavingsPlanDataByInstanceID[instanceID]
  1073. return data, ok
  1074. }
  1075. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  1076. key := k.Features()
  1077. if spotInfo, ok := aws.spotPricing(k.ID()); ok {
  1078. var spotcost string
  1079. log.DedupedInfof(5, "Looking up spot data from feed for node %s", k.ID())
  1080. arr := strings.Split(spotInfo.Charge, " ")
  1081. if len(arr) == 2 {
  1082. spotcost = arr[0]
  1083. } else {
  1084. log.Infof("Spot data for node %s is missing", k.ID())
  1085. }
  1086. return &Node{
  1087. Cost: spotcost,
  1088. VCPU: terms.VCpu,
  1089. RAM: terms.Memory,
  1090. GPU: terms.GPU,
  1091. Storage: terms.Storage,
  1092. BaseCPUPrice: aws.BaseCPUPrice,
  1093. BaseRAMPrice: aws.BaseRAMPrice,
  1094. BaseGPUPrice: aws.BaseGPUPrice,
  1095. UsageType: PreemptibleType,
  1096. }, nil
  1097. } else if aws.isPreemptible(key) { // Preemptible but we don't have any data in the pricing report.
  1098. log.DedupedWarningf(5, "Node %s marked preemptible but we have no data in spot feed", k.ID())
  1099. return &Node{
  1100. VCPU: terms.VCpu,
  1101. VCPUCost: aws.BaseSpotCPUPrice,
  1102. RAM: terms.Memory,
  1103. GPU: terms.GPU,
  1104. Storage: terms.Storage,
  1105. BaseCPUPrice: aws.BaseCPUPrice,
  1106. BaseRAMPrice: aws.BaseRAMPrice,
  1107. BaseGPUPrice: aws.BaseGPUPrice,
  1108. UsageType: PreemptibleType,
  1109. }, nil
  1110. } else if sp, ok := aws.savingsPlanPricing(k.ID()); ok {
  1111. strCost := fmt.Sprintf("%f", sp.EffectiveCost)
  1112. return &Node{
  1113. Cost: strCost,
  1114. VCPU: terms.VCpu,
  1115. RAM: terms.Memory,
  1116. GPU: terms.GPU,
  1117. Storage: terms.Storage,
  1118. BaseCPUPrice: aws.BaseCPUPrice,
  1119. BaseRAMPrice: aws.BaseRAMPrice,
  1120. BaseGPUPrice: aws.BaseGPUPrice,
  1121. UsageType: usageType,
  1122. }, nil
  1123. } else if ri, ok := aws.reservedInstancePricing(k.ID()); ok {
  1124. strCost := fmt.Sprintf("%f", ri.EffectiveCost)
  1125. return &Node{
  1126. Cost: strCost,
  1127. VCPU: terms.VCpu,
  1128. RAM: terms.Memory,
  1129. GPU: terms.GPU,
  1130. Storage: terms.Storage,
  1131. BaseCPUPrice: aws.BaseCPUPrice,
  1132. BaseRAMPrice: aws.BaseRAMPrice,
  1133. BaseGPUPrice: aws.BaseGPUPrice,
  1134. UsageType: usageType,
  1135. }, nil
  1136. }
  1137. var cost string
  1138. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  1139. if ok {
  1140. cost = c.PricePerUnit.USD
  1141. } else {
  1142. // Check for Chinese pricing before throwing error
  1143. c, ok = terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCodeCn+HourlyRateCodeCn]
  1144. if ok {
  1145. cost = c.PricePerUnit.CNY
  1146. } else {
  1147. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  1148. }
  1149. }
  1150. return &Node{
  1151. Cost: cost,
  1152. VCPU: terms.VCpu,
  1153. RAM: terms.Memory,
  1154. GPU: terms.GPU,
  1155. Storage: terms.Storage,
  1156. BaseCPUPrice: aws.BaseCPUPrice,
  1157. BaseRAMPrice: aws.BaseRAMPrice,
  1158. BaseGPUPrice: aws.BaseGPUPrice,
  1159. UsageType: usageType,
  1160. }, nil
  1161. }
  1162. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  1163. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  1164. aws.DownloadPricingDataLock.RLock()
  1165. defer aws.DownloadPricingDataLock.RUnlock()
  1166. key := k.Features()
  1167. usageType := "ondemand"
  1168. if aws.isPreemptible(key) {
  1169. usageType = PreemptibleType
  1170. }
  1171. terms, ok := aws.Pricing[key]
  1172. if ok {
  1173. return aws.createNode(terms, usageType, k)
  1174. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  1175. aws.DownloadPricingDataLock.RUnlock()
  1176. err := aws.DownloadPricingData()
  1177. aws.DownloadPricingDataLock.RLock()
  1178. if err != nil {
  1179. return &Node{
  1180. Cost: aws.BaseCPUPrice,
  1181. BaseCPUPrice: aws.BaseCPUPrice,
  1182. BaseRAMPrice: aws.BaseRAMPrice,
  1183. BaseGPUPrice: aws.BaseGPUPrice,
  1184. UsageType: usageType,
  1185. UsesBaseCPUPrice: true,
  1186. }, err
  1187. }
  1188. terms, termsOk := aws.Pricing[key]
  1189. if !termsOk {
  1190. return &Node{
  1191. Cost: aws.BaseCPUPrice,
  1192. BaseCPUPrice: aws.BaseCPUPrice,
  1193. BaseRAMPrice: aws.BaseRAMPrice,
  1194. BaseGPUPrice: aws.BaseGPUPrice,
  1195. UsageType: usageType,
  1196. UsesBaseCPUPrice: true,
  1197. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  1198. }
  1199. return aws.createNode(terms, usageType, k)
  1200. } else { // Fall back to base pricing if we can't find the key. Base pricing is handled at the costmodel level.
  1201. return nil, fmt.Errorf("Invalid Pricing Key \"%s\"", key)
  1202. }
  1203. }
  1204. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  1205. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  1206. defaultClusterName := "AWS Cluster #1"
  1207. c, err := awsProvider.GetConfig()
  1208. if err != nil {
  1209. return nil, err
  1210. }
  1211. remoteEnabled := env.IsRemoteEnabled()
  1212. makeStructure := func(clusterName string) (map[string]string, error) {
  1213. m := make(map[string]string)
  1214. m["name"] = clusterName
  1215. m["provider"] = kubecost.AWSProvider
  1216. m["account"] = c.AthenaProjectID // this value requires configuration but is unavailable else where
  1217. m["region"] = awsProvider.clusterRegion
  1218. m["id"] = env.GetClusterID()
  1219. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1220. m["provisioner"] = awsProvider.clusterProvisioner
  1221. return m, nil
  1222. }
  1223. if c.ClusterName != "" {
  1224. return makeStructure(c.ClusterName)
  1225. }
  1226. maybeClusterId := env.GetAWSClusterID()
  1227. if len(maybeClusterId) != 0 {
  1228. log.Infof("Returning \"%s\" as ClusterName", maybeClusterId)
  1229. return makeStructure(maybeClusterId)
  1230. }
  1231. log.Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", env.AWSClusterIDEnvVar)
  1232. return makeStructure(defaultClusterName)
  1233. }
  1234. // updates the authentication to the latest values (via config or secret)
  1235. func (aws *AWS) ConfigureAuth() error {
  1236. c, err := aws.Config.GetCustomPricingData()
  1237. if err != nil {
  1238. log.Errorf("Error downloading default pricing data: %s", err.Error())
  1239. }
  1240. return aws.ConfigureAuthWith(c)
  1241. }
  1242. // updates the authentication to the latest values (via config or secret)
  1243. func (aws *AWS) ConfigureAuthWith(config *CustomPricing) error {
  1244. accessKeyID, accessKeySecret := aws.getAWSAuth(false, config)
  1245. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1246. err := env.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1247. if err != nil {
  1248. return err
  1249. }
  1250. err = env.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1251. if err != nil {
  1252. return err
  1253. }
  1254. }
  1255. return nil
  1256. }
  1257. // Gets the aws key id and secret
  1258. func (aws *AWS) getAWSAuth(forceReload bool, cp *CustomPricing) (string, string) {
  1259. // 1. Check config values first (set from frontend UI)
  1260. if cp.ServiceKeyName != "" && cp.ServiceKeySecret != "" {
  1261. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1262. Message: "AWS ServiceKey exists",
  1263. Status: true,
  1264. })
  1265. return cp.ServiceKeyName, cp.ServiceKeySecret
  1266. }
  1267. // 2. Check for secret
  1268. s, _ := aws.loadAWSAuthSecret(forceReload)
  1269. if s != nil && s.AccessKeyID != "" && s.SecretAccessKey != "" {
  1270. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1271. Message: "AWS ServiceKey exists",
  1272. Status: true,
  1273. })
  1274. return s.AccessKeyID, s.SecretAccessKey
  1275. }
  1276. // 3. Fall back to env vars
  1277. if env.GetAWSAccessKeyID() == "" || env.GetAWSAccessKeyID() == "" {
  1278. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1279. Message: "AWS ServiceKey exists",
  1280. Status: false,
  1281. })
  1282. } else {
  1283. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1284. Message: "AWS ServiceKey exists",
  1285. Status: true,
  1286. })
  1287. }
  1288. return env.GetAWSAccessKeyID(), env.GetAWSAccessKeySecret()
  1289. }
  1290. // Load once and cache the result (even on failure). This is an install time secret, so
  1291. // we don't expect the secret to change. If it does, however, we can force reload using
  1292. // the input parameter.
  1293. func (aws *AWS) loadAWSAuthSecret(force bool) (*AWSAccessKey, error) {
  1294. if !force && loadedAWSSecret {
  1295. return awsSecret, nil
  1296. }
  1297. loadedAWSSecret = true
  1298. exists, err := fileutil.FileExists(authSecretPath)
  1299. if !exists || err != nil {
  1300. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  1301. }
  1302. result, err := os.ReadFile(authSecretPath)
  1303. if err != nil {
  1304. return nil, err
  1305. }
  1306. var ak AWSAccessKey
  1307. err = json.Unmarshal(result, &ak)
  1308. if err != nil {
  1309. return nil, err
  1310. }
  1311. awsSecret = &ak
  1312. return awsSecret, nil
  1313. }
  1314. func (aws *AWS) getAddressesForRegion(ctx context.Context, region string) (*ec2.DescribeAddressesOutput, error) {
  1315. aak, err := aws.GetAWSAccessKey()
  1316. if err != nil {
  1317. return nil, err
  1318. }
  1319. cfg, err := aak.CreateConfig(region)
  1320. if err != nil {
  1321. return nil, err
  1322. }
  1323. cli := ec2.NewFromConfig(cfg)
  1324. return cli.DescribeAddresses(ctx, &ec2.DescribeAddressesInput{})
  1325. }
  1326. func (aws *AWS) getAllAddresses() ([]*ec2Types.Address, error) {
  1327. aws.ConfigureAuth() // load authentication data into env vars
  1328. addressCh := make(chan *ec2.DescribeAddressesOutput, len(awsRegions))
  1329. errorCh := make(chan error, len(awsRegions))
  1330. var wg sync.WaitGroup
  1331. wg.Add(len(awsRegions))
  1332. // Get volumes from each AWS region
  1333. for _, r := range awsRegions {
  1334. // Fetch IP address response and send results and errors to their
  1335. // respective channels
  1336. go func(region string) {
  1337. defer wg.Done()
  1338. defer errs.HandlePanic()
  1339. // Query for first page of volume results
  1340. resp, err := aws.getAddressesForRegion(context.TODO(), region)
  1341. if err != nil {
  1342. errorCh <- err
  1343. return
  1344. }
  1345. addressCh <- resp
  1346. }(r)
  1347. }
  1348. // Close the result channels after everything has been sent
  1349. go func() {
  1350. defer errs.HandlePanic()
  1351. wg.Wait()
  1352. close(errorCh)
  1353. close(addressCh)
  1354. }()
  1355. var addresses []*ec2Types.Address
  1356. for adds := range addressCh {
  1357. for _, add := range adds.Addresses {
  1358. a := add // duplicate to avoid pointer to iterator
  1359. addresses = append(addresses, &a)
  1360. }
  1361. }
  1362. var errs []error
  1363. for err := range errorCh {
  1364. log.DedupedWarningf(5, "unable to get addresses: %s", err)
  1365. errs = append(errs, err)
  1366. }
  1367. // Return error if no addresses are returned
  1368. if len(errs) > 0 && len(addresses) == 0 {
  1369. return nil, fmt.Errorf("%d error(s) retrieving addresses: %v", len(errs), errs)
  1370. }
  1371. return addresses, nil
  1372. }
  1373. // GetAddresses retrieves EC2 addresses
  1374. func (aws *AWS) GetAddresses() ([]byte, error) {
  1375. addresses, err := aws.getAllAddresses()
  1376. if err != nil {
  1377. return nil, err
  1378. }
  1379. // Format the response this way to match the JSON-encoded formatting of a single response
  1380. // from DescribeAddresss, so that consumers can always expect AWS disk responses to have
  1381. // a "Addresss" key at the top level.
  1382. return json.Marshal(map[string][]*ec2Types.Address{
  1383. "Addresses": addresses,
  1384. })
  1385. }
  1386. func (aws *AWS) isAddressOrphaned(address *ec2Types.Address) bool {
  1387. if address.AssociationId != nil {
  1388. return false
  1389. }
  1390. return true
  1391. }
  1392. func (aws *AWS) getDisksForRegion(ctx context.Context, region string, maxResults int32, nextToken *string) (*ec2.DescribeVolumesOutput, error) {
  1393. aak, err := aws.GetAWSAccessKey()
  1394. if err != nil {
  1395. return nil, err
  1396. }
  1397. cfg, err := aak.CreateConfig(region)
  1398. if err != nil {
  1399. return nil, err
  1400. }
  1401. cli := ec2.NewFromConfig(cfg)
  1402. return cli.DescribeVolumes(ctx, &ec2.DescribeVolumesInput{
  1403. MaxResults: &maxResults,
  1404. NextToken: nextToken,
  1405. })
  1406. }
  1407. func (aws *AWS) getAllDisks() ([]*ec2Types.Volume, error) {
  1408. aws.ConfigureAuth() // load authentication data into env vars
  1409. volumeCh := make(chan *ec2.DescribeVolumesOutput, len(awsRegions))
  1410. errorCh := make(chan error, len(awsRegions))
  1411. var wg sync.WaitGroup
  1412. wg.Add(len(awsRegions))
  1413. // Get volumes from each AWS region
  1414. for _, r := range awsRegions {
  1415. // Fetch volume response and send results and errors to their
  1416. // respective channels
  1417. go func(region string) {
  1418. defer wg.Done()
  1419. defer errs.HandlePanic()
  1420. // Query for first page of volume results
  1421. resp, err := aws.getDisksForRegion(context.TODO(), region, 1000, nil)
  1422. if err != nil {
  1423. errorCh <- err
  1424. return
  1425. }
  1426. volumeCh <- resp
  1427. // A NextToken indicates more pages of results. Keep querying
  1428. // until all pages are retrieved.
  1429. for resp.NextToken != nil {
  1430. resp, err = aws.getDisksForRegion(context.TODO(), region, 100, resp.NextToken)
  1431. if err != nil {
  1432. errorCh <- err
  1433. return
  1434. }
  1435. volumeCh <- resp
  1436. }
  1437. }(r)
  1438. }
  1439. // Close the result channels after everything has been sent
  1440. go func() {
  1441. defer errs.HandlePanic()
  1442. wg.Wait()
  1443. close(errorCh)
  1444. close(volumeCh)
  1445. }()
  1446. var volumes []*ec2Types.Volume
  1447. for vols := range volumeCh {
  1448. for _, vol := range vols.Volumes {
  1449. v := vol // duplicate to avoid pointer to iterator
  1450. volumes = append(volumes, &v)
  1451. }
  1452. }
  1453. var errs []error
  1454. for err := range errorCh {
  1455. log.DedupedWarningf(5, "unable to get disks: %s", err)
  1456. errs = append(errs, err)
  1457. }
  1458. // Return error if no volumes are returned
  1459. if len(errs) > 0 && len(volumes) == 0 {
  1460. return nil, fmt.Errorf("%d error(s) retrieving volumes: %v", len(errs), errs)
  1461. }
  1462. return volumes, nil
  1463. }
  1464. // 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.
  1465. func (aws *AWS) GetDisks() ([]byte, error) {
  1466. volumes, err := aws.getAllDisks()
  1467. if err != nil {
  1468. return nil, err
  1469. }
  1470. // Format the response this way to match the JSON-encoded formatting of a single response
  1471. // from DescribeVolumes, so that consumers can always expect AWS disk responses to have
  1472. // a "Volumes" key at the top level.
  1473. return json.Marshal(map[string][]*ec2Types.Volume{
  1474. "Volumes": volumes,
  1475. })
  1476. }
  1477. func (aws *AWS) isDiskOrphaned(vol *ec2Types.Volume) bool {
  1478. // Do not consider volume orphaned if in use
  1479. if vol.State == InUseState {
  1480. return false
  1481. }
  1482. // Do not consider volume orphaned if volume is attached to any attachments
  1483. if len(vol.Attachments) != 0 {
  1484. for _, attachment := range vol.Attachments {
  1485. if attachment.State == AttachedState {
  1486. return false
  1487. }
  1488. }
  1489. }
  1490. return true
  1491. }
  1492. func (aws *AWS) GetOrphanedResources() ([]OrphanedResource, error) {
  1493. volumes, err := aws.getAllDisks()
  1494. if err != nil {
  1495. return nil, err
  1496. }
  1497. addresses, err := aws.getAllAddresses()
  1498. if err != nil {
  1499. return nil, err
  1500. }
  1501. var orphanedResources []OrphanedResource
  1502. for _, volume := range volumes {
  1503. if aws.isDiskOrphaned(volume) {
  1504. cost, err := aws.findCostForDisk(volume)
  1505. if err != nil {
  1506. return nil, err
  1507. }
  1508. var volumeSize int64
  1509. if volume.Size != nil {
  1510. volumeSize = int64(*volume.Size)
  1511. }
  1512. // This is turning us-east-1a into us-east-1
  1513. var zone string
  1514. if volume.AvailabilityZone != nil {
  1515. zone = *volume.AvailabilityZone
  1516. }
  1517. var region, url string
  1518. region = regionRx.FindString(zone)
  1519. if region != "" {
  1520. url = "https://console.aws.amazon.com/ec2/home?region=" + region + "#Volumes:sort=desc:createTime"
  1521. } else {
  1522. url = "https://console.aws.amazon.com/ec2/home?#Volumes:sort=desc:createTime"
  1523. }
  1524. or := OrphanedResource{
  1525. Kind: "disk",
  1526. Region: zone,
  1527. Size: &volumeSize,
  1528. DiskName: *volume.VolumeId,
  1529. Url: url,
  1530. MonthlyCost: cost,
  1531. }
  1532. orphanedResources = append(orphanedResources, or)
  1533. }
  1534. }
  1535. for _, address := range addresses {
  1536. if aws.isAddressOrphaned(address) {
  1537. cost := AWSHourlyPublicIPCost * timeutil.HoursPerMonth
  1538. desc := map[string]string{}
  1539. for _, tag := range address.Tags {
  1540. if tag.Key == nil {
  1541. continue
  1542. }
  1543. if tag.Value == nil {
  1544. desc[*tag.Key] = ""
  1545. } else {
  1546. desc[*tag.Key] = *tag.Value
  1547. }
  1548. }
  1549. or := OrphanedResource{
  1550. Kind: "address",
  1551. Address: *address.PublicIp,
  1552. Description: desc,
  1553. Url: "http://console.aws.amazon.com/ec2/home?#Addresses",
  1554. MonthlyCost: &cost,
  1555. }
  1556. orphanedResources = append(orphanedResources, or)
  1557. }
  1558. }
  1559. return orphanedResources, nil
  1560. }
  1561. func (aws *AWS) findCostForDisk(disk *ec2Types.Volume) (*float64, error) {
  1562. //todo: use AWS pricing from all regions
  1563. if disk.AvailabilityZone == nil {
  1564. return nil, fmt.Errorf("nil region")
  1565. }
  1566. if disk.Size == nil {
  1567. return nil, fmt.Errorf("nil disk size")
  1568. }
  1569. class := volTypes[string(disk.VolumeType)]
  1570. key := "us-east-2" + "," + class
  1571. priceStr := aws.Pricing[key].PV.Cost
  1572. price, err := strconv.ParseFloat(priceStr, 64)
  1573. if err != nil {
  1574. return nil, err
  1575. }
  1576. cost := price * timeutil.HoursPerMonth * float64(*disk.Size)
  1577. return &cost, nil
  1578. }
  1579. // QueryAthenaPaginated executes athena query and processes results.
  1580. func (aws *AWS) QueryAthenaPaginated(ctx context.Context, query string, fn func(*athena.GetQueryResultsOutput) bool) error {
  1581. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  1582. if err != nil {
  1583. return err
  1584. }
  1585. if awsAthenaInfo.AthenaDatabase == "" || awsAthenaInfo.AthenaTable == "" || awsAthenaInfo.AthenaRegion == "" ||
  1586. awsAthenaInfo.AthenaBucketName == "" || awsAthenaInfo.AccountID == "" {
  1587. return fmt.Errorf("QueryAthenaPaginated: athena configuration incomplete")
  1588. }
  1589. queryExecutionCtx := &athenaTypes.QueryExecutionContext{
  1590. Database: awsSDK.String(awsAthenaInfo.AthenaDatabase),
  1591. }
  1592. resultConfiguration := &athenaTypes.ResultConfiguration{
  1593. OutputLocation: awsSDK.String(awsAthenaInfo.AthenaBucketName),
  1594. }
  1595. startQueryExecutionInput := &athena.StartQueryExecutionInput{
  1596. QueryString: awsSDK.String(query),
  1597. QueryExecutionContext: queryExecutionCtx,
  1598. ResultConfiguration: resultConfiguration,
  1599. }
  1600. // Only set if there is a value, the default input is nil which defaults to the 'primary' workgroup
  1601. if awsAthenaInfo.AthenaWorkgroup != "" {
  1602. startQueryExecutionInput.WorkGroup = awsSDK.String(awsAthenaInfo.AthenaWorkgroup)
  1603. }
  1604. // Create Athena Client
  1605. cfg, err := awsAthenaInfo.CreateConfig()
  1606. if err != nil {
  1607. log.Errorf("Could not retrieve Athena Configuration: %s", err.Error())
  1608. }
  1609. cli := athena.NewFromConfig(cfg)
  1610. // Query Athena
  1611. startQueryExecutionOutput, err := cli.StartQueryExecution(ctx, startQueryExecutionInput)
  1612. if err != nil {
  1613. return fmt.Errorf("QueryAthenaPaginated: start query error: %s", err.Error())
  1614. }
  1615. err = waitForQueryToComplete(ctx, cli, startQueryExecutionOutput.QueryExecutionId)
  1616. if err != nil {
  1617. return fmt.Errorf("QueryAthenaPaginated: query execution error: %s", err.Error())
  1618. }
  1619. queryResultsInput := &athena.GetQueryResultsInput{
  1620. QueryExecutionId: startQueryExecutionOutput.QueryExecutionId,
  1621. }
  1622. getQueryResultsPaginator := athena.NewGetQueryResultsPaginator(cli, queryResultsInput)
  1623. for getQueryResultsPaginator.HasMorePages() {
  1624. pg, err := getQueryResultsPaginator.NextPage(ctx)
  1625. if err != nil {
  1626. log.Errorf("QueryAthenaPaginated: NextPage error: %s", err.Error())
  1627. continue
  1628. }
  1629. fn(pg)
  1630. }
  1631. return nil
  1632. }
  1633. func waitForQueryToComplete(ctx context.Context, client *athena.Client, queryExecutionID *string) error {
  1634. inp := &athena.GetQueryExecutionInput{
  1635. QueryExecutionId: queryExecutionID,
  1636. }
  1637. isQueryStillRunning := true
  1638. for isQueryStillRunning {
  1639. qe, err := client.GetQueryExecution(ctx, inp)
  1640. if err != nil {
  1641. return err
  1642. }
  1643. if qe.QueryExecution.Status.State == "SUCCEEDED" {
  1644. isQueryStillRunning = false
  1645. continue
  1646. }
  1647. if qe.QueryExecution.Status.State != "RUNNING" && qe.QueryExecution.Status.State != "QUEUED" {
  1648. return fmt.Errorf("no query results available for query %s", *queryExecutionID)
  1649. }
  1650. time.Sleep(2 * time.Second)
  1651. }
  1652. return nil
  1653. }
  1654. type SavingsPlanData struct {
  1655. ResourceID string
  1656. EffectiveCost float64
  1657. SavingsPlanARN string
  1658. MostRecentDate string
  1659. }
  1660. func (aws *AWS) GetSavingsPlanDataFromAthena() error {
  1661. cfg, err := aws.GetConfig()
  1662. if err != nil {
  1663. aws.RIPricingError = err
  1664. return err
  1665. }
  1666. if cfg.AthenaBucketName == "" {
  1667. err = fmt.Errorf("No Athena Bucket configured")
  1668. aws.RIPricingError = err
  1669. return err
  1670. }
  1671. if aws.SavingsPlanDataByInstanceID == nil {
  1672. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData)
  1673. }
  1674. tNow := time.Now()
  1675. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1676. start := tOneDayAgo.Format("2006-01-02")
  1677. end := tNow.Format("2006-01-02")
  1678. // Use Savings Plan Effective Rate as an estimation for cost, assuming the 1h most recent period got a fully loaded savings plan.
  1679. //
  1680. q := `SELECT
  1681. line_item_usage_start_date,
  1682. savings_plan_savings_plan_a_r_n,
  1683. line_item_resource_id,
  1684. savings_plan_savings_plan_rate
  1685. FROM %s as cost_data
  1686. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1687. AND line_item_line_item_type = 'SavingsPlanCoveredUsage' ORDER BY
  1688. line_item_usage_start_date DESC`
  1689. page := 0
  1690. processResults := func(op *athena.GetQueryResultsOutput) bool {
  1691. if op == nil {
  1692. log.Errorf("GetSavingsPlanDataFromAthena: Athena page is nil")
  1693. return false
  1694. } else if op.ResultSet == nil {
  1695. log.Errorf("GetSavingsPlanDataFromAthena: Athena page.ResultSet is nil")
  1696. return false
  1697. }
  1698. aws.SavingsPlanDataLock.Lock()
  1699. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData) // Clean out the old data and only report a savingsplan price if its in the most recent run.
  1700. mostRecentDate := ""
  1701. iter := op.ResultSet.Rows
  1702. if page == 0 && len(iter) > 0 {
  1703. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  1704. }
  1705. page++
  1706. for _, r := range iter {
  1707. d := *r.Data[0].VarCharValue
  1708. if mostRecentDate == "" {
  1709. mostRecentDate = d
  1710. } else if mostRecentDate != d { // Get all most recent assignments
  1711. break
  1712. }
  1713. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1714. if err != nil {
  1715. log.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1716. }
  1717. r := &SavingsPlanData{
  1718. ResourceID: *r.Data[2].VarCharValue,
  1719. EffectiveCost: cost,
  1720. SavingsPlanARN: *r.Data[1].VarCharValue,
  1721. MostRecentDate: d,
  1722. }
  1723. aws.SavingsPlanDataByInstanceID[r.ResourceID] = r
  1724. }
  1725. log.Debugf("Found %d savings plan applied instances", len(aws.SavingsPlanDataByInstanceID))
  1726. for k, r := range aws.SavingsPlanDataByInstanceID {
  1727. log.DedupedInfof(5, "Savings Plan Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1728. }
  1729. aws.SavingsPlanDataLock.Unlock()
  1730. return true
  1731. }
  1732. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1733. log.Debugf("Running Query: %s", query)
  1734. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  1735. if err != nil {
  1736. aws.RIPricingError = err
  1737. return fmt.Errorf("Error fetching Savings Plan Data: %s", err)
  1738. }
  1739. return nil
  1740. }
  1741. type RIData struct {
  1742. ResourceID string
  1743. EffectiveCost float64
  1744. ReservationARN string
  1745. MostRecentDate string
  1746. }
  1747. func (aws *AWS) GetReservationDataFromAthena() error {
  1748. cfg, err := aws.GetConfig()
  1749. if err != nil {
  1750. aws.RIPricingError = err
  1751. return err
  1752. }
  1753. if cfg.AthenaBucketName == "" {
  1754. err = fmt.Errorf("No Athena Bucket configured")
  1755. aws.RIPricingError = err
  1756. return err
  1757. }
  1758. // Query for all column names in advance in order to validate configured
  1759. // label columns
  1760. columns, _ := aws.fetchColumns()
  1761. if !columns["reservation_reservation_a_r_n"] || !columns["reservation_effective_cost"] {
  1762. err = fmt.Errorf("no reservation data available in Athena")
  1763. aws.RIPricingError = err
  1764. return err
  1765. }
  1766. if aws.RIPricingByInstanceID == nil {
  1767. aws.RIPricingByInstanceID = make(map[string]*RIData)
  1768. }
  1769. tNow := time.Now()
  1770. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1771. start := tOneDayAgo.Format("2006-01-02")
  1772. end := tNow.Format("2006-01-02")
  1773. q := `SELECT
  1774. line_item_usage_start_date,
  1775. reservation_reservation_a_r_n,
  1776. line_item_resource_id,
  1777. reservation_effective_cost
  1778. FROM %s as cost_data
  1779. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1780. AND reservation_reservation_a_r_n <> '' ORDER BY
  1781. line_item_usage_start_date DESC`
  1782. page := 0
  1783. processResults := func(op *athena.GetQueryResultsOutput) bool {
  1784. if op == nil {
  1785. log.Errorf("GetReservationDataFromAthena: Athena page is nil")
  1786. return false
  1787. } else if op.ResultSet == nil {
  1788. log.Errorf("GetReservationDataFromAthena: Athena page.ResultSet is nil")
  1789. return false
  1790. }
  1791. aws.RIDataLock.Lock()
  1792. aws.RIPricingByInstanceID = make(map[string]*RIData) // Clean out the old data and only report a RI price if its in the most recent run.
  1793. mostRecentDate := ""
  1794. iter := op.ResultSet.Rows
  1795. if page == 0 && len(iter) > 0 {
  1796. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  1797. }
  1798. page++
  1799. for _, r := range iter {
  1800. d := *r.Data[0].VarCharValue
  1801. if mostRecentDate == "" {
  1802. mostRecentDate = d
  1803. } else if mostRecentDate != d { // Get all most recent assignments
  1804. break
  1805. }
  1806. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1807. if err != nil {
  1808. log.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1809. }
  1810. r := &RIData{
  1811. ResourceID: *r.Data[2].VarCharValue,
  1812. EffectiveCost: cost,
  1813. ReservationARN: *r.Data[1].VarCharValue,
  1814. MostRecentDate: d,
  1815. }
  1816. aws.RIPricingByInstanceID[r.ResourceID] = r
  1817. }
  1818. log.Debugf("Found %d reserved instances", len(aws.RIPricingByInstanceID))
  1819. for k, r := range aws.RIPricingByInstanceID {
  1820. log.DedupedInfof(5, "Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1821. }
  1822. aws.RIDataLock.Unlock()
  1823. return true
  1824. }
  1825. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1826. log.Debugf("Running Query: %s", query)
  1827. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  1828. if err != nil {
  1829. aws.RIPricingError = err
  1830. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  1831. }
  1832. aws.RIPricingError = nil
  1833. return nil
  1834. }
  1835. // fetchColumns returns a list of the names of all columns in the configured
  1836. // Athena tables
  1837. func (aws *AWS) fetchColumns() (map[string]bool, error) {
  1838. columnSet := map[string]bool{}
  1839. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  1840. if err != nil {
  1841. return nil, err
  1842. }
  1843. // This Query is supported by Athena tables and views
  1844. q := `SELECT column_name FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s'`
  1845. query := fmt.Sprintf(q, awsAthenaInfo.AthenaDatabase, awsAthenaInfo.AthenaTable)
  1846. pageNum := 0
  1847. athenaErr := aws.QueryAthenaPaginated(context.TODO(), query, func(page *athena.GetQueryResultsOutput) bool {
  1848. if page == nil {
  1849. log.Errorf("fetchColumns: Athena page is nil")
  1850. return false
  1851. } else if page.ResultSet == nil {
  1852. log.Errorf("fetchColumns: Athena page.ResultSet is nil")
  1853. return false
  1854. }
  1855. // remove header row 'column_name'
  1856. rows := page.ResultSet.Rows[1:]
  1857. for _, row := range rows {
  1858. columnSet[*row.Data[0].VarCharValue] = true
  1859. }
  1860. pageNum++
  1861. return true
  1862. })
  1863. if athenaErr != nil {
  1864. return columnSet, athenaErr
  1865. }
  1866. if len(columnSet) == 0 {
  1867. log.Infof("No columns retrieved from Athena")
  1868. }
  1869. return columnSet, nil
  1870. }
  1871. type spotInfo struct {
  1872. Timestamp string `csv:"Timestamp"`
  1873. UsageType string `csv:"UsageType"`
  1874. Operation string `csv:"Operation"`
  1875. InstanceID string `csv:"InstanceID"`
  1876. MyBidID string `csv:"MyBidID"`
  1877. MyMaxPrice string `csv:"MyMaxPrice"`
  1878. MarketPrice string `csv:"MarketPrice"`
  1879. Charge string `csv:"Charge"`
  1880. Version string `csv:"Version"`
  1881. }
  1882. func (aws *AWS) parseSpotData(bucket string, prefix string, projectID string, region string) (map[string]*spotInfo, error) {
  1883. aws.ConfigureAuth() // configure aws api authentication by setting env vars
  1884. s3Prefix := projectID
  1885. if len(prefix) != 0 {
  1886. s3Prefix = prefix + "/" + s3Prefix
  1887. }
  1888. aak, err := aws.GetAWSAccessKey()
  1889. if err != nil {
  1890. return nil, err
  1891. }
  1892. cfg, err := aak.CreateConfig(region)
  1893. if err != nil {
  1894. return nil, err
  1895. }
  1896. cli := s3.NewFromConfig(cfg)
  1897. downloader := manager.NewDownloader(cli)
  1898. tNow := time.Now()
  1899. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1900. ls := &s3.ListObjectsInput{
  1901. Bucket: awsSDK.String(bucket),
  1902. Prefix: awsSDK.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1903. }
  1904. ls2 := &s3.ListObjectsInput{
  1905. Bucket: awsSDK.String(bucket),
  1906. Prefix: awsSDK.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1907. }
  1908. lso, err := cli.ListObjects(context.TODO(), ls)
  1909. if err != nil {
  1910. aws.serviceAccountChecks.set("bucketList", &ServiceAccountCheck{
  1911. Message: "Bucket List Permissions Available",
  1912. Status: false,
  1913. AdditionalInfo: err.Error(),
  1914. })
  1915. return nil, err
  1916. } else {
  1917. aws.serviceAccountChecks.set("bucketList", &ServiceAccountCheck{
  1918. Message: "Bucket List Permissions Available",
  1919. Status: true,
  1920. })
  1921. }
  1922. lsoLen := len(lso.Contents)
  1923. log.Debugf("Found %d spot data files from yesterday", lsoLen)
  1924. if lsoLen == 0 {
  1925. log.Debugf("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1926. }
  1927. lso2, err := cli.ListObjects(context.TODO(), ls2)
  1928. if err != nil {
  1929. return nil, err
  1930. }
  1931. lso2Len := len(lso2.Contents)
  1932. log.Debugf("Found %d spot data files from today", lso2Len)
  1933. if lso2Len == 0 {
  1934. log.Debugf("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1935. }
  1936. // TODO: Worth it to use LastModifiedDate to determine if we should reparse the spot data?
  1937. var keys []*string
  1938. for _, obj := range lso.Contents {
  1939. keys = append(keys, obj.Key)
  1940. }
  1941. for _, obj := range lso2.Contents {
  1942. keys = append(keys, obj.Key)
  1943. }
  1944. header, err := csvutil.Header(spotInfo{}, "csv")
  1945. if err != nil {
  1946. return nil, err
  1947. }
  1948. fieldsPerRecord := len(header)
  1949. spots := make(map[string]*spotInfo)
  1950. for _, key := range keys {
  1951. getObj := &s3.GetObjectInput{
  1952. Bucket: awsSDK.String(bucket),
  1953. Key: key,
  1954. }
  1955. buf := manager.NewWriteAtBuffer([]byte{})
  1956. _, err := downloader.Download(context.TODO(), buf, getObj)
  1957. if err != nil {
  1958. aws.serviceAccountChecks.set("objectList", &ServiceAccountCheck{
  1959. Message: "Object Get Permissions Available",
  1960. Status: false,
  1961. AdditionalInfo: err.Error(),
  1962. })
  1963. return nil, err
  1964. } else {
  1965. aws.serviceAccountChecks.set("objectList", &ServiceAccountCheck{
  1966. Message: "Object Get Permissions Available",
  1967. Status: true,
  1968. })
  1969. }
  1970. r := bytes.NewReader(buf.Bytes())
  1971. gr, err := gzip.NewReader(r)
  1972. if err != nil {
  1973. return nil, err
  1974. }
  1975. csvReader := csv.NewReader(gr)
  1976. csvReader.Comma = '\t'
  1977. csvReader.FieldsPerRecord = fieldsPerRecord
  1978. dec, err := csvutil.NewDecoder(csvReader, header...)
  1979. if err != nil {
  1980. return nil, err
  1981. }
  1982. var foundVersion string
  1983. for {
  1984. spot := spotInfo{}
  1985. err := dec.Decode(&spot)
  1986. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1987. if err == io.EOF {
  1988. break
  1989. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1990. rec := dec.Record()
  1991. // the first two "Record()" will be the comment lines
  1992. // and they show up as len() == 1
  1993. // the first of which is "#Version"
  1994. // the second of which is "#Fields: "
  1995. if len(rec) != 1 {
  1996. log.Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1997. continue
  1998. }
  1999. if len(foundVersion) == 0 {
  2000. spotFeedVersion := rec[0]
  2001. log.Debugf("Spot feed version is \"%s\"", spotFeedVersion)
  2002. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  2003. if matches != nil {
  2004. foundVersion = matches[1]
  2005. if foundVersion != supportedSpotFeedVersion {
  2006. log.Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  2007. break
  2008. }
  2009. }
  2010. continue
  2011. } else if strings.Index(rec[0], "#") == 0 {
  2012. continue
  2013. } else {
  2014. log.Infof("skipping non-TSV line: %s", rec)
  2015. continue
  2016. }
  2017. } else if err != nil {
  2018. log.Warnf("Error during spot info decode: %+v", err)
  2019. continue
  2020. }
  2021. log.DedupedInfof(5, "Found spot info for: %s", spot.InstanceID)
  2022. spots[spot.InstanceID] = &spot
  2023. }
  2024. gr.Close()
  2025. }
  2026. return spots, nil
  2027. }
  2028. // ApplyReservedInstancePricing TODO
  2029. func (aws *AWS) ApplyReservedInstancePricing(nodes map[string]*Node) {
  2030. }
  2031. func (aws *AWS) ServiceAccountStatus() *ServiceAccountStatus {
  2032. return aws.serviceAccountChecks.getStatus()
  2033. }
  2034. func (aws *AWS) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  2035. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  2036. }
  2037. // Regions returns a predefined list of AWS regions
  2038. func (aws *AWS) Regions() []string {
  2039. return awsRegions
  2040. }