awsprovider.go 68 KB

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