provider.go 69 KB

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