provider.go 79 KB

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