awsprovider.go 63 KB

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