awsprovider.go 68 KB

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