awsprovider.go 63 KB

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