provider.go 80 KB

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