awsprovider.go 69 KB

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