provider.go 80 KB

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