awsprovider.go 68 KB

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