awsprovider.go 70 KB

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