awsprovider.go 70 KB

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