awsprovider.go 65 KB

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