awsprovider.go 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  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. "net/url"
  12. "os"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "k8s.io/klog"
  19. "github.com/kubecost/cost-model/pkg/clustercache"
  20. "github.com/aws/aws-sdk-go/aws"
  21. "github.com/aws/aws-sdk-go/aws/awserr"
  22. "github.com/aws/aws-sdk-go/aws/session"
  23. "github.com/aws/aws-sdk-go/service/athena"
  24. "github.com/aws/aws-sdk-go/service/ec2"
  25. "github.com/aws/aws-sdk-go/service/s3"
  26. "github.com/aws/aws-sdk-go/service/s3/s3manager"
  27. "github.com/jszwec/csvutil"
  28. v1 "k8s.io/api/core/v1"
  29. )
  30. const awsAccessKeyIDEnvVar = "AWS_ACCESS_KEY_ID"
  31. const awsAccessKeySecretEnvVar = "AWS_SECRET_ACCESS_KEY"
  32. const awsReservedInstancePricePerHour = 0.0287
  33. const supportedSpotFeedVersion = "1"
  34. const SpotInfoUpdateType = "spotinfo"
  35. const AthenaInfoUpdateType = "athenainfo"
  36. // AWS represents an Amazon Provider
  37. type AWS struct {
  38. Pricing map[string]*AWSProductTerms
  39. SpotPricingByInstanceID map[string]*spotInfo
  40. RIPricingByInstanceID map[string]*RIData
  41. RIDataRunning bool
  42. RIDataLock sync.RWMutex
  43. ValidPricingKeys map[string]bool
  44. Clientset clustercache.ClusterCache
  45. BaseCPUPrice string
  46. BaseRAMPrice string
  47. BaseGPUPrice string
  48. BaseSpotCPUPrice string
  49. BaseSpotRAMPrice string
  50. SpotLabelName string
  51. SpotLabelValue string
  52. ServiceKeyName string
  53. ServiceKeySecret string
  54. SpotDataRegion string
  55. SpotDataBucket string
  56. SpotDataPrefix string
  57. ProjectID string
  58. DownloadPricingDataLock sync.RWMutex
  59. Config *ProviderConfig
  60. *CustomProvider
  61. }
  62. // AWSPricing maps a k8s node to an AWS Pricing "product"
  63. type AWSPricing struct {
  64. Products map[string]*AWSProduct `json:"products"`
  65. Terms AWSPricingTerms `json:"terms"`
  66. }
  67. // AWSProduct represents a purchased SKU
  68. type AWSProduct struct {
  69. Sku string `json:"sku"`
  70. Attributes AWSProductAttributes `json:"attributes"`
  71. }
  72. // AWSProductAttributes represents metadata about the product used to map to a node.
  73. type AWSProductAttributes struct {
  74. Location string `json:"location"`
  75. InstanceType string `json:"instanceType"`
  76. Memory string `json:"memory"`
  77. Storage string `json:"storage"`
  78. VCpu string `json:"vcpu"`
  79. UsageType string `json:"usagetype"`
  80. OperatingSystem string `json:"operatingSystem"`
  81. PreInstalledSw string `json:"preInstalledSw"`
  82. InstanceFamily string `json:"instanceFamily"`
  83. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  84. }
  85. // AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
  86. type AWSPricingTerms struct {
  87. OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
  88. Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
  89. }
  90. // AWSOfferTerm is a sku extension used to pay for the node.
  91. type AWSOfferTerm struct {
  92. Sku string `json:"sku"`
  93. PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
  94. }
  95. // AWSRateCode encodes data about the price of a product
  96. type AWSRateCode struct {
  97. Unit string `json:"unit"`
  98. PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
  99. }
  100. // AWSCurrencyCode is the localized currency. (TODO: support non-USD)
  101. type AWSCurrencyCode struct {
  102. USD string `json:"USD"`
  103. }
  104. // AWSProductTerms represents the full terms of the product
  105. type AWSProductTerms struct {
  106. Sku string `json:"sku"`
  107. OnDemand *AWSOfferTerm `json:"OnDemand"`
  108. Reserved *AWSOfferTerm `json:"Reserved"`
  109. Memory string `json:"memory"`
  110. Storage string `json:"storage"`
  111. VCpu string `json:"vcpu"`
  112. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  113. PV *PV `json:"pv"`
  114. }
  115. // ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
  116. const ClusterIdEnvVar = "AWS_CLUSTER_ID"
  117. // OnDemandRateCode is appended to an node sku
  118. const OnDemandRateCode = ".JRTCKXETXF"
  119. // ReservedRateCode is appended to a node sku
  120. const ReservedRateCode = ".38NPMPTW36"
  121. // HourlyRateCode is appended to a node sku
  122. const HourlyRateCode = ".6YS6EN2CT7"
  123. // volTypes are used to map between AWS UsageTypes and
  124. // EBS volume types, as they would appear in K8s storage class
  125. // name and the EC2 API.
  126. var volTypes = map[string]string{
  127. "EBS:VolumeUsage.gp2": "gp2",
  128. "EBS:VolumeUsage": "standard",
  129. "EBS:VolumeUsage.sc1": "sc1",
  130. "EBS:VolumeP-IOPS.piops": "io1",
  131. "EBS:VolumeUsage.st1": "st1",
  132. "EBS:VolumeUsage.piops": "io1",
  133. "gp2": "EBS:VolumeUsage.gp2",
  134. "standard": "EBS:VolumeUsage",
  135. "sc1": "EBS:VolumeUsage.sc1",
  136. "io1": "EBS:VolumeUsage.piops",
  137. "st1": "EBS:VolumeUsage.st1",
  138. }
  139. // locationToRegion maps AWS region names (As they come from Billing)
  140. // to actual region identifiers
  141. var locationToRegion = map[string]string{
  142. "US East (Ohio)": "us-east-2",
  143. "US East (N. Virginia)": "us-east-1",
  144. "US West (N. California)": "us-west-1",
  145. "US West (Oregon)": "us-west-2",
  146. "Asia Pacific (Hong Kong)": "ap-east-1",
  147. "Asia Pacific (Mumbai)": "ap-south-1",
  148. "Asia Pacific (Osaka-Local)": "ap-northeast-3",
  149. "Asia Pacific (Seoul)": "ap-northeast-2",
  150. "Asia Pacific (Singapore)": "ap-southeast-1",
  151. "Asia Pacific (Sydney)": "ap-southeast-2",
  152. "Asia Pacific (Tokyo)": "ap-northeast-1",
  153. "Canada (Central)": "ca-central-1",
  154. "China (Beijing)": "cn-north-1",
  155. "China (Ningxia)": "cn-northwest-1",
  156. "EU (Frankfurt)": "eu-central-1",
  157. "EU (Ireland)": "eu-west-1",
  158. "EU (London)": "eu-west-2",
  159. "EU (Paris)": "eu-west-3",
  160. "EU (Stockholm)": "eu-north-1",
  161. "South America (Sao Paulo)": "sa-east-1",
  162. "AWS GovCloud (US-East)": "us-gov-east-1",
  163. "AWS GovCloud (US)": "us-gov-west-1",
  164. }
  165. var regionToBillingRegionCode = map[string]string{
  166. "us-east-2": "USE2",
  167. "us-east-1": "",
  168. "us-west-1": "USW1",
  169. "us-west-2": "USW2",
  170. "ap-east-1": "APE1",
  171. "ap-south-1": "APS3",
  172. "ap-northeast-3": "APN3",
  173. "ap-northeast-2": "APN2",
  174. "ap-southeast-1": "APS1",
  175. "ap-southeast-2": "APS2",
  176. "ap-northeast-1": "APN1",
  177. "ca-central-1": "CAN1",
  178. "cn-north-1": "",
  179. "cn-northwest-1": "",
  180. "eu-central-1": "EUC1",
  181. "eu-west-1": "EU",
  182. "eu-west-2": "EUW2",
  183. "eu-west-3": "EUW3",
  184. "eu-north-1": "EUN1",
  185. "sa-east-1": "SAE1",
  186. "us-gov-east-1": "UGE1",
  187. "us-gov-west-1": "UGW1",
  188. }
  189. func (aws *AWS) GetLocalStorageQuery(window, offset string, rate bool, used bool) string {
  190. return ""
  191. }
  192. // KubeAttrConversion maps the k8s labels for region to an aws region
  193. func (aws *AWS) KubeAttrConversion(location, instanceType, operatingSystem string) string {
  194. operatingSystem = strings.ToLower(operatingSystem)
  195. region := locationToRegion[location]
  196. return region + "," + instanceType + "," + operatingSystem
  197. }
  198. type AwsSpotFeedInfo struct {
  199. BucketName string `json:"bucketName"`
  200. Prefix string `json:"prefix"`
  201. Region string `json:"region"`
  202. AccountID string `json:"projectID"`
  203. ServiceKeyName string `json:"serviceKeyName"`
  204. ServiceKeySecret string `json:"serviceKeySecret"`
  205. SpotLabel string `json:"spotLabel"`
  206. SpotLabelValue string `json:"spotLabelValue"`
  207. }
  208. type AwsAthenaInfo struct {
  209. AthenaBucketName string `json:"athenaBucketName"`
  210. AthenaRegion string `json:"athenaRegion"`
  211. AthenaDatabase string `json:"athenaDatabase"`
  212. AthenaTable string `json:"athenaTable"`
  213. ServiceKeyName string `json:"serviceKeyName"`
  214. ServiceKeySecret string `json:"serviceKeySecret"`
  215. AccountID string `json:"projectID"`
  216. }
  217. func (aws *AWS) GetManagementPlatform() (string, error) {
  218. nodes := aws.Clientset.GetAllNodes()
  219. if len(nodes) > 0 {
  220. n := nodes[0]
  221. version := n.Status.NodeInfo.KubeletVersion
  222. if strings.Contains(version, "eks") {
  223. return "eks", nil
  224. }
  225. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  226. return "kops", nil
  227. }
  228. }
  229. return "", nil
  230. }
  231. func (aws *AWS) GetConfig() (*CustomPricing, error) {
  232. c, err := aws.Config.GetCustomPricingData()
  233. if c.Discount == "" {
  234. c.Discount = "0%"
  235. }
  236. if c.NegotiatedDiscount == "" {
  237. c.NegotiatedDiscount = "0%"
  238. }
  239. if err != nil {
  240. return nil, err
  241. }
  242. return c, nil
  243. }
  244. func (aws *AWS) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  245. return aws.Config.UpdateFromMap(a)
  246. }
  247. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  248. return aws.Config.Update(func(c *CustomPricing) error {
  249. if updateType == SpotInfoUpdateType {
  250. a := AwsSpotFeedInfo{}
  251. err := json.NewDecoder(r).Decode(&a)
  252. if err != nil {
  253. return err
  254. }
  255. c.ServiceKeyName = a.ServiceKeyName
  256. c.ServiceKeySecret = a.ServiceKeySecret
  257. c.SpotDataPrefix = a.Prefix
  258. c.SpotDataBucket = a.BucketName
  259. c.ProjectID = a.AccountID
  260. c.SpotDataRegion = a.Region
  261. c.SpotLabel = a.SpotLabel
  262. c.SpotLabelValue = a.SpotLabelValue
  263. } else if updateType == AthenaInfoUpdateType {
  264. a := AwsAthenaInfo{}
  265. err := json.NewDecoder(r).Decode(&a)
  266. if err != nil {
  267. return err
  268. }
  269. c.AthenaBucketName = a.AthenaBucketName
  270. c.AthenaRegion = a.AthenaRegion
  271. c.AthenaDatabase = a.AthenaDatabase
  272. c.AthenaTable = a.AthenaTable
  273. c.ServiceKeyName = a.ServiceKeyName
  274. c.ServiceKeySecret = a.ServiceKeySecret
  275. c.AthenaProjectID = a.AccountID
  276. } else {
  277. a := make(map[string]interface{})
  278. err := json.NewDecoder(r).Decode(&a)
  279. if err != nil {
  280. return err
  281. }
  282. for k, v := range a {
  283. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  284. vstr, ok := v.(string)
  285. if ok {
  286. err := SetCustomPricingField(c, kUpper, vstr)
  287. if err != nil {
  288. return err
  289. }
  290. } else {
  291. sci := v.(map[string]interface{})
  292. sc := make(map[string]string)
  293. for k, val := range sci {
  294. sc[k] = val.(string)
  295. }
  296. c.SharedCosts = sc //todo: support reflection/multiple map fields
  297. }
  298. }
  299. }
  300. remoteEnabled := os.Getenv(remoteEnabled)
  301. if remoteEnabled == "true" {
  302. err := UpdateClusterMeta(os.Getenv(clusterIDKey), c.ClusterName)
  303. if err != nil {
  304. return err
  305. }
  306. }
  307. return nil
  308. })
  309. }
  310. type awsKey struct {
  311. SpotLabelName string
  312. SpotLabelValue string
  313. Labels map[string]string
  314. ProviderID string
  315. }
  316. func (k *awsKey) GPUType() string {
  317. return ""
  318. }
  319. func (k *awsKey) ID() string {
  320. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)") // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  321. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  322. if matchNum == 2 {
  323. return group
  324. }
  325. }
  326. klog.V(3).Infof("Could not find instance ID in \"%s\"", k.ProviderID)
  327. return ""
  328. }
  329. func (k *awsKey) Features() string {
  330. instanceType := k.Labels[v1.LabelInstanceType]
  331. var operatingSystem string
  332. operatingSystem, ok := k.Labels[v1.LabelOSStable]
  333. if !ok {
  334. operatingSystem = k.Labels["beta.kubernetes.io/os"]
  335. }
  336. region := k.Labels[v1.LabelZoneRegion]
  337. key := region + "," + instanceType + "," + operatingSystem
  338. usageType := "preemptible"
  339. spotKey := key + "," + usageType
  340. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  341. return spotKey
  342. }
  343. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  344. return spotKey
  345. }
  346. return key
  347. }
  348. func (aws *AWS) PVPricing(pvk PVKey) (*PV, error) {
  349. pricing, ok := aws.Pricing[pvk.Features()]
  350. if !ok {
  351. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  352. return &PV{}, nil
  353. }
  354. return pricing.PV, nil
  355. }
  356. type awsPVKey struct {
  357. Labels map[string]string
  358. StorageClassParameters map[string]string
  359. StorageClassName string
  360. Name string
  361. DefaultRegion string
  362. }
  363. func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  364. return &awsPVKey{
  365. Labels: pv.Labels,
  366. StorageClassName: pv.Spec.StorageClassName,
  367. StorageClassParameters: parameters,
  368. Name: pv.Name,
  369. DefaultRegion: defaultRegion,
  370. }
  371. }
  372. func (key *awsPVKey) GetStorageClass() string {
  373. return key.StorageClassName
  374. }
  375. func (key *awsPVKey) Features() string {
  376. storageClass := key.StorageClassParameters["type"]
  377. if storageClass == "standard" {
  378. storageClass = "gp2"
  379. }
  380. // Storage class names are generally EBS volume types (gp2)
  381. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  382. // Converts between the 2
  383. region := key.Labels[v1.LabelZoneRegion]
  384. //if region == "" {
  385. // region = "us-east-1"
  386. //}
  387. class, ok := volTypes[storageClass]
  388. if !ok {
  389. klog.V(4).Infof("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  390. }
  391. return region + "," + class
  392. }
  393. // GetKey maps node labels to information needed to retrieve pricing data
  394. func (aws *AWS) GetKey(labels map[string]string) Key {
  395. return &awsKey{
  396. SpotLabelName: aws.SpotLabelName,
  397. SpotLabelValue: aws.SpotLabelValue,
  398. Labels: labels,
  399. ProviderID: labels["providerID"],
  400. }
  401. }
  402. func (aws *AWS) isPreemptible(key string) bool {
  403. s := strings.Split(key, ",")
  404. if len(s) == 4 && s[3] == "preemptible" {
  405. return true
  406. }
  407. return false
  408. }
  409. // DownloadPricingData fetches data from the AWS Pricing API
  410. func (aws *AWS) DownloadPricingData() error {
  411. aws.DownloadPricingDataLock.Lock()
  412. defer aws.DownloadPricingDataLock.Unlock()
  413. c, err := aws.Config.GetCustomPricingData()
  414. if err != nil {
  415. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  416. }
  417. aws.BaseCPUPrice = c.CPU
  418. aws.BaseRAMPrice = c.RAM
  419. aws.BaseGPUPrice = c.GPU
  420. aws.BaseSpotCPUPrice = c.SpotCPU
  421. aws.BaseSpotRAMPrice = c.SpotRAM
  422. aws.SpotLabelName = c.SpotLabel
  423. aws.SpotLabelValue = c.SpotLabelValue
  424. aws.SpotDataBucket = c.SpotDataBucket
  425. aws.SpotDataPrefix = c.SpotDataPrefix
  426. aws.ProjectID = c.ProjectID
  427. aws.SpotDataRegion = c.SpotDataRegion
  428. aws.ServiceKeyName = c.ServiceKeyName
  429. aws.ServiceKeySecret = c.ServiceKeySecret
  430. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  431. klog.V(1).Infof("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  432. }
  433. nodeList := aws.Clientset.GetAllNodes()
  434. inputkeys := make(map[string]bool)
  435. for _, n := range nodeList {
  436. labels := n.GetObjectMeta().GetLabels()
  437. key := aws.GetKey(labels)
  438. inputkeys[key.Features()] = true
  439. }
  440. pvList := aws.Clientset.GetAllPersistentVolumes()
  441. storageClasses := aws.Clientset.GetAllStorageClasses()
  442. storageClassMap := make(map[string]map[string]string)
  443. for _, storageClass := range storageClasses {
  444. params := storageClass.Parameters
  445. storageClassMap[storageClass.ObjectMeta.Name] = params
  446. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  447. storageClassMap["default"] = params
  448. storageClassMap[""] = params
  449. }
  450. }
  451. pvkeys := make(map[string]PVKey)
  452. for _, pv := range pvList {
  453. params, ok := storageClassMap[pv.Spec.StorageClassName]
  454. if !ok {
  455. klog.V(2).Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  456. continue
  457. }
  458. key := aws.GetPVKey(pv, params, "")
  459. pvkeys[key.Features()] = key
  460. }
  461. if !aws.RIDataRunning && c.AthenaBucketName != "" {
  462. err = aws.GetReservationDataFromAthena() // Block until one run has completed.
  463. if err != nil {
  464. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  465. } else { // If we make one successful run, check on new reservation data every hour
  466. go func() {
  467. for {
  468. aws.RIDataRunning = true
  469. klog.Infof("Reserved Instance watcher running... next update in 1h")
  470. time.Sleep(time.Hour)
  471. err := aws.GetReservationDataFromAthena()
  472. if err != nil {
  473. klog.Infof("Error updating RI data: %s", err.Error())
  474. }
  475. }
  476. }()
  477. }
  478. }
  479. aws.Pricing = make(map[string]*AWSProductTerms)
  480. aws.ValidPricingKeys = make(map[string]bool)
  481. skusToKeys := make(map[string]string)
  482. pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json"
  483. klog.V(2).Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  484. resp, err := http.Get(pricingURL)
  485. if err != nil {
  486. klog.V(2).Infof("Bogus fetch of \"%s\": %v", pricingURL, err)
  487. return err
  488. }
  489. klog.V(2).Infof("Finished downloading \"%s\"", pricingURL)
  490. dec := json.NewDecoder(resp.Body)
  491. for {
  492. t, err := dec.Token()
  493. if err == io.EOF {
  494. klog.V(2).Infof("done loading \"%s\"\n", pricingURL)
  495. break
  496. }
  497. if t == "products" {
  498. _, err := dec.Token() // this should parse the opening "{""
  499. if err != nil {
  500. return err
  501. }
  502. for dec.More() {
  503. _, err := dec.Token() // the sku token
  504. if err != nil {
  505. return err
  506. }
  507. product := &AWSProduct{}
  508. err = dec.Decode(&product)
  509. if err != nil {
  510. klog.V(1).Infof("Error parsing response from \"%s\": %v", pricingURL, err.Error())
  511. break
  512. }
  513. if product.Attributes.PreInstalledSw == "NA" &&
  514. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) {
  515. key := aws.KubeAttrConversion(product.Attributes.Location, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  516. spotKey := key + ",preemptible"
  517. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  518. productTerms := &AWSProductTerms{
  519. Sku: product.Sku,
  520. Memory: product.Attributes.Memory,
  521. Storage: product.Attributes.Storage,
  522. VCpu: product.Attributes.VCpu,
  523. GPU: product.Attributes.GPU,
  524. }
  525. aws.Pricing[key] = productTerms
  526. aws.Pricing[spotKey] = productTerms
  527. skusToKeys[product.Sku] = key
  528. }
  529. aws.ValidPricingKeys[key] = true
  530. aws.ValidPricingKeys[spotKey] = true
  531. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  532. // UsageTypes may be prefixed with a region code - we're removing this when using
  533. // volTypes to keep lookups generic
  534. usageTypeRegx := regexp.MustCompile(".*(-|^)(EBS.+)")
  535. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  536. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  537. key := locationToRegion[product.Attributes.Location] + "," + usageTypeNoRegion
  538. spotKey := key + ",preemptible"
  539. pv := &PV{
  540. Class: volTypes[usageTypeNoRegion],
  541. Region: locationToRegion[product.Attributes.Location],
  542. }
  543. productTerms := &AWSProductTerms{
  544. Sku: product.Sku,
  545. PV: pv,
  546. }
  547. aws.Pricing[key] = productTerms
  548. aws.Pricing[spotKey] = productTerms
  549. skusToKeys[product.Sku] = key
  550. aws.ValidPricingKeys[key] = true
  551. aws.ValidPricingKeys[spotKey] = true
  552. }
  553. }
  554. }
  555. if t == "terms" {
  556. _, err := dec.Token() // this should parse the opening "{""
  557. if err != nil {
  558. return err
  559. }
  560. termType, err := dec.Token()
  561. if err != nil {
  562. return err
  563. }
  564. if termType == "OnDemand" {
  565. _, err := dec.Token()
  566. if err != nil { // again, should parse an opening "{"
  567. return err
  568. }
  569. for dec.More() {
  570. sku, err := dec.Token()
  571. if err != nil {
  572. return err
  573. }
  574. _, err = dec.Token() // another opening "{"
  575. if err != nil {
  576. return err
  577. }
  578. skuOnDemand, err := dec.Token()
  579. if err != nil {
  580. return err
  581. }
  582. offerTerm := &AWSOfferTerm{}
  583. err = dec.Decode(&offerTerm)
  584. if err != nil {
  585. klog.V(1).Infof("Error decoding AWS Offer Term: " + err.Error())
  586. }
  587. if sku.(string)+OnDemandRateCode == skuOnDemand {
  588. key, ok := skusToKeys[sku.(string)]
  589. spotKey := key + ",preemptible"
  590. if ok {
  591. aws.Pricing[key].OnDemand = offerTerm
  592. aws.Pricing[spotKey].OnDemand = offerTerm
  593. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  594. // If the specific UsageType is the per IO cost used on io1 volumes
  595. // we need to add the per IO cost to the io1 PV cost
  596. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  597. // Add the per IO cost to the PV object for the io1 volume type
  598. aws.Pricing[key].PV.CostPerIO = cost
  599. } else if strings.Contains(key, "EBS:Volume") {
  600. // If volume, we need to get hourly cost and add it to the PV object
  601. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  602. costFloat, _ := strconv.ParseFloat(cost, 64)
  603. hourlyPrice := costFloat / 730
  604. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  605. }
  606. }
  607. }
  608. _, err = dec.Token()
  609. if err != nil {
  610. return err
  611. }
  612. }
  613. _, err = dec.Token()
  614. if err != nil {
  615. return err
  616. }
  617. }
  618. }
  619. }
  620. sp, err := parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion, aws.ServiceKeyName, aws.ServiceKeySecret)
  621. if err != nil {
  622. klog.V(1).Infof("Skipping AWS spot data download: %s", err.Error())
  623. } else {
  624. aws.SpotPricingByInstanceID = sp
  625. }
  626. return nil
  627. }
  628. // Stubbed NetworkPricing for AWS. Pull directly from aws.json for now
  629. func (aws *AWS) NetworkPricing() (*Network, error) {
  630. cpricing, err := aws.Config.GetCustomPricingData()
  631. if err != nil {
  632. return nil, err
  633. }
  634. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  635. if err != nil {
  636. return nil, err
  637. }
  638. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  639. if err != nil {
  640. return nil, err
  641. }
  642. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  643. if err != nil {
  644. return nil, err
  645. }
  646. return &Network{
  647. ZoneNetworkEgressCost: znec,
  648. RegionNetworkEgressCost: rnec,
  649. InternetNetworkEgressCost: inec,
  650. }, nil
  651. }
  652. // AllNodePricing returns all the billing data fetched.
  653. func (aws *AWS) AllNodePricing() (interface{}, error) {
  654. aws.DownloadPricingDataLock.RLock()
  655. defer aws.DownloadPricingDataLock.RUnlock()
  656. return aws.Pricing, nil
  657. }
  658. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  659. key := k.Features()
  660. aws.RIDataLock.RLock()
  661. defer aws.RIDataLock.RUnlock()
  662. if aws.isPreemptible(key) {
  663. if spotInfo, ok := aws.SpotPricingByInstanceID[k.ID()]; ok { // try and match directly to an ID for pricing. We'll still need the features
  664. var spotcost string
  665. arr := strings.Split(spotInfo.Charge, " ")
  666. if len(arr) == 2 {
  667. spotcost = arr[0]
  668. } else {
  669. klog.V(2).Infof("Spot data for node %s is missing", k.ID())
  670. }
  671. return &Node{
  672. Cost: spotcost,
  673. VCPU: terms.VCpu,
  674. RAM: terms.Memory,
  675. GPU: terms.GPU,
  676. Storage: terms.Storage,
  677. BaseCPUPrice: aws.BaseCPUPrice,
  678. BaseRAMPrice: aws.BaseRAMPrice,
  679. BaseGPUPrice: aws.BaseGPUPrice,
  680. UsageType: usageType,
  681. }, nil
  682. }
  683. return &Node{
  684. VCPU: terms.VCpu,
  685. VCPUCost: aws.BaseSpotCPUPrice,
  686. RAM: terms.Memory,
  687. GPU: terms.GPU,
  688. RAMCost: aws.BaseSpotRAMPrice,
  689. Storage: terms.Storage,
  690. BaseCPUPrice: aws.BaseCPUPrice,
  691. BaseRAMPrice: aws.BaseRAMPrice,
  692. BaseGPUPrice: aws.BaseGPUPrice,
  693. UsageType: usageType,
  694. }, nil
  695. } else if ri, ok := aws.RIPricingByInstanceID[k.ID()]; ok {
  696. strCost := fmt.Sprintf("%f", ri.EffectiveCost)
  697. return &Node{
  698. Cost: strCost,
  699. VCPU: terms.VCpu,
  700. RAM: terms.Memory,
  701. GPU: terms.GPU,
  702. Storage: terms.Storage,
  703. BaseCPUPrice: aws.BaseCPUPrice,
  704. BaseRAMPrice: aws.BaseRAMPrice,
  705. BaseGPUPrice: aws.BaseGPUPrice,
  706. UsageType: usageType,
  707. }, nil
  708. }
  709. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  710. if !ok {
  711. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  712. }
  713. cost := c.PricePerUnit.USD
  714. return &Node{
  715. Cost: cost,
  716. VCPU: terms.VCpu,
  717. RAM: terms.Memory,
  718. GPU: terms.GPU,
  719. Storage: terms.Storage,
  720. BaseCPUPrice: aws.BaseCPUPrice,
  721. BaseRAMPrice: aws.BaseRAMPrice,
  722. BaseGPUPrice: aws.BaseGPUPrice,
  723. UsageType: usageType,
  724. }, nil
  725. }
  726. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  727. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  728. aws.DownloadPricingDataLock.RLock()
  729. defer aws.DownloadPricingDataLock.RUnlock()
  730. key := k.Features()
  731. usageType := "ondemand"
  732. if aws.isPreemptible(key) {
  733. usageType = "preemptible"
  734. }
  735. terms, ok := aws.Pricing[key]
  736. if ok {
  737. return aws.createNode(terms, usageType, k)
  738. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  739. aws.DownloadPricingDataLock.RUnlock()
  740. err := aws.DownloadPricingData()
  741. aws.DownloadPricingDataLock.RLock()
  742. if err != nil {
  743. return &Node{
  744. Cost: aws.BaseCPUPrice,
  745. BaseCPUPrice: aws.BaseCPUPrice,
  746. BaseRAMPrice: aws.BaseRAMPrice,
  747. BaseGPUPrice: aws.BaseGPUPrice,
  748. UsageType: usageType,
  749. UsesBaseCPUPrice: true,
  750. }, err
  751. }
  752. terms, termsOk := aws.Pricing[key]
  753. if !termsOk {
  754. return &Node{
  755. Cost: aws.BaseCPUPrice,
  756. BaseCPUPrice: aws.BaseCPUPrice,
  757. BaseRAMPrice: aws.BaseRAMPrice,
  758. BaseGPUPrice: aws.BaseGPUPrice,
  759. UsageType: usageType,
  760. UsesBaseCPUPrice: true,
  761. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  762. }
  763. return aws.createNode(terms, usageType, k)
  764. } else { // Fall back to base pricing if we can't find the key.
  765. klog.V(1).Infof("Invalid Pricing Key \"%s\"", key)
  766. return &Node{
  767. Cost: aws.BaseCPUPrice,
  768. BaseCPUPrice: aws.BaseCPUPrice,
  769. BaseRAMPrice: aws.BaseRAMPrice,
  770. BaseGPUPrice: aws.BaseGPUPrice,
  771. UsageType: usageType,
  772. UsesBaseCPUPrice: true,
  773. }, nil
  774. }
  775. }
  776. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  777. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  778. defaultClusterName := "AWS Cluster #1"
  779. c, err := awsProvider.GetConfig()
  780. if err != nil {
  781. return nil, err
  782. }
  783. remote := os.Getenv(remoteEnabled)
  784. remoteEnabled := false
  785. if os.Getenv(remote) == "true" {
  786. remoteEnabled = true
  787. }
  788. if c.ClusterName != "" {
  789. m := make(map[string]string)
  790. m["name"] = c.ClusterName
  791. m["provider"] = "AWS"
  792. m["id"] = os.Getenv(clusterIDKey)
  793. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  794. return m, nil
  795. }
  796. makeStructure := func(clusterName string) (map[string]string, error) {
  797. klog.V(2).Infof("Returning \"%s\" as ClusterName", clusterName)
  798. m := make(map[string]string)
  799. m["name"] = clusterName
  800. m["provider"] = "AWS"
  801. m["id"] = os.Getenv(clusterIDKey)
  802. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  803. return m, nil
  804. }
  805. maybeClusterId := os.Getenv(ClusterIdEnvVar)
  806. if len(maybeClusterId) != 0 {
  807. return makeStructure(maybeClusterId)
  808. }
  809. // TODO: This should be cached, it can take a long time to hit the API
  810. //provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  811. //clusterIdRx := regexp.MustCompile("^kubernetes\\.io/cluster/([^/]+)")
  812. //klog.Infof("nodelist get here %s", time.Now())
  813. //nodeList := awsProvider.Clientset.GetAllNodes()
  814. //klog.Infof("nodelist done here %s", time.Now())
  815. /*for _, n := range nodeList {
  816. region := ""
  817. instanceId := ""
  818. providerId := n.Spec.ProviderID
  819. for matchNum, group := range provIdRx.FindStringSubmatch(providerId) {
  820. if matchNum == 1 {
  821. region = group
  822. } else if matchNum == 2 {
  823. instanceId = group
  824. }
  825. }
  826. if len(instanceId) == 0 {
  827. klog.V(2).Infof("Unable to decode Node.ProviderID \"%s\", skipping it", providerId)
  828. continue
  829. }
  830. c := &aws.Config{
  831. Region: aws.String(region),
  832. }
  833. s := session.Must(session.NewSession(c))
  834. ec2Svc := ec2.New(s)
  835. di, diErr := ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{
  836. InstanceIds: []*string{
  837. aws.String(instanceId),
  838. },
  839. })
  840. if diErr != nil {
  841. klog.Infof("Error describing instances: %s", diErr)
  842. continue
  843. }
  844. if len(di.Reservations) != 1 {
  845. klog.V(2).Infof("Expected 1 Reservation back from DescribeInstances(%s), received %d", instanceId, len(di.Reservations))
  846. continue
  847. }
  848. res := di.Reservations[0]
  849. if len(res.Instances) != 1 {
  850. klog.V(2).Infof("Expected 1 Instance back from DescribeInstances(%s), received %d", instanceId, len(res.Instances))
  851. continue
  852. }
  853. inst := res.Instances[0]
  854. for _, tag := range inst.Tags {
  855. tagKey := *tag.Key
  856. for matchNum, group := range clusterIdRx.FindStringSubmatch(tagKey) {
  857. if matchNum != 1 {
  858. continue
  859. }
  860. return makeStructure(group)
  861. }
  862. }
  863. }*/
  864. klog.V(2).Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", ClusterIdEnvVar)
  865. return makeStructure(defaultClusterName)
  866. }
  867. // AddServiceKey adds an AWS service key, useful for pulling down out-of-cluster costs. Optional-- the container this runs in can be directly authorized.
  868. func (*AWS) AddServiceKey(formValues url.Values) error {
  869. keyID := formValues.Get("access_key_ID")
  870. key := formValues.Get("secret_access_key")
  871. m := make(map[string]string)
  872. m["access_key_ID"] = keyID
  873. m["secret_access_key"] = key
  874. result, err := json.Marshal(m)
  875. if err != nil {
  876. return err
  877. }
  878. return ioutil.WriteFile("/var/configs/key.json", result, 0644)
  879. }
  880. func (aws *AWS) configureAWSAuth() error {
  881. accessKeyID := aws.ServiceKeyName
  882. accessKeySecret := aws.ServiceKeySecret
  883. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  884. err := os.Setenv(awsAccessKeyIDEnvVar, accessKeyID)
  885. if err != nil {
  886. return err
  887. }
  888. err = os.Setenv(awsAccessKeySecretEnvVar, accessKeySecret)
  889. if err != nil {
  890. return err
  891. }
  892. }
  893. return nil
  894. }
  895. func getClusterConfig(ccFile string) (map[string]string, error) {
  896. clusterConfig, err := os.Open(ccFile)
  897. if err != nil {
  898. return nil, err
  899. }
  900. defer clusterConfig.Close()
  901. b, err := ioutil.ReadAll(clusterConfig)
  902. if err != nil {
  903. return nil, err
  904. }
  905. var clusterConf map[string]string
  906. err = json.Unmarshal([]byte(b), &clusterConf)
  907. if err != nil {
  908. return nil, err
  909. }
  910. return clusterConf, nil
  911. }
  912. // 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.
  913. func (a *AWS) GetDisks() ([]byte, error) {
  914. err := a.configureAWSAuth()
  915. if err != nil {
  916. return nil, err
  917. }
  918. clusterConfig, err := getClusterConfig("/var/configs/cluster.json")
  919. if err != nil {
  920. return nil, err
  921. }
  922. region := aws.String(clusterConfig["region"])
  923. c := &aws.Config{
  924. Region: region,
  925. }
  926. s := session.Must(session.NewSession(c))
  927. ec2Svc := ec2.New(s)
  928. input := &ec2.DescribeVolumesInput{}
  929. volumeResult, err := ec2Svc.DescribeVolumes(input)
  930. if err != nil {
  931. if aerr, ok := err.(awserr.Error); ok {
  932. switch aerr.Code() {
  933. default:
  934. return nil, aerr
  935. }
  936. } else {
  937. return nil, err
  938. }
  939. }
  940. return json.Marshal(volumeResult)
  941. }
  942. // ConvertToGlueColumnFormat takes a string and runs through various regex
  943. // and string replacement statements to convert it to a format compatible
  944. // with AWS Glue and Athena column names.
  945. // Following guidance from AWS provided here ('Column Names' section):
  946. // https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/run-athena-sql.html
  947. // It returns a string containing the column name in proper column name format and length.
  948. func ConvertToGlueColumnFormat(column_name string) string {
  949. klog.V(5).Infof("Converting string \"%s\" to proper AWS Glue column name.", column_name)
  950. // An underscore is added in front of uppercase letters
  951. capital_underscore := regexp.MustCompile(`[A-Z]`)
  952. final := capital_underscore.ReplaceAllString(column_name, `_$0`)
  953. // Any non-alphanumeric characters are replaced with an underscore
  954. no_space_punc := regexp.MustCompile(`[\s]{1,}|[^A-Za-z0-9]`)
  955. final = no_space_punc.ReplaceAllString(final, "_")
  956. // Duplicate underscores are removed
  957. no_dup_underscore := regexp.MustCompile(`_{2,}`)
  958. final = no_dup_underscore.ReplaceAllString(final, "_")
  959. // Any leading and trailing underscores are removed
  960. no_front_end_underscore := regexp.MustCompile(`(^\_|\_$)`)
  961. final = no_front_end_underscore.ReplaceAllString(final, "")
  962. // Uppercase to lowercase
  963. final = strings.ToLower(final)
  964. // Longer column name than expected - remove _ left to right
  965. allowed_col_len := 128
  966. undersc_to_remove := len(final) - allowed_col_len
  967. if undersc_to_remove > 0 {
  968. final = strings.Replace(final, "_", "", undersc_to_remove)
  969. }
  970. // If removing all of the underscores still didn't
  971. // make the column name < 128 characters, trim it!
  972. if len(final) > allowed_col_len {
  973. final = final[:allowed_col_len]
  974. }
  975. klog.V(5).Infof("Column name being returned: \"%s\". Length: \"%d\".", final, len(final))
  976. return final
  977. }
  978. func generateAWSGroupBy(lastIdx int) string {
  979. sequence := []string{}
  980. for i := 1; i < lastIdx+1; i++ {
  981. sequence = append(sequence, strconv.Itoa(i))
  982. }
  983. return strings.Join(sequence, ",")
  984. }
  985. func (a *AWS) QueryAthenaBillingData(query string) (*athena.GetQueryResultsOutput, error) {
  986. customPricing, err := a.GetConfig()
  987. if err != nil {
  988. return nil, err
  989. }
  990. if customPricing.ServiceKeyName != "" {
  991. err = os.Setenv(awsAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  992. if err != nil {
  993. return nil, err
  994. }
  995. err = os.Setenv(awsAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  996. if err != nil {
  997. return nil, err
  998. }
  999. }
  1000. region := aws.String(customPricing.AthenaRegion)
  1001. resultsBucket := customPricing.AthenaBucketName
  1002. database := customPricing.AthenaDatabase
  1003. c := &aws.Config{
  1004. Region: region,
  1005. }
  1006. s := session.Must(session.NewSession(c))
  1007. svc := athena.New(s)
  1008. var e athena.StartQueryExecutionInput
  1009. var r athena.ResultConfiguration
  1010. r.SetOutputLocation(resultsBucket)
  1011. e.SetResultConfiguration(&r)
  1012. e.SetQueryString(query)
  1013. var q athena.QueryExecutionContext
  1014. q.SetDatabase(database)
  1015. e.SetQueryExecutionContext(&q)
  1016. res, err := svc.StartQueryExecution(&e)
  1017. if err != nil {
  1018. return nil, err
  1019. }
  1020. klog.V(2).Infof("StartQueryExecution result:")
  1021. klog.V(2).Infof(res.GoString())
  1022. var qri athena.GetQueryExecutionInput
  1023. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1024. var qrop *athena.GetQueryExecutionOutput
  1025. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1026. for {
  1027. qrop, err = svc.GetQueryExecution(&qri)
  1028. if err != nil {
  1029. return nil, err
  1030. }
  1031. if *qrop.QueryExecution.Status.State != "RUNNING" {
  1032. break
  1033. }
  1034. time.Sleep(duration)
  1035. }
  1036. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1037. var ip athena.GetQueryResultsInput
  1038. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1039. return svc.GetQueryResults(&ip)
  1040. } else {
  1041. return nil, fmt.Errorf("No results available for %s", query)
  1042. }
  1043. }
  1044. type RIData struct {
  1045. ResourceID string
  1046. EffectiveCost float64
  1047. ReservationARN string
  1048. MostRecentDate string
  1049. }
  1050. func (a *AWS) GetReservationDataFromAthena() error {
  1051. cfg, err := a.GetConfig()
  1052. if err != nil {
  1053. return err
  1054. }
  1055. if cfg.AthenaBucketName == "" {
  1056. return fmt.Errorf("No Athena Bucket configured")
  1057. }
  1058. if a.RIPricingByInstanceID == nil {
  1059. a.RIPricingByInstanceID = make(map[string]*RIData)
  1060. }
  1061. tNow := time.Now()
  1062. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1063. start := tOneDayAgo.Format("2006-01-02")
  1064. end := tNow.Format("2006-01-02")
  1065. q := `SELECT
  1066. line_item_usage_start_date,
  1067. reservation_reservation_a_r_n,
  1068. line_item_resource_id,
  1069. reservation_effective_cost
  1070. FROM athena_test as cost_data
  1071. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1072. AND reservation_reservation_a_r_n <> '' ORDER BY
  1073. line_item_usage_start_date DESC`
  1074. query := fmt.Sprintf(q, start, end)
  1075. op, err := a.QueryAthenaBillingData(query)
  1076. if err != nil {
  1077. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  1078. }
  1079. klog.Infof("Fetching RI data...")
  1080. if len(op.ResultSet.Rows) > 1 {
  1081. a.RIDataLock.Lock()
  1082. mostRecentDate := ""
  1083. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  1084. d := *r.Data[0].VarCharValue
  1085. if mostRecentDate == "" {
  1086. mostRecentDate = d
  1087. } else if mostRecentDate != d { // Get all most recent assignments
  1088. break
  1089. }
  1090. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1091. if err != nil {
  1092. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1093. }
  1094. r := &RIData{
  1095. ResourceID: *r.Data[2].VarCharValue,
  1096. EffectiveCost: cost,
  1097. ReservationARN: *r.Data[1].VarCharValue,
  1098. MostRecentDate: d,
  1099. }
  1100. a.RIPricingByInstanceID[r.ResourceID] = r
  1101. }
  1102. klog.V(1).Infof("Found %d reserved instances", len(a.RIPricingByInstanceID))
  1103. for k, r := range a.RIPricingByInstanceID {
  1104. klog.V(1).Infof("Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1105. }
  1106. a.RIDataLock.Unlock()
  1107. } else {
  1108. klog.Infof("No reserved instance data found")
  1109. }
  1110. return nil
  1111. }
  1112. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  1113. // "start" and "end" are dates of the format YYYY-MM-DD
  1114. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  1115. func (a *AWS) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  1116. customPricing, err := a.GetConfig()
  1117. if err != nil {
  1118. return nil, err
  1119. }
  1120. formattedAggregators := []string{}
  1121. for _, agg := range aggregators {
  1122. aggregator_column_name := "resource_tags_user_" + agg
  1123. aggregator_column_name = ConvertToGlueColumnFormat(aggregator_column_name)
  1124. formattedAggregators = append(formattedAggregators, aggregator_column_name)
  1125. }
  1126. aggregatorNames := strings.Join(formattedAggregators, ",")
  1127. filter_column_name := "resource_tags_user_" + filterType
  1128. filter_column_name = ConvertToGlueColumnFormat(filter_column_name)
  1129. var query string
  1130. var lastIdx int
  1131. if filterType != "kubernetes_" { // This gets appended upstream and is equivalent to no filter.
  1132. lastIdx = len(formattedAggregators) + 3
  1133. groupby := generateAWSGroupBy(lastIdx)
  1134. query = fmt.Sprintf(`SELECT
  1135. CAST(line_item_usage_start_date AS DATE) as start_date,
  1136. %s,
  1137. line_item_product_code,
  1138. %s,
  1139. SUM(line_item_blended_cost) as blended_cost
  1140. FROM %s as cost_data
  1141. WHERE (%s='%s') AND line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1142. GROUP BY %s`, aggregatorNames, filter_column_name, customPricing.AthenaTable, filter_column_name, filterValue, start, end, groupby)
  1143. } else {
  1144. lastIdx = len(formattedAggregators) + 2
  1145. groupby := generateAWSGroupBy(lastIdx)
  1146. query = fmt.Sprintf(`SELECT
  1147. CAST(line_item_usage_start_date AS DATE) as start_date,
  1148. %s,
  1149. line_item_product_code,
  1150. SUM(line_item_blended_cost) as blended_cost
  1151. FROM %s as cost_data
  1152. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1153. GROUP BY %s`, aggregatorNames, customPricing.AthenaTable, start, end, groupby)
  1154. }
  1155. klog.V(3).Infof("Running Query: %s", query)
  1156. if customPricing.ServiceKeyName != "" {
  1157. err = os.Setenv(awsAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1158. if err != nil {
  1159. return nil, err
  1160. }
  1161. err = os.Setenv(awsAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1162. if err != nil {
  1163. return nil, err
  1164. }
  1165. }
  1166. region := aws.String(customPricing.AthenaRegion)
  1167. resultsBucket := customPricing.AthenaBucketName
  1168. database := customPricing.AthenaDatabase
  1169. c := &aws.Config{
  1170. Region: region,
  1171. }
  1172. s := session.Must(session.NewSession(c))
  1173. svc := athena.New(s)
  1174. var e athena.StartQueryExecutionInput
  1175. var r athena.ResultConfiguration
  1176. r.SetOutputLocation(resultsBucket)
  1177. e.SetResultConfiguration(&r)
  1178. e.SetQueryString(query)
  1179. var q athena.QueryExecutionContext
  1180. q.SetDatabase(database)
  1181. e.SetQueryExecutionContext(&q)
  1182. res, err := svc.StartQueryExecution(&e)
  1183. if err != nil {
  1184. return nil, err
  1185. }
  1186. klog.V(2).Infof("StartQueryExecution result:")
  1187. klog.V(2).Infof(res.GoString())
  1188. var qri athena.GetQueryExecutionInput
  1189. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1190. var qrop *athena.GetQueryExecutionOutput
  1191. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1192. for {
  1193. qrop, err = svc.GetQueryExecution(&qri)
  1194. if err != nil {
  1195. return nil, err
  1196. }
  1197. if *qrop.QueryExecution.Status.State != "RUNNING" {
  1198. break
  1199. }
  1200. time.Sleep(duration)
  1201. }
  1202. var oocAllocs []*OutOfClusterAllocation
  1203. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1204. var ip athena.GetQueryResultsInput
  1205. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1206. op, err := svc.GetQueryResults(&ip)
  1207. if err != nil {
  1208. return nil, err
  1209. }
  1210. if len(op.ResultSet.Rows) > 1 {
  1211. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  1212. cost, err := strconv.ParseFloat(*r.Data[lastIdx].VarCharValue, 64)
  1213. if err != nil {
  1214. return nil, err
  1215. }
  1216. environment := ""
  1217. for _, d := range r.Data[1 : len(formattedAggregators)+1] {
  1218. if *d.VarCharValue != "" {
  1219. environment = *d.VarCharValue // just set to the first nonempty match
  1220. }
  1221. break
  1222. }
  1223. ooc := &OutOfClusterAllocation{
  1224. Aggregator: strings.Join(aggregators, ","),
  1225. Environment: environment,
  1226. Service: *r.Data[len(formattedAggregators)+1].VarCharValue,
  1227. Cost: cost,
  1228. }
  1229. oocAllocs = append(oocAllocs, ooc)
  1230. }
  1231. } else {
  1232. klog.V(1).Infof("No results available for %s at database %s between %s and %s", strings.Join(formattedAggregators, ","), customPricing.AthenaTable, start, end)
  1233. }
  1234. }
  1235. if customPricing.BillingDataDataset != "" && !crossCluster { // There is GCP data, meaning someone has tried to configure a GCP out-of-cluster allocation.
  1236. gcp, err := NewCrossClusterProvider("gcp", "aws.json", a.Clientset)
  1237. if err != nil {
  1238. klog.Infof("Could not instantiate cross-cluster provider %s", err.Error())
  1239. }
  1240. gcpOOC, err := gcp.ExternalAllocations(start, end, aggregators, filterType, filterValue, true)
  1241. if err != nil {
  1242. klog.Infof("Could not fetch cross-cluster costs %s", err.Error())
  1243. }
  1244. oocAllocs = append(oocAllocs, gcpOOC...)
  1245. }
  1246. return oocAllocs, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  1247. }
  1248. // QuerySQL can query a properly configured Athena database.
  1249. // Used to fetch billing data.
  1250. // Requires a json config in /var/configs with key region, output, and database.
  1251. func (a *AWS) QuerySQL(query string) ([]byte, error) {
  1252. customPricing, err := a.GetConfig()
  1253. if err != nil {
  1254. return nil, err
  1255. }
  1256. if customPricing.ServiceKeyName != "" {
  1257. err = os.Setenv(awsAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1258. if err != nil {
  1259. return nil, err
  1260. }
  1261. err = os.Setenv(awsAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1262. if err != nil {
  1263. return nil, err
  1264. }
  1265. }
  1266. athenaConfigs, err := os.Open("/var/configs/athena.json")
  1267. if err != nil {
  1268. return nil, err
  1269. }
  1270. defer athenaConfigs.Close()
  1271. b, err := ioutil.ReadAll(athenaConfigs)
  1272. if err != nil {
  1273. return nil, err
  1274. }
  1275. var athenaConf map[string]string
  1276. json.Unmarshal([]byte(b), &athenaConf)
  1277. region := aws.String(customPricing.AthenaRegion)
  1278. resultsBucket := customPricing.AthenaBucketName
  1279. database := customPricing.AthenaDatabase
  1280. c := &aws.Config{
  1281. Region: region,
  1282. }
  1283. s := session.Must(session.NewSession(c))
  1284. svc := athena.New(s)
  1285. var e athena.StartQueryExecutionInput
  1286. var r athena.ResultConfiguration
  1287. r.SetOutputLocation(resultsBucket)
  1288. e.SetResultConfiguration(&r)
  1289. e.SetQueryString(query)
  1290. var q athena.QueryExecutionContext
  1291. q.SetDatabase(database)
  1292. e.SetQueryExecutionContext(&q)
  1293. res, err := svc.StartQueryExecution(&e)
  1294. if err != nil {
  1295. return nil, err
  1296. }
  1297. klog.V(2).Infof("StartQueryExecution result:")
  1298. klog.V(2).Infof(res.GoString())
  1299. var qri athena.GetQueryExecutionInput
  1300. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1301. var qrop *athena.GetQueryExecutionOutput
  1302. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1303. for {
  1304. qrop, err = svc.GetQueryExecution(&qri)
  1305. if err != nil {
  1306. return nil, err
  1307. }
  1308. if *qrop.QueryExecution.Status.State != "RUNNING" {
  1309. break
  1310. }
  1311. time.Sleep(duration)
  1312. }
  1313. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1314. var ip athena.GetQueryResultsInput
  1315. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1316. op, err := svc.GetQueryResults(&ip)
  1317. if err != nil {
  1318. return nil, err
  1319. }
  1320. b, err := json.Marshal(op.ResultSet)
  1321. if err != nil {
  1322. return nil, err
  1323. }
  1324. return b, nil
  1325. }
  1326. return nil, fmt.Errorf("Error getting query results : %s", *qrop.QueryExecution.Status.State)
  1327. }
  1328. type spotInfo struct {
  1329. Timestamp string `csv:"Timestamp"`
  1330. UsageType string `csv:"UsageType"`
  1331. Operation string `csv:"Operation"`
  1332. InstanceID string `csv:"InstanceID"`
  1333. MyBidID string `csv:"MyBidID"`
  1334. MyMaxPrice string `csv:"MyMaxPrice"`
  1335. MarketPrice string `csv:"MarketPrice"`
  1336. Charge string `csv:"Charge"`
  1337. Version string `csv:"Version"`
  1338. }
  1339. type fnames []*string
  1340. func (f fnames) Len() int {
  1341. return len(f)
  1342. }
  1343. func (f fnames) Swap(i, j int) {
  1344. f[i], f[j] = f[j], f[i]
  1345. }
  1346. func (f fnames) Less(i, j int) bool {
  1347. key1 := strings.Split(*f[i], ".")
  1348. key2 := strings.Split(*f[j], ".")
  1349. t1, err := time.Parse("2006-01-02-15", key1[1])
  1350. if err != nil {
  1351. klog.V(1).Info("Unable to parse timestamp" + key1[1])
  1352. return false
  1353. }
  1354. t2, err := time.Parse("2006-01-02-15", key2[1])
  1355. if err != nil {
  1356. klog.V(1).Info("Unable to parse timestamp" + key2[1])
  1357. return false
  1358. }
  1359. return t1.Before(t2)
  1360. }
  1361. func parseSpotData(bucket string, prefix string, projectID string, region string, accessKeyID string, accessKeySecret string) (map[string]*spotInfo, error) {
  1362. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1363. err := os.Setenv(awsAccessKeyIDEnvVar, accessKeyID)
  1364. if err != nil {
  1365. return nil, err
  1366. }
  1367. err = os.Setenv(awsAccessKeySecretEnvVar, accessKeySecret)
  1368. if err != nil {
  1369. return nil, err
  1370. }
  1371. }
  1372. s3Prefix := projectID
  1373. if len(prefix) != 0 {
  1374. s3Prefix = prefix + "/" + s3Prefix
  1375. }
  1376. c := aws.NewConfig().WithRegion(region)
  1377. s := session.Must(session.NewSession(c))
  1378. s3Svc := s3.New(s)
  1379. downloader := s3manager.NewDownloaderWithClient(s3Svc)
  1380. tNow := time.Now()
  1381. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1382. ls := &s3.ListObjectsInput{
  1383. Bucket: aws.String(bucket),
  1384. Prefix: aws.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1385. }
  1386. ls2 := &s3.ListObjectsInput{
  1387. Bucket: aws.String(bucket),
  1388. Prefix: aws.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1389. }
  1390. lso, err := s3Svc.ListObjects(ls)
  1391. if err != nil {
  1392. return nil, err
  1393. }
  1394. lsoLen := len(lso.Contents)
  1395. klog.V(2).Infof("Found %d spot data files from yesterday", lsoLen)
  1396. if lsoLen == 0 {
  1397. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1398. }
  1399. lso2, err := s3Svc.ListObjects(ls2)
  1400. if err != nil {
  1401. return nil, err
  1402. }
  1403. lso2Len := len(lso2.Contents)
  1404. klog.V(2).Infof("Found %d spot data files from today", lso2Len)
  1405. if lso2Len == 0 {
  1406. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1407. }
  1408. var keys []*string
  1409. for _, obj := range lso.Contents {
  1410. keys = append(keys, obj.Key)
  1411. }
  1412. for _, obj := range lso2.Contents {
  1413. keys = append(keys, obj.Key)
  1414. }
  1415. versionRx := regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  1416. header, err := csvutil.Header(spotInfo{}, "csv")
  1417. if err != nil {
  1418. return nil, err
  1419. }
  1420. fieldsPerRecord := len(header)
  1421. spots := make(map[string]*spotInfo)
  1422. for _, key := range keys {
  1423. getObj := &s3.GetObjectInput{
  1424. Bucket: aws.String(bucket),
  1425. Key: key,
  1426. }
  1427. buf := aws.NewWriteAtBuffer([]byte{})
  1428. _, err := downloader.Download(buf, getObj)
  1429. if err != nil {
  1430. return nil, err
  1431. }
  1432. r := bytes.NewReader(buf.Bytes())
  1433. gr, err := gzip.NewReader(r)
  1434. if err != nil {
  1435. return nil, err
  1436. }
  1437. csvReader := csv.NewReader(gr)
  1438. csvReader.Comma = '\t'
  1439. csvReader.FieldsPerRecord = fieldsPerRecord
  1440. dec, err := csvutil.NewDecoder(csvReader, header...)
  1441. if err != nil {
  1442. return nil, err
  1443. }
  1444. var foundVersion string
  1445. for {
  1446. spot := spotInfo{}
  1447. err := dec.Decode(&spot)
  1448. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1449. if err == io.EOF {
  1450. break
  1451. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1452. rec := dec.Record()
  1453. // the first two "Record()" will be the comment lines
  1454. // and they show up as len() == 1
  1455. // the first of which is "#Version"
  1456. // the second of which is "#Fields: "
  1457. if len(rec) != 1 {
  1458. klog.V(2).Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1459. continue
  1460. }
  1461. if len(foundVersion) == 0 {
  1462. spotFeedVersion := rec[0]
  1463. klog.V(4).Infof("Spot feed version is \"%s\"", spotFeedVersion)
  1464. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  1465. if matches != nil {
  1466. foundVersion = matches[1]
  1467. if foundVersion != supportedSpotFeedVersion {
  1468. klog.V(2).Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  1469. break
  1470. }
  1471. }
  1472. continue
  1473. } else if strings.Index(rec[0], "#") == 0 {
  1474. continue
  1475. } else {
  1476. klog.V(3).Infof("skipping non-TSV line: %s", rec)
  1477. continue
  1478. }
  1479. } else if err != nil {
  1480. klog.V(2).Infof("Error during spot info decode: %+v", err)
  1481. continue
  1482. }
  1483. klog.V(4).Infof("Found spot info %+v", spot)
  1484. spots[spot.InstanceID] = &spot
  1485. }
  1486. gr.Close()
  1487. }
  1488. return spots, nil
  1489. }
  1490. func (a *AWS) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1491. /*
  1492. numReserved := len(a.ReservedInstances)
  1493. // Early return if no reserved instance data loaded
  1494. if numReserved == 0 {
  1495. klog.V(4).Infof("[Reserved] No Reserved Instances")
  1496. return
  1497. }
  1498. cfg, err := a.GetConfig()
  1499. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1500. if err != nil {
  1501. klog.V(3).Infof("Could not parse default cpu price")
  1502. defaultCPU = 0.031611
  1503. }
  1504. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1505. if err != nil {
  1506. klog.V(3).Infof("Could not parse default ram price")
  1507. defaultRAM = 0.004237
  1508. }
  1509. cpuToRAMRatio := defaultCPU / defaultRAM
  1510. now := time.Now()
  1511. instances := make(map[string][]*AWSReservedInstance)
  1512. for _, r := range a.ReservedInstances {
  1513. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1514. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  1515. continue
  1516. }
  1517. _, ok := instances[r.Region]
  1518. if !ok {
  1519. instances[r.Region] = []*AWSReservedInstance{r}
  1520. } else {
  1521. instances[r.Region] = append(instances[r.Region], r)
  1522. }
  1523. }
  1524. awsNodes := make(map[string]*v1.Node)
  1525. currentNodes := a.Clientset.GetAllNodes()
  1526. // Create a node name -> node map
  1527. for _, awsNode := range currentNodes {
  1528. awsNodes[awsNode.GetName()] = awsNode
  1529. }
  1530. // go through all provider nodes using k8s nodes for region
  1531. for nodeName, node := range nodes {
  1532. // Reset reserved allocation to prevent double allocation
  1533. node.Reserved = nil
  1534. kNode, ok := awsNodes[nodeName]
  1535. if !ok {
  1536. klog.V(1).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  1537. continue
  1538. }
  1539. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  1540. if !ok {
  1541. klog.V(1).Infof("[Reserved] Could not find node region")
  1542. continue
  1543. }
  1544. reservedInstances, ok := instances[nodeRegion]
  1545. if !ok {
  1546. klog.V(1).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  1547. continue
  1548. }
  1549. // Determine the InstanceType of the node
  1550. instanceType, ok := kNode.Labels["beta.kubernetes.io/instance-type"]
  1551. if !ok {
  1552. continue
  1553. }
  1554. ramBytes, err := strconv.ParseFloat(node.RAMBytes, 64)
  1555. if err != nil {
  1556. continue
  1557. }
  1558. ramGB := ramBytes / 1024 / 1024 / 1024
  1559. cpu, err := strconv.ParseFloat(node.VCPU, 64)
  1560. if err != nil {
  1561. continue
  1562. }
  1563. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1564. node.Reserved = &ReservedInstanceData{
  1565. ReservedCPU: 0,
  1566. ReservedRAM: 0,
  1567. }
  1568. for i, reservedInstance := range reservedInstances {
  1569. if reservedInstance.InstanceType == instanceType {
  1570. // Use < 0 to mark as ALL
  1571. node.Reserved.ReservedCPU = -1
  1572. node.Reserved.ReservedRAM = -1
  1573. // Set Costs based on CPU/RAM ratios
  1574. ramPrice := reservedInstance.PricePerHour / ramMultiple
  1575. node.Reserved.CPUCost = ramPrice * cpuToRAMRatio
  1576. node.Reserved.RAMCost = ramPrice
  1577. // Remove the reserve from the temporary slice to prevent
  1578. // being reallocated
  1579. instances[nodeRegion] = append(reservedInstances[:i], reservedInstances[i+1:]...)
  1580. break
  1581. }
  1582. }
  1583. }*/
  1584. }
  1585. type AWSReservedInstance struct {
  1586. Zone string
  1587. Region string
  1588. InstanceType string
  1589. InstanceCount int64
  1590. InstanceTenacy string
  1591. StartDate time.Time
  1592. EndDate time.Time
  1593. PricePerHour float64
  1594. }
  1595. func (ari *AWSReservedInstance) String() string {
  1596. 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)
  1597. }
  1598. func isReservedInstanceHourlyPrice(rc *ec2.RecurringCharge) bool {
  1599. return rc != nil && rc.Frequency != nil && *rc.Frequency == "Hourly"
  1600. }
  1601. func getReservedInstancePrice(ri *ec2.ReservedInstances) (float64, error) {
  1602. var pricePerHour float64
  1603. if len(ri.RecurringCharges) > 0 {
  1604. for _, rc := range ri.RecurringCharges {
  1605. if isReservedInstanceHourlyPrice(rc) {
  1606. pricePerHour = *rc.Amount
  1607. break
  1608. }
  1609. }
  1610. }
  1611. // If we're still unable to resolve hourly price, try fixed -> hourly
  1612. if pricePerHour == 0 {
  1613. if ri.Duration != nil && ri.FixedPrice != nil {
  1614. var durHours float64
  1615. durSeconds := float64(*ri.Duration)
  1616. fixedPrice := float64(*ri.FixedPrice)
  1617. if durSeconds != 0 && fixedPrice != 0 {
  1618. durHours = durSeconds / 60 / 60
  1619. pricePerHour = fixedPrice / durHours
  1620. }
  1621. }
  1622. }
  1623. if pricePerHour == 0 {
  1624. return 0, fmt.Errorf("Failed to resolve an hourly price from FixedPrice or Recurring Costs")
  1625. }
  1626. return pricePerHour, nil
  1627. }
  1628. func getRegionReservedInstances(region string) ([]*AWSReservedInstance, error) {
  1629. c := &aws.Config{
  1630. Region: aws.String(region),
  1631. }
  1632. s := session.Must(session.NewSession(c))
  1633. svc := ec2.New(s)
  1634. response, err := svc.DescribeReservedInstances(&ec2.DescribeReservedInstancesInput{})
  1635. if err != nil {
  1636. return nil, err
  1637. }
  1638. var reservedInstances []*AWSReservedInstance
  1639. for _, ri := range response.ReservedInstances {
  1640. var zone string
  1641. if ri.AvailabilityZone != nil {
  1642. zone = *ri.AvailabilityZone
  1643. }
  1644. pricePerHour, err := getReservedInstancePrice(ri)
  1645. if err != nil {
  1646. klog.V(1).Infof("Error Resolving Price: %s", err.Error())
  1647. continue
  1648. }
  1649. reservedInstances = append(reservedInstances, &AWSReservedInstance{
  1650. Zone: zone,
  1651. Region: region,
  1652. InstanceType: *ri.InstanceType,
  1653. InstanceCount: *ri.InstanceCount,
  1654. InstanceTenacy: *ri.InstanceTenancy,
  1655. StartDate: *ri.Start,
  1656. EndDate: *ri.End,
  1657. PricePerHour: pricePerHour,
  1658. })
  1659. }
  1660. return reservedInstances, nil
  1661. }
  1662. func (a *AWS) getReservedInstances() ([]*AWSReservedInstance, error) {
  1663. err := a.configureAWSAuth()
  1664. if err != nil {
  1665. return nil, fmt.Errorf("Error Configuring aws auth: %s", err.Error())
  1666. }
  1667. var reservedInstances []*AWSReservedInstance
  1668. nodes := a.Clientset.GetAllNodes()
  1669. regionsSeen := make(map[string]bool)
  1670. for _, node := range nodes {
  1671. region, ok := node.Labels[v1.LabelZoneRegion]
  1672. if !ok {
  1673. continue
  1674. }
  1675. if regionsSeen[region] {
  1676. continue
  1677. }
  1678. ris, err := getRegionReservedInstances(region)
  1679. if err != nil {
  1680. klog.V(3).Infof("Error getting reserved instances: %s", err.Error())
  1681. continue
  1682. }
  1683. regionsSeen[region] = true
  1684. reservedInstances = append(reservedInstances, ris...)
  1685. }
  1686. return reservedInstances, nil
  1687. }