awsprovider.go 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448
  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. fffrc := 0.025
  769. afrc := 0.010
  770. lbidc := 0.008
  771. numForwardingRules := 1.0
  772. dataIngressGB := 0.0
  773. var totalCost float64
  774. if numForwardingRules < 5 {
  775. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  776. } else {
  777. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  778. }
  779. return &LoadBalancer{
  780. Cost: totalCost,
  781. }, nil
  782. }
  783. // AllNodePricing returns all the billing data fetched.
  784. func (aws *AWS) AllNodePricing() (interface{}, error) {
  785. aws.DownloadPricingDataLock.RLock()
  786. defer aws.DownloadPricingDataLock.RUnlock()
  787. return aws.Pricing, nil
  788. }
  789. func (aws *AWS) spotPricing(instanceID string) (*spotInfo, bool) {
  790. aws.SpotPricingLock.RLock()
  791. defer aws.SpotPricingLock.RUnlock()
  792. info, ok := aws.SpotPricingByInstanceID[instanceID]
  793. return info, ok
  794. }
  795. func (aws *AWS) reservedInstancePricing(instanceID string) (*RIData, bool) {
  796. aws.RIDataLock.RLock()
  797. defer aws.RIDataLock.RUnlock()
  798. data, ok := aws.RIPricingByInstanceID[instanceID]
  799. return data, ok
  800. }
  801. func (aws *AWS) savingsPlanPricing(instanceID string) (*SavingsPlanData, bool) {
  802. aws.SavingsPlanDataLock.RLock()
  803. defer aws.SavingsPlanDataLock.RUnlock()
  804. data, ok := aws.SavingsPlanDataByInstanceID[instanceID]
  805. return data, ok
  806. }
  807. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  808. key := k.Features()
  809. if spotInfo, ok := aws.spotPricing(k.ID()); ok {
  810. var spotcost string
  811. log.DedupedInfof(5, "Looking up spot data from feed for node %s", k.ID())
  812. arr := strings.Split(spotInfo.Charge, " ")
  813. if len(arr) == 2 {
  814. spotcost = arr[0]
  815. } else {
  816. klog.V(2).Infof("Spot data for node %s is missing", k.ID())
  817. }
  818. return &Node{
  819. Cost: spotcost,
  820. VCPU: terms.VCpu,
  821. RAM: terms.Memory,
  822. GPU: terms.GPU,
  823. Storage: terms.Storage,
  824. BaseCPUPrice: aws.BaseCPUPrice,
  825. BaseRAMPrice: aws.BaseRAMPrice,
  826. BaseGPUPrice: aws.BaseGPUPrice,
  827. UsageType: usageType,
  828. }, nil
  829. } else if aws.isPreemptible(key) { // Preemptible but we don't have any data in the pricing report.
  830. log.DedupedWarningf(5, "Node %s marked preemitible but we have no data in spot feed", k.ID())
  831. return &Node{
  832. VCPU: terms.VCpu,
  833. VCPUCost: aws.BaseSpotCPUPrice,
  834. RAM: terms.Memory,
  835. GPU: terms.GPU,
  836. RAMCost: aws.BaseSpotRAMPrice,
  837. Storage: terms.Storage,
  838. BaseCPUPrice: aws.BaseCPUPrice,
  839. BaseRAMPrice: aws.BaseRAMPrice,
  840. BaseGPUPrice: aws.BaseGPUPrice,
  841. UsageType: usageType,
  842. }, nil
  843. } else if sp, ok := aws.savingsPlanPricing(k.ID()); ok {
  844. strCost := fmt.Sprintf("%f", sp.EffectiveCost)
  845. return &Node{
  846. Cost: strCost,
  847. VCPU: terms.VCpu,
  848. RAM: terms.Memory,
  849. GPU: terms.GPU,
  850. Storage: terms.Storage,
  851. BaseCPUPrice: aws.BaseCPUPrice,
  852. BaseRAMPrice: aws.BaseRAMPrice,
  853. BaseGPUPrice: aws.BaseGPUPrice,
  854. UsageType: usageType,
  855. }, nil
  856. } else if ri, ok := aws.reservedInstancePricing(k.ID()); ok {
  857. strCost := fmt.Sprintf("%f", ri.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. }
  870. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  871. if !ok {
  872. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  873. }
  874. cost := c.PricePerUnit.USD
  875. return &Node{
  876. Cost: cost,
  877. VCPU: terms.VCpu,
  878. RAM: terms.Memory,
  879. GPU: terms.GPU,
  880. Storage: terms.Storage,
  881. BaseCPUPrice: aws.BaseCPUPrice,
  882. BaseRAMPrice: aws.BaseRAMPrice,
  883. BaseGPUPrice: aws.BaseGPUPrice,
  884. UsageType: usageType,
  885. }, nil
  886. }
  887. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  888. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  889. aws.DownloadPricingDataLock.RLock()
  890. defer aws.DownloadPricingDataLock.RUnlock()
  891. key := k.Features()
  892. usageType := "ondemand"
  893. if aws.isPreemptible(key) {
  894. usageType = "preemptible"
  895. }
  896. terms, ok := aws.Pricing[key]
  897. if ok {
  898. return aws.createNode(terms, usageType, k)
  899. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  900. aws.DownloadPricingDataLock.RUnlock()
  901. err := aws.DownloadPricingData()
  902. aws.DownloadPricingDataLock.RLock()
  903. if err != nil {
  904. return &Node{
  905. Cost: aws.BaseCPUPrice,
  906. BaseCPUPrice: aws.BaseCPUPrice,
  907. BaseRAMPrice: aws.BaseRAMPrice,
  908. BaseGPUPrice: aws.BaseGPUPrice,
  909. UsageType: usageType,
  910. UsesBaseCPUPrice: true,
  911. }, err
  912. }
  913. terms, termsOk := aws.Pricing[key]
  914. if !termsOk {
  915. return &Node{
  916. Cost: aws.BaseCPUPrice,
  917. BaseCPUPrice: aws.BaseCPUPrice,
  918. BaseRAMPrice: aws.BaseRAMPrice,
  919. BaseGPUPrice: aws.BaseGPUPrice,
  920. UsageType: usageType,
  921. UsesBaseCPUPrice: true,
  922. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  923. }
  924. return aws.createNode(terms, usageType, k)
  925. } else { // Fall back to base pricing if we can't find the key. Base pricing is handled at the costmodel level.
  926. return nil, fmt.Errorf("Invalid Pricing Key \"%s\"", key)
  927. }
  928. }
  929. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  930. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  931. defaultClusterName := "AWS Cluster #1"
  932. c, err := awsProvider.GetConfig()
  933. if err != nil {
  934. return nil, err
  935. }
  936. remoteEnabled := env.IsRemoteEnabled()
  937. if c.ClusterName != "" {
  938. m := make(map[string]string)
  939. m["name"] = c.ClusterName
  940. m["provider"] = "AWS"
  941. m["id"] = env.GetClusterID()
  942. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  943. m["provisioner"] = awsProvider.clusterProvisioner
  944. return m, nil
  945. }
  946. makeStructure := func(clusterName string) (map[string]string, error) {
  947. klog.V(2).Infof("Returning \"%s\" as ClusterName", clusterName)
  948. m := make(map[string]string)
  949. m["name"] = clusterName
  950. m["provider"] = "AWS"
  951. m["id"] = env.GetClusterID()
  952. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  953. return m, nil
  954. }
  955. maybeClusterId := env.GetAWSClusterID()
  956. if len(maybeClusterId) != 0 {
  957. return makeStructure(maybeClusterId)
  958. }
  959. // TODO: This should be cached, it can take a long time to hit the API
  960. //provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  961. //clusterIdRx := regexp.MustCompile("^kubernetes\\.io/cluster/([^/]+)")
  962. //klog.Infof("nodelist get here %s", time.Now())
  963. //nodeList := awsProvider.Clientset.GetAllNodes()
  964. //klog.Infof("nodelist done here %s", time.Now())
  965. /*for _, n := range nodeList {
  966. region := ""
  967. instanceId := ""
  968. providerId := n.Spec.ProviderID
  969. for matchNum, group := range provIdRx.FindStringSubmatch(providerId) {
  970. if matchNum == 1 {
  971. region = group
  972. } else if matchNum == 2 {
  973. instanceId = group
  974. }
  975. }
  976. if len(instanceId) == 0 {
  977. klog.V(2).Infof("Unable to decode Node.ProviderID \"%s\", skipping it", providerId)
  978. continue
  979. }
  980. c := &aws.Config{
  981. Region: aws.String(region),
  982. }
  983. s := session.Must(session.NewSession(c))
  984. ec2Svc := ec2.New(s)
  985. di, diErr := ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{
  986. InstanceIds: []*string{
  987. aws.String(instanceId),
  988. },
  989. })
  990. if diErr != nil {
  991. klog.Infof("Error describing instances: %s", diErr)
  992. continue
  993. }
  994. if len(di.Reservations) != 1 {
  995. klog.V(2).Infof("Expected 1 Reservation back from DescribeInstances(%s), received %d", instanceId, len(di.Reservations))
  996. continue
  997. }
  998. res := di.Reservations[0]
  999. if len(res.Instances) != 1 {
  1000. klog.V(2).Infof("Expected 1 Instance back from DescribeInstances(%s), received %d", instanceId, len(res.Instances))
  1001. continue
  1002. }
  1003. inst := res.Instances[0]
  1004. for _, tag := range inst.Tags {
  1005. tagKey := *tag.Key
  1006. for matchNum, group := range clusterIdRx.FindStringSubmatch(tagKey) {
  1007. if matchNum != 1 {
  1008. continue
  1009. }
  1010. return makeStructure(group)
  1011. }
  1012. }
  1013. }*/
  1014. klog.V(2).Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", env.AWSClusterIDEnvVar)
  1015. return makeStructure(defaultClusterName)
  1016. }
  1017. // Gets the aws key id and secret
  1018. func (aws *AWS) getAWSAuth(forceReload bool, cp *CustomPricing) (string, string) {
  1019. if aws.ServiceAccountChecks == nil { // safety in case checks don't exist
  1020. aws.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  1021. }
  1022. // 1. Check config values first (set from frontend UI)
  1023. if cp.ServiceKeyName != "" && cp.ServiceKeySecret != "" {
  1024. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1025. Message: "AWS ServiceKey exists",
  1026. Status: true,
  1027. }
  1028. return cp.ServiceKeyName, cp.ServiceKeySecret
  1029. }
  1030. // 2. Check for secret
  1031. s, _ := aws.loadAWSAuthSecret(forceReload)
  1032. if s != nil && s.AccessKeyID != "" && s.SecretAccessKey != "" {
  1033. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1034. Message: "AWS ServiceKey exists",
  1035. Status: true,
  1036. }
  1037. return s.AccessKeyID, s.SecretAccessKey
  1038. }
  1039. // 3. Fall back to env vars
  1040. if env.GetAWSAccessKeyID() == "" || env.GetAWSAccessKeyID() == "" {
  1041. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1042. Message: "AWS ServiceKey exists",
  1043. Status: false,
  1044. }
  1045. } else {
  1046. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1047. Message: "AWS ServiceKey exists",
  1048. Status: true,
  1049. }
  1050. }
  1051. return env.GetAWSAccessKeyID(), env.GetAWSAccessKeySecret()
  1052. }
  1053. // Load once and cache the result (even on failure). This is an install time secret, so
  1054. // we don't expect the secret to change. If it does, however, we can force reload using
  1055. // the input parameter.
  1056. func (aws *AWS) loadAWSAuthSecret(force bool) (*AWSAccessKey, error) {
  1057. if !force && loadedAWSSecret {
  1058. return awsSecret, nil
  1059. }
  1060. loadedAWSSecret = true
  1061. exists, err := util.FileExists(authSecretPath)
  1062. if !exists || err != nil {
  1063. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  1064. }
  1065. result, err := ioutil.ReadFile(authSecretPath)
  1066. if err != nil {
  1067. return nil, err
  1068. }
  1069. var ak AWSAccessKey
  1070. err = json.Unmarshal(result, &ak)
  1071. if err != nil {
  1072. return nil, err
  1073. }
  1074. awsSecret = &ak
  1075. return awsSecret, nil
  1076. }
  1077. func (aws *AWS) configureAWSAuth() error {
  1078. accessKeyID := aws.ServiceKeyName
  1079. accessKeySecret := aws.ServiceKeySecret
  1080. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1081. err := env.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1082. if err != nil {
  1083. return err
  1084. }
  1085. err = env.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1086. if err != nil {
  1087. return err
  1088. }
  1089. }
  1090. return nil
  1091. }
  1092. func getClusterConfig(ccFile string) (map[string]string, error) {
  1093. clusterConfig, err := os.Open(ccFile)
  1094. if err != nil {
  1095. return nil, err
  1096. }
  1097. defer clusterConfig.Close()
  1098. b, err := ioutil.ReadAll(clusterConfig)
  1099. if err != nil {
  1100. return nil, err
  1101. }
  1102. var clusterConf map[string]string
  1103. err = json.Unmarshal([]byte(b), &clusterConf)
  1104. if err != nil {
  1105. return nil, err
  1106. }
  1107. return clusterConf, nil
  1108. }
  1109. // SetKeyEnv ensures that the two environment variables necessary to configure
  1110. // a new AWS Session are set.
  1111. func (a *AWS) SetKeyEnv() error {
  1112. // TODO add this to the helm chart, mirroring the cost-model
  1113. // configPath := env.GetConfigPath()
  1114. configPath := defaultConfigPath
  1115. path := configPath + "aws.json"
  1116. if _, err := os.Stat(path); err != nil {
  1117. if os.IsNotExist(err) {
  1118. log.DedupedErrorf(5, "file %s does not exist", path)
  1119. } else {
  1120. log.DedupedErrorf(5, "other file open error: %s", err)
  1121. }
  1122. return err
  1123. }
  1124. jsonFile, err := os.Open(path)
  1125. defer jsonFile.Close()
  1126. configMap := map[string]string{}
  1127. configBytes, err := ioutil.ReadAll(jsonFile)
  1128. if err != nil {
  1129. return err
  1130. }
  1131. json.Unmarshal([]byte(configBytes), &configMap)
  1132. keyName := configMap["awsServiceKeyName"]
  1133. keySecret := configMap["awsServiceKeySecret"]
  1134. // These are required before calling NewEnvCredentials below
  1135. env.Set(env.AWSAccessKeyIDEnvVar, keyName)
  1136. env.Set(env.AWSAccessKeySecretEnvVar, keySecret)
  1137. return nil
  1138. }
  1139. func (a *AWS) getAddressesForRegion(region string) (*ec2.DescribeAddressesOutput, error) {
  1140. sess, err := session.NewSession(&aws.Config{
  1141. Region: aws.String(region),
  1142. Credentials: credentials.NewEnvCredentials(),
  1143. })
  1144. if err != nil {
  1145. return nil, err
  1146. }
  1147. ec2Svc := ec2.New(sess)
  1148. return ec2Svc.DescribeAddresses(&ec2.DescribeAddressesInput{})
  1149. }
  1150. func (a *AWS) GetAddresses() ([]byte, error) {
  1151. if err := a.SetKeyEnv(); err != nil {
  1152. return nil, err
  1153. }
  1154. addressCh := make(chan *ec2.DescribeAddressesOutput, len(awsRegions))
  1155. errorCh := make(chan error, len(awsRegions))
  1156. var wg sync.WaitGroup
  1157. wg.Add(len(awsRegions))
  1158. // Get volumes from each AWS region
  1159. for _, r := range awsRegions {
  1160. // Fetch IP address response and send results and errors to their
  1161. // respective channels
  1162. go func(region string) {
  1163. defer wg.Done()
  1164. defer errors.HandlePanic()
  1165. // Query for first page of volume results
  1166. resp, err := a.getAddressesForRegion(region)
  1167. if err != nil {
  1168. if aerr, ok := err.(awserr.Error); ok {
  1169. switch aerr.Code() {
  1170. default:
  1171. errorCh <- aerr
  1172. }
  1173. return
  1174. } else {
  1175. errorCh <- err
  1176. return
  1177. }
  1178. }
  1179. addressCh <- resp
  1180. }(r)
  1181. }
  1182. // Close the result channels after everything has been sent
  1183. go func() {
  1184. defer errors.HandlePanic()
  1185. wg.Wait()
  1186. close(errorCh)
  1187. close(addressCh)
  1188. }()
  1189. addresses := []*ec2.Address{}
  1190. for adds := range addressCh {
  1191. addresses = append(addresses, adds.Addresses...)
  1192. }
  1193. errors := []error{}
  1194. for err := range errorCh {
  1195. log.DedupedWarningf(5, "unable to get addresses: %s", err)
  1196. errors = append(errors, err)
  1197. }
  1198. // Return error if no addresses are returned
  1199. if len(errors) > 0 && len(addresses) == 0 {
  1200. return nil, fmt.Errorf("%d error(s) retrieving addresses: %v", len(errors), errors)
  1201. }
  1202. // Format the response this way to match the JSON-encoded formatting of a single response
  1203. // from DescribeAddresss, so that consumers can always expect AWS disk responses to have
  1204. // a "Addresss" key at the top level.
  1205. return json.Marshal(map[string][]*ec2.Address{
  1206. "Addresses": addresses,
  1207. })
  1208. }
  1209. func (a *AWS) getDisksForRegion(region string, maxResults int64, nextToken *string) (*ec2.DescribeVolumesOutput, error) {
  1210. sess, err := session.NewSession(&aws.Config{
  1211. Region: aws.String(region),
  1212. Credentials: credentials.NewEnvCredentials(),
  1213. })
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. ec2Svc := ec2.New(sess)
  1218. return ec2Svc.DescribeVolumes(&ec2.DescribeVolumesInput{
  1219. MaxResults: &maxResults,
  1220. NextToken: nextToken,
  1221. })
  1222. }
  1223. // 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.
  1224. func (a *AWS) GetDisks() ([]byte, error) {
  1225. if err := a.SetKeyEnv(); err != nil {
  1226. return nil, err
  1227. }
  1228. volumeCh := make(chan *ec2.DescribeVolumesOutput, len(awsRegions))
  1229. errorCh := make(chan error, len(awsRegions))
  1230. var wg sync.WaitGroup
  1231. wg.Add(len(awsRegions))
  1232. // Get volumes from each AWS region
  1233. for _, r := range awsRegions {
  1234. // Fetch volume response and send results and errors to their
  1235. // respective channels
  1236. go func(region string) {
  1237. defer wg.Done()
  1238. defer errors.HandlePanic()
  1239. // Query for first page of volume results
  1240. resp, err := a.getDisksForRegion(region, 1000, nil)
  1241. if err != nil {
  1242. if aerr, ok := err.(awserr.Error); ok {
  1243. switch aerr.Code() {
  1244. default:
  1245. errorCh <- aerr
  1246. }
  1247. return
  1248. } else {
  1249. errorCh <- err
  1250. return
  1251. }
  1252. }
  1253. volumeCh <- resp
  1254. // A NextToken indicates more pages of results. Keep querying
  1255. // until all pages are retrieved.
  1256. for resp.NextToken != nil {
  1257. resp, err = a.getDisksForRegion(region, 100, resp.NextToken)
  1258. if err != nil {
  1259. if aerr, ok := err.(awserr.Error); ok {
  1260. switch aerr.Code() {
  1261. default:
  1262. errorCh <- aerr
  1263. }
  1264. return
  1265. } else {
  1266. errorCh <- err
  1267. return
  1268. }
  1269. }
  1270. volumeCh <- resp
  1271. }
  1272. }(r)
  1273. }
  1274. // Close the result channels after everything has been sent
  1275. go func() {
  1276. defer errors.HandlePanic()
  1277. wg.Wait()
  1278. close(errorCh)
  1279. close(volumeCh)
  1280. }()
  1281. volumes := []*ec2.Volume{}
  1282. for vols := range volumeCh {
  1283. volumes = append(volumes, vols.Volumes...)
  1284. }
  1285. errors := []error{}
  1286. for err := range errorCh {
  1287. log.DedupedWarningf(5, "unable to get disks: %s", err)
  1288. errors = append(errors, err)
  1289. }
  1290. // Return error if no volumes are returned
  1291. if len(errors) > 0 && len(volumes) == 0 {
  1292. return nil, fmt.Errorf("%d error(s) retrieving volumes: %v", len(errors), errors)
  1293. }
  1294. // Format the response this way to match the JSON-encoded formatting of a single response
  1295. // from DescribeVolumes, so that consumers can always expect AWS disk responses to have
  1296. // a "Volumes" key at the top level.
  1297. return json.Marshal(map[string][]*ec2.Volume{
  1298. "Volumes": volumes,
  1299. })
  1300. }
  1301. // ConvertToGlueColumnFormat takes a string and runs through various regex
  1302. // and string replacement statements to convert it to a format compatible
  1303. // with AWS Glue and Athena column names.
  1304. // Following guidance from AWS provided here ('Column Names' section):
  1305. // https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/run-athena-sql.html
  1306. // It returns a string containing the column name in proper column name format and length.
  1307. func ConvertToGlueColumnFormat(column_name string) string {
  1308. klog.V(5).Infof("Converting string \"%s\" to proper AWS Glue column name.", column_name)
  1309. // An underscore is added in front of uppercase letters
  1310. capital_underscore := regexp.MustCompile(`[A-Z]`)
  1311. final := capital_underscore.ReplaceAllString(column_name, `_$0`)
  1312. // Any non-alphanumeric characters are replaced with an underscore
  1313. no_space_punc := regexp.MustCompile(`[\s]{1,}|[^A-Za-z0-9]`)
  1314. final = no_space_punc.ReplaceAllString(final, "_")
  1315. // Duplicate underscores are removed
  1316. no_dup_underscore := regexp.MustCompile(`_{2,}`)
  1317. final = no_dup_underscore.ReplaceAllString(final, "_")
  1318. // Any leading and trailing underscores are removed
  1319. no_front_end_underscore := regexp.MustCompile(`(^\_|\_$)`)
  1320. final = no_front_end_underscore.ReplaceAllString(final, "")
  1321. // Uppercase to lowercase
  1322. final = strings.ToLower(final)
  1323. // Longer column name than expected - remove _ left to right
  1324. allowed_col_len := 128
  1325. undersc_to_remove := len(final) - allowed_col_len
  1326. if undersc_to_remove > 0 {
  1327. final = strings.Replace(final, "_", "", undersc_to_remove)
  1328. }
  1329. // If removing all of the underscores still didn't
  1330. // make the column name < 128 characters, trim it!
  1331. if len(final) > allowed_col_len {
  1332. final = final[:allowed_col_len]
  1333. }
  1334. klog.V(5).Infof("Column name being returned: \"%s\". Length: \"%d\".", final, len(final))
  1335. return final
  1336. }
  1337. func generateAWSGroupBy(lastIdx int) string {
  1338. sequence := []string{}
  1339. for i := 1; i < lastIdx+1; i++ {
  1340. sequence = append(sequence, strconv.Itoa(i))
  1341. }
  1342. return strings.Join(sequence, ",")
  1343. }
  1344. func (a *AWS) QueryAthenaBillingData(query string) (*athena.GetQueryResultsOutput, error) {
  1345. customPricing, err := a.GetConfig()
  1346. if err != nil {
  1347. return nil, err
  1348. }
  1349. if customPricing.ServiceKeyName != "" {
  1350. err = env.Set(env.AWSAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1351. if err != nil {
  1352. return nil, err
  1353. }
  1354. err = env.Set(env.AWSAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1355. if err != nil {
  1356. return nil, err
  1357. }
  1358. }
  1359. region := aws.String(customPricing.AthenaRegion)
  1360. resultsBucket := customPricing.AthenaBucketName
  1361. database := customPricing.AthenaDatabase
  1362. c := &aws.Config{
  1363. Region: region,
  1364. }
  1365. s := session.Must(session.NewSession(c))
  1366. svc := athena.New(s)
  1367. if customPricing.MasterPayerARN != "" {
  1368. creds := stscreds.NewCredentials(s, customPricing.MasterPayerARN)
  1369. svc = athena.New(s, &aws.Config{
  1370. Region: region,
  1371. Credentials: creds,
  1372. })
  1373. }
  1374. var e athena.StartQueryExecutionInput
  1375. var r athena.ResultConfiguration
  1376. r.SetOutputLocation(resultsBucket)
  1377. e.SetResultConfiguration(&r)
  1378. e.SetQueryString(query)
  1379. var q athena.QueryExecutionContext
  1380. q.SetDatabase(database)
  1381. e.SetQueryExecutionContext(&q)
  1382. res, err := svc.StartQueryExecution(&e)
  1383. if err != nil {
  1384. return nil, err
  1385. }
  1386. klog.V(2).Infof("StartQueryExecution result:")
  1387. klog.V(2).Infof(res.GoString())
  1388. var qri athena.GetQueryExecutionInput
  1389. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1390. var qrop *athena.GetQueryExecutionOutput
  1391. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1392. for {
  1393. qrop, err = svc.GetQueryExecution(&qri)
  1394. if err != nil {
  1395. return nil, err
  1396. }
  1397. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1398. break
  1399. }
  1400. time.Sleep(duration)
  1401. }
  1402. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1403. var ip athena.GetQueryResultsInput
  1404. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1405. return svc.GetQueryResults(&ip)
  1406. } else {
  1407. return nil, fmt.Errorf("No results available for %s", query)
  1408. }
  1409. }
  1410. type SavingsPlanData struct {
  1411. ResourceID string
  1412. EffectiveCost float64
  1413. SavingsPlanARN string
  1414. MostRecentDate string
  1415. }
  1416. func (a *AWS) GetSavingsPlanDataFromAthena() error {
  1417. cfg, err := a.GetConfig()
  1418. if err != nil {
  1419. return err
  1420. }
  1421. if cfg.AthenaBucketName == "" {
  1422. return fmt.Errorf("No Athena Bucket configured")
  1423. }
  1424. if a.SavingsPlanDataByInstanceID == nil {
  1425. a.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData)
  1426. }
  1427. tNow := time.Now()
  1428. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1429. start := tOneDayAgo.Format("2006-01-02")
  1430. end := tNow.Format("2006-01-02")
  1431. q := `SELECT
  1432. line_item_usage_start_date,
  1433. savings_plan_savings_plan_a_r_n,
  1434. line_item_resource_id,
  1435. savings_plan_savings_plan_effective_cost
  1436. FROM %s as cost_data
  1437. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1438. AND line_item_line_item_type = 'SavingsPlanCoveredUsage' ORDER BY
  1439. line_item_usage_start_date DESC`
  1440. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1441. op, err := a.QueryAthenaBillingData(query)
  1442. if err != nil {
  1443. return fmt.Errorf("Error fetching Savings Plan Data: %s", err)
  1444. }
  1445. klog.Infof("Fetching SavingsPlan data...")
  1446. if len(op.ResultSet.Rows) > 1 {
  1447. a.SavingsPlanDataLock.Lock()
  1448. mostRecentDate := ""
  1449. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  1450. d := *r.Data[0].VarCharValue
  1451. if mostRecentDate == "" {
  1452. mostRecentDate = d
  1453. } else if mostRecentDate != d { // Get all most recent assignments
  1454. break
  1455. }
  1456. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1457. if err != nil {
  1458. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1459. }
  1460. r := &SavingsPlanData{
  1461. ResourceID: *r.Data[2].VarCharValue,
  1462. EffectiveCost: cost,
  1463. SavingsPlanARN: *r.Data[1].VarCharValue,
  1464. MostRecentDate: d,
  1465. }
  1466. a.SavingsPlanDataByInstanceID[r.ResourceID] = r
  1467. }
  1468. klog.V(1).Infof("Found %d savings plan applied instances", len(a.SavingsPlanDataByInstanceID))
  1469. for k, r := range a.SavingsPlanDataByInstanceID {
  1470. log.DedupedInfof(5, "Savings Plan Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1471. }
  1472. a.SavingsPlanDataLock.Unlock()
  1473. } else {
  1474. klog.Infof("No savings plan applied instance data found")
  1475. }
  1476. return nil
  1477. }
  1478. type RIData struct {
  1479. ResourceID string
  1480. EffectiveCost float64
  1481. ReservationARN string
  1482. MostRecentDate string
  1483. }
  1484. func (a *AWS) GetReservationDataFromAthena() error {
  1485. cfg, err := a.GetConfig()
  1486. if err != nil {
  1487. return err
  1488. }
  1489. if cfg.AthenaBucketName == "" {
  1490. return fmt.Errorf("No Athena Bucket configured")
  1491. }
  1492. if a.RIPricingByInstanceID == nil {
  1493. a.RIPricingByInstanceID = make(map[string]*RIData)
  1494. }
  1495. tNow := time.Now()
  1496. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1497. start := tOneDayAgo.Format("2006-01-02")
  1498. end := tNow.Format("2006-01-02")
  1499. q := `SELECT
  1500. line_item_usage_start_date,
  1501. reservation_reservation_a_r_n,
  1502. line_item_resource_id,
  1503. reservation_effective_cost
  1504. FROM %s as cost_data
  1505. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1506. AND reservation_reservation_a_r_n <> '' ORDER BY
  1507. line_item_usage_start_date DESC`
  1508. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1509. op, err := a.QueryAthenaBillingData(query)
  1510. if err != nil {
  1511. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  1512. }
  1513. klog.Infof("Fetching RI data...")
  1514. if len(op.ResultSet.Rows) > 1 {
  1515. a.RIDataLock.Lock()
  1516. mostRecentDate := ""
  1517. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  1518. d := *r.Data[0].VarCharValue
  1519. if mostRecentDate == "" {
  1520. mostRecentDate = d
  1521. } else if mostRecentDate != d { // Get all most recent assignments
  1522. break
  1523. }
  1524. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1525. if err != nil {
  1526. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1527. }
  1528. r := &RIData{
  1529. ResourceID: *r.Data[2].VarCharValue,
  1530. EffectiveCost: cost,
  1531. ReservationARN: *r.Data[1].VarCharValue,
  1532. MostRecentDate: d,
  1533. }
  1534. a.RIPricingByInstanceID[r.ResourceID] = r
  1535. }
  1536. klog.V(1).Infof("Found %d reserved instances", len(a.RIPricingByInstanceID))
  1537. for k, r := range a.RIPricingByInstanceID {
  1538. log.DedupedInfof(5, "Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1539. }
  1540. a.RIDataLock.Unlock()
  1541. } else {
  1542. klog.Infof("No reserved instance data found")
  1543. }
  1544. return nil
  1545. }
  1546. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  1547. // "start" and "end" are dates of the format YYYY-MM-DD
  1548. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  1549. func (a *AWS) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  1550. customPricing, err := a.GetConfig()
  1551. if err != nil {
  1552. return nil, err
  1553. }
  1554. formattedAggregators := []string{}
  1555. for _, agg := range aggregators {
  1556. aggregator_column_name := "resource_tags_user_" + agg
  1557. aggregator_column_name = ConvertToGlueColumnFormat(aggregator_column_name)
  1558. formattedAggregators = append(formattedAggregators, aggregator_column_name)
  1559. }
  1560. aggregatorNames := strings.Join(formattedAggregators, ",")
  1561. aggregatorOr := strings.Join(formattedAggregators, " <> '' OR ")
  1562. aggregatorOr = aggregatorOr + " <> ''"
  1563. filter_column_name := "resource_tags_user_" + filterType
  1564. filter_column_name = ConvertToGlueColumnFormat(filter_column_name)
  1565. var query string
  1566. var lastIdx int
  1567. if filterType != "kubernetes_" { // This gets appended upstream and is equivalent to no filter.
  1568. lastIdx = len(formattedAggregators) + 3
  1569. groupby := generateAWSGroupBy(lastIdx)
  1570. query = fmt.Sprintf(`SELECT
  1571. CAST(line_item_usage_start_date AS DATE) as start_date,
  1572. %s,
  1573. line_item_product_code,
  1574. %s,
  1575. SUM(line_item_blended_cost) as blended_cost
  1576. FROM %s as cost_data
  1577. WHERE (%s='%s') AND line_item_usage_start_date BETWEEN date '%s' AND date '%s' AND (%s)
  1578. GROUP BY %s`, aggregatorNames, filter_column_name, customPricing.AthenaTable, filter_column_name, filterValue, start, end, aggregatorOr, groupby)
  1579. } else {
  1580. lastIdx = len(formattedAggregators) + 2
  1581. groupby := generateAWSGroupBy(lastIdx)
  1582. query = fmt.Sprintf(`SELECT
  1583. CAST(line_item_usage_start_date AS DATE) as start_date,
  1584. %s,
  1585. line_item_product_code,
  1586. SUM(line_item_blended_cost) as blended_cost
  1587. FROM %s as cost_data
  1588. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s' AND (%s)
  1589. GROUP BY %s`, aggregatorNames, customPricing.AthenaTable, start, end, aggregatorOr, groupby)
  1590. }
  1591. klog.V(3).Infof("Running Query: %s", query)
  1592. if customPricing.ServiceKeyName != "" {
  1593. err = env.Set(env.AWSAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1594. if err != nil {
  1595. return nil, err
  1596. }
  1597. err = env.Set(env.AWSAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1598. if err != nil {
  1599. return nil, err
  1600. }
  1601. }
  1602. region := aws.String(customPricing.AthenaRegion)
  1603. resultsBucket := customPricing.AthenaBucketName
  1604. database := customPricing.AthenaDatabase
  1605. c := &aws.Config{
  1606. Region: region,
  1607. }
  1608. s := session.Must(session.NewSession(c))
  1609. svc := athena.New(s)
  1610. if customPricing.MasterPayerARN != "" {
  1611. creds := stscreds.NewCredentials(s, customPricing.MasterPayerARN)
  1612. svc = athena.New(s, &aws.Config{
  1613. Region: region,
  1614. Credentials: creds,
  1615. })
  1616. }
  1617. var e athena.StartQueryExecutionInput
  1618. var r athena.ResultConfiguration
  1619. r.SetOutputLocation(resultsBucket)
  1620. e.SetResultConfiguration(&r)
  1621. e.SetQueryString(query)
  1622. var q athena.QueryExecutionContext
  1623. q.SetDatabase(database)
  1624. e.SetQueryExecutionContext(&q)
  1625. res, err := svc.StartQueryExecution(&e)
  1626. if err != nil {
  1627. return nil, err
  1628. }
  1629. klog.V(2).Infof("StartQueryExecution result:")
  1630. klog.V(2).Infof(res.GoString())
  1631. var qri athena.GetQueryExecutionInput
  1632. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1633. var qrop *athena.GetQueryExecutionOutput
  1634. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1635. for {
  1636. qrop, err = svc.GetQueryExecution(&qri)
  1637. if err != nil {
  1638. return nil, err
  1639. }
  1640. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1641. break
  1642. }
  1643. time.Sleep(duration)
  1644. }
  1645. var oocAllocs []*OutOfClusterAllocation
  1646. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1647. var ip athena.GetQueryResultsInput
  1648. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1649. op, err := svc.GetQueryResults(&ip)
  1650. if err != nil {
  1651. return nil, err
  1652. }
  1653. if len(op.ResultSet.Rows) > 1 {
  1654. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows))] {
  1655. cost, err := strconv.ParseFloat(*r.Data[lastIdx].VarCharValue, 64)
  1656. if err != nil {
  1657. return nil, err
  1658. }
  1659. environment := ""
  1660. for _, d := range r.Data[1 : len(formattedAggregators)+1] {
  1661. if *d.VarCharValue != "" {
  1662. environment = *d.VarCharValue // just set to the first nonempty match
  1663. }
  1664. break
  1665. }
  1666. ooc := &OutOfClusterAllocation{
  1667. Aggregator: strings.Join(aggregators, ","),
  1668. Environment: environment,
  1669. Service: *r.Data[len(formattedAggregators)+1].VarCharValue,
  1670. Cost: cost,
  1671. }
  1672. oocAllocs = append(oocAllocs, ooc)
  1673. }
  1674. } else {
  1675. klog.V(1).Infof("No results available for %s at database %s between %s and %s", strings.Join(formattedAggregators, ","), customPricing.AthenaTable, start, end)
  1676. }
  1677. }
  1678. if customPricing.BillingDataDataset != "" && !crossCluster { // There is GCP data, meaning someone has tried to configure a GCP out-of-cluster allocation.
  1679. gcp, err := NewCrossClusterProvider("gcp", "aws.json", a.Clientset)
  1680. if err != nil {
  1681. klog.Infof("Could not instantiate cross-cluster provider %s", err.Error())
  1682. }
  1683. gcpOOC, err := gcp.ExternalAllocations(start, end, aggregators, filterType, filterValue, true)
  1684. if err != nil {
  1685. klog.Infof("Could not fetch cross-cluster costs %s", err.Error())
  1686. }
  1687. oocAllocs = append(oocAllocs, gcpOOC...)
  1688. }
  1689. return oocAllocs, nil
  1690. }
  1691. // QuerySQL can query a properly configured Athena database.
  1692. // Used to fetch billing data.
  1693. // Requires a json config in /var/configs with key region, output, and database.
  1694. func (a *AWS) QuerySQL(query string) ([]byte, error) {
  1695. customPricing, err := a.GetConfig()
  1696. if err != nil {
  1697. return nil, err
  1698. }
  1699. if customPricing.ServiceKeyName != "" {
  1700. err = env.Set(env.AWSAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1701. if err != nil {
  1702. return nil, err
  1703. }
  1704. err = env.Set(env.AWSAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1705. if err != nil {
  1706. return nil, err
  1707. }
  1708. }
  1709. athenaConfigs, err := os.Open("/var/configs/athena.json")
  1710. if err != nil {
  1711. return nil, err
  1712. }
  1713. defer athenaConfigs.Close()
  1714. b, err := ioutil.ReadAll(athenaConfigs)
  1715. if err != nil {
  1716. return nil, err
  1717. }
  1718. var athenaConf map[string]string
  1719. json.Unmarshal([]byte(b), &athenaConf)
  1720. region := aws.String(customPricing.AthenaRegion)
  1721. resultsBucket := customPricing.AthenaBucketName
  1722. database := customPricing.AthenaDatabase
  1723. c := &aws.Config{
  1724. Region: region,
  1725. }
  1726. s := session.Must(session.NewSession(c))
  1727. svc := athena.New(s)
  1728. var e athena.StartQueryExecutionInput
  1729. var r athena.ResultConfiguration
  1730. r.SetOutputLocation(resultsBucket)
  1731. e.SetResultConfiguration(&r)
  1732. e.SetQueryString(query)
  1733. var q athena.QueryExecutionContext
  1734. q.SetDatabase(database)
  1735. e.SetQueryExecutionContext(&q)
  1736. res, err := svc.StartQueryExecution(&e)
  1737. if err != nil {
  1738. return nil, err
  1739. }
  1740. klog.V(2).Infof("StartQueryExecution result:")
  1741. klog.V(2).Infof(res.GoString())
  1742. var qri athena.GetQueryExecutionInput
  1743. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1744. var qrop *athena.GetQueryExecutionOutput
  1745. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1746. for {
  1747. qrop, err = svc.GetQueryExecution(&qri)
  1748. if err != nil {
  1749. return nil, err
  1750. }
  1751. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1752. break
  1753. }
  1754. time.Sleep(duration)
  1755. }
  1756. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1757. var ip athena.GetQueryResultsInput
  1758. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1759. op, err := svc.GetQueryResults(&ip)
  1760. if err != nil {
  1761. return nil, err
  1762. }
  1763. b, err := json.Marshal(op.ResultSet)
  1764. if err != nil {
  1765. return nil, err
  1766. }
  1767. return b, nil
  1768. }
  1769. return nil, fmt.Errorf("Error getting query results : %s", *qrop.QueryExecution.Status.State)
  1770. }
  1771. type spotInfo struct {
  1772. Timestamp string `csv:"Timestamp"`
  1773. UsageType string `csv:"UsageType"`
  1774. Operation string `csv:"Operation"`
  1775. InstanceID string `csv:"InstanceID"`
  1776. MyBidID string `csv:"MyBidID"`
  1777. MyMaxPrice string `csv:"MyMaxPrice"`
  1778. MarketPrice string `csv:"MarketPrice"`
  1779. Charge string `csv:"Charge"`
  1780. Version string `csv:"Version"`
  1781. }
  1782. type fnames []*string
  1783. func (f fnames) Len() int {
  1784. return len(f)
  1785. }
  1786. func (f fnames) Swap(i, j int) {
  1787. f[i], f[j] = f[j], f[i]
  1788. }
  1789. func (f fnames) Less(i, j int) bool {
  1790. key1 := strings.Split(*f[i], ".")
  1791. key2 := strings.Split(*f[j], ".")
  1792. t1, err := time.Parse("2006-01-02-15", key1[1])
  1793. if err != nil {
  1794. klog.V(1).Info("Unable to parse timestamp" + key1[1])
  1795. return false
  1796. }
  1797. t2, err := time.Parse("2006-01-02-15", key2[1])
  1798. if err != nil {
  1799. klog.V(1).Info("Unable to parse timestamp" + key2[1])
  1800. return false
  1801. }
  1802. return t1.Before(t2)
  1803. }
  1804. func (a *AWS) parseSpotData(bucket string, prefix string, projectID string, region string, accessKeyID string, accessKeySecret string) (map[string]*spotInfo, error) {
  1805. if a.ServiceAccountChecks == nil { // Set up checks to store error/success states
  1806. a.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  1807. }
  1808. // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1809. if accessKeyID != "" && accessKeySecret != "" {
  1810. err := env.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1811. if err != nil {
  1812. return nil, err
  1813. }
  1814. err = env.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1815. if err != nil {
  1816. return nil, err
  1817. }
  1818. }
  1819. s3Prefix := projectID
  1820. if len(prefix) != 0 {
  1821. s3Prefix = prefix + "/" + s3Prefix
  1822. }
  1823. c := aws.NewConfig().WithRegion(region)
  1824. s := session.Must(session.NewSession(c))
  1825. s3Svc := s3.New(s)
  1826. downloader := s3manager.NewDownloaderWithClient(s3Svc)
  1827. tNow := time.Now()
  1828. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1829. ls := &s3.ListObjectsInput{
  1830. Bucket: aws.String(bucket),
  1831. Prefix: aws.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1832. }
  1833. ls2 := &s3.ListObjectsInput{
  1834. Bucket: aws.String(bucket),
  1835. Prefix: aws.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1836. }
  1837. lso, err := s3Svc.ListObjects(ls)
  1838. if err != nil {
  1839. a.ServiceAccountChecks["bucketList"] = &ServiceAccountCheck{
  1840. Message: "Bucket List Permissions Available",
  1841. Status: false,
  1842. AdditionalInfo: err.Error(),
  1843. }
  1844. return nil, err
  1845. } else {
  1846. a.ServiceAccountChecks["bucketList"] = &ServiceAccountCheck{
  1847. Message: "Bucket List Permissions Available",
  1848. Status: true,
  1849. }
  1850. }
  1851. lsoLen := len(lso.Contents)
  1852. klog.V(2).Infof("Found %d spot data files from yesterday", lsoLen)
  1853. if lsoLen == 0 {
  1854. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1855. }
  1856. lso2, err := s3Svc.ListObjects(ls2)
  1857. if err != nil {
  1858. return nil, err
  1859. }
  1860. lso2Len := len(lso2.Contents)
  1861. klog.V(2).Infof("Found %d spot data files from today", lso2Len)
  1862. if lso2Len == 0 {
  1863. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1864. }
  1865. // TODO: Worth it to use LastModifiedDate to determine if we should reparse the spot data?
  1866. var keys []*string
  1867. for _, obj := range lso.Contents {
  1868. keys = append(keys, obj.Key)
  1869. }
  1870. for _, obj := range lso2.Contents {
  1871. keys = append(keys, obj.Key)
  1872. }
  1873. versionRx := regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  1874. header, err := csvutil.Header(spotInfo{}, "csv")
  1875. if err != nil {
  1876. return nil, err
  1877. }
  1878. fieldsPerRecord := len(header)
  1879. spots := make(map[string]*spotInfo)
  1880. for _, key := range keys {
  1881. getObj := &s3.GetObjectInput{
  1882. Bucket: aws.String(bucket),
  1883. Key: key,
  1884. }
  1885. buf := aws.NewWriteAtBuffer([]byte{})
  1886. _, err := downloader.Download(buf, getObj)
  1887. if err != nil {
  1888. a.ServiceAccountChecks["objectList"] = &ServiceAccountCheck{
  1889. Message: "Object Get Permissions Available",
  1890. Status: false,
  1891. AdditionalInfo: err.Error(),
  1892. }
  1893. return nil, err
  1894. } else {
  1895. a.ServiceAccountChecks["objectList"] = &ServiceAccountCheck{
  1896. Message: "Object Get Permissions Available",
  1897. Status: true,
  1898. }
  1899. }
  1900. r := bytes.NewReader(buf.Bytes())
  1901. gr, err := gzip.NewReader(r)
  1902. if err != nil {
  1903. return nil, err
  1904. }
  1905. csvReader := csv.NewReader(gr)
  1906. csvReader.Comma = '\t'
  1907. csvReader.FieldsPerRecord = fieldsPerRecord
  1908. dec, err := csvutil.NewDecoder(csvReader, header...)
  1909. if err != nil {
  1910. return nil, err
  1911. }
  1912. var foundVersion string
  1913. for {
  1914. spot := spotInfo{}
  1915. err := dec.Decode(&spot)
  1916. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1917. if err == io.EOF {
  1918. break
  1919. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1920. rec := dec.Record()
  1921. // the first two "Record()" will be the comment lines
  1922. // and they show up as len() == 1
  1923. // the first of which is "#Version"
  1924. // the second of which is "#Fields: "
  1925. if len(rec) != 1 {
  1926. klog.V(2).Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1927. continue
  1928. }
  1929. if len(foundVersion) == 0 {
  1930. spotFeedVersion := rec[0]
  1931. klog.V(4).Infof("Spot feed version is \"%s\"", spotFeedVersion)
  1932. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  1933. if matches != nil {
  1934. foundVersion = matches[1]
  1935. if foundVersion != supportedSpotFeedVersion {
  1936. klog.V(2).Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  1937. break
  1938. }
  1939. }
  1940. continue
  1941. } else if strings.Index(rec[0], "#") == 0 {
  1942. continue
  1943. } else {
  1944. klog.V(3).Infof("skipping non-TSV line: %s", rec)
  1945. continue
  1946. }
  1947. } else if err != nil {
  1948. klog.V(2).Infof("Error during spot info decode: %+v", err)
  1949. continue
  1950. }
  1951. log.DedupedInfof(5, "Found spot info for: %s", spot.InstanceID)
  1952. spots[spot.InstanceID] = &spot
  1953. }
  1954. gr.Close()
  1955. }
  1956. return spots, nil
  1957. }
  1958. func (a *AWS) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1959. /*
  1960. numReserved := len(a.ReservedInstances)
  1961. // Early return if no reserved instance data loaded
  1962. if numReserved == 0 {
  1963. klog.V(4).Infof("[Reserved] No Reserved Instances")
  1964. return
  1965. }
  1966. cfg, err := a.GetConfig()
  1967. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1968. if err != nil {
  1969. klog.V(3).Infof("Could not parse default cpu price")
  1970. defaultCPU = 0.031611
  1971. }
  1972. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1973. if err != nil {
  1974. klog.V(3).Infof("Could not parse default ram price")
  1975. defaultRAM = 0.004237
  1976. }
  1977. cpuToRAMRatio := defaultCPU / defaultRAM
  1978. now := time.Now()
  1979. instances := make(map[string][]*AWSReservedInstance)
  1980. for _, r := range a.ReservedInstances {
  1981. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1982. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  1983. continue
  1984. }
  1985. _, ok := instances[r.Region]
  1986. if !ok {
  1987. instances[r.Region] = []*AWSReservedInstance{r}
  1988. } else {
  1989. instances[r.Region] = append(instances[r.Region], r)
  1990. }
  1991. }
  1992. awsNodes := make(map[string]*v1.Node)
  1993. currentNodes := a.Clientset.GetAllNodes()
  1994. // Create a node name -> node map
  1995. for _, awsNode := range currentNodes {
  1996. awsNodes[awsNode.GetName()] = awsNode
  1997. }
  1998. // go through all provider nodes using k8s nodes for region
  1999. for nodeName, node := range nodes {
  2000. // Reset reserved allocation to prevent double allocation
  2001. node.Reserved = nil
  2002. kNode, ok := awsNodes[nodeName]
  2003. if !ok {
  2004. klog.V(1).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  2005. continue
  2006. }
  2007. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  2008. if !ok {
  2009. klog.V(1).Infof("[Reserved] Could not find node region")
  2010. continue
  2011. }
  2012. reservedInstances, ok := instances[nodeRegion]
  2013. if !ok {
  2014. klog.V(1).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  2015. continue
  2016. }
  2017. // Determine the InstanceType of the node
  2018. instanceType, ok := kNode.Labels["beta.kubernetes.io/instance-type"]
  2019. if !ok {
  2020. continue
  2021. }
  2022. ramBytes, err := strconv.ParseFloat(node.RAMBytes, 64)
  2023. if err != nil {
  2024. continue
  2025. }
  2026. ramGB := ramBytes / 1024 / 1024 / 1024
  2027. cpu, err := strconv.ParseFloat(node.VCPU, 64)
  2028. if err != nil {
  2029. continue
  2030. }
  2031. ramMultiple := cpu*cpuToRAMRatio + ramGB
  2032. node.Reserved = &ReservedInstanceData{
  2033. ReservedCPU: 0,
  2034. ReservedRAM: 0,
  2035. }
  2036. for i, reservedInstance := range reservedInstances {
  2037. if reservedInstance.InstanceType == instanceType {
  2038. // Use < 0 to mark as ALL
  2039. node.Reserved.ReservedCPU = -1
  2040. node.Reserved.ReservedRAM = -1
  2041. // Set Costs based on CPU/RAM ratios
  2042. ramPrice := reservedInstance.PricePerHour / ramMultiple
  2043. node.Reserved.CPUCost = ramPrice * cpuToRAMRatio
  2044. node.Reserved.RAMCost = ramPrice
  2045. // Remove the reserve from the temporary slice to prevent
  2046. // being reallocated
  2047. instances[nodeRegion] = append(reservedInstances[:i], reservedInstances[i+1:]...)
  2048. break
  2049. }
  2050. }
  2051. }*/
  2052. }
  2053. type AWSReservedInstance struct {
  2054. Zone string
  2055. Region string
  2056. InstanceType string
  2057. InstanceCount int64
  2058. InstanceTenacy string
  2059. StartDate time.Time
  2060. EndDate time.Time
  2061. PricePerHour float64
  2062. }
  2063. func (ari *AWSReservedInstance) String() string {
  2064. 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)
  2065. }
  2066. func isReservedInstanceHourlyPrice(rc *ec2.RecurringCharge) bool {
  2067. return rc != nil && rc.Frequency != nil && *rc.Frequency == "Hourly"
  2068. }
  2069. func getReservedInstancePrice(ri *ec2.ReservedInstances) (float64, error) {
  2070. var pricePerHour float64
  2071. if len(ri.RecurringCharges) > 0 {
  2072. for _, rc := range ri.RecurringCharges {
  2073. if isReservedInstanceHourlyPrice(rc) {
  2074. pricePerHour = *rc.Amount
  2075. break
  2076. }
  2077. }
  2078. }
  2079. // If we're still unable to resolve hourly price, try fixed -> hourly
  2080. if pricePerHour == 0 {
  2081. if ri.Duration != nil && ri.FixedPrice != nil {
  2082. var durHours float64
  2083. durSeconds := float64(*ri.Duration)
  2084. fixedPrice := float64(*ri.FixedPrice)
  2085. if durSeconds != 0 && fixedPrice != 0 {
  2086. durHours = durSeconds / 60 / 60
  2087. pricePerHour = fixedPrice / durHours
  2088. }
  2089. }
  2090. }
  2091. if pricePerHour == 0 {
  2092. return 0, fmt.Errorf("Failed to resolve an hourly price from FixedPrice or Recurring Costs")
  2093. }
  2094. return pricePerHour, nil
  2095. }
  2096. func getRegionReservedInstances(region string) ([]*AWSReservedInstance, error) {
  2097. c := &aws.Config{
  2098. Region: aws.String(region),
  2099. }
  2100. s := session.Must(session.NewSession(c))
  2101. svc := ec2.New(s)
  2102. response, err := svc.DescribeReservedInstances(&ec2.DescribeReservedInstancesInput{})
  2103. if err != nil {
  2104. return nil, err
  2105. }
  2106. var reservedInstances []*AWSReservedInstance
  2107. for _, ri := range response.ReservedInstances {
  2108. var zone string
  2109. if ri.AvailabilityZone != nil {
  2110. zone = *ri.AvailabilityZone
  2111. }
  2112. pricePerHour, err := getReservedInstancePrice(ri)
  2113. if err != nil {
  2114. klog.V(1).Infof("Error Resolving Price: %s", err.Error())
  2115. continue
  2116. }
  2117. reservedInstances = append(reservedInstances, &AWSReservedInstance{
  2118. Zone: zone,
  2119. Region: region,
  2120. InstanceType: *ri.InstanceType,
  2121. InstanceCount: *ri.InstanceCount,
  2122. InstanceTenacy: *ri.InstanceTenancy,
  2123. StartDate: *ri.Start,
  2124. EndDate: *ri.End,
  2125. PricePerHour: pricePerHour,
  2126. })
  2127. }
  2128. return reservedInstances, nil
  2129. }
  2130. func (a *AWS) getReservedInstances() ([]*AWSReservedInstance, error) {
  2131. err := a.configureAWSAuth()
  2132. if err != nil {
  2133. return nil, fmt.Errorf("Error Configuring aws auth: %s", err.Error())
  2134. }
  2135. var reservedInstances []*AWSReservedInstance
  2136. nodes := a.Clientset.GetAllNodes()
  2137. regionsSeen := make(map[string]bool)
  2138. for _, node := range nodes {
  2139. region, ok := node.Labels[v1.LabelZoneRegion]
  2140. if !ok {
  2141. continue
  2142. }
  2143. if regionsSeen[region] {
  2144. continue
  2145. }
  2146. ris, err := getRegionReservedInstances(region)
  2147. if err != nil {
  2148. klog.V(3).Infof("Error getting reserved instances: %s", err.Error())
  2149. continue
  2150. }
  2151. regionsSeen[region] = true
  2152. reservedInstances = append(reservedInstances, ris...)
  2153. }
  2154. return reservedInstances, nil
  2155. }
  2156. func (a *AWS) ServiceAccountStatus() *ServiceAccountStatus {
  2157. checks := []*ServiceAccountCheck{}
  2158. for _, v := range a.ServiceAccountChecks {
  2159. checks = append(checks, v)
  2160. }
  2161. return &ServiceAccountStatus{
  2162. Checks: checks,
  2163. }
  2164. }
  2165. func (aws *AWS) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  2166. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  2167. }
  2168. func (aws *AWS) ParseID(id string) string {
  2169. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  2170. rx := regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  2171. match := rx.FindStringSubmatch(id)
  2172. if len(match) < 2 {
  2173. if id != "" {
  2174. log.Infof("awsprovider.ParseID: failed to parse %s", id)
  2175. }
  2176. return id
  2177. }
  2178. return match[1]
  2179. }