awsprovider.go 70 KB

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