awsprovider.go 68 KB

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