awsprovider.go 66 KB

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