awsprovider.go 70 KB

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