awsprovider.go 70 KB

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