awsprovider.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337
  1. package cloud
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "encoding/csv"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "k8s.io/klog"
  18. "github.com/kubecost/cost-model/pkg/clustercache"
  19. "github.com/kubecost/cost-model/pkg/env"
  20. "github.com/kubecost/cost-model/pkg/errors"
  21. "github.com/kubecost/cost-model/pkg/log"
  22. "github.com/kubecost/cost-model/pkg/util"
  23. "github.com/aws/aws-sdk-go/aws"
  24. "github.com/aws/aws-sdk-go/aws/awserr"
  25. "github.com/aws/aws-sdk-go/aws/credentials"
  26. "github.com/aws/aws-sdk-go/aws/credentials/stscreds"
  27. "github.com/aws/aws-sdk-go/aws/session"
  28. "github.com/aws/aws-sdk-go/service/athena"
  29. "github.com/aws/aws-sdk-go/service/ec2"
  30. "github.com/aws/aws-sdk-go/service/s3"
  31. "github.com/aws/aws-sdk-go/service/s3/s3manager"
  32. "github.com/jszwec/csvutil"
  33. v1 "k8s.io/api/core/v1"
  34. )
  35. const awsReservedInstancePricePerHour = 0.0287
  36. const supportedSpotFeedVersion = "1"
  37. const SpotInfoUpdateType = "spotinfo"
  38. const AthenaInfoUpdateType = "athenainfo"
  39. // How often spot data is refreshed
  40. const SpotRefreshDuration = 15 * time.Minute
  41. const defaultConfigPath = "/var/configs/"
  42. var awsRegions = []string{
  43. "us-east-2",
  44. "us-east-1",
  45. "us-west-1",
  46. "us-west-2",
  47. "ap-east-1",
  48. "ap-south-1",
  49. "ap-northeast-3",
  50. "ap-northeast-2",
  51. "ap-southeast-1",
  52. "ap-southeast-2",
  53. "ap-northeast-1",
  54. "ca-central-1",
  55. "cn-north-1",
  56. "cn-northwest-1",
  57. "eu-central-1",
  58. "eu-west-1",
  59. "eu-west-2",
  60. "eu-west-3",
  61. "eu-north-1",
  62. "me-south-1",
  63. "sa-east-1",
  64. "us-gov-east-1",
  65. "us-gov-west-1",
  66. }
  67. // AWS represents an Amazon Provider
  68. type AWS struct {
  69. Pricing map[string]*AWSProductTerms
  70. SpotPricingByInstanceID map[string]*spotInfo
  71. SpotPricingUpdatedAt *time.Time
  72. SpotRefreshRunning bool
  73. SpotPricingLock sync.RWMutex
  74. RIPricingByInstanceID map[string]*RIData
  75. RIDataRunning bool
  76. RIDataLock sync.RWMutex
  77. SavingsPlanDataByInstanceID map[string]*SavingsPlanData
  78. SavingsPlanDataRunning bool
  79. SavingsPlanDataLock sync.RWMutex
  80. ValidPricingKeys map[string]bool
  81. Clientset clustercache.ClusterCache
  82. BaseCPUPrice string
  83. BaseRAMPrice string
  84. BaseGPUPrice string
  85. BaseSpotCPUPrice string
  86. BaseSpotRAMPrice string
  87. SpotLabelName string
  88. SpotLabelValue string
  89. ServiceKeyName string
  90. ServiceKeySecret string
  91. SpotDataRegion string
  92. SpotDataBucket string
  93. SpotDataPrefix string
  94. ProjectID string
  95. DownloadPricingDataLock sync.RWMutex
  96. Config *ProviderConfig
  97. *CustomProvider
  98. }
  99. type AWSAccessKey struct {
  100. AccessKeyID string `json:"aws_access_key_id"`
  101. SecretAccessKey string `json:"aws_secret_access_key"`
  102. }
  103. // AWSPricing maps a k8s node to an AWS Pricing "product"
  104. type AWSPricing struct {
  105. Products map[string]*AWSProduct `json:"products"`
  106. Terms AWSPricingTerms `json:"terms"`
  107. }
  108. // AWSProduct represents a purchased SKU
  109. type AWSProduct struct {
  110. Sku string `json:"sku"`
  111. Attributes AWSProductAttributes `json:"attributes"`
  112. }
  113. // AWSProductAttributes represents metadata about the product used to map to a node.
  114. type AWSProductAttributes struct {
  115. Location string `json:"location"`
  116. InstanceType string `json:"instanceType"`
  117. Memory string `json:"memory"`
  118. Storage string `json:"storage"`
  119. VCpu string `json:"vcpu"`
  120. UsageType string `json:"usagetype"`
  121. OperatingSystem string `json:"operatingSystem"`
  122. PreInstalledSw string `json:"preInstalledSw"`
  123. InstanceFamily string `json:"instanceFamily"`
  124. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  125. }
  126. // AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
  127. type AWSPricingTerms struct {
  128. OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
  129. Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
  130. }
  131. // AWSOfferTerm is a sku extension used to pay for the node.
  132. type AWSOfferTerm struct {
  133. Sku string `json:"sku"`
  134. PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
  135. }
  136. // AWSRateCode encodes data about the price of a product
  137. type AWSRateCode struct {
  138. Unit string `json:"unit"`
  139. PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
  140. }
  141. // AWSCurrencyCode is the localized currency. (TODO: support non-USD)
  142. type AWSCurrencyCode struct {
  143. USD string `json:"USD"`
  144. }
  145. // AWSProductTerms represents the full terms of the product
  146. type AWSProductTerms struct {
  147. Sku string `json:"sku"`
  148. OnDemand *AWSOfferTerm `json:"OnDemand"`
  149. Reserved *AWSOfferTerm `json:"Reserved"`
  150. Memory string `json:"memory"`
  151. Storage string `json:"storage"`
  152. VCpu string `json:"vcpu"`
  153. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  154. PV *PV `json:"pv"`
  155. }
  156. // ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
  157. const ClusterIdEnvVar = "AWS_CLUSTER_ID"
  158. // OnDemandRateCode is appended to an node sku
  159. const OnDemandRateCode = ".JRTCKXETXF"
  160. // ReservedRateCode is appended to a node sku
  161. const ReservedRateCode = ".38NPMPTW36"
  162. // HourlyRateCode is appended to a node sku
  163. const HourlyRateCode = ".6YS6EN2CT7"
  164. // volTypes are used to map between AWS UsageTypes and
  165. // EBS volume types, as they would appear in K8s storage class
  166. // name and the EC2 API.
  167. var volTypes = map[string]string{
  168. "EBS:VolumeUsage.gp2": "gp2",
  169. "EBS:VolumeUsage": "standard",
  170. "EBS:VolumeUsage.sc1": "sc1",
  171. "EBS:VolumeP-IOPS.piops": "io1",
  172. "EBS:VolumeUsage.st1": "st1",
  173. "EBS:VolumeUsage.piops": "io1",
  174. "gp2": "EBS:VolumeUsage.gp2",
  175. "standard": "EBS:VolumeUsage",
  176. "sc1": "EBS:VolumeUsage.sc1",
  177. "io1": "EBS:VolumeUsage.piops",
  178. "st1": "EBS:VolumeUsage.st1",
  179. }
  180. // locationToRegion maps AWS region names (As they come from Billing)
  181. // to actual region identifiers
  182. var locationToRegion = map[string]string{
  183. "US East (Ohio)": "us-east-2",
  184. "US East (N. Virginia)": "us-east-1",
  185. "US West (N. California)": "us-west-1",
  186. "US West (Oregon)": "us-west-2",
  187. "Asia Pacific (Hong Kong)": "ap-east-1",
  188. "Asia Pacific (Mumbai)": "ap-south-1",
  189. "Asia Pacific (Osaka-Local)": "ap-northeast-3",
  190. "Asia Pacific (Seoul)": "ap-northeast-2",
  191. "Asia Pacific (Singapore)": "ap-southeast-1",
  192. "Asia Pacific (Sydney)": "ap-southeast-2",
  193. "Asia Pacific (Tokyo)": "ap-northeast-1",
  194. "Canada (Central)": "ca-central-1",
  195. "China (Beijing)": "cn-north-1",
  196. "China (Ningxia)": "cn-northwest-1",
  197. "EU (Frankfurt)": "eu-central-1",
  198. "EU (Ireland)": "eu-west-1",
  199. "EU (London)": "eu-west-2",
  200. "EU (Paris)": "eu-west-3",
  201. "EU (Stockholm)": "eu-north-1",
  202. "South America (Sao Paulo)": "sa-east-1",
  203. "AWS GovCloud (US-East)": "us-gov-east-1",
  204. "AWS GovCloud (US)": "us-gov-west-1",
  205. }
  206. var regionToBillingRegionCode = map[string]string{
  207. "us-east-2": "USE2",
  208. "us-east-1": "",
  209. "us-west-1": "USW1",
  210. "us-west-2": "USW2",
  211. "ap-east-1": "APE1",
  212. "ap-south-1": "APS3",
  213. "ap-northeast-3": "APN3",
  214. "ap-northeast-2": "APN2",
  215. "ap-southeast-1": "APS1",
  216. "ap-southeast-2": "APS2",
  217. "ap-northeast-1": "APN1",
  218. "ca-central-1": "CAN1",
  219. "cn-north-1": "",
  220. "cn-northwest-1": "",
  221. "eu-central-1": "EUC1",
  222. "eu-west-1": "EU",
  223. "eu-west-2": "EUW2",
  224. "eu-west-3": "EUW3",
  225. "eu-north-1": "EUN1",
  226. "sa-east-1": "SAE1",
  227. "us-gov-east-1": "UGE1",
  228. "us-gov-west-1": "UGW1",
  229. }
  230. var loadedAWSSecret bool = false
  231. var awsSecret *AWSAccessKey = nil
  232. func (aws *AWS) GetLocalStorageQuery(window, offset string, rate bool, used bool) string {
  233. return ""
  234. }
  235. // KubeAttrConversion maps the k8s labels for region to an aws region
  236. func (aws *AWS) KubeAttrConversion(location, instanceType, operatingSystem string) string {
  237. operatingSystem = strings.ToLower(operatingSystem)
  238. region := locationToRegion[location]
  239. return region + "," + instanceType + "," + operatingSystem
  240. }
  241. type AwsSpotFeedInfo struct {
  242. BucketName string `json:"bucketName"`
  243. Prefix string `json:"prefix"`
  244. Region string `json:"region"`
  245. AccountID string `json:"projectID"`
  246. ServiceKeyName string `json:"serviceKeyName"`
  247. ServiceKeySecret string `json:"serviceKeySecret"`
  248. SpotLabel string `json:"spotLabel"`
  249. SpotLabelValue string `json:"spotLabelValue"`
  250. }
  251. type AwsAthenaInfo struct {
  252. AthenaBucketName string `json:"athenaBucketName"`
  253. AthenaRegion string `json:"athenaRegion"`
  254. AthenaDatabase string `json:"athenaDatabase"`
  255. AthenaTable string `json:"athenaTable"`
  256. ServiceKeyName string `json:"serviceKeyName"`
  257. ServiceKeySecret string `json:"serviceKeySecret"`
  258. AccountID string `json:"projectID"`
  259. MasterPayerARN string `json:"masterPayerARN"`
  260. }
  261. func (aws *AWS) GetManagementPlatform() (string, error) {
  262. nodes := aws.Clientset.GetAllNodes()
  263. if len(nodes) > 0 {
  264. n := nodes[0]
  265. version := n.Status.NodeInfo.KubeletVersion
  266. if strings.Contains(version, "eks") {
  267. return "eks", nil
  268. }
  269. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  270. return "kops", nil
  271. }
  272. }
  273. return "", nil
  274. }
  275. func (aws *AWS) GetConfig() (*CustomPricing, error) {
  276. c, err := aws.Config.GetCustomPricingData()
  277. if c.Discount == "" {
  278. c.Discount = "0%"
  279. }
  280. if c.NegotiatedDiscount == "" {
  281. c.NegotiatedDiscount = "0%"
  282. }
  283. if err != nil {
  284. return nil, err
  285. }
  286. return c, nil
  287. }
  288. func (aws *AWS) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  289. return aws.Config.UpdateFromMap(a)
  290. }
  291. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  292. return aws.Config.Update(func(c *CustomPricing) error {
  293. if updateType == SpotInfoUpdateType {
  294. a := AwsSpotFeedInfo{}
  295. err := json.NewDecoder(r).Decode(&a)
  296. if err != nil {
  297. return err
  298. }
  299. c.ServiceKeyName = a.ServiceKeyName
  300. if a.ServiceKeySecret != "" {
  301. c.ServiceKeySecret = a.ServiceKeySecret
  302. }
  303. c.SpotDataPrefix = a.Prefix
  304. c.SpotDataBucket = a.BucketName
  305. c.ProjectID = a.AccountID
  306. c.SpotDataRegion = a.Region
  307. c.SpotLabel = a.SpotLabel
  308. c.SpotLabelValue = a.SpotLabelValue
  309. } else if updateType == AthenaInfoUpdateType {
  310. a := AwsAthenaInfo{}
  311. err := json.NewDecoder(r).Decode(&a)
  312. if err != nil {
  313. return err
  314. }
  315. c.AthenaBucketName = a.AthenaBucketName
  316. c.AthenaRegion = a.AthenaRegion
  317. c.AthenaDatabase = a.AthenaDatabase
  318. c.AthenaTable = a.AthenaTable
  319. c.ServiceKeyName = a.ServiceKeyName
  320. if a.ServiceKeySecret != "" {
  321. c.ServiceKeySecret = a.ServiceKeySecret
  322. }
  323. if a.MasterPayerARN != "" {
  324. c.MasterPayerARN = a.MasterPayerARN
  325. }
  326. c.AthenaProjectID = a.AccountID
  327. } else {
  328. a := make(map[string]interface{})
  329. err := json.NewDecoder(r).Decode(&a)
  330. if err != nil {
  331. return err
  332. }
  333. for k, v := range a {
  334. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  335. vstr, ok := v.(string)
  336. if ok {
  337. err := SetCustomPricingField(c, kUpper, vstr)
  338. if err != nil {
  339. return err
  340. }
  341. } else {
  342. sci := v.(map[string]interface{})
  343. sc := make(map[string]string)
  344. for k, val := range sci {
  345. sc[k] = val.(string)
  346. }
  347. c.SharedCosts = sc //todo: support reflection/multiple map fields
  348. }
  349. }
  350. }
  351. if env.IsRemoteEnabled() {
  352. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  353. if err != nil {
  354. return err
  355. }
  356. }
  357. return nil
  358. })
  359. }
  360. type awsKey struct {
  361. SpotLabelName string
  362. SpotLabelValue string
  363. Labels map[string]string
  364. ProviderID string
  365. }
  366. func (k *awsKey) GPUType() string {
  367. return ""
  368. }
  369. func (k *awsKey) ID() string {
  370. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)") // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  371. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  372. if matchNum == 2 {
  373. return group
  374. }
  375. }
  376. klog.V(3).Infof("Could not find instance ID in \"%s\"", k.ProviderID)
  377. return ""
  378. }
  379. func (k *awsKey) Features() string {
  380. instanceType := k.Labels[v1.LabelInstanceType]
  381. var operatingSystem string
  382. operatingSystem, ok := k.Labels[v1.LabelOSStable]
  383. if !ok {
  384. operatingSystem = k.Labels["beta.kubernetes.io/os"]
  385. }
  386. region := k.Labels[v1.LabelZoneRegion]
  387. key := region + "," + instanceType + "," + operatingSystem
  388. usageType := "preemptible"
  389. spotKey := key + "," + usageType
  390. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  391. return spotKey
  392. }
  393. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  394. return spotKey
  395. }
  396. return key
  397. }
  398. func (aws *AWS) PVPricing(pvk PVKey) (*PV, error) {
  399. pricing, ok := aws.Pricing[pvk.Features()]
  400. if !ok {
  401. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  402. return &PV{}, nil
  403. }
  404. return pricing.PV, nil
  405. }
  406. type awsPVKey struct {
  407. Labels map[string]string
  408. StorageClassParameters map[string]string
  409. StorageClassName string
  410. Name string
  411. DefaultRegion string
  412. }
  413. func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  414. return &awsPVKey{
  415. Labels: pv.Labels,
  416. StorageClassName: pv.Spec.StorageClassName,
  417. StorageClassParameters: parameters,
  418. Name: pv.Name,
  419. DefaultRegion: defaultRegion,
  420. }
  421. }
  422. func (key *awsPVKey) GetStorageClass() string {
  423. return key.StorageClassName
  424. }
  425. func (key *awsPVKey) Features() string {
  426. storageClass := key.StorageClassParameters["type"]
  427. if storageClass == "standard" {
  428. storageClass = "gp2"
  429. }
  430. // Storage class names are generally EBS volume types (gp2)
  431. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  432. // Converts between the 2
  433. region := key.Labels[v1.LabelZoneRegion]
  434. //if region == "" {
  435. // region = "us-east-1"
  436. //}
  437. class, ok := volTypes[storageClass]
  438. if !ok {
  439. klog.V(4).Infof("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  440. }
  441. return region + "," + class
  442. }
  443. // GetKey maps node labels to information needed to retrieve pricing data
  444. func (aws *AWS) GetKey(labels map[string]string, n *v1.Node) Key {
  445. return &awsKey{
  446. SpotLabelName: aws.SpotLabelName,
  447. SpotLabelValue: aws.SpotLabelValue,
  448. Labels: labels,
  449. ProviderID: labels["providerID"],
  450. }
  451. }
  452. func (aws *AWS) isPreemptible(key string) bool {
  453. s := strings.Split(key, ",")
  454. if len(s) == 4 && s[3] == "preemptible" {
  455. return true
  456. }
  457. return false
  458. }
  459. // DownloadPricingData fetches data from the AWS Pricing API
  460. func (aws *AWS) DownloadPricingData() error {
  461. aws.DownloadPricingDataLock.Lock()
  462. defer aws.DownloadPricingDataLock.Unlock()
  463. c, err := aws.Config.GetCustomPricingData()
  464. if err != nil {
  465. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  466. }
  467. aws.BaseCPUPrice = c.CPU
  468. aws.BaseRAMPrice = c.RAM
  469. aws.BaseGPUPrice = c.GPU
  470. aws.BaseSpotCPUPrice = c.SpotCPU
  471. aws.BaseSpotRAMPrice = c.SpotRAM
  472. aws.SpotLabelName = c.SpotLabel
  473. aws.SpotLabelValue = c.SpotLabelValue
  474. aws.SpotDataBucket = c.SpotDataBucket
  475. aws.SpotDataPrefix = c.SpotDataPrefix
  476. aws.ProjectID = c.ProjectID
  477. aws.SpotDataRegion = c.SpotDataRegion
  478. skn, sks := aws.getAWSAuth(false, c)
  479. aws.ServiceKeyName = skn
  480. aws.ServiceKeySecret = sks
  481. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  482. klog.V(1).Infof("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  483. }
  484. nodeList := aws.Clientset.GetAllNodes()
  485. inputkeys := make(map[string]bool)
  486. for _, n := range nodeList {
  487. labels := n.GetObjectMeta().GetLabels()
  488. key := aws.GetKey(labels, n)
  489. inputkeys[key.Features()] = true
  490. }
  491. pvList := aws.Clientset.GetAllPersistentVolumes()
  492. storageClasses := aws.Clientset.GetAllStorageClasses()
  493. storageClassMap := make(map[string]map[string]string)
  494. for _, storageClass := range storageClasses {
  495. params := storageClass.Parameters
  496. storageClassMap[storageClass.ObjectMeta.Name] = params
  497. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  498. storageClassMap["default"] = params
  499. storageClassMap[""] = params
  500. }
  501. }
  502. pvkeys := make(map[string]PVKey)
  503. for _, pv := range pvList {
  504. params, ok := storageClassMap[pv.Spec.StorageClassName]
  505. if !ok {
  506. klog.V(2).Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  507. continue
  508. }
  509. key := aws.GetPVKey(pv, params, "")
  510. pvkeys[key.Features()] = key
  511. }
  512. // RIDataRunning establishes the existance of the goroutine. Since it's possible we
  513. // run multiple downloads, we don't want to create multiple go routines if one already exists
  514. if !aws.RIDataRunning && c.AthenaBucketName != "" {
  515. err = aws.GetReservationDataFromAthena() // Block until one run has completed.
  516. if err != nil {
  517. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  518. } else { // If we make one successful run, check on new reservation data every hour
  519. go func() {
  520. defer errors.HandlePanic()
  521. aws.RIDataRunning = true
  522. for {
  523. klog.Infof("Reserved Instance watcher running... next update in 1h")
  524. time.Sleep(time.Hour)
  525. err := aws.GetReservationDataFromAthena()
  526. if err != nil {
  527. klog.Infof("Error updating RI data: %s", err.Error())
  528. }
  529. }
  530. }()
  531. }
  532. }
  533. if !aws.SavingsPlanDataRunning && c.AthenaBucketName != "" {
  534. err = aws.GetSavingsPlanDataFromAthena()
  535. if err != nil {
  536. klog.V(1).Infof("Failed to lookup savings plan data: %s", err.Error())
  537. } else {
  538. go func() {
  539. defer errors.HandlePanic()
  540. aws.SavingsPlanDataRunning = true
  541. for {
  542. klog.Infof("Savings Plan watcher running... next update in 1h")
  543. time.Sleep(time.Hour)
  544. err := aws.GetSavingsPlanDataFromAthena()
  545. if err != nil {
  546. klog.Infof("Error updating Savings Plan data: %s", err.Error())
  547. }
  548. }
  549. }()
  550. }
  551. }
  552. aws.Pricing = make(map[string]*AWSProductTerms)
  553. aws.ValidPricingKeys = make(map[string]bool)
  554. skusToKeys := make(map[string]string)
  555. pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json"
  556. klog.V(2).Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  557. resp, err := http.Get(pricingURL)
  558. if err != nil {
  559. klog.V(2).Infof("Bogus fetch of \"%s\": %v", pricingURL, err)
  560. return err
  561. }
  562. klog.V(2).Infof("Finished downloading \"%s\"", pricingURL)
  563. dec := json.NewDecoder(resp.Body)
  564. for {
  565. t, err := dec.Token()
  566. if err == io.EOF {
  567. klog.V(2).Infof("done loading \"%s\"\n", pricingURL)
  568. break
  569. }
  570. if t == "products" {
  571. _, err := dec.Token() // this should parse the opening "{""
  572. if err != nil {
  573. return err
  574. }
  575. for dec.More() {
  576. _, err := dec.Token() // the sku token
  577. if err != nil {
  578. return err
  579. }
  580. product := &AWSProduct{}
  581. err = dec.Decode(&product)
  582. if err != nil {
  583. klog.V(1).Infof("Error parsing response from \"%s\": %v", pricingURL, err.Error())
  584. break
  585. }
  586. if product.Attributes.PreInstalledSw == "NA" &&
  587. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) {
  588. key := aws.KubeAttrConversion(product.Attributes.Location, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  589. spotKey := key + ",preemptible"
  590. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  591. productTerms := &AWSProductTerms{
  592. Sku: product.Sku,
  593. Memory: product.Attributes.Memory,
  594. Storage: product.Attributes.Storage,
  595. VCpu: product.Attributes.VCpu,
  596. GPU: product.Attributes.GPU,
  597. }
  598. aws.Pricing[key] = productTerms
  599. aws.Pricing[spotKey] = productTerms
  600. skusToKeys[product.Sku] = key
  601. }
  602. aws.ValidPricingKeys[key] = true
  603. aws.ValidPricingKeys[spotKey] = true
  604. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  605. // UsageTypes may be prefixed with a region code - we're removing this when using
  606. // volTypes to keep lookups generic
  607. usageTypeRegx := regexp.MustCompile(".*(-|^)(EBS.+)")
  608. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  609. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  610. key := locationToRegion[product.Attributes.Location] + "," + usageTypeNoRegion
  611. spotKey := key + ",preemptible"
  612. pv := &PV{
  613. Class: volTypes[usageTypeNoRegion],
  614. Region: locationToRegion[product.Attributes.Location],
  615. }
  616. productTerms := &AWSProductTerms{
  617. Sku: product.Sku,
  618. PV: pv,
  619. }
  620. aws.Pricing[key] = productTerms
  621. aws.Pricing[spotKey] = productTerms
  622. skusToKeys[product.Sku] = key
  623. aws.ValidPricingKeys[key] = true
  624. aws.ValidPricingKeys[spotKey] = true
  625. }
  626. }
  627. }
  628. if t == "terms" {
  629. _, err := dec.Token() // this should parse the opening "{""
  630. if err != nil {
  631. return err
  632. }
  633. termType, err := dec.Token()
  634. if err != nil {
  635. return err
  636. }
  637. if termType == "OnDemand" {
  638. _, err := dec.Token()
  639. if err != nil { // again, should parse an opening "{"
  640. return err
  641. }
  642. for dec.More() {
  643. sku, err := dec.Token()
  644. if err != nil {
  645. return err
  646. }
  647. _, err = dec.Token() // another opening "{"
  648. if err != nil {
  649. return err
  650. }
  651. skuOnDemand, err := dec.Token()
  652. if err != nil {
  653. return err
  654. }
  655. offerTerm := &AWSOfferTerm{}
  656. err = dec.Decode(&offerTerm)
  657. if err != nil {
  658. klog.V(1).Infof("Error decoding AWS Offer Term: " + err.Error())
  659. }
  660. if sku.(string)+OnDemandRateCode == skuOnDemand {
  661. key, ok := skusToKeys[sku.(string)]
  662. spotKey := key + ",preemptible"
  663. if ok {
  664. aws.Pricing[key].OnDemand = offerTerm
  665. aws.Pricing[spotKey].OnDemand = offerTerm
  666. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  667. // If the specific UsageType is the per IO cost used on io1 volumes
  668. // we need to add the per IO cost to the io1 PV cost
  669. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  670. // Add the per IO cost to the PV object for the io1 volume type
  671. aws.Pricing[key].PV.CostPerIO = cost
  672. } else if strings.Contains(key, "EBS:Volume") {
  673. // If volume, we need to get hourly cost and add it to the PV object
  674. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  675. costFloat, _ := strconv.ParseFloat(cost, 64)
  676. hourlyPrice := costFloat / 730
  677. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  678. }
  679. }
  680. }
  681. _, err = dec.Token()
  682. if err != nil {
  683. return err
  684. }
  685. }
  686. _, err = dec.Token()
  687. if err != nil {
  688. return err
  689. }
  690. }
  691. }
  692. }
  693. // Always run spot pricing refresh when performing download
  694. aws.refreshSpotPricing(true)
  695. // Only start a single refresh goroutine
  696. if !aws.SpotRefreshRunning {
  697. aws.SpotRefreshRunning = true
  698. go func() {
  699. defer errors.HandlePanic()
  700. for {
  701. klog.Infof("Spot Pricing Refresh scheduled in %.2f minutes.", SpotRefreshDuration.Minutes())
  702. time.Sleep(SpotRefreshDuration)
  703. // Reoccurring refresh checks update times
  704. aws.refreshSpotPricing(false)
  705. }
  706. }()
  707. }
  708. return nil
  709. }
  710. func (aws *AWS) refreshSpotPricing(force bool) {
  711. aws.SpotPricingLock.Lock()
  712. defer aws.SpotPricingLock.Unlock()
  713. now := time.Now().UTC()
  714. updateTime := now.Add(-SpotRefreshDuration)
  715. // Return if there was an update time set and an hour hasn't elapsed
  716. if !force && aws.SpotPricingUpdatedAt != nil && aws.SpotPricingUpdatedAt.After(updateTime) {
  717. return
  718. }
  719. sp, err := parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion, aws.ServiceKeyName, aws.ServiceKeySecret)
  720. if err != nil {
  721. klog.V(1).Infof("Skipping AWS spot data download: %s", err.Error())
  722. return
  723. }
  724. // update time last updated
  725. aws.SpotPricingUpdatedAt = &now
  726. aws.SpotPricingByInstanceID = sp
  727. }
  728. // Stubbed NetworkPricing for AWS. Pull directly from aws.json for now
  729. func (aws *AWS) NetworkPricing() (*Network, error) {
  730. cpricing, err := aws.Config.GetCustomPricingData()
  731. if err != nil {
  732. return nil, err
  733. }
  734. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  735. if err != nil {
  736. return nil, err
  737. }
  738. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  739. if err != nil {
  740. return nil, err
  741. }
  742. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  743. if err != nil {
  744. return nil, err
  745. }
  746. return &Network{
  747. ZoneNetworkEgressCost: znec,
  748. RegionNetworkEgressCost: rnec,
  749. InternetNetworkEgressCost: inec,
  750. }, nil
  751. }
  752. // AllNodePricing returns all the billing data fetched.
  753. func (aws *AWS) AllNodePricing() (interface{}, error) {
  754. aws.DownloadPricingDataLock.RLock()
  755. defer aws.DownloadPricingDataLock.RUnlock()
  756. return aws.Pricing, nil
  757. }
  758. func (aws *AWS) spotPricing(instanceID string) (*spotInfo, bool) {
  759. aws.SpotPricingLock.RLock()
  760. defer aws.SpotPricingLock.RUnlock()
  761. info, ok := aws.SpotPricingByInstanceID[instanceID]
  762. return info, ok
  763. }
  764. func (aws *AWS) reservedInstancePricing(instanceID string) (*RIData, bool) {
  765. aws.RIDataLock.RLock()
  766. defer aws.RIDataLock.RUnlock()
  767. data, ok := aws.RIPricingByInstanceID[instanceID]
  768. return data, ok
  769. }
  770. func (aws *AWS) savingsPlanPricing(instanceID string) (*SavingsPlanData, bool) {
  771. aws.SavingsPlanDataLock.RLock()
  772. defer aws.SavingsPlanDataLock.RUnlock()
  773. data, ok := aws.SavingsPlanDataByInstanceID[instanceID]
  774. return data, ok
  775. }
  776. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  777. key := k.Features()
  778. if spotInfo, ok := aws.spotPricing(k.ID()); ok {
  779. var spotcost string
  780. klog.V(3).Infof("Looking up spot data from feed for node %s", k.ID())
  781. arr := strings.Split(spotInfo.Charge, " ")
  782. if len(arr) == 2 {
  783. spotcost = arr[0]
  784. } else {
  785. klog.V(2).Infof("Spot data for node %s is missing", k.ID())
  786. }
  787. return &Node{
  788. Cost: spotcost,
  789. VCPU: terms.VCpu,
  790. RAM: terms.Memory,
  791. GPU: terms.GPU,
  792. Storage: terms.Storage,
  793. BaseCPUPrice: aws.BaseCPUPrice,
  794. BaseRAMPrice: aws.BaseRAMPrice,
  795. BaseGPUPrice: aws.BaseGPUPrice,
  796. UsageType: usageType,
  797. }, nil
  798. } else if aws.isPreemptible(key) { // Preemptible but we don't have any data in the pricing report.
  799. klog.Infof("Node %s marked preemitible but we have no data in spot feed", k.ID())
  800. return &Node{
  801. VCPU: terms.VCpu,
  802. VCPUCost: aws.BaseSpotCPUPrice,
  803. RAM: terms.Memory,
  804. GPU: terms.GPU,
  805. RAMCost: aws.BaseSpotRAMPrice,
  806. Storage: terms.Storage,
  807. BaseCPUPrice: aws.BaseCPUPrice,
  808. BaseRAMPrice: aws.BaseRAMPrice,
  809. BaseGPUPrice: aws.BaseGPUPrice,
  810. UsageType: usageType,
  811. }, nil
  812. } else if sp, ok := aws.savingsPlanPricing(k.ID()); ok {
  813. strCost := fmt.Sprintf("%f", sp.EffectiveCost)
  814. return &Node{
  815. Cost: strCost,
  816. VCPU: terms.VCpu,
  817. RAM: terms.Memory,
  818. GPU: terms.GPU,
  819. Storage: terms.Storage,
  820. BaseCPUPrice: aws.BaseCPUPrice,
  821. BaseRAMPrice: aws.BaseRAMPrice,
  822. BaseGPUPrice: aws.BaseGPUPrice,
  823. UsageType: usageType,
  824. }, nil
  825. } else if ri, ok := aws.reservedInstancePricing(k.ID()); ok {
  826. strCost := fmt.Sprintf("%f", ri.EffectiveCost)
  827. return &Node{
  828. Cost: strCost,
  829. VCPU: terms.VCpu,
  830. RAM: terms.Memory,
  831. GPU: terms.GPU,
  832. Storage: terms.Storage,
  833. BaseCPUPrice: aws.BaseCPUPrice,
  834. BaseRAMPrice: aws.BaseRAMPrice,
  835. BaseGPUPrice: aws.BaseGPUPrice,
  836. UsageType: usageType,
  837. }, nil
  838. }
  839. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  840. if !ok {
  841. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  842. }
  843. cost := c.PricePerUnit.USD
  844. return &Node{
  845. Cost: cost,
  846. VCPU: terms.VCpu,
  847. RAM: terms.Memory,
  848. GPU: terms.GPU,
  849. Storage: terms.Storage,
  850. BaseCPUPrice: aws.BaseCPUPrice,
  851. BaseRAMPrice: aws.BaseRAMPrice,
  852. BaseGPUPrice: aws.BaseGPUPrice,
  853. UsageType: usageType,
  854. }, nil
  855. }
  856. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  857. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  858. aws.DownloadPricingDataLock.RLock()
  859. defer aws.DownloadPricingDataLock.RUnlock()
  860. key := k.Features()
  861. usageType := "ondemand"
  862. if aws.isPreemptible(key) {
  863. usageType = "preemptible"
  864. }
  865. terms, ok := aws.Pricing[key]
  866. if ok {
  867. return aws.createNode(terms, usageType, k)
  868. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  869. aws.DownloadPricingDataLock.RUnlock()
  870. err := aws.DownloadPricingData()
  871. aws.DownloadPricingDataLock.RLock()
  872. if err != nil {
  873. return &Node{
  874. Cost: aws.BaseCPUPrice,
  875. BaseCPUPrice: aws.BaseCPUPrice,
  876. BaseRAMPrice: aws.BaseRAMPrice,
  877. BaseGPUPrice: aws.BaseGPUPrice,
  878. UsageType: usageType,
  879. UsesBaseCPUPrice: true,
  880. }, err
  881. }
  882. terms, termsOk := aws.Pricing[key]
  883. if !termsOk {
  884. return &Node{
  885. Cost: aws.BaseCPUPrice,
  886. BaseCPUPrice: aws.BaseCPUPrice,
  887. BaseRAMPrice: aws.BaseRAMPrice,
  888. BaseGPUPrice: aws.BaseGPUPrice,
  889. UsageType: usageType,
  890. UsesBaseCPUPrice: true,
  891. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  892. }
  893. return aws.createNode(terms, usageType, k)
  894. } else { // Fall back to base pricing if we can't find the key.
  895. klog.V(1).Infof("Invalid Pricing Key \"%s\"", key)
  896. return &Node{
  897. Cost: aws.BaseCPUPrice,
  898. BaseCPUPrice: aws.BaseCPUPrice,
  899. BaseRAMPrice: aws.BaseRAMPrice,
  900. BaseGPUPrice: aws.BaseGPUPrice,
  901. UsageType: usageType,
  902. UsesBaseCPUPrice: true,
  903. }, nil
  904. }
  905. }
  906. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  907. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  908. defaultClusterName := "AWS Cluster #1"
  909. c, err := awsProvider.GetConfig()
  910. if err != nil {
  911. return nil, err
  912. }
  913. remoteEnabled := env.IsRemoteEnabled()
  914. if c.ClusterName != "" {
  915. m := make(map[string]string)
  916. m["name"] = c.ClusterName
  917. m["provider"] = "AWS"
  918. m["id"] = env.GetClusterID()
  919. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  920. return m, nil
  921. }
  922. makeStructure := func(clusterName string) (map[string]string, error) {
  923. klog.V(2).Infof("Returning \"%s\" as ClusterName", clusterName)
  924. m := make(map[string]string)
  925. m["name"] = clusterName
  926. m["provider"] = "AWS"
  927. m["id"] = env.GetClusterID()
  928. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  929. return m, nil
  930. }
  931. maybeClusterId := env.GetAWSClusterID()
  932. if len(maybeClusterId) != 0 {
  933. return makeStructure(maybeClusterId)
  934. }
  935. // TODO: This should be cached, it can take a long time to hit the API
  936. //provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  937. //clusterIdRx := regexp.MustCompile("^kubernetes\\.io/cluster/([^/]+)")
  938. //klog.Infof("nodelist get here %s", time.Now())
  939. //nodeList := awsProvider.Clientset.GetAllNodes()
  940. //klog.Infof("nodelist done here %s", time.Now())
  941. /*for _, n := range nodeList {
  942. region := ""
  943. instanceId := ""
  944. providerId := n.Spec.ProviderID
  945. for matchNum, group := range provIdRx.FindStringSubmatch(providerId) {
  946. if matchNum == 1 {
  947. region = group
  948. } else if matchNum == 2 {
  949. instanceId = group
  950. }
  951. }
  952. if len(instanceId) == 0 {
  953. klog.V(2).Infof("Unable to decode Node.ProviderID \"%s\", skipping it", providerId)
  954. continue
  955. }
  956. c := &aws.Config{
  957. Region: aws.String(region),
  958. }
  959. s := session.Must(session.NewSession(c))
  960. ec2Svc := ec2.New(s)
  961. di, diErr := ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{
  962. InstanceIds: []*string{
  963. aws.String(instanceId),
  964. },
  965. })
  966. if diErr != nil {
  967. klog.Infof("Error describing instances: %s", diErr)
  968. continue
  969. }
  970. if len(di.Reservations) != 1 {
  971. klog.V(2).Infof("Expected 1 Reservation back from DescribeInstances(%s), received %d", instanceId, len(di.Reservations))
  972. continue
  973. }
  974. res := di.Reservations[0]
  975. if len(res.Instances) != 1 {
  976. klog.V(2).Infof("Expected 1 Instance back from DescribeInstances(%s), received %d", instanceId, len(res.Instances))
  977. continue
  978. }
  979. inst := res.Instances[0]
  980. for _, tag := range inst.Tags {
  981. tagKey := *tag.Key
  982. for matchNum, group := range clusterIdRx.FindStringSubmatch(tagKey) {
  983. if matchNum != 1 {
  984. continue
  985. }
  986. return makeStructure(group)
  987. }
  988. }
  989. }*/
  990. klog.V(2).Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", env.AWSClusterIDEnvVar)
  991. return makeStructure(defaultClusterName)
  992. }
  993. // Gets the aws key id and secret
  994. func (aws *AWS) getAWSAuth(forceReload bool, cp *CustomPricing) (string, string) {
  995. // 1. Check config values first (set from frontend UI)
  996. if cp.ServiceKeyName != "" && cp.ServiceKeySecret != "" {
  997. return cp.ServiceKeyName, cp.ServiceKeySecret
  998. }
  999. // 2. Check for secret
  1000. s, _ := aws.loadAWSAuthSecret(forceReload)
  1001. if s != nil && s.AccessKeyID != "" && s.SecretAccessKey != "" {
  1002. return s.AccessKeyID, s.SecretAccessKey
  1003. }
  1004. // 3. Fall back to env vars
  1005. return env.GetAWSAccessKeyID(), env.GetAWSAccessKeySecret()
  1006. }
  1007. // Load once and cache the result (even on failure). This is an install time secret, so
  1008. // we don't expect the secret to change. If it does, however, we can force reload using
  1009. // the input parameter.
  1010. func (aws *AWS) loadAWSAuthSecret(force bool) (*AWSAccessKey, error) {
  1011. if !force && loadedAWSSecret {
  1012. return awsSecret, nil
  1013. }
  1014. loadedAWSSecret = true
  1015. exists, err := util.FileExists(authSecretPath)
  1016. if !exists || err != nil {
  1017. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  1018. }
  1019. result, err := ioutil.ReadFile(authSecretPath)
  1020. if err != nil {
  1021. return nil, err
  1022. }
  1023. var ak AWSAccessKey
  1024. err = json.Unmarshal(result, &ak)
  1025. if err != nil {
  1026. return nil, err
  1027. }
  1028. awsSecret = &ak
  1029. return awsSecret, nil
  1030. }
  1031. func (aws *AWS) configureAWSAuth() error {
  1032. accessKeyID := aws.ServiceKeyName
  1033. accessKeySecret := aws.ServiceKeySecret
  1034. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1035. err := env.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1036. if err != nil {
  1037. return err
  1038. }
  1039. err = env.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1040. if err != nil {
  1041. return err
  1042. }
  1043. }
  1044. return nil
  1045. }
  1046. func getClusterConfig(ccFile string) (map[string]string, error) {
  1047. clusterConfig, err := os.Open(ccFile)
  1048. if err != nil {
  1049. return nil, err
  1050. }
  1051. defer clusterConfig.Close()
  1052. b, err := ioutil.ReadAll(clusterConfig)
  1053. if err != nil {
  1054. return nil, err
  1055. }
  1056. var clusterConf map[string]string
  1057. err = json.Unmarshal([]byte(b), &clusterConf)
  1058. if err != nil {
  1059. return nil, err
  1060. }
  1061. return clusterConf, nil
  1062. }
  1063. // SetKeyEnv ensures that the two environment variables necessary to configure
  1064. // a new AWS Session are set.
  1065. func (a *AWS) SetKeyEnv() error {
  1066. // TODO add this to the helm chart, mirroring the cost-model
  1067. // configPath := env.GetConfigPath()
  1068. configPath := defaultConfigPath
  1069. path := configPath + "aws.json"
  1070. if _, err := os.Stat(path); err != nil {
  1071. if os.IsNotExist(err) {
  1072. log.DedupedErrorf(5, "file %s does not exist", path)
  1073. } else {
  1074. log.DedupedErrorf(5, "other file open error: %s", err)
  1075. }
  1076. return err
  1077. }
  1078. jsonFile, err := os.Open(path)
  1079. defer jsonFile.Close()
  1080. configMap := map[string]string{}
  1081. configBytes, err := ioutil.ReadAll(jsonFile)
  1082. if err != nil {
  1083. return err
  1084. }
  1085. json.Unmarshal([]byte(configBytes), &configMap)
  1086. keyName := configMap["awsServiceKeyName"]
  1087. keySecret := configMap["awsServiceKeySecret"]
  1088. // These are required before calling NewEnvCredentials below
  1089. env.Set(env.AWSAccessKeyIDEnvVar, keyName)
  1090. env.Set(env.AWSAccessKeySecretEnvVar, keySecret)
  1091. return nil
  1092. }
  1093. func (a *AWS) getAddressesForRegion(region string) (*ec2.DescribeAddressesOutput, error) {
  1094. sess, err := session.NewSession(&aws.Config{
  1095. Region: aws.String(region),
  1096. Credentials: credentials.NewEnvCredentials(),
  1097. })
  1098. if err != nil {
  1099. return nil, err
  1100. }
  1101. ec2Svc := ec2.New(sess)
  1102. return ec2Svc.DescribeAddresses(&ec2.DescribeAddressesInput{})
  1103. }
  1104. func (a *AWS) GetAddresses() ([]byte, error) {
  1105. if err := a.SetKeyEnv(); err != nil {
  1106. return nil, err
  1107. }
  1108. addressCh := make(chan *ec2.DescribeAddressesOutput, len(awsRegions))
  1109. errorCh := make(chan error, len(awsRegions))
  1110. var wg sync.WaitGroup
  1111. wg.Add(len(awsRegions))
  1112. // Get volumes from each AWS region
  1113. for _, r := range awsRegions {
  1114. // Fetch IP address response and send results and errors to their
  1115. // respective channels
  1116. go func(region string) {
  1117. defer wg.Done()
  1118. defer errors.HandlePanic()
  1119. // Query for first page of volume results
  1120. resp, err := a.getAddressesForRegion(region)
  1121. if err != nil {
  1122. if aerr, ok := err.(awserr.Error); ok {
  1123. switch aerr.Code() {
  1124. default:
  1125. errorCh <- aerr
  1126. }
  1127. return
  1128. } else {
  1129. errorCh <- err
  1130. return
  1131. }
  1132. }
  1133. addressCh <- resp
  1134. }(r)
  1135. }
  1136. // Close the result channels after everything has been sent
  1137. go func() {
  1138. defer errors.HandlePanic()
  1139. wg.Wait()
  1140. close(errorCh)
  1141. close(addressCh)
  1142. }()
  1143. addresses := []*ec2.Address{}
  1144. for adds := range addressCh {
  1145. addresses = append(addresses, adds.Addresses...)
  1146. }
  1147. errors := []error{}
  1148. for err := range errorCh {
  1149. log.DedupedWarningf(5, "unable to get addresses: %s", err)
  1150. errors = append(errors, err)
  1151. }
  1152. // Return error if no addresses are returned
  1153. if len(errors) > 0 && len(addresses) == 0 {
  1154. return nil, fmt.Errorf("%d error(s) retrieving addresses: %v", len(errors), errors)
  1155. }
  1156. // Format the response this way to match the JSON-encoded formatting of a single response
  1157. // from DescribeAddresss, so that consumers can always expect AWS disk responses to have
  1158. // a "Addresss" key at the top level.
  1159. return json.Marshal(map[string][]*ec2.Address{
  1160. "Addresses": addresses,
  1161. })
  1162. }
  1163. func (a *AWS) getDisksForRegion(region string, maxResults int64, nextToken *string) (*ec2.DescribeVolumesOutput, error) {
  1164. sess, err := session.NewSession(&aws.Config{
  1165. Region: aws.String(region),
  1166. Credentials: credentials.NewEnvCredentials(),
  1167. })
  1168. if err != nil {
  1169. return nil, err
  1170. }
  1171. ec2Svc := ec2.New(sess)
  1172. return ec2Svc.DescribeVolumes(&ec2.DescribeVolumesInput{
  1173. MaxResults: &maxResults,
  1174. NextToken: nextToken,
  1175. })
  1176. }
  1177. // 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.
  1178. func (a *AWS) GetDisks() ([]byte, error) {
  1179. if err := a.SetKeyEnv(); err != nil {
  1180. return nil, err
  1181. }
  1182. volumeCh := make(chan *ec2.DescribeVolumesOutput, len(awsRegions))
  1183. errorCh := make(chan error, len(awsRegions))
  1184. var wg sync.WaitGroup
  1185. wg.Add(len(awsRegions))
  1186. // Get volumes from each AWS region
  1187. for _, r := range awsRegions {
  1188. // Fetch volume response and send results and errors to their
  1189. // respective channels
  1190. go func(region string) {
  1191. defer wg.Done()
  1192. defer errors.HandlePanic()
  1193. // Query for first page of volume results
  1194. resp, err := a.getDisksForRegion(region, 1000, nil)
  1195. if err != nil {
  1196. if aerr, ok := err.(awserr.Error); ok {
  1197. switch aerr.Code() {
  1198. default:
  1199. errorCh <- aerr
  1200. }
  1201. return
  1202. } else {
  1203. errorCh <- err
  1204. return
  1205. }
  1206. }
  1207. volumeCh <- resp
  1208. // A NextToken indicates more pages of results. Keep querying
  1209. // until all pages are retrieved.
  1210. for resp.NextToken != nil {
  1211. resp, err = a.getDisksForRegion(region, 100, resp.NextToken)
  1212. if err != nil {
  1213. if aerr, ok := err.(awserr.Error); ok {
  1214. switch aerr.Code() {
  1215. default:
  1216. errorCh <- aerr
  1217. }
  1218. return
  1219. } else {
  1220. errorCh <- err
  1221. return
  1222. }
  1223. }
  1224. volumeCh <- resp
  1225. }
  1226. }(r)
  1227. }
  1228. // Close the result channels after everything has been sent
  1229. go func() {
  1230. defer errors.HandlePanic()
  1231. wg.Wait()
  1232. close(errorCh)
  1233. close(volumeCh)
  1234. }()
  1235. volumes := []*ec2.Volume{}
  1236. for vols := range volumeCh {
  1237. volumes = append(volumes, vols.Volumes...)
  1238. }
  1239. errors := []error{}
  1240. for err := range errorCh {
  1241. log.DedupedWarningf(5, "unable to get disks: %s", err)
  1242. errors = append(errors, err)
  1243. }
  1244. // Return error if no volumes are returned
  1245. if len(errors) > 0 && len(volumes) == 0 {
  1246. return nil, fmt.Errorf("%d error(s) retrieving volumes: %v", len(errors), errors)
  1247. }
  1248. // Format the response this way to match the JSON-encoded formatting of a single response
  1249. // from DescribeVolumes, so that consumers can always expect AWS disk responses to have
  1250. // a "Volumes" key at the top level.
  1251. return json.Marshal(map[string][]*ec2.Volume{
  1252. "Volumes": volumes,
  1253. })
  1254. }
  1255. // ConvertToGlueColumnFormat takes a string and runs through various regex
  1256. // and string replacement statements to convert it to a format compatible
  1257. // with AWS Glue and Athena column names.
  1258. // Following guidance from AWS provided here ('Column Names' section):
  1259. // https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/run-athena-sql.html
  1260. // It returns a string containing the column name in proper column name format and length.
  1261. func ConvertToGlueColumnFormat(column_name string) string {
  1262. klog.V(5).Infof("Converting string \"%s\" to proper AWS Glue column name.", column_name)
  1263. // An underscore is added in front of uppercase letters
  1264. capital_underscore := regexp.MustCompile(`[A-Z]`)
  1265. final := capital_underscore.ReplaceAllString(column_name, `_$0`)
  1266. // Any non-alphanumeric characters are replaced with an underscore
  1267. no_space_punc := regexp.MustCompile(`[\s]{1,}|[^A-Za-z0-9]`)
  1268. final = no_space_punc.ReplaceAllString(final, "_")
  1269. // Duplicate underscores are removed
  1270. no_dup_underscore := regexp.MustCompile(`_{2,}`)
  1271. final = no_dup_underscore.ReplaceAllString(final, "_")
  1272. // Any leading and trailing underscores are removed
  1273. no_front_end_underscore := regexp.MustCompile(`(^\_|\_$)`)
  1274. final = no_front_end_underscore.ReplaceAllString(final, "")
  1275. // Uppercase to lowercase
  1276. final = strings.ToLower(final)
  1277. // Longer column name than expected - remove _ left to right
  1278. allowed_col_len := 128
  1279. undersc_to_remove := len(final) - allowed_col_len
  1280. if undersc_to_remove > 0 {
  1281. final = strings.Replace(final, "_", "", undersc_to_remove)
  1282. }
  1283. // If removing all of the underscores still didn't
  1284. // make the column name < 128 characters, trim it!
  1285. if len(final) > allowed_col_len {
  1286. final = final[:allowed_col_len]
  1287. }
  1288. klog.V(5).Infof("Column name being returned: \"%s\". Length: \"%d\".", final, len(final))
  1289. return final
  1290. }
  1291. func generateAWSGroupBy(lastIdx int) string {
  1292. sequence := []string{}
  1293. for i := 1; i < lastIdx+1; i++ {
  1294. sequence = append(sequence, strconv.Itoa(i))
  1295. }
  1296. return strings.Join(sequence, ",")
  1297. }
  1298. func (a *AWS) QueryAthenaBillingData(query string) (*athena.GetQueryResultsOutput, error) {
  1299. customPricing, err := a.GetConfig()
  1300. if err != nil {
  1301. return nil, err
  1302. }
  1303. if customPricing.ServiceKeyName != "" {
  1304. err = env.Set(env.AWSAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1305. if err != nil {
  1306. return nil, err
  1307. }
  1308. err = env.Set(env.AWSAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1309. if err != nil {
  1310. return nil, err
  1311. }
  1312. }
  1313. region := aws.String(customPricing.AthenaRegion)
  1314. resultsBucket := customPricing.AthenaBucketName
  1315. database := customPricing.AthenaDatabase
  1316. c := &aws.Config{
  1317. Region: region,
  1318. }
  1319. s := session.Must(session.NewSession(c))
  1320. svc := athena.New(s)
  1321. if customPricing.MasterPayerARN != "" {
  1322. creds := stscreds.NewCredentials(s, customPricing.MasterPayerARN)
  1323. svc = athena.New(s, &aws.Config{
  1324. Region: region,
  1325. Credentials: creds,
  1326. })
  1327. }
  1328. var e athena.StartQueryExecutionInput
  1329. var r athena.ResultConfiguration
  1330. r.SetOutputLocation(resultsBucket)
  1331. e.SetResultConfiguration(&r)
  1332. e.SetQueryString(query)
  1333. var q athena.QueryExecutionContext
  1334. q.SetDatabase(database)
  1335. e.SetQueryExecutionContext(&q)
  1336. res, err := svc.StartQueryExecution(&e)
  1337. if err != nil {
  1338. return nil, err
  1339. }
  1340. klog.V(2).Infof("StartQueryExecution result:")
  1341. klog.V(2).Infof(res.GoString())
  1342. var qri athena.GetQueryExecutionInput
  1343. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1344. var qrop *athena.GetQueryExecutionOutput
  1345. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1346. for {
  1347. qrop, err = svc.GetQueryExecution(&qri)
  1348. if err != nil {
  1349. return nil, err
  1350. }
  1351. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1352. break
  1353. }
  1354. time.Sleep(duration)
  1355. }
  1356. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1357. var ip athena.GetQueryResultsInput
  1358. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1359. return svc.GetQueryResults(&ip)
  1360. } else {
  1361. return nil, fmt.Errorf("No results available for %s", query)
  1362. }
  1363. }
  1364. type SavingsPlanData struct {
  1365. ResourceID string
  1366. EffectiveCost float64
  1367. SavingsPlanARN string
  1368. MostRecentDate string
  1369. }
  1370. func (a *AWS) GetSavingsPlanDataFromAthena() error {
  1371. cfg, err := a.GetConfig()
  1372. if err != nil {
  1373. return err
  1374. }
  1375. if cfg.AthenaBucketName == "" {
  1376. return fmt.Errorf("No Athena Bucket configured")
  1377. }
  1378. if a.SavingsPlanDataByInstanceID == nil {
  1379. a.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData)
  1380. }
  1381. tNow := time.Now()
  1382. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1383. start := tOneDayAgo.Format("2006-01-02")
  1384. end := tNow.Format("2006-01-02")
  1385. q := `SELECT
  1386. line_item_usage_start_date,
  1387. savings_plan_savings_plan_a_r_n,
  1388. line_item_resource_id,
  1389. savings_plan_savings_plan_effective_cost
  1390. FROM %s as cost_data
  1391. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1392. AND line_item_line_item_type = 'SavingsPlanCoveredUsage' ORDER BY
  1393. line_item_usage_start_date DESC`
  1394. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1395. op, err := a.QueryAthenaBillingData(query)
  1396. if err != nil {
  1397. return fmt.Errorf("Error fetching Savings Plan Data: %s", err)
  1398. }
  1399. klog.Infof("Fetching SavingsPlan data...")
  1400. if len(op.ResultSet.Rows) > 1 {
  1401. a.SavingsPlanDataLock.Lock()
  1402. mostRecentDate := ""
  1403. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  1404. d := *r.Data[0].VarCharValue
  1405. if mostRecentDate == "" {
  1406. mostRecentDate = d
  1407. } else if mostRecentDate != d { // Get all most recent assignments
  1408. break
  1409. }
  1410. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1411. if err != nil {
  1412. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1413. }
  1414. r := &SavingsPlanData{
  1415. ResourceID: *r.Data[2].VarCharValue,
  1416. EffectiveCost: cost,
  1417. SavingsPlanARN: *r.Data[1].VarCharValue,
  1418. MostRecentDate: d,
  1419. }
  1420. a.SavingsPlanDataByInstanceID[r.ResourceID] = r
  1421. }
  1422. klog.V(1).Infof("Found %d savings plan applied instances", len(a.SavingsPlanDataByInstanceID))
  1423. for k, r := range a.SavingsPlanDataByInstanceID {
  1424. klog.V(1).Infof("Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1425. }
  1426. a.SavingsPlanDataLock.Unlock()
  1427. } else {
  1428. klog.Infof("No savings plan applied instance data found")
  1429. }
  1430. return nil
  1431. }
  1432. type RIData struct {
  1433. ResourceID string
  1434. EffectiveCost float64
  1435. ReservationARN string
  1436. MostRecentDate string
  1437. }
  1438. func (a *AWS) GetReservationDataFromAthena() error {
  1439. cfg, err := a.GetConfig()
  1440. if err != nil {
  1441. return err
  1442. }
  1443. if cfg.AthenaBucketName == "" {
  1444. return fmt.Errorf("No Athena Bucket configured")
  1445. }
  1446. if a.RIPricingByInstanceID == nil {
  1447. a.RIPricingByInstanceID = make(map[string]*RIData)
  1448. }
  1449. tNow := time.Now()
  1450. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1451. start := tOneDayAgo.Format("2006-01-02")
  1452. end := tNow.Format("2006-01-02")
  1453. q := `SELECT
  1454. line_item_usage_start_date,
  1455. reservation_reservation_a_r_n,
  1456. line_item_resource_id,
  1457. reservation_effective_cost
  1458. FROM %s as cost_data
  1459. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1460. AND reservation_reservation_a_r_n <> '' ORDER BY
  1461. line_item_usage_start_date DESC`
  1462. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1463. op, err := a.QueryAthenaBillingData(query)
  1464. if err != nil {
  1465. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  1466. }
  1467. klog.Infof("Fetching RI data...")
  1468. if len(op.ResultSet.Rows) > 1 {
  1469. a.RIDataLock.Lock()
  1470. mostRecentDate := ""
  1471. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  1472. d := *r.Data[0].VarCharValue
  1473. if mostRecentDate == "" {
  1474. mostRecentDate = d
  1475. } else if mostRecentDate != d { // Get all most recent assignments
  1476. break
  1477. }
  1478. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1479. if err != nil {
  1480. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1481. }
  1482. r := &RIData{
  1483. ResourceID: *r.Data[2].VarCharValue,
  1484. EffectiveCost: cost,
  1485. ReservationARN: *r.Data[1].VarCharValue,
  1486. MostRecentDate: d,
  1487. }
  1488. a.RIPricingByInstanceID[r.ResourceID] = r
  1489. }
  1490. klog.V(1).Infof("Found %d reserved instances", len(a.RIPricingByInstanceID))
  1491. for k, r := range a.RIPricingByInstanceID {
  1492. klog.V(1).Infof("Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1493. }
  1494. a.RIDataLock.Unlock()
  1495. } else {
  1496. klog.Infof("No reserved instance data found")
  1497. }
  1498. return nil
  1499. }
  1500. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  1501. // "start" and "end" are dates of the format YYYY-MM-DD
  1502. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  1503. func (a *AWS) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  1504. customPricing, err := a.GetConfig()
  1505. if err != nil {
  1506. return nil, err
  1507. }
  1508. formattedAggregators := []string{}
  1509. for _, agg := range aggregators {
  1510. aggregator_column_name := "resource_tags_user_" + agg
  1511. aggregator_column_name = ConvertToGlueColumnFormat(aggregator_column_name)
  1512. formattedAggregators = append(formattedAggregators, aggregator_column_name)
  1513. }
  1514. aggregatorNames := strings.Join(formattedAggregators, ",")
  1515. aggregatorOr := strings.Join(formattedAggregators, " <> '' OR ")
  1516. aggregatorOr = aggregatorOr + " <> ''"
  1517. filter_column_name := "resource_tags_user_" + filterType
  1518. filter_column_name = ConvertToGlueColumnFormat(filter_column_name)
  1519. var query string
  1520. var lastIdx int
  1521. if filterType != "kubernetes_" { // This gets appended upstream and is equivalent to no filter.
  1522. lastIdx = len(formattedAggregators) + 3
  1523. groupby := generateAWSGroupBy(lastIdx)
  1524. query = fmt.Sprintf(`SELECT
  1525. CAST(line_item_usage_start_date AS DATE) as start_date,
  1526. %s,
  1527. line_item_product_code,
  1528. %s,
  1529. SUM(line_item_blended_cost) as blended_cost
  1530. FROM %s as cost_data
  1531. WHERE (%s='%s') AND line_item_usage_start_date BETWEEN date '%s' AND date '%s' AND (%s)
  1532. GROUP BY %s`, aggregatorNames, filter_column_name, customPricing.AthenaTable, filter_column_name, filterValue, start, end, aggregatorOr, groupby)
  1533. } else {
  1534. lastIdx = len(formattedAggregators) + 2
  1535. groupby := generateAWSGroupBy(lastIdx)
  1536. query = fmt.Sprintf(`SELECT
  1537. CAST(line_item_usage_start_date AS DATE) as start_date,
  1538. %s,
  1539. line_item_product_code,
  1540. SUM(line_item_blended_cost) as blended_cost
  1541. FROM %s as cost_data
  1542. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s' AND (%s)
  1543. GROUP BY %s`, aggregatorNames, customPricing.AthenaTable, start, end, aggregatorOr, groupby)
  1544. }
  1545. klog.V(3).Infof("Running Query: %s", query)
  1546. if customPricing.ServiceKeyName != "" {
  1547. err = env.Set(env.AWSAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1548. if err != nil {
  1549. return nil, err
  1550. }
  1551. err = env.Set(env.AWSAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1552. if err != nil {
  1553. return nil, err
  1554. }
  1555. }
  1556. region := aws.String(customPricing.AthenaRegion)
  1557. resultsBucket := customPricing.AthenaBucketName
  1558. database := customPricing.AthenaDatabase
  1559. c := &aws.Config{
  1560. Region: region,
  1561. }
  1562. s := session.Must(session.NewSession(c))
  1563. svc := athena.New(s)
  1564. var e athena.StartQueryExecutionInput
  1565. var r athena.ResultConfiguration
  1566. r.SetOutputLocation(resultsBucket)
  1567. e.SetResultConfiguration(&r)
  1568. e.SetQueryString(query)
  1569. var q athena.QueryExecutionContext
  1570. q.SetDatabase(database)
  1571. e.SetQueryExecutionContext(&q)
  1572. res, err := svc.StartQueryExecution(&e)
  1573. if err != nil {
  1574. return nil, err
  1575. }
  1576. klog.V(2).Infof("StartQueryExecution result:")
  1577. klog.V(2).Infof(res.GoString())
  1578. var qri athena.GetQueryExecutionInput
  1579. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1580. var qrop *athena.GetQueryExecutionOutput
  1581. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1582. for {
  1583. qrop, err = svc.GetQueryExecution(&qri)
  1584. if err != nil {
  1585. return nil, err
  1586. }
  1587. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1588. break
  1589. }
  1590. time.Sleep(duration)
  1591. }
  1592. var oocAllocs []*OutOfClusterAllocation
  1593. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1594. var ip athena.GetQueryResultsInput
  1595. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1596. op, err := svc.GetQueryResults(&ip)
  1597. if err != nil {
  1598. return nil, err
  1599. }
  1600. if len(op.ResultSet.Rows) > 1 {
  1601. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows))] {
  1602. cost, err := strconv.ParseFloat(*r.Data[lastIdx].VarCharValue, 64)
  1603. if err != nil {
  1604. return nil, err
  1605. }
  1606. environment := ""
  1607. for _, d := range r.Data[1 : len(formattedAggregators)+1] {
  1608. if *d.VarCharValue != "" {
  1609. environment = *d.VarCharValue // just set to the first nonempty match
  1610. }
  1611. break
  1612. }
  1613. ooc := &OutOfClusterAllocation{
  1614. Aggregator: strings.Join(aggregators, ","),
  1615. Environment: environment,
  1616. Service: *r.Data[len(formattedAggregators)+1].VarCharValue,
  1617. Cost: cost,
  1618. }
  1619. oocAllocs = append(oocAllocs, ooc)
  1620. }
  1621. } else {
  1622. klog.V(1).Infof("No results available for %s at database %s between %s and %s", strings.Join(formattedAggregators, ","), customPricing.AthenaTable, start, end)
  1623. }
  1624. }
  1625. if customPricing.BillingDataDataset != "" && !crossCluster { // There is GCP data, meaning someone has tried to configure a GCP out-of-cluster allocation.
  1626. gcp, err := NewCrossClusterProvider("gcp", "aws.json", a.Clientset)
  1627. if err != nil {
  1628. klog.Infof("Could not instantiate cross-cluster provider %s", err.Error())
  1629. }
  1630. gcpOOC, err := gcp.ExternalAllocations(start, end, aggregators, filterType, filterValue, true)
  1631. if err != nil {
  1632. klog.Infof("Could not fetch cross-cluster costs %s", err.Error())
  1633. }
  1634. oocAllocs = append(oocAllocs, gcpOOC...)
  1635. }
  1636. return oocAllocs, nil
  1637. }
  1638. // QuerySQL can query a properly configured Athena database.
  1639. // Used to fetch billing data.
  1640. // Requires a json config in /var/configs with key region, output, and database.
  1641. func (a *AWS) QuerySQL(query string) ([]byte, error) {
  1642. customPricing, err := a.GetConfig()
  1643. if err != nil {
  1644. return nil, err
  1645. }
  1646. if customPricing.ServiceKeyName != "" {
  1647. err = env.Set(env.AWSAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1648. if err != nil {
  1649. return nil, err
  1650. }
  1651. err = env.Set(env.AWSAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1652. if err != nil {
  1653. return nil, err
  1654. }
  1655. }
  1656. athenaConfigs, err := os.Open("/var/configs/athena.json")
  1657. if err != nil {
  1658. return nil, err
  1659. }
  1660. defer athenaConfigs.Close()
  1661. b, err := ioutil.ReadAll(athenaConfigs)
  1662. if err != nil {
  1663. return nil, err
  1664. }
  1665. var athenaConf map[string]string
  1666. json.Unmarshal([]byte(b), &athenaConf)
  1667. region := aws.String(customPricing.AthenaRegion)
  1668. resultsBucket := customPricing.AthenaBucketName
  1669. database := customPricing.AthenaDatabase
  1670. c := &aws.Config{
  1671. Region: region,
  1672. }
  1673. s := session.Must(session.NewSession(c))
  1674. svc := athena.New(s)
  1675. var e athena.StartQueryExecutionInput
  1676. var r athena.ResultConfiguration
  1677. r.SetOutputLocation(resultsBucket)
  1678. e.SetResultConfiguration(&r)
  1679. e.SetQueryString(query)
  1680. var q athena.QueryExecutionContext
  1681. q.SetDatabase(database)
  1682. e.SetQueryExecutionContext(&q)
  1683. res, err := svc.StartQueryExecution(&e)
  1684. if err != nil {
  1685. return nil, err
  1686. }
  1687. klog.V(2).Infof("StartQueryExecution result:")
  1688. klog.V(2).Infof(res.GoString())
  1689. var qri athena.GetQueryExecutionInput
  1690. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1691. var qrop *athena.GetQueryExecutionOutput
  1692. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1693. for {
  1694. qrop, err = svc.GetQueryExecution(&qri)
  1695. if err != nil {
  1696. return nil, err
  1697. }
  1698. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1699. break
  1700. }
  1701. time.Sleep(duration)
  1702. }
  1703. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1704. var ip athena.GetQueryResultsInput
  1705. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1706. op, err := svc.GetQueryResults(&ip)
  1707. if err != nil {
  1708. return nil, err
  1709. }
  1710. b, err := json.Marshal(op.ResultSet)
  1711. if err != nil {
  1712. return nil, err
  1713. }
  1714. return b, nil
  1715. }
  1716. return nil, fmt.Errorf("Error getting query results : %s", *qrop.QueryExecution.Status.State)
  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. type fnames []*string
  1730. func (f fnames) Len() int {
  1731. return len(f)
  1732. }
  1733. func (f fnames) Swap(i, j int) {
  1734. f[i], f[j] = f[j], f[i]
  1735. }
  1736. func (f fnames) Less(i, j int) bool {
  1737. key1 := strings.Split(*f[i], ".")
  1738. key2 := strings.Split(*f[j], ".")
  1739. t1, err := time.Parse("2006-01-02-15", key1[1])
  1740. if err != nil {
  1741. klog.V(1).Info("Unable to parse timestamp" + key1[1])
  1742. return false
  1743. }
  1744. t2, err := time.Parse("2006-01-02-15", key2[1])
  1745. if err != nil {
  1746. klog.V(1).Info("Unable to parse timestamp" + key2[1])
  1747. return false
  1748. }
  1749. return t1.Before(t2)
  1750. }
  1751. func parseSpotData(bucket string, prefix string, projectID string, region string, accessKeyID string, accessKeySecret string) (map[string]*spotInfo, error) {
  1752. // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1753. if accessKeyID != "" && accessKeySecret != "" {
  1754. err := env.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1755. if err != nil {
  1756. return nil, err
  1757. }
  1758. err = env.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1759. if err != nil {
  1760. return nil, err
  1761. }
  1762. }
  1763. s3Prefix := projectID
  1764. if len(prefix) != 0 {
  1765. s3Prefix = prefix + "/" + s3Prefix
  1766. }
  1767. c := aws.NewConfig().WithRegion(region)
  1768. s := session.Must(session.NewSession(c))
  1769. s3Svc := s3.New(s)
  1770. downloader := s3manager.NewDownloaderWithClient(s3Svc)
  1771. tNow := time.Now()
  1772. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1773. ls := &s3.ListObjectsInput{
  1774. Bucket: aws.String(bucket),
  1775. Prefix: aws.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1776. }
  1777. ls2 := &s3.ListObjectsInput{
  1778. Bucket: aws.String(bucket),
  1779. Prefix: aws.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1780. }
  1781. lso, err := s3Svc.ListObjects(ls)
  1782. if err != nil {
  1783. return nil, err
  1784. }
  1785. lsoLen := len(lso.Contents)
  1786. klog.V(2).Infof("Found %d spot data files from yesterday", lsoLen)
  1787. if lsoLen == 0 {
  1788. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1789. }
  1790. lso2, err := s3Svc.ListObjects(ls2)
  1791. if err != nil {
  1792. return nil, err
  1793. }
  1794. lso2Len := len(lso2.Contents)
  1795. klog.V(2).Infof("Found %d spot data files from today", lso2Len)
  1796. if lso2Len == 0 {
  1797. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1798. }
  1799. // TODO: Worth it to use LastModifiedDate to determine if we should reparse the spot data?
  1800. var keys []*string
  1801. for _, obj := range lso.Contents {
  1802. keys = append(keys, obj.Key)
  1803. }
  1804. for _, obj := range lso2.Contents {
  1805. keys = append(keys, obj.Key)
  1806. }
  1807. versionRx := regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  1808. header, err := csvutil.Header(spotInfo{}, "csv")
  1809. if err != nil {
  1810. return nil, err
  1811. }
  1812. fieldsPerRecord := len(header)
  1813. spots := make(map[string]*spotInfo)
  1814. for _, key := range keys {
  1815. getObj := &s3.GetObjectInput{
  1816. Bucket: aws.String(bucket),
  1817. Key: key,
  1818. }
  1819. buf := aws.NewWriteAtBuffer([]byte{})
  1820. _, err := downloader.Download(buf, getObj)
  1821. if err != nil {
  1822. return nil, err
  1823. }
  1824. r := bytes.NewReader(buf.Bytes())
  1825. gr, err := gzip.NewReader(r)
  1826. if err != nil {
  1827. return nil, err
  1828. }
  1829. csvReader := csv.NewReader(gr)
  1830. csvReader.Comma = '\t'
  1831. csvReader.FieldsPerRecord = fieldsPerRecord
  1832. dec, err := csvutil.NewDecoder(csvReader, header...)
  1833. if err != nil {
  1834. return nil, err
  1835. }
  1836. var foundVersion string
  1837. for {
  1838. spot := spotInfo{}
  1839. err := dec.Decode(&spot)
  1840. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1841. if err == io.EOF {
  1842. break
  1843. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1844. rec := dec.Record()
  1845. // the first two "Record()" will be the comment lines
  1846. // and they show up as len() == 1
  1847. // the first of which is "#Version"
  1848. // the second of which is "#Fields: "
  1849. if len(rec) != 1 {
  1850. klog.V(2).Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1851. continue
  1852. }
  1853. if len(foundVersion) == 0 {
  1854. spotFeedVersion := rec[0]
  1855. klog.V(4).Infof("Spot feed version is \"%s\"", spotFeedVersion)
  1856. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  1857. if matches != nil {
  1858. foundVersion = matches[1]
  1859. if foundVersion != supportedSpotFeedVersion {
  1860. klog.V(2).Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  1861. break
  1862. }
  1863. }
  1864. continue
  1865. } else if strings.Index(rec[0], "#") == 0 {
  1866. continue
  1867. } else {
  1868. klog.V(3).Infof("skipping non-TSV line: %s", rec)
  1869. continue
  1870. }
  1871. } else if err != nil {
  1872. klog.V(2).Infof("Error during spot info decode: %+v", err)
  1873. continue
  1874. }
  1875. log.DedupedInfof(5, "Found spot info for: %s", spot.InstanceID)
  1876. spots[spot.InstanceID] = &spot
  1877. }
  1878. gr.Close()
  1879. }
  1880. return spots, nil
  1881. }
  1882. func (a *AWS) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1883. /*
  1884. numReserved := len(a.ReservedInstances)
  1885. // Early return if no reserved instance data loaded
  1886. if numReserved == 0 {
  1887. klog.V(4).Infof("[Reserved] No Reserved Instances")
  1888. return
  1889. }
  1890. cfg, err := a.GetConfig()
  1891. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1892. if err != nil {
  1893. klog.V(3).Infof("Could not parse default cpu price")
  1894. defaultCPU = 0.031611
  1895. }
  1896. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1897. if err != nil {
  1898. klog.V(3).Infof("Could not parse default ram price")
  1899. defaultRAM = 0.004237
  1900. }
  1901. cpuToRAMRatio := defaultCPU / defaultRAM
  1902. now := time.Now()
  1903. instances := make(map[string][]*AWSReservedInstance)
  1904. for _, r := range a.ReservedInstances {
  1905. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1906. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  1907. continue
  1908. }
  1909. _, ok := instances[r.Region]
  1910. if !ok {
  1911. instances[r.Region] = []*AWSReservedInstance{r}
  1912. } else {
  1913. instances[r.Region] = append(instances[r.Region], r)
  1914. }
  1915. }
  1916. awsNodes := make(map[string]*v1.Node)
  1917. currentNodes := a.Clientset.GetAllNodes()
  1918. // Create a node name -> node map
  1919. for _, awsNode := range currentNodes {
  1920. awsNodes[awsNode.GetName()] = awsNode
  1921. }
  1922. // go through all provider nodes using k8s nodes for region
  1923. for nodeName, node := range nodes {
  1924. // Reset reserved allocation to prevent double allocation
  1925. node.Reserved = nil
  1926. kNode, ok := awsNodes[nodeName]
  1927. if !ok {
  1928. klog.V(1).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  1929. continue
  1930. }
  1931. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  1932. if !ok {
  1933. klog.V(1).Infof("[Reserved] Could not find node region")
  1934. continue
  1935. }
  1936. reservedInstances, ok := instances[nodeRegion]
  1937. if !ok {
  1938. klog.V(1).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  1939. continue
  1940. }
  1941. // Determine the InstanceType of the node
  1942. instanceType, ok := kNode.Labels["beta.kubernetes.io/instance-type"]
  1943. if !ok {
  1944. continue
  1945. }
  1946. ramBytes, err := strconv.ParseFloat(node.RAMBytes, 64)
  1947. if err != nil {
  1948. continue
  1949. }
  1950. ramGB := ramBytes / 1024 / 1024 / 1024
  1951. cpu, err := strconv.ParseFloat(node.VCPU, 64)
  1952. if err != nil {
  1953. continue
  1954. }
  1955. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1956. node.Reserved = &ReservedInstanceData{
  1957. ReservedCPU: 0,
  1958. ReservedRAM: 0,
  1959. }
  1960. for i, reservedInstance := range reservedInstances {
  1961. if reservedInstance.InstanceType == instanceType {
  1962. // Use < 0 to mark as ALL
  1963. node.Reserved.ReservedCPU = -1
  1964. node.Reserved.ReservedRAM = -1
  1965. // Set Costs based on CPU/RAM ratios
  1966. ramPrice := reservedInstance.PricePerHour / ramMultiple
  1967. node.Reserved.CPUCost = ramPrice * cpuToRAMRatio
  1968. node.Reserved.RAMCost = ramPrice
  1969. // Remove the reserve from the temporary slice to prevent
  1970. // being reallocated
  1971. instances[nodeRegion] = append(reservedInstances[:i], reservedInstances[i+1:]...)
  1972. break
  1973. }
  1974. }
  1975. }*/
  1976. }
  1977. type AWSReservedInstance struct {
  1978. Zone string
  1979. Region string
  1980. InstanceType string
  1981. InstanceCount int64
  1982. InstanceTenacy string
  1983. StartDate time.Time
  1984. EndDate time.Time
  1985. PricePerHour float64
  1986. }
  1987. func (ari *AWSReservedInstance) String() string {
  1988. return fmt.Sprintf("[Zone: %s, Region: %s, Type: %s, Count: %d, Tenacy: %s, Start: %+v, End: %+v, Price: %f]", ari.Zone, ari.Region, ari.InstanceType, ari.InstanceCount, ari.InstanceTenacy, ari.StartDate, ari.EndDate, ari.PricePerHour)
  1989. }
  1990. func isReservedInstanceHourlyPrice(rc *ec2.RecurringCharge) bool {
  1991. return rc != nil && rc.Frequency != nil && *rc.Frequency == "Hourly"
  1992. }
  1993. func getReservedInstancePrice(ri *ec2.ReservedInstances) (float64, error) {
  1994. var pricePerHour float64
  1995. if len(ri.RecurringCharges) > 0 {
  1996. for _, rc := range ri.RecurringCharges {
  1997. if isReservedInstanceHourlyPrice(rc) {
  1998. pricePerHour = *rc.Amount
  1999. break
  2000. }
  2001. }
  2002. }
  2003. // If we're still unable to resolve hourly price, try fixed -> hourly
  2004. if pricePerHour == 0 {
  2005. if ri.Duration != nil && ri.FixedPrice != nil {
  2006. var durHours float64
  2007. durSeconds := float64(*ri.Duration)
  2008. fixedPrice := float64(*ri.FixedPrice)
  2009. if durSeconds != 0 && fixedPrice != 0 {
  2010. durHours = durSeconds / 60 / 60
  2011. pricePerHour = fixedPrice / durHours
  2012. }
  2013. }
  2014. }
  2015. if pricePerHour == 0 {
  2016. return 0, fmt.Errorf("Failed to resolve an hourly price from FixedPrice or Recurring Costs")
  2017. }
  2018. return pricePerHour, nil
  2019. }
  2020. func getRegionReservedInstances(region string) ([]*AWSReservedInstance, error) {
  2021. c := &aws.Config{
  2022. Region: aws.String(region),
  2023. }
  2024. s := session.Must(session.NewSession(c))
  2025. svc := ec2.New(s)
  2026. response, err := svc.DescribeReservedInstances(&ec2.DescribeReservedInstancesInput{})
  2027. if err != nil {
  2028. return nil, err
  2029. }
  2030. var reservedInstances []*AWSReservedInstance
  2031. for _, ri := range response.ReservedInstances {
  2032. var zone string
  2033. if ri.AvailabilityZone != nil {
  2034. zone = *ri.AvailabilityZone
  2035. }
  2036. pricePerHour, err := getReservedInstancePrice(ri)
  2037. if err != nil {
  2038. klog.V(1).Infof("Error Resolving Price: %s", err.Error())
  2039. continue
  2040. }
  2041. reservedInstances = append(reservedInstances, &AWSReservedInstance{
  2042. Zone: zone,
  2043. Region: region,
  2044. InstanceType: *ri.InstanceType,
  2045. InstanceCount: *ri.InstanceCount,
  2046. InstanceTenacy: *ri.InstanceTenancy,
  2047. StartDate: *ri.Start,
  2048. EndDate: *ri.End,
  2049. PricePerHour: pricePerHour,
  2050. })
  2051. }
  2052. return reservedInstances, nil
  2053. }
  2054. func (a *AWS) getReservedInstances() ([]*AWSReservedInstance, error) {
  2055. err := a.configureAWSAuth()
  2056. if err != nil {
  2057. return nil, fmt.Errorf("Error Configuring aws auth: %s", err.Error())
  2058. }
  2059. var reservedInstances []*AWSReservedInstance
  2060. nodes := a.Clientset.GetAllNodes()
  2061. regionsSeen := make(map[string]bool)
  2062. for _, node := range nodes {
  2063. region, ok := node.Labels[v1.LabelZoneRegion]
  2064. if !ok {
  2065. continue
  2066. }
  2067. if regionsSeen[region] {
  2068. continue
  2069. }
  2070. ris, err := getRegionReservedInstances(region)
  2071. if err != nil {
  2072. klog.V(3).Infof("Error getting reserved instances: %s", err.Error())
  2073. continue
  2074. }
  2075. regionsSeen[region] = true
  2076. reservedInstances = append(reservedInstances, ris...)
  2077. }
  2078. return reservedInstances, nil
  2079. }