provider.go 75 KB

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