provider.go 75 KB

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