awsprovider.go 69 KB

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