awsprovider.go 69 KB

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