awsprovider.go 71 KB

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