provider.go 69 KB

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