provider.go 72 KB

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