awsprovider.go 69 KB

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