awsprovider.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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. "net/url"
  12. "os"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "k8s.io/klog"
  19. "github.com/aws/aws-sdk-go/aws"
  20. "github.com/aws/aws-sdk-go/aws/awserr"
  21. "github.com/aws/aws-sdk-go/aws/session"
  22. "github.com/aws/aws-sdk-go/service/athena"
  23. "github.com/aws/aws-sdk-go/service/ec2"
  24. "github.com/aws/aws-sdk-go/service/s3"
  25. "github.com/aws/aws-sdk-go/service/s3/s3manager"
  26. "github.com/jszwec/csvutil"
  27. v1 "k8s.io/api/core/v1"
  28. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  29. "k8s.io/client-go/kubernetes"
  30. )
  31. const awsAccessKeyIDEnvVar = "AWS_ACCESS_KEY_ID"
  32. const awsAccessKeySecretEnvVar = "AWS_SECRET_ACCESS_KEY"
  33. const supportedSpotFeedVersion = "1"
  34. const SpotInfoUpdateType = "spotinfo"
  35. const AthenaInfoUpdateType = "athenainfo"
  36. // AWS represents an Amazon Provider
  37. type AWS struct {
  38. Pricing map[string]*AWSProductTerms
  39. SpotPricingByInstanceID map[string]*spotInfo
  40. ValidPricingKeys map[string]bool
  41. Clientset *kubernetes.Clientset
  42. BaseCPUPrice string
  43. BaseRAMPrice string
  44. BaseGPUPrice string
  45. BaseSpotCPUPrice string
  46. BaseSpotRAMPrice string
  47. SpotLabelName string
  48. SpotLabelValue string
  49. ServiceKeyName string
  50. ServiceKeySecret string
  51. SpotDataRegion string
  52. SpotDataBucket string
  53. SpotDataPrefix string
  54. ProjectID string
  55. DownloadPricingDataLock sync.RWMutex
  56. *CustomProvider
  57. }
  58. // AWSPricing maps a k8s node to an AWS Pricing "product"
  59. type AWSPricing struct {
  60. Products map[string]*AWSProduct `json:"products"`
  61. Terms AWSPricingTerms `json:"terms"`
  62. }
  63. // AWSProduct represents a purchased SKU
  64. type AWSProduct struct {
  65. Sku string `json:"sku"`
  66. Attributes AWSProductAttributes `json:"attributes"`
  67. }
  68. // AWSProductAttributes represents metadata about the product used to map to a node.
  69. type AWSProductAttributes struct {
  70. Location string `json:"location"`
  71. InstanceType string `json:"instanceType"`
  72. Memory string `json:"memory"`
  73. Storage string `json:"storage"`
  74. VCpu string `json:"vcpu"`
  75. UsageType string `json:"usagetype"`
  76. OperatingSystem string `json:"operatingSystem"`
  77. PreInstalledSw string `json:"preInstalledSw"`
  78. InstanceFamily string `json:"instanceFamily"`
  79. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  80. }
  81. // AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
  82. type AWSPricingTerms struct {
  83. OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
  84. Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
  85. }
  86. // AWSOfferTerm is a sku extension used to pay for the node.
  87. type AWSOfferTerm struct {
  88. Sku string `json:"sku"`
  89. PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
  90. }
  91. // AWSRateCode encodes data about the price of a product
  92. type AWSRateCode struct {
  93. Unit string `json:"unit"`
  94. PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
  95. }
  96. // AWSCurrencyCode is the localized currency. (TODO: support non-USD)
  97. type AWSCurrencyCode struct {
  98. USD string `json:"USD"`
  99. }
  100. // AWSProductTerms represents the full terms of the product
  101. type AWSProductTerms struct {
  102. Sku string `json:"sku"`
  103. OnDemand *AWSOfferTerm `json:"OnDemand"`
  104. Reserved *AWSOfferTerm `json:"Reserved"`
  105. Memory string `json:"memory"`
  106. Storage string `json:"storage"`
  107. VCpu string `json:"vcpu"`
  108. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  109. PV *PV `json:"pv"`
  110. }
  111. // ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
  112. const ClusterIdEnvVar = "AWS_CLUSTER_ID"
  113. // OnDemandRateCode is appended to an node sku
  114. const OnDemandRateCode = ".JRTCKXETXF"
  115. // ReservedRateCode is appended to a node sku
  116. const ReservedRateCode = ".38NPMPTW36"
  117. // HourlyRateCode is appended to a node sku
  118. const HourlyRateCode = ".6YS6EN2CT7"
  119. // volTypes are used to map between AWS UsageTypes and
  120. // EBS volume types, as they would appear in K8s storage class
  121. // name and the EC2 API.
  122. var volTypes = map[string]string{
  123. "EBS:VolumeUsage.gp2": "gp2",
  124. "EBS:VolumeUsage": "standard",
  125. "EBS:VolumeUsage.sc1": "sc1",
  126. "EBS:VolumeP-IOPS.piops": "io1",
  127. "EBS:VolumeUsage.st1": "st1",
  128. "EBS:VolumeUsage.piops": "io1",
  129. "gp2": "EBS:VolumeUsage.gp2",
  130. "standard": "EBS:VolumeUsage",
  131. "sc1": "EBS:VolumeUsage.sc1",
  132. "io1": "EBS:VolumeUsage.piops",
  133. "st1": "EBS:VolumeUsage.st1",
  134. }
  135. // locationToRegion maps AWS region names (As they come from Billing)
  136. // to actual region identifiers
  137. var locationToRegion = map[string]string{
  138. "US East (Ohio)": "us-east-2",
  139. "US East (N. Virginia)": "us-east-1",
  140. "US West (N. California)": "us-west-1",
  141. "US West (Oregon)": "us-west-2",
  142. "Asia Pacific (Hong Kong)": "ap-east-1",
  143. "Asia Pacific (Mumbai)": "ap-south-1",
  144. "Asia Pacific (Osaka-Local)": "ap-northeast-3",
  145. "Asia Pacific (Seoul)": "ap-northeast-2",
  146. "Asia Pacific (Singapore)": "ap-southeast-1",
  147. "Asia Pacific (Sydney)": "ap-southeast-2",
  148. "Asia Pacific (Tokyo)": "ap-northeast-1",
  149. "Canada (Central)": "ca-central-1",
  150. "China (Beijing)": "cn-north-1",
  151. "China (Ningxia)": "cn-northwest-1",
  152. "EU (Frankfurt)": "eu-central-1",
  153. "EU (Ireland)": "eu-west-1",
  154. "EU (London)": "eu-west-2",
  155. "EU (Paris)": "eu-west-3",
  156. "EU (Stockholm)": "eu-north-1",
  157. "South America (Sao Paulo)": "sa-east-1",
  158. "AWS GovCloud (US-East)": "us-gov-east-1",
  159. "AWS GovCloud (US)": "us-gov-west-1",
  160. }
  161. var regionToBillingRegionCode = map[string]string{
  162. "us-east-2": "USE2",
  163. "us-east-1": "",
  164. "us-west-1": "USW1",
  165. "us-west-2": "USW2",
  166. "ap-east-1": "APE1",
  167. "ap-south-1": "APS3",
  168. "ap-northeast-3": "APN3",
  169. "ap-northeast-2": "APN2",
  170. "ap-southeast-1": "APS1",
  171. "ap-southeast-2": "APS2",
  172. "ap-northeast-1": "APN1",
  173. "ca-central-1": "CAN1",
  174. "cn-north-1": "",
  175. "cn-northwest-1": "",
  176. "eu-central-1": "EUC1",
  177. "eu-west-1": "EU",
  178. "eu-west-2": "EUW2",
  179. "eu-west-3": "EUW3",
  180. "eu-north-1": "EUN1",
  181. "sa-east-1": "SAE1",
  182. "us-gov-east-1": "UGE1",
  183. "us-gov-west-1": "UGW1",
  184. }
  185. func (aws *AWS) GetLocalStorageQuery() (string, error) {
  186. return "", nil
  187. }
  188. // KubeAttrConversion maps the k8s labels for region to an aws region
  189. func (aws *AWS) KubeAttrConversion(location, instanceType, operatingSystem string) string {
  190. operatingSystem = strings.ToLower(operatingSystem)
  191. region := locationToRegion[location]
  192. return region + "," + instanceType + "," + operatingSystem
  193. }
  194. type AwsSpotFeedInfo struct {
  195. BucketName string `json:"bucketName"`
  196. Prefix string `json:"prefix"`
  197. Region string `json:"region"`
  198. AccountID string `json:"projectID"`
  199. ServiceKeyName string `json:"serviceKeyName"`
  200. ServiceKeySecret string `json:"serviceKeySecret"`
  201. SpotLabel string `json:"spotLabel"`
  202. SpotLabelValue string `json:"spotLabelValue"`
  203. }
  204. type AwsAthenaInfo struct {
  205. AthenaBucketName string `json:"athenaBucketName"`
  206. AthenaRegion string `json:"athenaRegion"`
  207. AthenaDatabase string `json:"athenaDatabase"`
  208. AthenaTable string `json:"athenaTable"`
  209. ServiceKeyName string `json:"serviceKeyName"`
  210. ServiceKeySecret string `json:"serviceKeySecret"`
  211. AccountID string `json:"projectID"`
  212. }
  213. func (aws *AWS) GetManagementPlatform() (string, error) {
  214. nodes, err := aws.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  215. if err != nil {
  216. return "", err
  217. }
  218. if len(nodes.Items) > 0 {
  219. n := nodes.Items[0]
  220. version := n.Status.NodeInfo.KubeletVersion
  221. if strings.Contains(version, "eks") {
  222. return "eks", nil
  223. }
  224. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  225. return "kops", nil
  226. }
  227. }
  228. return "", nil
  229. }
  230. func (aws *AWS) GetConfig() (*CustomPricing, error) {
  231. c, err := GetDefaultPricingData("aws.json")
  232. if c.Discount == "" {
  233. c.Discount = "0%"
  234. }
  235. if err != nil {
  236. return nil, err
  237. }
  238. return c, nil
  239. }
  240. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  241. c, err := GetDefaultPricingData("aws.json")
  242. if err != nil {
  243. return nil, err
  244. }
  245. if updateType == SpotInfoUpdateType {
  246. a := AwsSpotFeedInfo{}
  247. err := json.NewDecoder(r).Decode(&a)
  248. if err != nil {
  249. return nil, err
  250. }
  251. if err != nil {
  252. return nil, err
  253. }
  254. c.ServiceKeyName = a.ServiceKeyName
  255. c.ServiceKeySecret = a.ServiceKeySecret
  256. c.SpotDataPrefix = a.Prefix
  257. c.SpotDataBucket = a.BucketName
  258. c.ProjectID = a.AccountID
  259. c.SpotDataRegion = a.Region
  260. c.SpotLabel = a.SpotLabel
  261. c.SpotLabelValue = a.SpotLabelValue
  262. } else if updateType == AthenaInfoUpdateType {
  263. a := AwsAthenaInfo{}
  264. err := json.NewDecoder(r).Decode(&a)
  265. if err != nil {
  266. return nil, err
  267. }
  268. c.AthenaBucketName = a.AthenaBucketName
  269. c.AthenaRegion = a.AthenaRegion
  270. c.AthenaDatabase = a.AthenaDatabase
  271. c.AthenaTable = a.AthenaTable
  272. c.ServiceKeyName = a.ServiceKeyName
  273. c.ServiceKeySecret = a.ServiceKeySecret
  274. c.ProjectID = a.AccountID
  275. } else {
  276. a := make(map[string]string)
  277. err = json.NewDecoder(r).Decode(&a)
  278. if err != nil {
  279. return nil, err
  280. }
  281. for k, v := range a {
  282. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  283. err := SetCustomPricingField(c, kUpper, v)
  284. if err != nil {
  285. return nil, err
  286. }
  287. }
  288. }
  289. cj, err := json.Marshal(c)
  290. if err != nil {
  291. return nil, err
  292. }
  293. path := os.Getenv("CONFIG_PATH")
  294. if path == "" {
  295. path = "/models/"
  296. }
  297. path += "aws.json"
  298. remoteEnabled := os.Getenv(remoteEnabled)
  299. if remoteEnabled == "true" {
  300. err = UpdateClusterMeta(os.Getenv(KC_CLUSTER_ID), c.ClusterName)
  301. if err != nil {
  302. return nil, err
  303. }
  304. }
  305. err = ioutil.WriteFile(path, cj, 0644)
  306. if err != nil {
  307. return nil, err
  308. }
  309. return c, nil
  310. }
  311. type awsKey struct {
  312. SpotLabelName string
  313. SpotLabelValue string
  314. Labels map[string]string
  315. ProviderID string
  316. }
  317. func (k *awsKey) GPUType() string {
  318. return ""
  319. }
  320. func (k *awsKey) ID() string {
  321. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)") // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  322. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  323. if matchNum == 2 {
  324. return group
  325. }
  326. }
  327. klog.V(3).Infof("Could not find instance ID in \"%s\"", k.ProviderID)
  328. return ""
  329. }
  330. func (k *awsKey) Features() string {
  331. instanceType := k.Labels[v1.LabelInstanceType]
  332. var operatingSystem string
  333. operatingSystem, ok := k.Labels[v1.LabelOSStable]
  334. if !ok {
  335. operatingSystem = k.Labels["beta.kubernetes.io/os"]
  336. }
  337. region := k.Labels[v1.LabelZoneRegion]
  338. key := region + "," + instanceType + "," + operatingSystem
  339. usageType := "preemptible"
  340. spotKey := key + "," + usageType
  341. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  342. return spotKey
  343. }
  344. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  345. return spotKey
  346. }
  347. return key
  348. }
  349. func (aws *AWS) PVPricing(pvk PVKey) (*PV, error) {
  350. pricing, ok := aws.Pricing[pvk.Features()]
  351. if !ok {
  352. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  353. return &PV{}, nil
  354. }
  355. return pricing.PV, nil
  356. }
  357. type awsPVKey struct {
  358. Labels map[string]string
  359. StorageClassParameters map[string]string
  360. StorageClassName string
  361. Name string
  362. }
  363. func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  364. return &awsPVKey{
  365. Labels: pv.Labels,
  366. StorageClassName: pv.Spec.StorageClassName,
  367. StorageClassParameters: parameters,
  368. Name: pv.Name,
  369. }
  370. }
  371. func (key *awsPVKey) GetStorageClass() string {
  372. return key.StorageClassName
  373. }
  374. func (key *awsPVKey) Features() string {
  375. storageClass := key.StorageClassParameters["type"]
  376. if storageClass == "standard" {
  377. storageClass = "gp2"
  378. }
  379. // Storage class names are generally EBS volume types (gp2)
  380. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  381. // Converts between the 2
  382. region := key.Labels[v1.LabelZoneRegion]
  383. //if region == "" {
  384. // region = "us-east-1"
  385. //}
  386. class, ok := volTypes[storageClass]
  387. if !ok {
  388. klog.Infof("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  389. }
  390. return region + "," + class
  391. }
  392. // GetKey maps node labels to information needed to retrieve pricing data
  393. func (aws *AWS) GetKey(labels map[string]string) Key {
  394. return &awsKey{
  395. SpotLabelName: aws.SpotLabelName,
  396. SpotLabelValue: aws.SpotLabelValue,
  397. Labels: labels,
  398. ProviderID: labels["providerID"],
  399. }
  400. }
  401. func (aws *AWS) isPreemptible(key string) bool {
  402. s := strings.Split(key, ",")
  403. if len(s) == 4 && s[3] == "preemptible" {
  404. return true
  405. }
  406. return false
  407. }
  408. // DownloadPricingData fetches data from the AWS Pricing API
  409. func (aws *AWS) DownloadPricingData() error {
  410. aws.DownloadPricingDataLock.Lock()
  411. defer aws.DownloadPricingDataLock.Unlock()
  412. c, err := GetDefaultPricingData("aws.json")
  413. if err != nil {
  414. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  415. }
  416. aws.BaseCPUPrice = c.CPU
  417. aws.BaseRAMPrice = c.RAM
  418. aws.BaseGPUPrice = c.GPU
  419. aws.BaseSpotCPUPrice = c.SpotCPU
  420. aws.BaseSpotRAMPrice = c.SpotRAM
  421. aws.SpotLabelName = c.SpotLabel
  422. aws.SpotLabelValue = c.SpotLabelValue
  423. aws.SpotDataBucket = c.SpotDataBucket
  424. aws.SpotDataPrefix = c.SpotDataPrefix
  425. aws.ProjectID = c.ProjectID
  426. aws.SpotDataRegion = c.SpotDataRegion
  427. aws.ServiceKeyName = c.ServiceKeyName
  428. aws.ServiceKeySecret = c.ServiceKeySecret
  429. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  430. klog.V(1).Infof("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  431. }
  432. nodeList, err := aws.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  433. if err != nil {
  434. return err
  435. }
  436. inputkeys := make(map[string]bool)
  437. for _, n := range nodeList.Items {
  438. labels := n.GetObjectMeta().GetLabels()
  439. key := aws.GetKey(labels)
  440. inputkeys[key.Features()] = true
  441. }
  442. pvList, err := aws.Clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  443. if err != nil {
  444. return err
  445. }
  446. storageClasses, err := aws.Clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  447. storageClassMap := make(map[string]map[string]string)
  448. for _, storageClass := range storageClasses.Items {
  449. params := storageClass.Parameters
  450. storageClassMap[storageClass.ObjectMeta.Name] = params
  451. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  452. storageClassMap["default"] = params
  453. storageClassMap[""] = params
  454. }
  455. }
  456. pvkeys := make(map[string]PVKey)
  457. for _, pv := range pvList.Items {
  458. params, ok := storageClassMap[pv.Spec.StorageClassName]
  459. if !ok {
  460. klog.V(2).Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  461. continue
  462. }
  463. key := aws.GetPVKey(&pv, params)
  464. pvkeys[key.Features()] = key
  465. }
  466. aws.Pricing = make(map[string]*AWSProductTerms)
  467. aws.ValidPricingKeys = make(map[string]bool)
  468. skusToKeys := make(map[string]string)
  469. pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json"
  470. klog.V(2).Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  471. resp, err := http.Get(pricingURL)
  472. if err != nil {
  473. klog.V(2).Infof("Bogus fetch of \"%s\": %v", pricingURL, err)
  474. return err
  475. }
  476. klog.V(2).Infof("Finished downloading \"%s\"", pricingURL)
  477. dec := json.NewDecoder(resp.Body)
  478. for {
  479. t, err := dec.Token()
  480. if err == io.EOF {
  481. klog.V(2).Infof("done loading \"%s\"\n", pricingURL)
  482. break
  483. }
  484. if t == "products" {
  485. _, err := dec.Token() // this should parse the opening "{""
  486. if err != nil {
  487. return err
  488. }
  489. for dec.More() {
  490. _, err := dec.Token() // the sku token
  491. if err != nil {
  492. return err
  493. }
  494. product := &AWSProduct{}
  495. err = dec.Decode(&product)
  496. if err != nil {
  497. klog.V(1).Infof("Error parsing response from \"%s\": %v", pricingURL, err.Error())
  498. break
  499. }
  500. if product.Attributes.PreInstalledSw == "NA" &&
  501. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) {
  502. key := aws.KubeAttrConversion(product.Attributes.Location, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  503. spotKey := key + ",preemptible"
  504. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  505. productTerms := &AWSProductTerms{
  506. Sku: product.Sku,
  507. Memory: product.Attributes.Memory,
  508. Storage: product.Attributes.Storage,
  509. VCpu: product.Attributes.VCpu,
  510. GPU: product.Attributes.GPU,
  511. }
  512. aws.Pricing[key] = productTerms
  513. aws.Pricing[spotKey] = productTerms
  514. skusToKeys[product.Sku] = key
  515. }
  516. aws.ValidPricingKeys[key] = true
  517. aws.ValidPricingKeys[spotKey] = true
  518. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  519. // UsageTypes may be prefixed with a region code - we're removing this when using
  520. // volTypes to keep lookups generic
  521. usageTypeRegx := regexp.MustCompile(".*(-|^)(EBS.+)")
  522. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  523. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  524. key := locationToRegion[product.Attributes.Location] + "," + usageTypeNoRegion
  525. spotKey := key + ",preemptible"
  526. pv := &PV{
  527. Class: volTypes[usageTypeNoRegion],
  528. Region: locationToRegion[product.Attributes.Location],
  529. }
  530. productTerms := &AWSProductTerms{
  531. Sku: product.Sku,
  532. PV: pv,
  533. }
  534. aws.Pricing[key] = productTerms
  535. aws.Pricing[spotKey] = productTerms
  536. skusToKeys[product.Sku] = key
  537. aws.ValidPricingKeys[key] = true
  538. aws.ValidPricingKeys[spotKey] = true
  539. }
  540. }
  541. }
  542. if t == "terms" {
  543. _, err := dec.Token() // this should parse the opening "{""
  544. if err != nil {
  545. return err
  546. }
  547. termType, err := dec.Token()
  548. if err != nil {
  549. return err
  550. }
  551. if termType == "OnDemand" {
  552. _, err := dec.Token()
  553. if err != nil { // again, should parse an opening "{"
  554. return err
  555. }
  556. for dec.More() {
  557. sku, err := dec.Token()
  558. if err != nil {
  559. return err
  560. }
  561. _, err = dec.Token() // another opening "{"
  562. if err != nil {
  563. return err
  564. }
  565. skuOnDemand, err := dec.Token()
  566. if err != nil {
  567. return err
  568. }
  569. offerTerm := &AWSOfferTerm{}
  570. err = dec.Decode(&offerTerm)
  571. if err != nil {
  572. klog.V(1).Infof("Error decoding AWS Offer Term: " + err.Error())
  573. }
  574. if sku.(string)+OnDemandRateCode == skuOnDemand {
  575. key, ok := skusToKeys[sku.(string)]
  576. spotKey := key + ",preemptible"
  577. if ok {
  578. aws.Pricing[key].OnDemand = offerTerm
  579. aws.Pricing[spotKey].OnDemand = offerTerm
  580. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  581. // If the specific UsageType is the per IO cost used on io1 volumes
  582. // we need to add the per IO cost to the io1 PV cost
  583. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  584. // Add the per IO cost to the PV object for the io1 volume type
  585. aws.Pricing[key].PV.CostPerIO = cost
  586. } else if strings.Contains(key, "EBS:Volume") {
  587. // If volume, we need to get hourly cost and add it to the PV object
  588. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  589. costFloat, _ := strconv.ParseFloat(cost, 64)
  590. hourlyPrice := costFloat / 730
  591. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  592. }
  593. }
  594. }
  595. _, err = dec.Token()
  596. if err != nil {
  597. return err
  598. }
  599. }
  600. _, err = dec.Token()
  601. if err != nil {
  602. return err
  603. }
  604. }
  605. }
  606. }
  607. sp, err := parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion, aws.ServiceKeyName, aws.ServiceKeySecret)
  608. if err != nil {
  609. klog.V(1).Infof("Skipping AWS spot data download: %s", err.Error())
  610. } else {
  611. aws.SpotPricingByInstanceID = sp
  612. }
  613. return nil
  614. }
  615. // AllNodePricing returns all the billing data fetched.
  616. func (aws *AWS) AllNodePricing() (interface{}, error) {
  617. aws.DownloadPricingDataLock.RLock()
  618. defer aws.DownloadPricingDataLock.RUnlock()
  619. return aws.Pricing, nil
  620. }
  621. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  622. key := k.Features()
  623. if aws.isPreemptible(key) {
  624. if spotInfo, ok := aws.SpotPricingByInstanceID[k.ID()]; ok { // try and match directly to an ID for pricing. We'll still need the features
  625. var spotcost string
  626. arr := strings.Split(spotInfo.Charge, " ")
  627. if len(arr) == 2 {
  628. spotcost = arr[0]
  629. } else {
  630. klog.V(2).Infof("Spot data for node %s is missing", k.ID())
  631. }
  632. klog.V(1).Infof("SPOT COST FOR %s: %s", k.Features, spotcost)
  633. return &Node{
  634. Cost: spotcost,
  635. VCPU: terms.VCpu,
  636. RAM: terms.Memory,
  637. GPU: terms.GPU,
  638. Storage: terms.Storage,
  639. BaseCPUPrice: aws.BaseCPUPrice,
  640. BaseRAMPrice: aws.BaseRAMPrice,
  641. BaseGPUPrice: aws.BaseGPUPrice,
  642. UsageType: usageType,
  643. }, nil
  644. }
  645. return &Node{
  646. VCPU: terms.VCpu,
  647. VCPUCost: aws.BaseSpotCPUPrice,
  648. RAM: terms.Memory,
  649. GPU: terms.GPU,
  650. RAMCost: aws.BaseSpotRAMPrice,
  651. Storage: terms.Storage,
  652. BaseCPUPrice: aws.BaseCPUPrice,
  653. BaseRAMPrice: aws.BaseRAMPrice,
  654. BaseGPUPrice: aws.BaseGPUPrice,
  655. UsageType: usageType,
  656. }, nil
  657. }
  658. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  659. if !ok {
  660. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  661. }
  662. cost := c.PricePerUnit.USD
  663. return &Node{
  664. Cost: cost,
  665. VCPU: terms.VCpu,
  666. RAM: terms.Memory,
  667. GPU: terms.GPU,
  668. Storage: terms.Storage,
  669. BaseCPUPrice: aws.BaseCPUPrice,
  670. BaseRAMPrice: aws.BaseRAMPrice,
  671. BaseGPUPrice: aws.BaseGPUPrice,
  672. UsageType: usageType,
  673. }, nil
  674. }
  675. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  676. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  677. aws.DownloadPricingDataLock.RLock()
  678. defer aws.DownloadPricingDataLock.RUnlock()
  679. key := k.Features()
  680. usageType := "ondemand"
  681. if aws.isPreemptible(key) {
  682. usageType = "preemptible"
  683. }
  684. terms, ok := aws.Pricing[key]
  685. if ok {
  686. return aws.createNode(terms, usageType, k)
  687. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  688. aws.DownloadPricingDataLock.RUnlock()
  689. err := aws.DownloadPricingData()
  690. aws.DownloadPricingDataLock.RLock()
  691. if err != nil {
  692. return &Node{
  693. Cost: aws.BaseCPUPrice,
  694. BaseCPUPrice: aws.BaseCPUPrice,
  695. BaseRAMPrice: aws.BaseRAMPrice,
  696. BaseGPUPrice: aws.BaseGPUPrice,
  697. UsageType: usageType,
  698. UsesBaseCPUPrice: true,
  699. }, err
  700. }
  701. terms, termsOk := aws.Pricing[key]
  702. if !termsOk {
  703. return &Node{
  704. Cost: aws.BaseCPUPrice,
  705. BaseCPUPrice: aws.BaseCPUPrice,
  706. BaseRAMPrice: aws.BaseRAMPrice,
  707. BaseGPUPrice: aws.BaseGPUPrice,
  708. UsageType: usageType,
  709. UsesBaseCPUPrice: true,
  710. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  711. }
  712. return aws.createNode(terms, usageType, k)
  713. } else { // Fall back to base pricing if we can't find the key.
  714. klog.V(1).Infof("Invalid Pricing Key \"%s\"", key)
  715. return &Node{
  716. Cost: aws.BaseCPUPrice,
  717. BaseCPUPrice: aws.BaseCPUPrice,
  718. BaseRAMPrice: aws.BaseRAMPrice,
  719. BaseGPUPrice: aws.BaseGPUPrice,
  720. UsageType: usageType,
  721. UsesBaseCPUPrice: true,
  722. }, nil
  723. }
  724. }
  725. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  726. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  727. defaultClusterName := "AWS Cluster #1"
  728. c, err := awsProvider.GetConfig()
  729. if c.ClusterName != "" {
  730. m := make(map[string]string)
  731. m["name"] = c.ClusterName
  732. m["provider"] = "AWS"
  733. return m, nil
  734. }
  735. makeStructure := func(clusterName string) (map[string]string, error) {
  736. klog.V(2).Infof("Returning \"%s\" as ClusterName", clusterName)
  737. m := make(map[string]string)
  738. m["name"] = clusterName
  739. m["provider"] = "AWS"
  740. m["id"] = os.Getenv(KC_CLUSTER_ID)
  741. return m, nil
  742. }
  743. maybeClusterId := os.Getenv(ClusterIdEnvVar)
  744. if len(maybeClusterId) != 0 {
  745. return makeStructure(maybeClusterId)
  746. }
  747. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  748. clusterIdRx := regexp.MustCompile("^kubernetes\\.io/cluster/([^/]+)")
  749. nodeList, err := awsProvider.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  750. if err != nil {
  751. return nil, err
  752. }
  753. for _, n := range nodeList.Items {
  754. region := ""
  755. instanceId := ""
  756. providerId := n.Spec.ProviderID
  757. for matchNum, group := range provIdRx.FindStringSubmatch(providerId) {
  758. if matchNum == 1 {
  759. region = group
  760. } else if matchNum == 2 {
  761. instanceId = group
  762. }
  763. }
  764. if len(instanceId) == 0 {
  765. klog.V(2).Infof("Unable to decode Node.ProviderID \"%s\", skipping it", providerId)
  766. continue
  767. }
  768. c := &aws.Config{
  769. Region: aws.String(region),
  770. }
  771. s := session.Must(session.NewSession(c))
  772. ec2Svc := ec2.New(s)
  773. di, diErr := ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{
  774. InstanceIds: []*string{
  775. aws.String(instanceId),
  776. },
  777. })
  778. if diErr != nil {
  779. // maybe log this?
  780. continue
  781. }
  782. if len(di.Reservations) != 1 {
  783. klog.V(2).Infof("Expected 1 Reservation back from DescribeInstances(%s), received %d", instanceId, len(di.Reservations))
  784. continue
  785. }
  786. res := di.Reservations[0]
  787. if len(res.Instances) != 1 {
  788. klog.V(2).Infof("Expected 1 Instance back from DescribeInstances(%s), received %d", instanceId, len(res.Instances))
  789. continue
  790. }
  791. inst := res.Instances[0]
  792. for _, tag := range inst.Tags {
  793. tagKey := *tag.Key
  794. for matchNum, group := range clusterIdRx.FindStringSubmatch(tagKey) {
  795. if matchNum != 1 {
  796. continue
  797. }
  798. return makeStructure(group)
  799. }
  800. }
  801. }
  802. klog.V(2).Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", ClusterIdEnvVar)
  803. return makeStructure(defaultClusterName)
  804. }
  805. // AddServiceKey adds an AWS service key, useful for pulling down out-of-cluster costs. Optional-- the container this runs in can be directly authorized.
  806. func (*AWS) AddServiceKey(formValues url.Values) error {
  807. keyID := formValues.Get("access_key_ID")
  808. key := formValues.Get("secret_access_key")
  809. m := make(map[string]string)
  810. m["access_key_ID"] = keyID
  811. m["secret_access_key"] = key
  812. result, err := json.Marshal(m)
  813. if err != nil {
  814. return err
  815. }
  816. return ioutil.WriteFile("/var/configs/key.json", result, 0644)
  817. }
  818. // 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.
  819. func (*AWS) GetDisks() ([]byte, error) {
  820. jsonFile, err := os.Open("/var/configs/key.json")
  821. if err == nil {
  822. byteValue, _ := ioutil.ReadAll(jsonFile)
  823. var result map[string]string
  824. err := json.Unmarshal([]byte(byteValue), &result)
  825. if err != nil {
  826. return nil, err
  827. }
  828. err = os.Setenv(awsAccessKeyIDEnvVar, result["access_key_ID"])
  829. if err != nil {
  830. return nil, err
  831. }
  832. err = os.Setenv(awsAccessKeySecretEnvVar, result["secret_access_key"])
  833. if err != nil {
  834. return nil, err
  835. }
  836. } else if os.IsNotExist(err) {
  837. klog.V(2).Infof("Using Default Credentials")
  838. } else {
  839. return nil, err
  840. }
  841. defer jsonFile.Close()
  842. clusterConfig, err := os.Open("/var/configs/cluster.json")
  843. if err != nil {
  844. return nil, err
  845. }
  846. defer clusterConfig.Close()
  847. b, err := ioutil.ReadAll(clusterConfig)
  848. if err != nil {
  849. return nil, err
  850. }
  851. var clusterConf map[string]string
  852. err = json.Unmarshal([]byte(b), &clusterConf)
  853. if err != nil {
  854. return nil, err
  855. }
  856. region := aws.String(clusterConf["region"])
  857. c := &aws.Config{
  858. Region: region,
  859. }
  860. s := session.Must(session.NewSession(c))
  861. ec2Svc := ec2.New(s)
  862. input := &ec2.DescribeVolumesInput{}
  863. volumeResult, err := ec2Svc.DescribeVolumes(input)
  864. if err != nil {
  865. if aerr, ok := err.(awserr.Error); ok {
  866. switch aerr.Code() {
  867. default:
  868. return nil, aerr
  869. }
  870. } else {
  871. return nil, err
  872. }
  873. }
  874. return json.Marshal(volumeResult)
  875. }
  876. // ConvertToGlueColumnFormat takes a string and runs through various regex
  877. // and string replacement statements to convert it to a format compatible
  878. // with AWS Glue and Athena column names.
  879. // Following guidance from AWS provided here ('Column Names' section):
  880. // https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/run-athena-sql.html
  881. // It returns a string containing the column name in proper column name format and length.
  882. func ConvertToGlueColumnFormat(column_name string) string {
  883. klog.V(5).Infof("Converting string \"%s\" to proper AWS Glue column name.", column_name)
  884. // An underscore is added in front of uppercase letters
  885. capital_underscore := regexp.MustCompile(`[A-Z]`)
  886. final := capital_underscore.ReplaceAllString(column_name, `_$0`)
  887. // Any non-alphanumeric characters are replaced with an underscore
  888. no_space_punc := regexp.MustCompile(`[\s]{1,}|[^A-Za-z0-9]`)
  889. final = no_space_punc.ReplaceAllString(final, "_")
  890. // Duplicate underscores are removed
  891. no_dup_underscore := regexp.MustCompile(`_{2,}`)
  892. final = no_dup_underscore.ReplaceAllString(final, "_")
  893. // Any leading and trailing underscores are removed
  894. no_front_end_underscore := regexp.MustCompile(`(^\_|\_$)`)
  895. final = no_front_end_underscore.ReplaceAllString(final, "")
  896. // Uppercase to lowercase
  897. final = strings.ToLower(final)
  898. // Longer column name than expected - remove _ left to right
  899. allowed_col_len := 128
  900. undersc_to_remove := len(final) - allowed_col_len
  901. if undersc_to_remove > 0 {
  902. final = strings.Replace(final, "_", "", undersc_to_remove)
  903. }
  904. // If removing all of the underscores still didn't
  905. // make the column name < 128 characters, trim it!
  906. if len(final) > allowed_col_len {
  907. final = final[:allowed_col_len]
  908. }
  909. klog.V(5).Infof("Column name being returned: \"%s\". Length: \"%d\".", final, len(final))
  910. return final
  911. }
  912. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  913. // "start" and "end" are dates of the format YYYY-MM-DD
  914. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  915. func (a *AWS) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  916. customPricing, err := a.GetConfig()
  917. if err != nil {
  918. return nil, err
  919. }
  920. aggregator_column_name := "resource_tags_user_kubernetes_" + aggregator
  921. aggregator_column_name = ConvertToGlueColumnFormat(aggregator_column_name)
  922. query := fmt.Sprintf(`SELECT
  923. CAST(line_item_usage_start_date AS DATE) as start_date,
  924. %s,
  925. line_item_product_code,
  926. SUM(line_item_blended_cost) as blended_cost
  927. FROM %s as cost_data
  928. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  929. GROUP BY 1,2,3`, aggregator_column_name, customPricing.AthenaTable, start, end)
  930. if customPricing.ServiceKeyName != "" {
  931. err = os.Setenv(awsAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  932. if err != nil {
  933. return nil, err
  934. }
  935. err = os.Setenv(awsAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  936. if err != nil {
  937. return nil, err
  938. }
  939. }
  940. region := aws.String(customPricing.AthenaRegion)
  941. resultsBucket := customPricing.AthenaBucketName
  942. database := customPricing.AthenaDatabase
  943. c := &aws.Config{
  944. Region: region,
  945. }
  946. s := session.Must(session.NewSession(c))
  947. svc := athena.New(s)
  948. var e athena.StartQueryExecutionInput
  949. var r athena.ResultConfiguration
  950. r.SetOutputLocation(resultsBucket)
  951. e.SetResultConfiguration(&r)
  952. e.SetQueryString(query)
  953. var q athena.QueryExecutionContext
  954. q.SetDatabase(database)
  955. e.SetQueryExecutionContext(&q)
  956. res, err := svc.StartQueryExecution(&e)
  957. if err != nil {
  958. return nil, err
  959. }
  960. klog.V(2).Infof("StartQueryExecution result:")
  961. klog.V(2).Infof(res.GoString())
  962. var qri athena.GetQueryExecutionInput
  963. qri.SetQueryExecutionId(*res.QueryExecutionId)
  964. var qrop *athena.GetQueryExecutionOutput
  965. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  966. for {
  967. qrop, err = svc.GetQueryExecution(&qri)
  968. if err != nil {
  969. return nil, err
  970. }
  971. if *qrop.QueryExecution.Status.State != "RUNNING" {
  972. break
  973. }
  974. time.Sleep(duration)
  975. }
  976. var oocAllocs []*OutOfClusterAllocation
  977. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  978. var ip athena.GetQueryResultsInput
  979. ip.SetQueryExecutionId(*res.QueryExecutionId)
  980. op, err := svc.GetQueryResults(&ip)
  981. if err != nil {
  982. return nil, err
  983. }
  984. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  985. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  986. if err != nil {
  987. return nil, err
  988. }
  989. ooc := &OutOfClusterAllocation{
  990. Aggregator: aggregator,
  991. Environment: *r.Data[1].VarCharValue,
  992. Service: *r.Data[2].VarCharValue,
  993. Cost: cost,
  994. }
  995. oocAllocs = append(oocAllocs, ooc)
  996. }
  997. }
  998. return oocAllocs, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  999. }
  1000. // QuerySQL can query a properly configured Athena database.
  1001. // Used to fetch billing data.
  1002. // Requires a json config in /var/configs with key region, output, and database.
  1003. func (a *AWS) QuerySQL(query string) ([]byte, error) {
  1004. customPricing, err := a.GetConfig()
  1005. if err != nil {
  1006. return nil, err
  1007. }
  1008. if customPricing.ServiceKeyName != "" {
  1009. err = os.Setenv(awsAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1010. if err != nil {
  1011. return nil, err
  1012. }
  1013. err = os.Setenv(awsAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. }
  1018. athenaConfigs, err := os.Open("/var/configs/athena.json")
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. defer athenaConfigs.Close()
  1023. b, err := ioutil.ReadAll(athenaConfigs)
  1024. if err != nil {
  1025. return nil, err
  1026. }
  1027. var athenaConf map[string]string
  1028. json.Unmarshal([]byte(b), &athenaConf)
  1029. region := aws.String(customPricing.AthenaRegion)
  1030. resultsBucket := customPricing.AthenaBucketName
  1031. database := customPricing.AthenaDatabase
  1032. c := &aws.Config{
  1033. Region: region,
  1034. }
  1035. s := session.Must(session.NewSession(c))
  1036. svc := athena.New(s)
  1037. var e athena.StartQueryExecutionInput
  1038. var r athena.ResultConfiguration
  1039. r.SetOutputLocation(resultsBucket)
  1040. e.SetResultConfiguration(&r)
  1041. e.SetQueryString(query)
  1042. var q athena.QueryExecutionContext
  1043. q.SetDatabase(database)
  1044. e.SetQueryExecutionContext(&q)
  1045. res, err := svc.StartQueryExecution(&e)
  1046. if err != nil {
  1047. return nil, err
  1048. }
  1049. klog.V(2).Infof("StartQueryExecution result:")
  1050. klog.V(2).Infof(res.GoString())
  1051. var qri athena.GetQueryExecutionInput
  1052. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1053. var qrop *athena.GetQueryExecutionOutput
  1054. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1055. for {
  1056. qrop, err = svc.GetQueryExecution(&qri)
  1057. if err != nil {
  1058. return nil, err
  1059. }
  1060. if *qrop.QueryExecution.Status.State != "RUNNING" {
  1061. break
  1062. }
  1063. time.Sleep(duration)
  1064. }
  1065. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1066. var ip athena.GetQueryResultsInput
  1067. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1068. op, err := svc.GetQueryResults(&ip)
  1069. if err != nil {
  1070. return nil, err
  1071. }
  1072. b, err := json.Marshal(op.ResultSet)
  1073. if err != nil {
  1074. return nil, err
  1075. }
  1076. return b, nil
  1077. }
  1078. return nil, fmt.Errorf("Error getting query results : %s", *qrop.QueryExecution.Status.State)
  1079. }
  1080. type spotInfo struct {
  1081. Timestamp string `csv:"Timestamp"`
  1082. UsageType string `csv:"UsageType"`
  1083. Operation string `csv:"Operation"`
  1084. InstanceID string `csv:"InstanceID"`
  1085. MyBidID string `csv:"MyBidID"`
  1086. MyMaxPrice string `csv:"MyMaxPrice"`
  1087. MarketPrice string `csv:"MarketPrice"`
  1088. Charge string `csv:"Charge"`
  1089. Version string `csv:"Version"`
  1090. }
  1091. type fnames []*string
  1092. func (f fnames) Len() int {
  1093. return len(f)
  1094. }
  1095. func (f fnames) Swap(i, j int) {
  1096. f[i], f[j] = f[j], f[i]
  1097. }
  1098. func (f fnames) Less(i, j int) bool {
  1099. key1 := strings.Split(*f[i], ".")
  1100. key2 := strings.Split(*f[j], ".")
  1101. t1, err := time.Parse("2006-01-02-15", key1[1])
  1102. if err != nil {
  1103. klog.V(1).Info("Unable to parse timestamp" + key1[1])
  1104. return false
  1105. }
  1106. t2, err := time.Parse("2006-01-02-15", key2[1])
  1107. if err != nil {
  1108. klog.V(1).Info("Unable to parse timestamp" + key2[1])
  1109. return false
  1110. }
  1111. return t1.Before(t2)
  1112. }
  1113. func parseSpotData(bucket string, prefix string, projectID string, region string, accessKeyID string, accessKeySecret string) (map[string]*spotInfo, error) {
  1114. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1115. err := os.Setenv(awsAccessKeyIDEnvVar, accessKeyID)
  1116. if err != nil {
  1117. return nil, err
  1118. }
  1119. err = os.Setenv(awsAccessKeySecretEnvVar, accessKeySecret)
  1120. if err != nil {
  1121. return nil, err
  1122. }
  1123. }
  1124. s3Prefix := projectID
  1125. if len(prefix) != 0 {
  1126. s3Prefix = prefix + "/" + s3Prefix
  1127. }
  1128. c := aws.NewConfig().WithRegion(region)
  1129. s := session.Must(session.NewSession(c))
  1130. s3Svc := s3.New(s)
  1131. downloader := s3manager.NewDownloaderWithClient(s3Svc)
  1132. tNow := time.Now()
  1133. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1134. ls := &s3.ListObjectsInput{
  1135. Bucket: aws.String(bucket),
  1136. Prefix: aws.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1137. }
  1138. ls2 := &s3.ListObjectsInput{
  1139. Bucket: aws.String(bucket),
  1140. Prefix: aws.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1141. }
  1142. lso, err := s3Svc.ListObjects(ls)
  1143. if err != nil {
  1144. return nil, err
  1145. }
  1146. lsoLen := len(lso.Contents)
  1147. klog.V(2).Infof("Found %d spot data files from yesterday", lsoLen)
  1148. if lsoLen == 0 {
  1149. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1150. }
  1151. lso2, err := s3Svc.ListObjects(ls2)
  1152. if err != nil {
  1153. return nil, err
  1154. }
  1155. lso2Len := len(lso2.Contents)
  1156. klog.V(2).Infof("Found %d spot data files from today", lso2Len)
  1157. if lso2Len == 0 {
  1158. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1159. }
  1160. var keys []*string
  1161. for _, obj := range lso.Contents {
  1162. keys = append(keys, obj.Key)
  1163. }
  1164. for _, obj := range lso2.Contents {
  1165. keys = append(keys, obj.Key)
  1166. }
  1167. versionRx := regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  1168. header, err := csvutil.Header(spotInfo{}, "csv")
  1169. if err != nil {
  1170. return nil, err
  1171. }
  1172. fieldsPerRecord := len(header)
  1173. spots := make(map[string]*spotInfo)
  1174. for _, key := range keys {
  1175. getObj := &s3.GetObjectInput{
  1176. Bucket: aws.String(bucket),
  1177. Key: key,
  1178. }
  1179. buf := aws.NewWriteAtBuffer([]byte{})
  1180. _, err := downloader.Download(buf, getObj)
  1181. if err != nil {
  1182. return nil, err
  1183. }
  1184. r := bytes.NewReader(buf.Bytes())
  1185. gr, err := gzip.NewReader(r)
  1186. if err != nil {
  1187. return nil, err
  1188. }
  1189. csvReader := csv.NewReader(gr)
  1190. csvReader.Comma = '\t'
  1191. csvReader.FieldsPerRecord = fieldsPerRecord
  1192. dec, err := csvutil.NewDecoder(csvReader, header...)
  1193. if err != nil {
  1194. return nil, err
  1195. }
  1196. var foundVersion string
  1197. for {
  1198. spot := spotInfo{}
  1199. err := dec.Decode(&spot)
  1200. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1201. if err == io.EOF {
  1202. break
  1203. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1204. rec := dec.Record()
  1205. // the first two "Record()" will be the comment lines
  1206. // and they show up as len() == 1
  1207. // the first of which is "#Version"
  1208. // the second of which is "#Fields: "
  1209. if len(rec) != 1 {
  1210. klog.V(2).Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1211. continue
  1212. }
  1213. if len(foundVersion) == 0 {
  1214. spotFeedVersion := rec[0]
  1215. klog.V(3).Infof("Spot feed version is \"%s\"", spotFeedVersion)
  1216. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  1217. if matches != nil {
  1218. foundVersion = matches[1]
  1219. if foundVersion != supportedSpotFeedVersion {
  1220. klog.V(2).Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  1221. break
  1222. }
  1223. }
  1224. continue
  1225. } else if strings.Index(rec[0], "#") == 0 {
  1226. continue
  1227. } else {
  1228. klog.V(3).Infof("skipping non-TSV line: %s", rec)
  1229. continue
  1230. }
  1231. } else if err != nil {
  1232. klog.V(2).Infof("Error during spot info decode: %+v", err)
  1233. continue
  1234. }
  1235. klog.V(3).Infof("Found spot info %+v", spot)
  1236. spots[spot.InstanceID] = &spot
  1237. }
  1238. gr.Close()
  1239. }
  1240. return spots, nil
  1241. }