awsprovider.go 68 KB

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