awsprovider.go 71 KB

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