awsprovider.go 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276
  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 supportedSpotFeedVersion = "1"
  36. const SpotInfoUpdateType = "spotinfo"
  37. const AthenaInfoUpdateType = "athenainfo"
  38. const PreemptibleType = "preemptible"
  39. const APIPricingSource = "Public API"
  40. const SpotPricingSource = "Spot Data Feed"
  41. const ReservedInstancePricingSource = "Savings Plan, Reservied Instance, and Out-Of-Cluster"
  42. func (aws *AWS) PricingSourceStatus() map[string]*PricingSource {
  43. sources := make(map[string]*PricingSource)
  44. sps := &PricingSource{
  45. Name: SpotPricingSource,
  46. }
  47. sps.Error = aws.SpotPricingStatus
  48. if sps.Error != "" {
  49. sps.Available = false
  50. } else if len(aws.SpotPricingByInstanceID) > 0 {
  51. sps.Available = true
  52. } else {
  53. sps.Error = "No spot instances detected"
  54. }
  55. sources[SpotPricingSource] = sps
  56. rps := &PricingSource{
  57. Name: ReservedInstancePricingSource,
  58. }
  59. rps.Error = aws.RIPricingStatus
  60. if rps.Error != "" {
  61. rps.Available = false
  62. } else {
  63. rps.Available = true
  64. }
  65. sources[ReservedInstancePricingSource] = rps
  66. return sources
  67. }
  68. // How often spot data is refreshed
  69. const SpotRefreshDuration = 15 * time.Minute
  70. const defaultConfigPath = "/var/configs/"
  71. var awsRegions = []string{
  72. "us-east-2",
  73. "us-east-1",
  74. "us-west-1",
  75. "us-west-2",
  76. "ap-east-1",
  77. "ap-south-1",
  78. "ap-northeast-3",
  79. "ap-northeast-2",
  80. "ap-southeast-1",
  81. "ap-southeast-2",
  82. "ap-northeast-1",
  83. "ca-central-1",
  84. "cn-north-1",
  85. "cn-northwest-1",
  86. "eu-central-1",
  87. "eu-west-1",
  88. "eu-west-2",
  89. "eu-west-3",
  90. "eu-north-1",
  91. "me-south-1",
  92. "sa-east-1",
  93. "us-gov-east-1",
  94. "us-gov-west-1",
  95. }
  96. // AWS represents an Amazon Provider
  97. type AWS struct {
  98. Pricing map[string]*AWSProductTerms
  99. SpotPricingByInstanceID map[string]*spotInfo
  100. SpotPricingUpdatedAt *time.Time
  101. SpotRefreshRunning bool
  102. SpotPricingLock sync.RWMutex
  103. SpotPricingStatus string
  104. RIPricingByInstanceID map[string]*RIData
  105. RIPricingStatus string
  106. RIDataRunning bool
  107. RIDataLock sync.RWMutex
  108. SavingsPlanDataByInstanceID map[string]*SavingsPlanData
  109. SavingsPlanDataRunning bool
  110. SavingsPlanDataLock sync.RWMutex
  111. ValidPricingKeys map[string]bool
  112. Clientset clustercache.ClusterCache
  113. BaseCPUPrice string
  114. BaseRAMPrice string
  115. BaseGPUPrice string
  116. BaseSpotCPUPrice string
  117. BaseSpotRAMPrice string
  118. BaseSpotGPUPrice string
  119. SpotLabelName string
  120. SpotLabelValue string
  121. SpotDataRegion string
  122. SpotDataBucket string
  123. SpotDataPrefix string
  124. ProjectID string
  125. DownloadPricingDataLock sync.RWMutex
  126. Config *ProviderConfig
  127. ServiceAccountChecks map[string]*ServiceAccountCheck
  128. clusterManagementPrice float64
  129. clusterProvisioner string
  130. *CustomProvider
  131. }
  132. type AWSAccessKey struct {
  133. AccessKeyID string `json:"aws_access_key_id"`
  134. SecretAccessKey string `json:"aws_secret_access_key"`
  135. }
  136. // AWSPricing maps a k8s node to an AWS Pricing "product"
  137. type AWSPricing struct {
  138. Products map[string]*AWSProduct `json:"products"`
  139. Terms AWSPricingTerms `json:"terms"`
  140. }
  141. // AWSProduct represents a purchased SKU
  142. type AWSProduct struct {
  143. Sku string `json:"sku"`
  144. Attributes AWSProductAttributes `json:"attributes"`
  145. }
  146. // AWSProductAttributes represents metadata about the product used to map to a node.
  147. type AWSProductAttributes struct {
  148. Location string `json:"location"`
  149. InstanceType string `json:"instanceType"`
  150. Memory string `json:"memory"`
  151. Storage string `json:"storage"`
  152. VCpu string `json:"vcpu"`
  153. UsageType string `json:"usagetype"`
  154. OperatingSystem string `json:"operatingSystem"`
  155. PreInstalledSw string `json:"preInstalledSw"`
  156. InstanceFamily string `json:"instanceFamily"`
  157. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  158. }
  159. // AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
  160. type AWSPricingTerms struct {
  161. OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
  162. Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
  163. }
  164. // AWSOfferTerm is a sku extension used to pay for the node.
  165. type AWSOfferTerm struct {
  166. Sku string `json:"sku"`
  167. PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
  168. }
  169. // AWSRateCode encodes data about the price of a product
  170. type AWSRateCode struct {
  171. Unit string `json:"unit"`
  172. PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
  173. }
  174. // AWSCurrencyCode is the localized currency. (TODO: support non-USD)
  175. type AWSCurrencyCode struct {
  176. USD string `json:"USD"`
  177. }
  178. // AWSProductTerms represents the full terms of the product
  179. type AWSProductTerms struct {
  180. Sku string `json:"sku"`
  181. OnDemand *AWSOfferTerm `json:"OnDemand"`
  182. Reserved *AWSOfferTerm `json:"Reserved"`
  183. Memory string `json:"memory"`
  184. Storage string `json:"storage"`
  185. VCpu string `json:"vcpu"`
  186. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  187. PV *PV `json:"pv"`
  188. }
  189. // ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
  190. const ClusterIdEnvVar = "AWS_CLUSTER_ID"
  191. // OnDemandRateCode is appended to an node sku
  192. const OnDemandRateCode = ".JRTCKXETXF"
  193. // ReservedRateCode is appended to a node sku
  194. const ReservedRateCode = ".38NPMPTW36"
  195. // HourlyRateCode is appended to a node sku
  196. const HourlyRateCode = ".6YS6EN2CT7"
  197. // volTypes are used to map between AWS UsageTypes and
  198. // EBS volume types, as they would appear in K8s storage class
  199. // name and the EC2 API.
  200. var volTypes = map[string]string{
  201. "EBS:VolumeUsage.gp2": "gp2",
  202. "EBS:VolumeUsage": "standard",
  203. "EBS:VolumeUsage.sc1": "sc1",
  204. "EBS:VolumeP-IOPS.piops": "io1",
  205. "EBS:VolumeUsage.st1": "st1",
  206. "EBS:VolumeUsage.piops": "io1",
  207. "gp2": "EBS:VolumeUsage.gp2",
  208. "standard": "EBS:VolumeUsage",
  209. "sc1": "EBS:VolumeUsage.sc1",
  210. "io1": "EBS:VolumeUsage.piops",
  211. "st1": "EBS:VolumeUsage.st1",
  212. }
  213. // locationToRegion maps AWS region names (As they come from Billing)
  214. // to actual region identifiers
  215. var locationToRegion = map[string]string{
  216. "US East (Ohio)": "us-east-2",
  217. "US East (N. Virginia)": "us-east-1",
  218. "US West (N. California)": "us-west-1",
  219. "US West (Oregon)": "us-west-2",
  220. "Asia Pacific (Hong Kong)": "ap-east-1",
  221. "Asia Pacific (Mumbai)": "ap-south-1",
  222. "Asia Pacific (Osaka-Local)": "ap-northeast-3",
  223. "Asia Pacific (Seoul)": "ap-northeast-2",
  224. "Asia Pacific (Singapore)": "ap-southeast-1",
  225. "Asia Pacific (Sydney)": "ap-southeast-2",
  226. "Asia Pacific (Tokyo)": "ap-northeast-1",
  227. "Canada (Central)": "ca-central-1",
  228. "China (Beijing)": "cn-north-1",
  229. "China (Ningxia)": "cn-northwest-1",
  230. "EU (Frankfurt)": "eu-central-1",
  231. "EU (Ireland)": "eu-west-1",
  232. "EU (London)": "eu-west-2",
  233. "EU (Paris)": "eu-west-3",
  234. "EU (Stockholm)": "eu-north-1",
  235. "South America (Sao Paulo)": "sa-east-1",
  236. "AWS GovCloud (US-East)": "us-gov-east-1",
  237. "AWS GovCloud (US)": "us-gov-west-1",
  238. }
  239. var regionToBillingRegionCode = map[string]string{
  240. "us-east-2": "USE2",
  241. "us-east-1": "",
  242. "us-west-1": "USW1",
  243. "us-west-2": "USW2",
  244. "ap-east-1": "APE1",
  245. "ap-south-1": "APS3",
  246. "ap-northeast-3": "APN3",
  247. "ap-northeast-2": "APN2",
  248. "ap-southeast-1": "APS1",
  249. "ap-southeast-2": "APS2",
  250. "ap-northeast-1": "APN1",
  251. "ca-central-1": "CAN1",
  252. "cn-north-1": "",
  253. "cn-northwest-1": "",
  254. "eu-central-1": "EUC1",
  255. "eu-west-1": "EU",
  256. "eu-west-2": "EUW2",
  257. "eu-west-3": "EUW3",
  258. "eu-north-1": "EUN1",
  259. "sa-east-1": "SAE1",
  260. "us-gov-east-1": "UGE1",
  261. "us-gov-west-1": "UGW1",
  262. }
  263. var loadedAWSSecret bool = false
  264. var awsSecret *AWSAccessKey = nil
  265. func (aws *AWS) GetLocalStorageQuery(window, offset string, rate bool, used bool) string {
  266. return ""
  267. }
  268. // KubeAttrConversion maps the k8s labels for region to an aws region
  269. func (aws *AWS) KubeAttrConversion(location, instanceType, operatingSystem string) string {
  270. operatingSystem = strings.ToLower(operatingSystem)
  271. region := locationToRegion[location]
  272. return region + "," + instanceType + "," + operatingSystem
  273. }
  274. type AwsSpotFeedInfo struct {
  275. BucketName string `json:"bucketName"`
  276. Prefix string `json:"prefix"`
  277. Region string `json:"region"`
  278. AccountID string `json:"projectID"`
  279. ServiceKeyName string `json:"serviceKeyName"`
  280. ServiceKeySecret string `json:"serviceKeySecret"`
  281. SpotLabel string `json:"spotLabel"`
  282. SpotLabelValue string `json:"spotLabelValue"`
  283. }
  284. type AwsAthenaInfo struct {
  285. AthenaBucketName string `json:"athenaBucketName"`
  286. AthenaRegion string `json:"athenaRegion"`
  287. AthenaDatabase string `json:"athenaDatabase"`
  288. AthenaTable string `json:"athenaTable"`
  289. ServiceKeyName string `json:"serviceKeyName"`
  290. ServiceKeySecret string `json:"serviceKeySecret"`
  291. AccountID string `json:"projectID"`
  292. MasterPayerARN string `json:"masterPayerARN"`
  293. }
  294. func (aws *AWS) GetManagementPlatform() (string, error) {
  295. nodes := aws.Clientset.GetAllNodes()
  296. if len(nodes) > 0 {
  297. n := nodes[0]
  298. version := n.Status.NodeInfo.KubeletVersion
  299. if strings.Contains(version, "eks") {
  300. return "eks", nil
  301. }
  302. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  303. return "kops", nil
  304. }
  305. }
  306. return "", nil
  307. }
  308. func (aws *AWS) GetConfig() (*CustomPricing, error) {
  309. c, err := aws.Config.GetCustomPricingData()
  310. if c.Discount == "" {
  311. c.Discount = "0%"
  312. }
  313. if c.NegotiatedDiscount == "" {
  314. c.NegotiatedDiscount = "0%"
  315. }
  316. if err != nil {
  317. return nil, err
  318. }
  319. return c, nil
  320. }
  321. func (aws *AWS) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  322. return aws.Config.UpdateFromMap(a)
  323. }
  324. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  325. return aws.Config.Update(func(c *CustomPricing) error {
  326. if updateType == SpotInfoUpdateType {
  327. a := AwsSpotFeedInfo{}
  328. err := json.NewDecoder(r).Decode(&a)
  329. if err != nil {
  330. return err
  331. }
  332. c.ServiceKeyName = a.ServiceKeyName
  333. if a.ServiceKeySecret != "" {
  334. c.ServiceKeySecret = a.ServiceKeySecret
  335. }
  336. c.SpotDataPrefix = a.Prefix
  337. c.SpotDataBucket = a.BucketName
  338. c.ProjectID = a.AccountID
  339. c.SpotDataRegion = a.Region
  340. c.SpotLabel = a.SpotLabel
  341. c.SpotLabelValue = a.SpotLabelValue
  342. } else if updateType == AthenaInfoUpdateType {
  343. a := AwsAthenaInfo{}
  344. err := json.NewDecoder(r).Decode(&a)
  345. if err != nil {
  346. return err
  347. }
  348. c.AthenaBucketName = a.AthenaBucketName
  349. c.AthenaRegion = a.AthenaRegion
  350. c.AthenaDatabase = a.AthenaDatabase
  351. c.AthenaTable = a.AthenaTable
  352. c.ServiceKeyName = a.ServiceKeyName
  353. if a.ServiceKeySecret != "" {
  354. c.ServiceKeySecret = a.ServiceKeySecret
  355. }
  356. if a.MasterPayerARN != "" {
  357. c.MasterPayerARN = a.MasterPayerARN
  358. }
  359. c.AthenaProjectID = a.AccountID
  360. } else {
  361. a := make(map[string]interface{})
  362. err := json.NewDecoder(r).Decode(&a)
  363. if err != nil {
  364. return err
  365. }
  366. for k, v := range a {
  367. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  368. vstr, ok := v.(string)
  369. if ok {
  370. err := SetCustomPricingField(c, kUpper, vstr)
  371. if err != nil {
  372. return err
  373. }
  374. } else {
  375. sci := v.(map[string]interface{})
  376. sc := make(map[string]string)
  377. for k, val := range sci {
  378. sc[k] = val.(string)
  379. }
  380. c.SharedCosts = sc //todo: support reflection/multiple map fields
  381. }
  382. }
  383. }
  384. if env.IsRemoteEnabled() {
  385. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  386. if err != nil {
  387. return err
  388. }
  389. }
  390. return nil
  391. })
  392. }
  393. type awsKey struct {
  394. SpotLabelName string
  395. SpotLabelValue string
  396. Labels map[string]string
  397. ProviderID string
  398. }
  399. func (k *awsKey) GPUType() string {
  400. return ""
  401. }
  402. func (k *awsKey) ID() string {
  403. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)") // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  404. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  405. if matchNum == 2 {
  406. return group
  407. }
  408. }
  409. klog.V(3).Infof("Could not find instance ID in \"%s\"", k.ProviderID)
  410. return ""
  411. }
  412. func (k *awsKey) Features() string {
  413. instanceType, _ := util.GetInstanceType(k.Labels)
  414. operatingSystem, _ := util.GetOperatingSystem(k.Labels)
  415. region, _ := util.GetRegion(k.Labels)
  416. key := region + "," + instanceType + "," + operatingSystem
  417. usageType := PreemptibleType
  418. spotKey := key + "," + usageType
  419. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  420. return spotKey
  421. }
  422. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  423. return spotKey
  424. }
  425. return key
  426. }
  427. func (aws *AWS) PVPricing(pvk PVKey) (*PV, error) {
  428. pricing, ok := aws.Pricing[pvk.Features()]
  429. if !ok {
  430. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  431. return &PV{}, nil
  432. }
  433. return pricing.PV, nil
  434. }
  435. type awsPVKey struct {
  436. Labels map[string]string
  437. StorageClassParameters map[string]string
  438. StorageClassName string
  439. Name string
  440. DefaultRegion string
  441. ProviderID string
  442. }
  443. func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  444. providerID := ""
  445. if pv.Spec.AWSElasticBlockStore != nil {
  446. providerID = pv.Spec.AWSElasticBlockStore.VolumeID
  447. }
  448. return &awsPVKey{
  449. Labels: pv.Labels,
  450. StorageClassName: pv.Spec.StorageClassName,
  451. StorageClassParameters: parameters,
  452. Name: pv.Name,
  453. DefaultRegion: defaultRegion,
  454. ProviderID: providerID,
  455. }
  456. }
  457. func (key *awsPVKey) ID() string {
  458. return key.ProviderID
  459. }
  460. func (key *awsPVKey) GetStorageClass() string {
  461. return key.StorageClassName
  462. }
  463. func (key *awsPVKey) Features() string {
  464. storageClass := key.StorageClassParameters["type"]
  465. if storageClass == "standard" {
  466. storageClass = "gp2"
  467. }
  468. // Storage class names are generally EBS volume types (gp2)
  469. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  470. // Converts between the 2
  471. region, _ := util.GetRegion(key.Labels)
  472. //if region == "" {
  473. // region = "us-east-1"
  474. //}
  475. class, ok := volTypes[storageClass]
  476. if !ok {
  477. klog.V(4).Infof("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  478. }
  479. return region + "," + class
  480. }
  481. // GetKey maps node labels to information needed to retrieve pricing data
  482. func (aws *AWS) GetKey(labels map[string]string, n *v1.Node) Key {
  483. return &awsKey{
  484. SpotLabelName: aws.SpotLabelName,
  485. SpotLabelValue: aws.SpotLabelValue,
  486. Labels: labels,
  487. ProviderID: labels["providerID"],
  488. }
  489. }
  490. func (aws *AWS) isPreemptible(key string) bool {
  491. s := strings.Split(key, ",")
  492. if len(s) == 4 && s[3] == PreemptibleType {
  493. return true
  494. }
  495. return false
  496. }
  497. func (aws *AWS) ClusterManagementPricing() (string, float64, error) {
  498. return aws.clusterProvisioner, aws.clusterManagementPrice, nil
  499. }
  500. // Use the pricing data from the current region. Fall back to using all region data if needed.
  501. func (aws *AWS) getRegionPricing(nodeList []*v1.Node) (*http.Response, string, error) {
  502. pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/"
  503. region := ""
  504. multiregion := false
  505. for _, n := range nodeList {
  506. labels := n.GetLabels()
  507. currentNodeRegion := ""
  508. if r, ok := util.GetRegion(labels); ok {
  509. currentNodeRegion = r
  510. } else {
  511. multiregion = true // We weren't able to detect the node's region, so pull all data.
  512. break
  513. }
  514. if region == "" { // We haven't set a region yet
  515. region = currentNodeRegion
  516. } else if region != "" && currentNodeRegion != region { // If two nodes have different regions here, we'll need to fetch all pricing data.
  517. multiregion = true
  518. break
  519. }
  520. }
  521. if region != "" && !multiregion {
  522. pricingURL += region + "/"
  523. }
  524. pricingURL += "index.json"
  525. klog.V(2).Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  526. resp, err := http.Get(pricingURL)
  527. if err != nil {
  528. klog.V(2).Infof("Bogus fetch of \"%s\": %v", pricingURL, err)
  529. return nil, pricingURL, err
  530. }
  531. return resp, pricingURL, err
  532. }
  533. // DownloadPricingData fetches data from the AWS Pricing API
  534. func (aws *AWS) DownloadPricingData() error {
  535. aws.DownloadPricingDataLock.Lock()
  536. defer aws.DownloadPricingDataLock.Unlock()
  537. if aws.ServiceAccountChecks == nil {
  538. aws.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  539. }
  540. c, err := aws.Config.GetCustomPricingData()
  541. if err != nil {
  542. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  543. }
  544. aws.BaseCPUPrice = c.CPU
  545. aws.BaseRAMPrice = c.RAM
  546. aws.BaseGPUPrice = c.GPU
  547. aws.BaseSpotCPUPrice = c.SpotCPU
  548. aws.BaseSpotRAMPrice = c.SpotRAM
  549. aws.BaseSpotGPUPrice = c.SpotGPU
  550. aws.SpotLabelName = c.SpotLabel
  551. aws.SpotLabelValue = c.SpotLabelValue
  552. aws.SpotDataBucket = c.SpotDataBucket
  553. aws.SpotDataPrefix = c.SpotDataPrefix
  554. aws.ProjectID = c.ProjectID
  555. aws.SpotDataRegion = c.SpotDataRegion
  556. aws.ConfigureAuthWith(c) // load aws authentication from configuration or secret
  557. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  558. klog.V(1).Infof("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  559. }
  560. nodeList := aws.Clientset.GetAllNodes()
  561. inputkeys := make(map[string]bool)
  562. for _, n := range nodeList {
  563. if _, ok := n.Labels["eks.amazonaws.com/nodegroup"]; ok {
  564. aws.clusterManagementPrice = 0.10
  565. aws.clusterProvisioner = "EKS"
  566. } else if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  567. aws.clusterProvisioner = "KOPS"
  568. }
  569. labels := n.GetObjectMeta().GetLabels()
  570. key := aws.GetKey(labels, n)
  571. inputkeys[key.Features()] = true
  572. }
  573. pvList := aws.Clientset.GetAllPersistentVolumes()
  574. storageClasses := aws.Clientset.GetAllStorageClasses()
  575. storageClassMap := make(map[string]map[string]string)
  576. for _, storageClass := range storageClasses {
  577. params := storageClass.Parameters
  578. storageClassMap[storageClass.ObjectMeta.Name] = params
  579. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  580. storageClassMap["default"] = params
  581. storageClassMap[""] = params
  582. }
  583. }
  584. pvkeys := make(map[string]PVKey)
  585. for _, pv := range pvList {
  586. params, ok := storageClassMap[pv.Spec.StorageClassName]
  587. if !ok {
  588. klog.V(2).Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  589. continue
  590. }
  591. key := aws.GetPVKey(pv, params, "")
  592. pvkeys[key.Features()] = key
  593. }
  594. // RIDataRunning establishes the existance of the goroutine. Since it's possible we
  595. // run multiple downloads, we don't want to create multiple go routines if one already exists
  596. if !aws.RIDataRunning && c.AthenaBucketName != "" {
  597. err = aws.GetReservationDataFromAthena() // Block until one run has completed.
  598. if err != nil {
  599. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  600. } else { // If we make one successful run, check on new reservation data every hour
  601. go func() {
  602. defer errors.HandlePanic()
  603. aws.RIDataRunning = true
  604. for {
  605. klog.Infof("Reserved Instance watcher running... next update in 1h")
  606. time.Sleep(time.Hour)
  607. err := aws.GetReservationDataFromAthena()
  608. if err != nil {
  609. klog.Infof("Error updating RI data: %s", err.Error())
  610. }
  611. }
  612. }()
  613. }
  614. }
  615. if !aws.SavingsPlanDataRunning && c.AthenaBucketName != "" {
  616. err = aws.GetSavingsPlanDataFromAthena()
  617. if err != nil {
  618. klog.V(1).Infof("Failed to lookup savings plan data: %s", err.Error())
  619. } else {
  620. go func() {
  621. defer errors.HandlePanic()
  622. aws.SavingsPlanDataRunning = true
  623. for {
  624. klog.Infof("Savings Plan watcher running... next update in 1h")
  625. time.Sleep(time.Hour)
  626. err := aws.GetSavingsPlanDataFromAthena()
  627. if err != nil {
  628. klog.Infof("Error updating Savings Plan data: %s", err.Error())
  629. }
  630. }
  631. }()
  632. }
  633. }
  634. aws.Pricing = make(map[string]*AWSProductTerms)
  635. aws.ValidPricingKeys = make(map[string]bool)
  636. skusToKeys := make(map[string]string)
  637. resp, pricingURL, err := aws.getRegionPricing(nodeList)
  638. if err != nil {
  639. return err
  640. }
  641. dec := json.NewDecoder(resp.Body)
  642. for {
  643. t, err := dec.Token()
  644. if err == io.EOF {
  645. klog.V(2).Infof("done loading \"%s\"\n", pricingURL)
  646. break
  647. }
  648. if t == "products" {
  649. _, err := dec.Token() // this should parse the opening "{""
  650. if err != nil {
  651. return err
  652. }
  653. for dec.More() {
  654. _, err := dec.Token() // the sku token
  655. if err != nil {
  656. return err
  657. }
  658. product := &AWSProduct{}
  659. err = dec.Decode(&product)
  660. if err != nil {
  661. klog.V(1).Infof("Error parsing response from \"%s\": %v", pricingURL, err.Error())
  662. break
  663. }
  664. if product.Attributes.PreInstalledSw == "NA" &&
  665. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) {
  666. key := aws.KubeAttrConversion(product.Attributes.Location, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  667. spotKey := key + ",preemptible"
  668. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  669. productTerms := &AWSProductTerms{
  670. Sku: product.Sku,
  671. Memory: product.Attributes.Memory,
  672. Storage: product.Attributes.Storage,
  673. VCpu: product.Attributes.VCpu,
  674. GPU: product.Attributes.GPU,
  675. }
  676. aws.Pricing[key] = productTerms
  677. aws.Pricing[spotKey] = productTerms
  678. skusToKeys[product.Sku] = key
  679. }
  680. aws.ValidPricingKeys[key] = true
  681. aws.ValidPricingKeys[spotKey] = true
  682. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  683. // UsageTypes may be prefixed with a region code - we're removing this when using
  684. // volTypes to keep lookups generic
  685. usageTypeRegx := regexp.MustCompile(".*(-|^)(EBS.+)")
  686. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  687. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  688. key := locationToRegion[product.Attributes.Location] + "," + usageTypeNoRegion
  689. spotKey := key + ",preemptible"
  690. pv := &PV{
  691. Class: volTypes[usageTypeNoRegion],
  692. Region: locationToRegion[product.Attributes.Location],
  693. }
  694. productTerms := &AWSProductTerms{
  695. Sku: product.Sku,
  696. PV: pv,
  697. }
  698. aws.Pricing[key] = productTerms
  699. aws.Pricing[spotKey] = productTerms
  700. skusToKeys[product.Sku] = key
  701. aws.ValidPricingKeys[key] = true
  702. aws.ValidPricingKeys[spotKey] = true
  703. }
  704. }
  705. }
  706. if t == "terms" {
  707. _, err := dec.Token() // this should parse the opening "{""
  708. if err != nil {
  709. return err
  710. }
  711. termType, err := dec.Token()
  712. if err != nil {
  713. return err
  714. }
  715. if termType == "OnDemand" {
  716. _, err := dec.Token()
  717. if err != nil { // again, should parse an opening "{"
  718. return err
  719. }
  720. for dec.More() {
  721. sku, err := dec.Token()
  722. if err != nil {
  723. return err
  724. }
  725. _, err = dec.Token() // another opening "{"
  726. if err != nil {
  727. return err
  728. }
  729. skuOnDemand, err := dec.Token()
  730. if err != nil {
  731. return err
  732. }
  733. offerTerm := &AWSOfferTerm{}
  734. err = dec.Decode(&offerTerm)
  735. if err != nil {
  736. klog.V(1).Infof("Error decoding AWS Offer Term: " + err.Error())
  737. }
  738. if sku.(string)+OnDemandRateCode == skuOnDemand {
  739. key, ok := skusToKeys[sku.(string)]
  740. spotKey := key + ",preemptible"
  741. if ok {
  742. aws.Pricing[key].OnDemand = offerTerm
  743. aws.Pricing[spotKey].OnDemand = offerTerm
  744. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  745. // If the specific UsageType is the per IO cost used on io1 volumes
  746. // we need to add the per IO cost to the io1 PV cost
  747. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  748. // Add the per IO cost to the PV object for the io1 volume type
  749. aws.Pricing[key].PV.CostPerIO = cost
  750. } else if strings.Contains(key, "EBS:Volume") {
  751. // If volume, we need to get hourly cost and add it to the PV object
  752. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  753. costFloat, _ := strconv.ParseFloat(cost, 64)
  754. hourlyPrice := costFloat / 730
  755. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  756. }
  757. }
  758. }
  759. _, err = dec.Token()
  760. if err != nil {
  761. return err
  762. }
  763. }
  764. _, err = dec.Token()
  765. if err != nil {
  766. return err
  767. }
  768. }
  769. }
  770. }
  771. klog.V(2).Infof("Finished downloading \"%s\"", pricingURL)
  772. // Always run spot pricing refresh when performing download
  773. aws.refreshSpotPricing(true)
  774. // Only start a single refresh goroutine
  775. if !aws.SpotRefreshRunning {
  776. aws.SpotRefreshRunning = true
  777. go func() {
  778. defer errors.HandlePanic()
  779. for {
  780. klog.Infof("Spot Pricing Refresh scheduled in %.2f minutes.", SpotRefreshDuration.Minutes())
  781. time.Sleep(SpotRefreshDuration)
  782. // Reoccurring refresh checks update times
  783. aws.refreshSpotPricing(false)
  784. }
  785. }()
  786. }
  787. return nil
  788. }
  789. func (aws *AWS) refreshSpotPricing(force bool) {
  790. aws.SpotPricingLock.Lock()
  791. defer aws.SpotPricingLock.Unlock()
  792. now := time.Now().UTC()
  793. updateTime := now.Add(-SpotRefreshDuration)
  794. // Return if there was an update time set and an hour hasn't elapsed
  795. if !force && aws.SpotPricingUpdatedAt != nil && aws.SpotPricingUpdatedAt.After(updateTime) {
  796. return
  797. }
  798. sp, err := aws.parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion)
  799. if err != nil {
  800. klog.V(1).Infof("Skipping AWS spot data download: %s", err.Error())
  801. aws.SpotPricingStatus = err.Error()
  802. return
  803. }
  804. aws.SpotPricingStatus = ""
  805. // update time last updated
  806. aws.SpotPricingUpdatedAt = &now
  807. aws.SpotPricingByInstanceID = sp
  808. }
  809. // Stubbed NetworkPricing for AWS. Pull directly from aws.json for now
  810. func (aws *AWS) NetworkPricing() (*Network, error) {
  811. cpricing, err := aws.Config.GetCustomPricingData()
  812. if err != nil {
  813. return nil, err
  814. }
  815. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  816. if err != nil {
  817. return nil, err
  818. }
  819. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  820. if err != nil {
  821. return nil, err
  822. }
  823. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  824. if err != nil {
  825. return nil, err
  826. }
  827. return &Network{
  828. ZoneNetworkEgressCost: znec,
  829. RegionNetworkEgressCost: rnec,
  830. InternetNetworkEgressCost: inec,
  831. }, nil
  832. }
  833. func (aws *AWS) LoadBalancerPricing() (*LoadBalancer, error) {
  834. fffrc := 0.025
  835. afrc := 0.010
  836. lbidc := 0.008
  837. numForwardingRules := 1.0
  838. dataIngressGB := 0.0
  839. var totalCost float64
  840. if numForwardingRules < 5 {
  841. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  842. } else {
  843. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  844. }
  845. return &LoadBalancer{
  846. Cost: totalCost,
  847. }, nil
  848. }
  849. // AllNodePricing returns all the billing data fetched.
  850. func (aws *AWS) AllNodePricing() (interface{}, error) {
  851. aws.DownloadPricingDataLock.RLock()
  852. defer aws.DownloadPricingDataLock.RUnlock()
  853. return aws.Pricing, nil
  854. }
  855. func (aws *AWS) spotPricing(instanceID string) (*spotInfo, bool) {
  856. aws.SpotPricingLock.RLock()
  857. defer aws.SpotPricingLock.RUnlock()
  858. info, ok := aws.SpotPricingByInstanceID[instanceID]
  859. return info, ok
  860. }
  861. func (aws *AWS) reservedInstancePricing(instanceID string) (*RIData, bool) {
  862. aws.RIDataLock.RLock()
  863. defer aws.RIDataLock.RUnlock()
  864. data, ok := aws.RIPricingByInstanceID[instanceID]
  865. return data, ok
  866. }
  867. func (aws *AWS) savingsPlanPricing(instanceID string) (*SavingsPlanData, bool) {
  868. aws.SavingsPlanDataLock.RLock()
  869. defer aws.SavingsPlanDataLock.RUnlock()
  870. data, ok := aws.SavingsPlanDataByInstanceID[instanceID]
  871. return data, ok
  872. }
  873. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  874. key := k.Features()
  875. if spotInfo, ok := aws.spotPricing(k.ID()); ok {
  876. var spotcost string
  877. log.DedupedInfof(5, "Looking up spot data from feed for node %s", k.ID())
  878. arr := strings.Split(spotInfo.Charge, " ")
  879. if len(arr) == 2 {
  880. spotcost = arr[0]
  881. } else {
  882. klog.V(2).Infof("Spot data for node %s is missing", k.ID())
  883. }
  884. return &Node{
  885. Cost: spotcost,
  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: PreemptibleType,
  894. }, nil
  895. } else if aws.isPreemptible(key) { // Preemptible but we don't have any data in the pricing report.
  896. log.DedupedWarningf(5, "Node %s marked preemptible but we have no data in spot feed", k.ID())
  897. return &Node{
  898. VCPU: terms.VCpu,
  899. VCPUCost: aws.BaseSpotCPUPrice,
  900. RAM: terms.Memory,
  901. GPU: terms.GPU,
  902. Storage: terms.Storage,
  903. BaseCPUPrice: aws.BaseCPUPrice,
  904. BaseRAMPrice: aws.BaseRAMPrice,
  905. BaseGPUPrice: aws.BaseGPUPrice,
  906. UsageType: PreemptibleType,
  907. }, nil
  908. } else if sp, ok := aws.savingsPlanPricing(k.ID()); ok {
  909. strCost := fmt.Sprintf("%f", sp.EffectiveCost)
  910. return &Node{
  911. Cost: strCost,
  912. VCPU: terms.VCpu,
  913. RAM: terms.Memory,
  914. GPU: terms.GPU,
  915. Storage: terms.Storage,
  916. BaseCPUPrice: aws.BaseCPUPrice,
  917. BaseRAMPrice: aws.BaseRAMPrice,
  918. BaseGPUPrice: aws.BaseGPUPrice,
  919. UsageType: usageType,
  920. }, nil
  921. } else if ri, ok := aws.reservedInstancePricing(k.ID()); ok {
  922. strCost := fmt.Sprintf("%f", ri.EffectiveCost)
  923. return &Node{
  924. Cost: strCost,
  925. VCPU: terms.VCpu,
  926. RAM: terms.Memory,
  927. GPU: terms.GPU,
  928. Storage: terms.Storage,
  929. BaseCPUPrice: aws.BaseCPUPrice,
  930. BaseRAMPrice: aws.BaseRAMPrice,
  931. BaseGPUPrice: aws.BaseGPUPrice,
  932. UsageType: usageType,
  933. }, nil
  934. }
  935. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  936. if !ok {
  937. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  938. }
  939. cost := c.PricePerUnit.USD
  940. return &Node{
  941. Cost: cost,
  942. VCPU: terms.VCpu,
  943. RAM: terms.Memory,
  944. GPU: terms.GPU,
  945. Storage: terms.Storage,
  946. BaseCPUPrice: aws.BaseCPUPrice,
  947. BaseRAMPrice: aws.BaseRAMPrice,
  948. BaseGPUPrice: aws.BaseGPUPrice,
  949. UsageType: usageType,
  950. }, nil
  951. }
  952. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  953. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  954. aws.DownloadPricingDataLock.RLock()
  955. defer aws.DownloadPricingDataLock.RUnlock()
  956. key := k.Features()
  957. usageType := "ondemand"
  958. if aws.isPreemptible(key) {
  959. usageType = PreemptibleType
  960. }
  961. terms, ok := aws.Pricing[key]
  962. if ok {
  963. return aws.createNode(terms, usageType, k)
  964. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  965. aws.DownloadPricingDataLock.RUnlock()
  966. err := aws.DownloadPricingData()
  967. aws.DownloadPricingDataLock.RLock()
  968. if err != nil {
  969. return &Node{
  970. Cost: aws.BaseCPUPrice,
  971. BaseCPUPrice: aws.BaseCPUPrice,
  972. BaseRAMPrice: aws.BaseRAMPrice,
  973. BaseGPUPrice: aws.BaseGPUPrice,
  974. UsageType: usageType,
  975. UsesBaseCPUPrice: true,
  976. }, err
  977. }
  978. terms, termsOk := aws.Pricing[key]
  979. if !termsOk {
  980. return &Node{
  981. Cost: aws.BaseCPUPrice,
  982. BaseCPUPrice: aws.BaseCPUPrice,
  983. BaseRAMPrice: aws.BaseRAMPrice,
  984. BaseGPUPrice: aws.BaseGPUPrice,
  985. UsageType: usageType,
  986. UsesBaseCPUPrice: true,
  987. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  988. }
  989. return aws.createNode(terms, usageType, k)
  990. } else { // Fall back to base pricing if we can't find the key. Base pricing is handled at the costmodel level.
  991. return nil, fmt.Errorf("Invalid Pricing Key \"%s\"", key)
  992. }
  993. }
  994. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  995. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  996. defaultClusterName := "AWS Cluster #1"
  997. c, err := awsProvider.GetConfig()
  998. if err != nil {
  999. return nil, err
  1000. }
  1001. remoteEnabled := env.IsRemoteEnabled()
  1002. if c.ClusterName != "" {
  1003. m := make(map[string]string)
  1004. m["name"] = c.ClusterName
  1005. m["provider"] = "AWS"
  1006. m["id"] = env.GetClusterID()
  1007. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1008. m["provisioner"] = awsProvider.clusterProvisioner
  1009. return m, nil
  1010. }
  1011. makeStructure := func(clusterName string) (map[string]string, error) {
  1012. klog.V(2).Infof("Returning \"%s\" as ClusterName", clusterName)
  1013. m := make(map[string]string)
  1014. m["name"] = clusterName
  1015. m["provider"] = "AWS"
  1016. m["id"] = env.GetClusterID()
  1017. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1018. return m, nil
  1019. }
  1020. maybeClusterId := env.GetAWSClusterID()
  1021. if len(maybeClusterId) != 0 {
  1022. return makeStructure(maybeClusterId)
  1023. }
  1024. // TODO: This should be cached, it can take a long time to hit the API
  1025. //provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  1026. //clusterIdRx := regexp.MustCompile("^kubernetes\\.io/cluster/([^/]+)")
  1027. //klog.Infof("nodelist get here %s", time.Now())
  1028. //nodeList := awsProvider.Clientset.GetAllNodes()
  1029. //klog.Infof("nodelist done here %s", time.Now())
  1030. /*for _, n := range nodeList {
  1031. region := ""
  1032. instanceId := ""
  1033. providerId := n.Spec.ProviderID
  1034. for matchNum, group := range provIdRx.FindStringSubmatch(providerId) {
  1035. if matchNum == 1 {
  1036. region = group
  1037. } else if matchNum == 2 {
  1038. instanceId = group
  1039. }
  1040. }
  1041. if len(instanceId) == 0 {
  1042. klog.V(2).Infof("Unable to decode Node.ProviderID \"%s\", skipping it", providerId)
  1043. continue
  1044. }
  1045. c := &aws.Config{
  1046. Region: aws.String(region),
  1047. }
  1048. s := session.Must(session.NewSession(c))
  1049. ec2Svc := ec2.New(s)
  1050. di, diErr := ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{
  1051. InstanceIds: []*string{
  1052. aws.String(instanceId),
  1053. },
  1054. })
  1055. if diErr != nil {
  1056. klog.Infof("Error describing instances: %s", diErr)
  1057. continue
  1058. }
  1059. if len(di.Reservations) != 1 {
  1060. klog.V(2).Infof("Expected 1 Reservation back from DescribeInstances(%s), received %d", instanceId, len(di.Reservations))
  1061. continue
  1062. }
  1063. res := di.Reservations[0]
  1064. if len(res.Instances) != 1 {
  1065. klog.V(2).Infof("Expected 1 Instance back from DescribeInstances(%s), received %d", instanceId, len(res.Instances))
  1066. continue
  1067. }
  1068. inst := res.Instances[0]
  1069. for _, tag := range inst.Tags {
  1070. tagKey := *tag.Key
  1071. for matchNum, group := range clusterIdRx.FindStringSubmatch(tagKey) {
  1072. if matchNum != 1 {
  1073. continue
  1074. }
  1075. return makeStructure(group)
  1076. }
  1077. }
  1078. }*/
  1079. klog.V(2).Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", env.AWSClusterIDEnvVar)
  1080. return makeStructure(defaultClusterName)
  1081. }
  1082. // updates the authentication to the latest values (via config or secret)
  1083. func (aws *AWS) ConfigureAuth() error {
  1084. c, err := aws.Config.GetCustomPricingData()
  1085. if err != nil {
  1086. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  1087. }
  1088. return aws.ConfigureAuthWith(c)
  1089. }
  1090. // updates the authentication to the latest values (via config or secret)
  1091. func (aws *AWS) ConfigureAuthWith(config *CustomPricing) error {
  1092. accessKeyID, accessKeySecret := aws.getAWSAuth(false, config)
  1093. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1094. err := env.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1095. if err != nil {
  1096. return err
  1097. }
  1098. err = env.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1099. if err != nil {
  1100. return err
  1101. }
  1102. }
  1103. return nil
  1104. }
  1105. // Gets the aws key id and secret
  1106. func (aws *AWS) getAWSAuth(forceReload bool, cp *CustomPricing) (string, string) {
  1107. if aws.ServiceAccountChecks == nil { // safety in case checks don't exist
  1108. aws.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  1109. }
  1110. // 1. Check config values first (set from frontend UI)
  1111. if cp.ServiceKeyName != "" && cp.ServiceKeySecret != "" {
  1112. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1113. Message: "AWS ServiceKey exists",
  1114. Status: true,
  1115. }
  1116. return cp.ServiceKeyName, cp.ServiceKeySecret
  1117. }
  1118. // 2. Check for secret
  1119. s, _ := aws.loadAWSAuthSecret(forceReload)
  1120. if s != nil && s.AccessKeyID != "" && s.SecretAccessKey != "" {
  1121. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1122. Message: "AWS ServiceKey exists",
  1123. Status: true,
  1124. }
  1125. return s.AccessKeyID, s.SecretAccessKey
  1126. }
  1127. // 3. Fall back to env vars
  1128. if env.GetAWSAccessKeyID() == "" || env.GetAWSAccessKeyID() == "" {
  1129. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1130. Message: "AWS ServiceKey exists",
  1131. Status: false,
  1132. }
  1133. } else {
  1134. aws.ServiceAccountChecks["hasKey"] = &ServiceAccountCheck{
  1135. Message: "AWS ServiceKey exists",
  1136. Status: true,
  1137. }
  1138. }
  1139. return env.GetAWSAccessKeyID(), env.GetAWSAccessKeySecret()
  1140. }
  1141. // Load once and cache the result (even on failure). This is an install time secret, so
  1142. // we don't expect the secret to change. If it does, however, we can force reload using
  1143. // the input parameter.
  1144. func (aws *AWS) loadAWSAuthSecret(force bool) (*AWSAccessKey, error) {
  1145. if !force && loadedAWSSecret {
  1146. return awsSecret, nil
  1147. }
  1148. loadedAWSSecret = true
  1149. exists, err := util.FileExists(authSecretPath)
  1150. if !exists || err != nil {
  1151. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  1152. }
  1153. result, err := ioutil.ReadFile(authSecretPath)
  1154. if err != nil {
  1155. return nil, err
  1156. }
  1157. var ak AWSAccessKey
  1158. err = json.Unmarshal(result, &ak)
  1159. if err != nil {
  1160. return nil, err
  1161. }
  1162. awsSecret = &ak
  1163. return awsSecret, nil
  1164. }
  1165. func getClusterConfig(ccFile string) (map[string]string, error) {
  1166. clusterConfig, err := os.Open(ccFile)
  1167. if err != nil {
  1168. return nil, err
  1169. }
  1170. defer clusterConfig.Close()
  1171. b, err := ioutil.ReadAll(clusterConfig)
  1172. if err != nil {
  1173. return nil, err
  1174. }
  1175. var clusterConf map[string]string
  1176. err = json.Unmarshal([]byte(b), &clusterConf)
  1177. if err != nil {
  1178. return nil, err
  1179. }
  1180. return clusterConf, nil
  1181. }
  1182. func (a *AWS) getAddressesForRegion(region string) (*ec2.DescribeAddressesOutput, error) {
  1183. sess, err := session.NewSession(&aws.Config{
  1184. Region: aws.String(region),
  1185. Credentials: credentials.NewEnvCredentials(),
  1186. })
  1187. if err != nil {
  1188. return nil, err
  1189. }
  1190. ec2Svc := ec2.New(sess)
  1191. return ec2Svc.DescribeAddresses(&ec2.DescribeAddressesInput{})
  1192. }
  1193. func (a *AWS) GetAddresses() ([]byte, error) {
  1194. a.ConfigureAuth() // load authentication data into env vars
  1195. addressCh := make(chan *ec2.DescribeAddressesOutput, len(awsRegions))
  1196. errorCh := make(chan error, len(awsRegions))
  1197. var wg sync.WaitGroup
  1198. wg.Add(len(awsRegions))
  1199. // Get volumes from each AWS region
  1200. for _, r := range awsRegions {
  1201. // Fetch IP address response and send results and errors to their
  1202. // respective channels
  1203. go func(region string) {
  1204. defer wg.Done()
  1205. defer errors.HandlePanic()
  1206. // Query for first page of volume results
  1207. resp, err := a.getAddressesForRegion(region)
  1208. if err != nil {
  1209. if aerr, ok := err.(awserr.Error); ok {
  1210. switch aerr.Code() {
  1211. default:
  1212. errorCh <- aerr
  1213. }
  1214. return
  1215. } else {
  1216. errorCh <- err
  1217. return
  1218. }
  1219. }
  1220. addressCh <- resp
  1221. }(r)
  1222. }
  1223. // Close the result channels after everything has been sent
  1224. go func() {
  1225. defer errors.HandlePanic()
  1226. wg.Wait()
  1227. close(errorCh)
  1228. close(addressCh)
  1229. }()
  1230. addresses := []*ec2.Address{}
  1231. for adds := range addressCh {
  1232. addresses = append(addresses, adds.Addresses...)
  1233. }
  1234. errors := []error{}
  1235. for err := range errorCh {
  1236. log.DedupedWarningf(5, "unable to get addresses: %s", err)
  1237. errors = append(errors, err)
  1238. }
  1239. // Return error if no addresses are returned
  1240. if len(errors) > 0 && len(addresses) == 0 {
  1241. return nil, fmt.Errorf("%d error(s) retrieving addresses: %v", len(errors), errors)
  1242. }
  1243. // Format the response this way to match the JSON-encoded formatting of a single response
  1244. // from DescribeAddresss, so that consumers can always expect AWS disk responses to have
  1245. // a "Addresss" key at the top level.
  1246. return json.Marshal(map[string][]*ec2.Address{
  1247. "Addresses": addresses,
  1248. })
  1249. }
  1250. func (a *AWS) getDisksForRegion(region string, maxResults int64, nextToken *string) (*ec2.DescribeVolumesOutput, error) {
  1251. sess, err := session.NewSession(&aws.Config{
  1252. Region: aws.String(region),
  1253. Credentials: credentials.NewEnvCredentials(),
  1254. })
  1255. if err != nil {
  1256. return nil, err
  1257. }
  1258. ec2Svc := ec2.New(sess)
  1259. return ec2Svc.DescribeVolumes(&ec2.DescribeVolumesInput{
  1260. MaxResults: &maxResults,
  1261. NextToken: nextToken,
  1262. })
  1263. }
  1264. // 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.
  1265. func (a *AWS) GetDisks() ([]byte, error) {
  1266. a.ConfigureAuth() // load authentication data into env vars
  1267. volumeCh := make(chan *ec2.DescribeVolumesOutput, len(awsRegions))
  1268. errorCh := make(chan error, len(awsRegions))
  1269. var wg sync.WaitGroup
  1270. wg.Add(len(awsRegions))
  1271. // Get volumes from each AWS region
  1272. for _, r := range awsRegions {
  1273. // Fetch volume response and send results and errors to their
  1274. // respective channels
  1275. go func(region string) {
  1276. defer wg.Done()
  1277. defer errors.HandlePanic()
  1278. // Query for first page of volume results
  1279. resp, err := a.getDisksForRegion(region, 1000, nil)
  1280. if err != nil {
  1281. if aerr, ok := err.(awserr.Error); ok {
  1282. switch aerr.Code() {
  1283. default:
  1284. errorCh <- aerr
  1285. }
  1286. return
  1287. } else {
  1288. errorCh <- err
  1289. return
  1290. }
  1291. }
  1292. volumeCh <- resp
  1293. // A NextToken indicates more pages of results. Keep querying
  1294. // until all pages are retrieved.
  1295. for resp.NextToken != nil {
  1296. resp, err = a.getDisksForRegion(region, 100, resp.NextToken)
  1297. if err != nil {
  1298. if aerr, ok := err.(awserr.Error); ok {
  1299. switch aerr.Code() {
  1300. default:
  1301. errorCh <- aerr
  1302. }
  1303. return
  1304. } else {
  1305. errorCh <- err
  1306. return
  1307. }
  1308. }
  1309. volumeCh <- resp
  1310. }
  1311. }(r)
  1312. }
  1313. // Close the result channels after everything has been sent
  1314. go func() {
  1315. defer errors.HandlePanic()
  1316. wg.Wait()
  1317. close(errorCh)
  1318. close(volumeCh)
  1319. }()
  1320. volumes := []*ec2.Volume{}
  1321. for vols := range volumeCh {
  1322. volumes = append(volumes, vols.Volumes...)
  1323. }
  1324. errors := []error{}
  1325. for err := range errorCh {
  1326. log.DedupedWarningf(5, "unable to get disks: %s", err)
  1327. errors = append(errors, err)
  1328. }
  1329. // Return error if no volumes are returned
  1330. if len(errors) > 0 && len(volumes) == 0 {
  1331. return nil, fmt.Errorf("%d error(s) retrieving volumes: %v", len(errors), errors)
  1332. }
  1333. // Format the response this way to match the JSON-encoded formatting of a single response
  1334. // from DescribeVolumes, so that consumers can always expect AWS disk responses to have
  1335. // a "Volumes" key at the top level.
  1336. return json.Marshal(map[string][]*ec2.Volume{
  1337. "Volumes": volumes,
  1338. })
  1339. }
  1340. // ConvertToGlueColumnFormat takes a string and runs through various regex
  1341. // and string replacement statements to convert it to a format compatible
  1342. // with AWS Glue and Athena column names.
  1343. // Following guidance from AWS provided here ('Column Names' section):
  1344. // https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/run-athena-sql.html
  1345. // It returns a string containing the column name in proper column name format and length.
  1346. func ConvertToGlueColumnFormat(column_name string) string {
  1347. klog.V(5).Infof("Converting string \"%s\" to proper AWS Glue column name.", column_name)
  1348. // An underscore is added in front of uppercase letters
  1349. capital_underscore := regexp.MustCompile(`[A-Z]`)
  1350. final := capital_underscore.ReplaceAllString(column_name, `_$0`)
  1351. // Any non-alphanumeric characters are replaced with an underscore
  1352. no_space_punc := regexp.MustCompile(`[\s]{1,}|[^A-Za-z0-9]`)
  1353. final = no_space_punc.ReplaceAllString(final, "_")
  1354. // Duplicate underscores are removed
  1355. no_dup_underscore := regexp.MustCompile(`_{2,}`)
  1356. final = no_dup_underscore.ReplaceAllString(final, "_")
  1357. // Any leading and trailing underscores are removed
  1358. no_front_end_underscore := regexp.MustCompile(`(^\_|\_$)`)
  1359. final = no_front_end_underscore.ReplaceAllString(final, "")
  1360. // Uppercase to lowercase
  1361. final = strings.ToLower(final)
  1362. // Longer column name than expected - remove _ left to right
  1363. allowed_col_len := 128
  1364. undersc_to_remove := len(final) - allowed_col_len
  1365. if undersc_to_remove > 0 {
  1366. final = strings.Replace(final, "_", "", undersc_to_remove)
  1367. }
  1368. // If removing all of the underscores still didn't
  1369. // make the column name < 128 characters, trim it!
  1370. if len(final) > allowed_col_len {
  1371. final = final[:allowed_col_len]
  1372. }
  1373. klog.V(5).Infof("Column name being returned: \"%s\". Length: \"%d\".", final, len(final))
  1374. return final
  1375. }
  1376. func generateAWSGroupBy(lastIdx int) string {
  1377. sequence := []string{}
  1378. for i := 1; i < lastIdx+1; i++ {
  1379. sequence = append(sequence, strconv.Itoa(i))
  1380. }
  1381. return strings.Join(sequence, ",")
  1382. }
  1383. func (a *AWS) QueryAthenaPaginated(query string) (*athena.GetQueryResultsInput, *athena.Athena, error) {
  1384. customPricing, err := a.GetConfig()
  1385. if err != nil {
  1386. return nil, nil, err
  1387. }
  1388. a.ConfigureAuthWith(customPricing)
  1389. region := aws.String(customPricing.AthenaRegion)
  1390. resultsBucket := customPricing.AthenaBucketName
  1391. database := customPricing.AthenaDatabase
  1392. c := &aws.Config{
  1393. Region: region,
  1394. }
  1395. s := session.Must(session.NewSession(c))
  1396. svc := athena.New(s)
  1397. if customPricing.MasterPayerARN != "" {
  1398. creds := stscreds.NewCredentials(s, customPricing.MasterPayerARN)
  1399. svc = athena.New(s, &aws.Config{
  1400. Region: region,
  1401. Credentials: creds,
  1402. })
  1403. }
  1404. var e athena.StartQueryExecutionInput
  1405. var r athena.ResultConfiguration
  1406. r.SetOutputLocation(resultsBucket)
  1407. e.SetResultConfiguration(&r)
  1408. e.SetQueryString(query)
  1409. var q athena.QueryExecutionContext
  1410. q.SetDatabase(database)
  1411. e.SetQueryExecutionContext(&q)
  1412. res, err := svc.StartQueryExecution(&e)
  1413. if err != nil {
  1414. return nil, svc, err
  1415. }
  1416. klog.V(2).Infof("StartQueryExecution result:")
  1417. klog.V(2).Infof(res.GoString())
  1418. var qri athena.GetQueryExecutionInput
  1419. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1420. var qrop *athena.GetQueryExecutionOutput
  1421. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1422. for {
  1423. qrop, err = svc.GetQueryExecution(&qri)
  1424. if err != nil {
  1425. return nil, svc, err
  1426. }
  1427. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1428. break
  1429. }
  1430. time.Sleep(duration)
  1431. }
  1432. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1433. var ip athena.GetQueryResultsInput
  1434. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1435. return &ip, svc, nil
  1436. } else {
  1437. return nil, svc, fmt.Errorf("No results available for %s", query)
  1438. }
  1439. }
  1440. func (a *AWS) QueryAthenaBillingData(query string) (*athena.GetQueryResultsOutput, error) {
  1441. customPricing, err := a.GetConfig()
  1442. if err != nil {
  1443. return nil, err
  1444. }
  1445. a.ConfigureAuthWith(customPricing) // load aws authentication from configuration or secret
  1446. region := aws.String(customPricing.AthenaRegion)
  1447. resultsBucket := customPricing.AthenaBucketName
  1448. database := customPricing.AthenaDatabase
  1449. c := &aws.Config{
  1450. Region: region,
  1451. }
  1452. s := session.Must(session.NewSession(c))
  1453. svc := athena.New(s)
  1454. if customPricing.MasterPayerARN != "" {
  1455. creds := stscreds.NewCredentials(s, customPricing.MasterPayerARN)
  1456. svc = athena.New(s, &aws.Config{
  1457. Region: region,
  1458. Credentials: creds,
  1459. })
  1460. }
  1461. var e athena.StartQueryExecutionInput
  1462. var r athena.ResultConfiguration
  1463. r.SetOutputLocation(resultsBucket)
  1464. e.SetResultConfiguration(&r)
  1465. e.SetQueryString(query)
  1466. var q athena.QueryExecutionContext
  1467. q.SetDatabase(database)
  1468. e.SetQueryExecutionContext(&q)
  1469. res, err := svc.StartQueryExecution(&e)
  1470. if err != nil {
  1471. return nil, err
  1472. }
  1473. klog.V(2).Infof("StartQueryExecution result:")
  1474. klog.V(2).Infof(res.GoString())
  1475. var qri athena.GetQueryExecutionInput
  1476. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1477. var qrop *athena.GetQueryExecutionOutput
  1478. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1479. for {
  1480. qrop, err = svc.GetQueryExecution(&qri)
  1481. if err != nil {
  1482. return nil, err
  1483. }
  1484. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1485. break
  1486. }
  1487. time.Sleep(duration)
  1488. }
  1489. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1490. var ip athena.GetQueryResultsInput
  1491. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1492. return svc.GetQueryResults(&ip)
  1493. } else {
  1494. return nil, fmt.Errorf("No results available for %s", query)
  1495. }
  1496. }
  1497. type SavingsPlanData struct {
  1498. ResourceID string
  1499. EffectiveCost float64
  1500. SavingsPlanARN string
  1501. MostRecentDate string
  1502. }
  1503. func (a *AWS) GetSavingsPlanDataFromAthena() error {
  1504. cfg, err := a.GetConfig()
  1505. if err != nil {
  1506. return err
  1507. }
  1508. if cfg.AthenaBucketName == "" {
  1509. return fmt.Errorf("No Athena Bucket configured")
  1510. }
  1511. if a.SavingsPlanDataByInstanceID == nil {
  1512. a.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData)
  1513. }
  1514. tNow := time.Now()
  1515. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1516. start := tOneDayAgo.Format("2006-01-02")
  1517. end := tNow.Format("2006-01-02")
  1518. // Use Savings Plan Effective Rate as an estimation for cost, assuming the 1h most recent period got a fully loaded savings plan.
  1519. //
  1520. q := `SELECT
  1521. line_item_usage_start_date,
  1522. savings_plan_savings_plan_a_r_n,
  1523. line_item_resource_id,
  1524. savings_plan_savings_plan_rate
  1525. FROM %s as cost_data
  1526. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1527. AND line_item_line_item_type = 'SavingsPlanCoveredUsage' ORDER BY
  1528. line_item_usage_start_date DESC`
  1529. page := 0
  1530. processResults := func(op *athena.GetQueryResultsOutput, lastpage bool) bool {
  1531. a.SavingsPlanDataLock.Lock()
  1532. a.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData) // Clean out the old data and only report a savingsplan price if its in the most recent run.
  1533. mostRecentDate := ""
  1534. iter := op.ResultSet.Rows
  1535. if page == 0 && len(iter) > 0 {
  1536. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  1537. }
  1538. page++
  1539. for _, r := range iter {
  1540. d := *r.Data[0].VarCharValue
  1541. if mostRecentDate == "" {
  1542. mostRecentDate = d
  1543. } else if mostRecentDate != d { // Get all most recent assignments
  1544. break
  1545. }
  1546. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1547. if err != nil {
  1548. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1549. }
  1550. r := &SavingsPlanData{
  1551. ResourceID: *r.Data[2].VarCharValue,
  1552. EffectiveCost: cost,
  1553. SavingsPlanARN: *r.Data[1].VarCharValue,
  1554. MostRecentDate: d,
  1555. }
  1556. a.SavingsPlanDataByInstanceID[r.ResourceID] = r
  1557. }
  1558. klog.V(1).Infof("Found %d savings plan applied instances", len(a.SavingsPlanDataByInstanceID))
  1559. for k, r := range a.SavingsPlanDataByInstanceID {
  1560. log.DedupedInfof(5, "Savings Plan Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1561. }
  1562. a.SavingsPlanDataLock.Unlock()
  1563. return true
  1564. }
  1565. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1566. klog.V(3).Infof("Running Query: %s", query)
  1567. ip, svc, err := a.QueryAthenaPaginated(query)
  1568. if err != nil {
  1569. return fmt.Errorf("Error fetching Savings Plan Data: %s", err)
  1570. }
  1571. athenaErr := svc.GetQueryResultsPages(ip, processResults)
  1572. if athenaErr != nil {
  1573. return athenaErr
  1574. }
  1575. return nil
  1576. }
  1577. type RIData struct {
  1578. ResourceID string
  1579. EffectiveCost float64
  1580. ReservationARN string
  1581. MostRecentDate string
  1582. }
  1583. func (a *AWS) GetReservationDataFromAthena() error {
  1584. cfg, err := a.GetConfig()
  1585. if err != nil {
  1586. return err
  1587. }
  1588. if cfg.AthenaBucketName == "" {
  1589. return fmt.Errorf("No Athena Bucket configured")
  1590. }
  1591. if a.RIPricingByInstanceID == nil {
  1592. a.RIPricingByInstanceID = make(map[string]*RIData)
  1593. }
  1594. tNow := time.Now()
  1595. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1596. start := tOneDayAgo.Format("2006-01-02")
  1597. end := tNow.Format("2006-01-02")
  1598. q := `SELECT
  1599. line_item_usage_start_date,
  1600. reservation_reservation_a_r_n,
  1601. line_item_resource_id,
  1602. reservation_effective_cost
  1603. FROM %s as cost_data
  1604. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1605. AND reservation_reservation_a_r_n <> '' ORDER BY
  1606. line_item_usage_start_date DESC`
  1607. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1608. op, err := a.QueryAthenaBillingData(query)
  1609. if err != nil {
  1610. a.RIPricingStatus = err.Error()
  1611. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  1612. }
  1613. a.RIPricingStatus = ""
  1614. klog.Infof("Fetching RI data...")
  1615. if len(op.ResultSet.Rows) > 1 {
  1616. a.RIDataLock.Lock()
  1617. mostRecentDate := ""
  1618. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  1619. d := *r.Data[0].VarCharValue
  1620. if mostRecentDate == "" {
  1621. mostRecentDate = d
  1622. } else if mostRecentDate != d { // Get all most recent assignments
  1623. break
  1624. }
  1625. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1626. if err != nil {
  1627. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1628. }
  1629. r := &RIData{
  1630. ResourceID: *r.Data[2].VarCharValue,
  1631. EffectiveCost: cost,
  1632. ReservationARN: *r.Data[1].VarCharValue,
  1633. MostRecentDate: d,
  1634. }
  1635. a.RIPricingByInstanceID[r.ResourceID] = r
  1636. }
  1637. klog.V(1).Infof("Found %d reserved instances", len(a.RIPricingByInstanceID))
  1638. for k, r := range a.RIPricingByInstanceID {
  1639. log.DedupedInfof(5, "Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1640. }
  1641. a.RIDataLock.Unlock()
  1642. } else {
  1643. klog.Infof("No reserved instance data found")
  1644. }
  1645. return nil
  1646. }
  1647. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  1648. // "start" and "end" are dates of the format YYYY-MM-DD
  1649. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  1650. func (a *AWS) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  1651. customPricing, err := a.GetConfig()
  1652. if err != nil {
  1653. return nil, err
  1654. }
  1655. formattedAggregators := []string{}
  1656. for _, agg := range aggregators {
  1657. aggregator_column_name := "resource_tags_user_" + agg
  1658. aggregator_column_name = ConvertToGlueColumnFormat(aggregator_column_name)
  1659. formattedAggregators = append(formattedAggregators, aggregator_column_name)
  1660. }
  1661. aggregatorNames := strings.Join(formattedAggregators, ",")
  1662. aggregatorOr := strings.Join(formattedAggregators, " <> '' OR ")
  1663. aggregatorOr = aggregatorOr + " <> ''"
  1664. filter_column_name := "resource_tags_user_" + filterType
  1665. filter_column_name = ConvertToGlueColumnFormat(filter_column_name)
  1666. var query string
  1667. var lastIdx int
  1668. if filterType != "kubernetes_" { // This gets appended upstream and is equivalent to no filter.
  1669. lastIdx = len(formattedAggregators) + 3
  1670. groupby := generateAWSGroupBy(lastIdx)
  1671. query = fmt.Sprintf(`SELECT
  1672. CAST(line_item_usage_start_date AS DATE) as start_date,
  1673. %s,
  1674. line_item_product_code,
  1675. %s,
  1676. SUM(line_item_blended_cost) as blended_cost
  1677. FROM %s as cost_data
  1678. WHERE (%s='%s') AND line_item_usage_start_date BETWEEN date '%s' AND date '%s' AND (%s)
  1679. GROUP BY %s`, aggregatorNames, filter_column_name, customPricing.AthenaTable, filter_column_name, filterValue, start, end, aggregatorOr, groupby)
  1680. } else {
  1681. lastIdx = len(formattedAggregators) + 2
  1682. groupby := generateAWSGroupBy(lastIdx)
  1683. query = fmt.Sprintf(`SELECT
  1684. CAST(line_item_usage_start_date AS DATE) as start_date,
  1685. %s,
  1686. line_item_product_code,
  1687. SUM(line_item_blended_cost) as blended_cost
  1688. FROM %s as cost_data
  1689. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s' AND (%s)
  1690. GROUP BY %s`, aggregatorNames, customPricing.AthenaTable, start, end, aggregatorOr, groupby)
  1691. }
  1692. var oocAllocs []*OutOfClusterAllocation
  1693. page := 0
  1694. processResults := func(op *athena.GetQueryResultsOutput, lastpage bool) bool {
  1695. iter := op.ResultSet.Rows
  1696. if page == 0 && len(iter) > 0 {
  1697. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  1698. }
  1699. page++
  1700. for _, r := range iter {
  1701. cost, err := strconv.ParseFloat(*r.Data[lastIdx].VarCharValue, 64)
  1702. if err != nil {
  1703. klog.Infof("Error converting cost `%s` from float ", *r.Data[lastIdx].VarCharValue)
  1704. }
  1705. environment := ""
  1706. for _, d := range r.Data[1 : len(formattedAggregators)+1] {
  1707. if *d.VarCharValue != "" {
  1708. environment = *d.VarCharValue // just set to the first nonempty match
  1709. }
  1710. break
  1711. }
  1712. ooc := &OutOfClusterAllocation{
  1713. Aggregator: strings.Join(aggregators, ","),
  1714. Environment: environment,
  1715. Service: *r.Data[len(formattedAggregators)+1].VarCharValue,
  1716. Cost: cost,
  1717. }
  1718. oocAllocs = append(oocAllocs, ooc)
  1719. }
  1720. return true
  1721. }
  1722. klog.V(3).Infof("Running Query: %s", query)
  1723. ip, svc, err := a.QueryAthenaPaginated(query)
  1724. athenaErr := svc.GetQueryResultsPages(ip, processResults)
  1725. if athenaErr != nil {
  1726. klog.Infof("RETURNING ATHENA ERROR")
  1727. return nil, athenaErr
  1728. }
  1729. if customPricing.BillingDataDataset != "" && !crossCluster { // There is GCP data, meaning someone has tried to configure a GCP out-of-cluster allocation.
  1730. gcp, err := NewCrossClusterProvider("gcp", "aws.json", a.Clientset)
  1731. if err != nil {
  1732. klog.Infof("Could not instantiate cross-cluster provider %s", err.Error())
  1733. }
  1734. gcpOOC, err := gcp.ExternalAllocations(start, end, aggregators, filterType, filterValue, true)
  1735. if err != nil {
  1736. klog.Infof("Could not fetch cross-cluster costs %s", err.Error())
  1737. }
  1738. oocAllocs = append(oocAllocs, gcpOOC...)
  1739. }
  1740. return oocAllocs, nil
  1741. }
  1742. // QuerySQL can query a properly configured Athena database.
  1743. // Used to fetch billing data.
  1744. // Requires a json config in /var/configs with key region, output, and database.
  1745. func (a *AWS) QuerySQL(query string) ([]byte, error) {
  1746. customPricing, err := a.GetConfig()
  1747. if err != nil {
  1748. return nil, err
  1749. }
  1750. a.ConfigureAuthWith(customPricing) // load aws authentication from configuration or secret
  1751. athenaConfigs, err := os.Open("/var/configs/athena.json")
  1752. if err != nil {
  1753. return nil, err
  1754. }
  1755. defer athenaConfigs.Close()
  1756. b, err := ioutil.ReadAll(athenaConfigs)
  1757. if err != nil {
  1758. return nil, err
  1759. }
  1760. var athenaConf map[string]string
  1761. json.Unmarshal([]byte(b), &athenaConf)
  1762. region := aws.String(customPricing.AthenaRegion)
  1763. resultsBucket := customPricing.AthenaBucketName
  1764. database := customPricing.AthenaDatabase
  1765. c := &aws.Config{
  1766. Region: region,
  1767. }
  1768. s := session.Must(session.NewSession(c))
  1769. svc := athena.New(s)
  1770. var e athena.StartQueryExecutionInput
  1771. var r athena.ResultConfiguration
  1772. r.SetOutputLocation(resultsBucket)
  1773. e.SetResultConfiguration(&r)
  1774. e.SetQueryString(query)
  1775. var q athena.QueryExecutionContext
  1776. q.SetDatabase(database)
  1777. e.SetQueryExecutionContext(&q)
  1778. res, err := svc.StartQueryExecution(&e)
  1779. if err != nil {
  1780. return nil, err
  1781. }
  1782. klog.V(2).Infof("StartQueryExecution result:")
  1783. klog.V(2).Infof(res.GoString())
  1784. var qri athena.GetQueryExecutionInput
  1785. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1786. var qrop *athena.GetQueryExecutionOutput
  1787. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1788. for {
  1789. qrop, err = svc.GetQueryExecution(&qri)
  1790. if err != nil {
  1791. return nil, err
  1792. }
  1793. if *qrop.QueryExecution.Status.State != "RUNNING" && *qrop.QueryExecution.Status.State != "QUEUED" {
  1794. break
  1795. }
  1796. time.Sleep(duration)
  1797. }
  1798. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1799. var ip athena.GetQueryResultsInput
  1800. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1801. op, err := svc.GetQueryResults(&ip)
  1802. if err != nil {
  1803. return nil, err
  1804. }
  1805. b, err := json.Marshal(op.ResultSet)
  1806. if err != nil {
  1807. return nil, err
  1808. }
  1809. return b, nil
  1810. }
  1811. return nil, fmt.Errorf("Error getting query results : %s", *qrop.QueryExecution.Status.State)
  1812. }
  1813. type spotInfo struct {
  1814. Timestamp string `csv:"Timestamp"`
  1815. UsageType string `csv:"UsageType"`
  1816. Operation string `csv:"Operation"`
  1817. InstanceID string `csv:"InstanceID"`
  1818. MyBidID string `csv:"MyBidID"`
  1819. MyMaxPrice string `csv:"MyMaxPrice"`
  1820. MarketPrice string `csv:"MarketPrice"`
  1821. Charge string `csv:"Charge"`
  1822. Version string `csv:"Version"`
  1823. }
  1824. type fnames []*string
  1825. func (f fnames) Len() int {
  1826. return len(f)
  1827. }
  1828. func (f fnames) Swap(i, j int) {
  1829. f[i], f[j] = f[j], f[i]
  1830. }
  1831. func (f fnames) Less(i, j int) bool {
  1832. key1 := strings.Split(*f[i], ".")
  1833. key2 := strings.Split(*f[j], ".")
  1834. t1, err := time.Parse("2006-01-02-15", key1[1])
  1835. if err != nil {
  1836. klog.V(1).Info("Unable to parse timestamp" + key1[1])
  1837. return false
  1838. }
  1839. t2, err := time.Parse("2006-01-02-15", key2[1])
  1840. if err != nil {
  1841. klog.V(1).Info("Unable to parse timestamp" + key2[1])
  1842. return false
  1843. }
  1844. return t1.Before(t2)
  1845. }
  1846. func (a *AWS) parseSpotData(bucket string, prefix string, projectID string, region string) (map[string]*spotInfo, error) {
  1847. if a.ServiceAccountChecks == nil { // Set up checks to store error/success states
  1848. a.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  1849. }
  1850. a.ConfigureAuth() // configure aws api authentication by setting env vars
  1851. s3Prefix := projectID
  1852. if len(prefix) != 0 {
  1853. s3Prefix = prefix + "/" + s3Prefix
  1854. }
  1855. c := aws.NewConfig().WithRegion(region)
  1856. s := session.Must(session.NewSession(c))
  1857. s3Svc := s3.New(s)
  1858. downloader := s3manager.NewDownloaderWithClient(s3Svc)
  1859. tNow := time.Now()
  1860. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1861. ls := &s3.ListObjectsInput{
  1862. Bucket: aws.String(bucket),
  1863. Prefix: aws.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1864. }
  1865. ls2 := &s3.ListObjectsInput{
  1866. Bucket: aws.String(bucket),
  1867. Prefix: aws.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1868. }
  1869. lso, err := s3Svc.ListObjects(ls)
  1870. if err != nil {
  1871. a.ServiceAccountChecks["bucketList"] = &ServiceAccountCheck{
  1872. Message: "Bucket List Permissions Available",
  1873. Status: false,
  1874. AdditionalInfo: err.Error(),
  1875. }
  1876. return nil, err
  1877. } else {
  1878. a.ServiceAccountChecks["bucketList"] = &ServiceAccountCheck{
  1879. Message: "Bucket List Permissions Available",
  1880. Status: true,
  1881. }
  1882. }
  1883. lsoLen := len(lso.Contents)
  1884. klog.V(2).Infof("Found %d spot data files from yesterday", lsoLen)
  1885. if lsoLen == 0 {
  1886. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1887. }
  1888. lso2, err := s3Svc.ListObjects(ls2)
  1889. if err != nil {
  1890. return nil, err
  1891. }
  1892. lso2Len := len(lso2.Contents)
  1893. klog.V(2).Infof("Found %d spot data files from today", lso2Len)
  1894. if lso2Len == 0 {
  1895. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1896. }
  1897. // TODO: Worth it to use LastModifiedDate to determine if we should reparse the spot data?
  1898. var keys []*string
  1899. for _, obj := range lso.Contents {
  1900. keys = append(keys, obj.Key)
  1901. }
  1902. for _, obj := range lso2.Contents {
  1903. keys = append(keys, obj.Key)
  1904. }
  1905. versionRx := regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  1906. header, err := csvutil.Header(spotInfo{}, "csv")
  1907. if err != nil {
  1908. return nil, err
  1909. }
  1910. fieldsPerRecord := len(header)
  1911. spots := make(map[string]*spotInfo)
  1912. for _, key := range keys {
  1913. getObj := &s3.GetObjectInput{
  1914. Bucket: aws.String(bucket),
  1915. Key: key,
  1916. }
  1917. buf := aws.NewWriteAtBuffer([]byte{})
  1918. _, err := downloader.Download(buf, getObj)
  1919. if err != nil {
  1920. a.ServiceAccountChecks["objectList"] = &ServiceAccountCheck{
  1921. Message: "Object Get Permissions Available",
  1922. Status: false,
  1923. AdditionalInfo: err.Error(),
  1924. }
  1925. return nil, err
  1926. } else {
  1927. a.ServiceAccountChecks["objectList"] = &ServiceAccountCheck{
  1928. Message: "Object Get Permissions Available",
  1929. Status: true,
  1930. }
  1931. }
  1932. r := bytes.NewReader(buf.Bytes())
  1933. gr, err := gzip.NewReader(r)
  1934. if err != nil {
  1935. return nil, err
  1936. }
  1937. csvReader := csv.NewReader(gr)
  1938. csvReader.Comma = '\t'
  1939. csvReader.FieldsPerRecord = fieldsPerRecord
  1940. dec, err := csvutil.NewDecoder(csvReader, header...)
  1941. if err != nil {
  1942. return nil, err
  1943. }
  1944. var foundVersion string
  1945. for {
  1946. spot := spotInfo{}
  1947. err := dec.Decode(&spot)
  1948. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1949. if err == io.EOF {
  1950. break
  1951. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1952. rec := dec.Record()
  1953. // the first two "Record()" will be the comment lines
  1954. // and they show up as len() == 1
  1955. // the first of which is "#Version"
  1956. // the second of which is "#Fields: "
  1957. if len(rec) != 1 {
  1958. klog.V(2).Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1959. continue
  1960. }
  1961. if len(foundVersion) == 0 {
  1962. spotFeedVersion := rec[0]
  1963. klog.V(4).Infof("Spot feed version is \"%s\"", spotFeedVersion)
  1964. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  1965. if matches != nil {
  1966. foundVersion = matches[1]
  1967. if foundVersion != supportedSpotFeedVersion {
  1968. klog.V(2).Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  1969. break
  1970. }
  1971. }
  1972. continue
  1973. } else if strings.Index(rec[0], "#") == 0 {
  1974. continue
  1975. } else {
  1976. klog.V(3).Infof("skipping non-TSV line: %s", rec)
  1977. continue
  1978. }
  1979. } else if err != nil {
  1980. klog.V(2).Infof("Error during spot info decode: %+v", err)
  1981. continue
  1982. }
  1983. log.DedupedInfof(5, "Found spot info for: %s", spot.InstanceID)
  1984. spots[spot.InstanceID] = &spot
  1985. }
  1986. gr.Close()
  1987. }
  1988. return spots, nil
  1989. }
  1990. func (a *AWS) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1991. }
  1992. func (a *AWS) ServiceAccountStatus() *ServiceAccountStatus {
  1993. checks := []*ServiceAccountCheck{}
  1994. for _, v := range a.ServiceAccountChecks {
  1995. checks = append(checks, v)
  1996. }
  1997. return &ServiceAccountStatus{
  1998. Checks: checks,
  1999. }
  2000. }
  2001. func (aws *AWS) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  2002. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  2003. }
  2004. func (aws *AWS) ParseID(id string) string {
  2005. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  2006. rx := regexp.MustCompile("aws://[^/]*/[^/]*/([^/]+)")
  2007. match := rx.FindStringSubmatch(id)
  2008. if len(match) < 2 {
  2009. if id != "" {
  2010. log.Infof("awsprovider.ParseID: failed to parse %s", id)
  2011. }
  2012. return id
  2013. }
  2014. return match[1]
  2015. }
  2016. func (aws *AWS) ParsePVID(id string) string {
  2017. rx := regexp.MustCompile("aws:/[^/]*/[^/]*/([^/]+)") // Capture "vol-0fc54c5e83b8d2b76" from "aws://us-east-2a/vol-0fc54c5e83b8d2b76"
  2018. match := rx.FindStringSubmatch(id)
  2019. if len(match) < 2 {
  2020. if id != "" {
  2021. log.Infof("awsprovider.ParseID: failed to parse %s", id)
  2022. }
  2023. return id
  2024. }
  2025. return match[1]
  2026. }