awsprovider.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  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. err = ioutil.WriteFile(path, cj, 0644)
  299. if err != nil {
  300. return nil, err
  301. }
  302. return c, nil
  303. }
  304. type awsKey struct {
  305. SpotLabelName string
  306. SpotLabelValue string
  307. Labels map[string]string
  308. ProviderID string
  309. }
  310. func (k *awsKey) GPUType() string {
  311. return ""
  312. }
  313. func (k *awsKey) ID() string {
  314. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)") // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  315. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  316. if matchNum == 2 {
  317. return group
  318. }
  319. }
  320. klog.V(3).Infof("Could not find instance ID in \"%s\"", k.ProviderID)
  321. return ""
  322. }
  323. func (k *awsKey) Features() string {
  324. instanceType := k.Labels[v1.LabelInstanceType]
  325. var operatingSystem string
  326. operatingSystem, ok := k.Labels[v1.LabelOSStable]
  327. if !ok {
  328. operatingSystem = k.Labels["beta.kubernetes.io/os"]
  329. }
  330. region := k.Labels[v1.LabelZoneRegion]
  331. key := region + "," + instanceType + "," + operatingSystem
  332. usageType := "preemptible"
  333. spotKey := key + "," + usageType
  334. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  335. return spotKey
  336. }
  337. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  338. return spotKey
  339. }
  340. return key
  341. }
  342. func (aws *AWS) PVPricing(pvk PVKey) (*PV, error) {
  343. if pvk.GetStorageClass() == "" {
  344. klog.V(3).Infof("Disk in %s does not have a storageclass set, cannot look up pricing info.", pvk.Features())
  345. return &PV{}, nil
  346. }
  347. pricing, ok := aws.Pricing[pvk.Features()]
  348. if !ok {
  349. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  350. return &PV{}, nil
  351. }
  352. return pricing.PV, nil
  353. }
  354. type awsPVKey struct {
  355. Labels map[string]string
  356. StorageClassParameters map[string]string
  357. StorageClassName string
  358. Name string
  359. }
  360. func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  361. return &awsPVKey{
  362. Labels: pv.Labels,
  363. StorageClassName: pv.Spec.StorageClassName,
  364. StorageClassParameters: parameters,
  365. Name: pv.Name,
  366. }
  367. }
  368. func (key *awsPVKey) GetStorageClass() string {
  369. return key.StorageClassName
  370. }
  371. func (key *awsPVKey) Features() string {
  372. storageClass := key.StorageClassParameters["type"]
  373. if storageClass == "standard" {
  374. storageClass = "gp2"
  375. }
  376. // Storage class names are generally EBS volume types (gp2)
  377. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  378. // Converts between the 2
  379. region := key.Labels[v1.LabelZoneRegion]
  380. //if region == "" {
  381. // region = "us-east-1"
  382. //}
  383. class, ok := volTypes[storageClass]
  384. if !ok {
  385. klog.Infof("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  386. }
  387. return region + "," + class
  388. }
  389. // GetKey maps node labels to information needed to retrieve pricing data
  390. func (aws *AWS) GetKey(labels map[string]string) Key {
  391. return &awsKey{
  392. SpotLabelName: aws.SpotLabelName,
  393. SpotLabelValue: aws.SpotLabelValue,
  394. Labels: labels,
  395. ProviderID: labels["providerID"],
  396. }
  397. }
  398. func (aws *AWS) isPreemptible(key string) bool {
  399. s := strings.Split(key, ",")
  400. if len(s) == 4 && s[3] == "preemptible" {
  401. return true
  402. }
  403. return false
  404. }
  405. // DownloadPricingData fetches data from the AWS Pricing API
  406. func (aws *AWS) DownloadPricingData() error {
  407. aws.DownloadPricingDataLock.Lock()
  408. defer aws.DownloadPricingDataLock.Unlock()
  409. c, err := GetDefaultPricingData("aws.json")
  410. if err != nil {
  411. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  412. }
  413. aws.BaseCPUPrice = c.CPU
  414. aws.BaseRAMPrice = c.RAM
  415. aws.BaseGPUPrice = c.GPU
  416. aws.BaseSpotCPUPrice = c.SpotCPU
  417. aws.BaseSpotRAMPrice = c.SpotRAM
  418. aws.SpotLabelName = c.SpotLabel
  419. aws.SpotLabelValue = c.SpotLabelValue
  420. aws.SpotDataBucket = c.SpotDataBucket
  421. aws.SpotDataPrefix = c.SpotDataPrefix
  422. aws.ProjectID = c.ProjectID
  423. aws.SpotDataRegion = c.SpotDataRegion
  424. aws.ServiceKeyName = c.ServiceKeyName
  425. aws.ServiceKeySecret = c.ServiceKeySecret
  426. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  427. klog.V(1).Infof("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  428. }
  429. nodeList, err := aws.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  430. if err != nil {
  431. return err
  432. }
  433. inputkeys := make(map[string]bool)
  434. for _, n := range nodeList.Items {
  435. labels := n.GetObjectMeta().GetLabels()
  436. key := aws.GetKey(labels)
  437. inputkeys[key.Features()] = true
  438. }
  439. pvList, err := aws.Clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  440. if err != nil {
  441. return err
  442. }
  443. storageClasses, err := aws.Clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  444. storageClassMap := make(map[string]map[string]string)
  445. for _, storageClass := range storageClasses.Items {
  446. params := storageClass.Parameters
  447. storageClassMap[storageClass.ObjectMeta.Name] = params
  448. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  449. storageClassMap["default"] = params
  450. }
  451. }
  452. pvkeys := make(map[string]PVKey)
  453. for _, pv := range pvList.Items {
  454. params, ok := storageClassMap[pv.Spec.StorageClassName]
  455. if !ok {
  456. klog.V(2).Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  457. continue
  458. }
  459. key := aws.GetPVKey(&pv, params)
  460. pvkeys[key.Features()] = key
  461. }
  462. aws.Pricing = make(map[string]*AWSProductTerms)
  463. aws.ValidPricingKeys = make(map[string]bool)
  464. skusToKeys := make(map[string]string)
  465. pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json"
  466. klog.V(2).Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  467. resp, err := http.Get(pricingURL)
  468. if err != nil {
  469. klog.V(2).Infof("Bogus fetch of \"%s\": %v", pricingURL, err)
  470. return err
  471. }
  472. klog.V(2).Infof("Finished downloading \"%s\"", pricingURL)
  473. dec := json.NewDecoder(resp.Body)
  474. for {
  475. t, err := dec.Token()
  476. if err == io.EOF {
  477. klog.V(2).Infof("done loading \"%s\"\n", pricingURL)
  478. break
  479. }
  480. if t == "products" {
  481. _, err := dec.Token() // this should parse the opening "{""
  482. if err != nil {
  483. return err
  484. }
  485. for dec.More() {
  486. _, err := dec.Token() // the sku token
  487. if err != nil {
  488. return err
  489. }
  490. product := &AWSProduct{}
  491. err = dec.Decode(&product)
  492. if err != nil {
  493. klog.V(1).Infof("Error parsing response from \"%s\": %v", pricingURL, err.Error())
  494. break
  495. }
  496. if product.Attributes.PreInstalledSw == "NA" &&
  497. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) {
  498. key := aws.KubeAttrConversion(product.Attributes.Location, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  499. spotKey := key + ",preemptible"
  500. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  501. productTerms := &AWSProductTerms{
  502. Sku: product.Sku,
  503. Memory: product.Attributes.Memory,
  504. Storage: product.Attributes.Storage,
  505. VCpu: product.Attributes.VCpu,
  506. GPU: product.Attributes.GPU,
  507. }
  508. aws.Pricing[key] = productTerms
  509. aws.Pricing[spotKey] = productTerms
  510. skusToKeys[product.Sku] = key
  511. }
  512. aws.ValidPricingKeys[key] = true
  513. aws.ValidPricingKeys[spotKey] = true
  514. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  515. // UsageTypes may be prefixed with a region code - we're removing this when using
  516. // volTypes to keep lookups generic
  517. usageTypeRegx := regexp.MustCompile(".*(-|^)(EBS.+)")
  518. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  519. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  520. key := locationToRegion[product.Attributes.Location] + "," + usageTypeNoRegion
  521. spotKey := key + ",preemptible"
  522. pv := &PV{
  523. Class: volTypes[usageTypeNoRegion],
  524. Region: locationToRegion[product.Attributes.Location],
  525. }
  526. productTerms := &AWSProductTerms{
  527. Sku: product.Sku,
  528. PV: pv,
  529. }
  530. aws.Pricing[key] = productTerms
  531. aws.Pricing[spotKey] = productTerms
  532. skusToKeys[product.Sku] = key
  533. aws.ValidPricingKeys[key] = true
  534. aws.ValidPricingKeys[spotKey] = true
  535. }
  536. }
  537. }
  538. if t == "terms" {
  539. _, err := dec.Token() // this should parse the opening "{""
  540. if err != nil {
  541. return err
  542. }
  543. termType, err := dec.Token()
  544. if err != nil {
  545. return err
  546. }
  547. if termType == "OnDemand" {
  548. _, err := dec.Token()
  549. if err != nil { // again, should parse an opening "{"
  550. return err
  551. }
  552. for dec.More() {
  553. sku, err := dec.Token()
  554. if err != nil {
  555. return err
  556. }
  557. _, err = dec.Token() // another opening "{"
  558. if err != nil {
  559. return err
  560. }
  561. skuOnDemand, err := dec.Token()
  562. if err != nil {
  563. return err
  564. }
  565. offerTerm := &AWSOfferTerm{}
  566. err = dec.Decode(&offerTerm)
  567. if err != nil {
  568. klog.V(1).Infof("Error decoding AWS Offer Term: " + err.Error())
  569. }
  570. if sku.(string)+OnDemandRateCode == skuOnDemand {
  571. key, ok := skusToKeys[sku.(string)]
  572. spotKey := key + ",preemptible"
  573. if ok {
  574. aws.Pricing[key].OnDemand = offerTerm
  575. aws.Pricing[spotKey].OnDemand = offerTerm
  576. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  577. // If the specific UsageType is the per IO cost used on io1 volumes
  578. // we need to add the per IO cost to the io1 PV cost
  579. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  580. // Add the per IO cost to the PV object for the io1 volume type
  581. aws.Pricing[key].PV.CostPerIO = cost
  582. } else if strings.Contains(key, "EBS:Volume") {
  583. // If volume, we need to get hourly cost and add it to the PV object
  584. cost := offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  585. costFloat, _ := strconv.ParseFloat(cost, 64)
  586. hourlyPrice := costFloat / 730
  587. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  588. }
  589. }
  590. }
  591. _, err = dec.Token()
  592. if err != nil {
  593. return err
  594. }
  595. }
  596. _, err = dec.Token()
  597. if err != nil {
  598. return err
  599. }
  600. }
  601. }
  602. }
  603. sp, err := parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion, aws.ServiceKeyName, aws.ServiceKeySecret)
  604. if err != nil {
  605. klog.V(1).Infof("Skipping AWS spot data download: %s", err.Error())
  606. } else {
  607. aws.SpotPricingByInstanceID = sp
  608. }
  609. return nil
  610. }
  611. // AllNodePricing returns all the billing data fetched.
  612. func (aws *AWS) AllNodePricing() (interface{}, error) {
  613. aws.DownloadPricingDataLock.RLock()
  614. defer aws.DownloadPricingDataLock.RUnlock()
  615. return aws.Pricing, nil
  616. }
  617. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  618. key := k.Features()
  619. if aws.isPreemptible(key) {
  620. if spotInfo, ok := aws.SpotPricingByInstanceID[k.ID()]; ok { // try and match directly to an ID for pricing. We'll still need the features
  621. var spotcost string
  622. arr := strings.Split(spotInfo.Charge, " ")
  623. if len(arr) == 2 {
  624. spotcost = arr[0]
  625. } else {
  626. klog.V(2).Infof("Spot data for node %s is missing", k.ID())
  627. }
  628. klog.V(1).Infof("SPOT COST FOR %s: %s", k.Features, spotcost)
  629. return &Node{
  630. Cost: spotcost,
  631. VCPU: terms.VCpu,
  632. RAM: terms.Memory,
  633. GPU: terms.GPU,
  634. Storage: terms.Storage,
  635. BaseCPUPrice: aws.BaseCPUPrice,
  636. BaseRAMPrice: aws.BaseRAMPrice,
  637. BaseGPUPrice: aws.BaseGPUPrice,
  638. UsageType: usageType,
  639. }, nil
  640. }
  641. return &Node{
  642. VCPU: terms.VCpu,
  643. VCPUCost: aws.BaseSpotCPUPrice,
  644. RAM: terms.Memory,
  645. GPU: terms.GPU,
  646. RAMCost: aws.BaseSpotRAMPrice,
  647. Storage: terms.Storage,
  648. BaseCPUPrice: aws.BaseCPUPrice,
  649. BaseRAMPrice: aws.BaseRAMPrice,
  650. BaseGPUPrice: aws.BaseGPUPrice,
  651. UsageType: usageType,
  652. }, nil
  653. }
  654. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  655. if !ok {
  656. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  657. }
  658. cost := c.PricePerUnit.USD
  659. return &Node{
  660. Cost: cost,
  661. VCPU: terms.VCpu,
  662. RAM: terms.Memory,
  663. GPU: terms.GPU,
  664. Storage: terms.Storage,
  665. BaseCPUPrice: aws.BaseCPUPrice,
  666. BaseRAMPrice: aws.BaseRAMPrice,
  667. BaseGPUPrice: aws.BaseGPUPrice,
  668. UsageType: usageType,
  669. }, nil
  670. }
  671. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  672. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  673. aws.DownloadPricingDataLock.RLock()
  674. defer aws.DownloadPricingDataLock.RUnlock()
  675. key := k.Features()
  676. usageType := "ondemand"
  677. if aws.isPreemptible(key) {
  678. usageType = "preemptible"
  679. }
  680. terms, ok := aws.Pricing[key]
  681. if ok {
  682. return aws.createNode(terms, usageType, k)
  683. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  684. aws.DownloadPricingDataLock.RUnlock()
  685. err := aws.DownloadPricingData()
  686. aws.DownloadPricingDataLock.RLock()
  687. if err != nil {
  688. return &Node{
  689. Cost: aws.BaseCPUPrice,
  690. BaseCPUPrice: aws.BaseCPUPrice,
  691. BaseRAMPrice: aws.BaseRAMPrice,
  692. BaseGPUPrice: aws.BaseGPUPrice,
  693. UsageType: usageType,
  694. UsesBaseCPUPrice: true,
  695. }, err
  696. }
  697. terms, termsOk := aws.Pricing[key]
  698. if !termsOk {
  699. return &Node{
  700. Cost: aws.BaseCPUPrice,
  701. BaseCPUPrice: aws.BaseCPUPrice,
  702. BaseRAMPrice: aws.BaseRAMPrice,
  703. BaseGPUPrice: aws.BaseGPUPrice,
  704. UsageType: usageType,
  705. UsesBaseCPUPrice: true,
  706. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  707. }
  708. return aws.createNode(terms, usageType, k)
  709. } else { // Fall back to base pricing if we can't find the key.
  710. klog.V(1).Infof("Invalid Pricing Key \"%s\"", key)
  711. return &Node{
  712. Cost: aws.BaseCPUPrice,
  713. BaseCPUPrice: aws.BaseCPUPrice,
  714. BaseRAMPrice: aws.BaseRAMPrice,
  715. BaseGPUPrice: aws.BaseGPUPrice,
  716. UsageType: usageType,
  717. UsesBaseCPUPrice: true,
  718. }, nil
  719. }
  720. }
  721. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  722. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  723. defaultClusterName := "AWS Cluster #1"
  724. c, err := awsProvider.GetConfig()
  725. if c.ClusterName != "" {
  726. m := make(map[string]string)
  727. m["name"] = c.ClusterName
  728. m["provider"] = "AWS"
  729. return m, nil
  730. }
  731. makeStructure := func(clusterName string) (map[string]string, error) {
  732. klog.V(2).Infof("Returning \"%s\" as ClusterName", clusterName)
  733. m := make(map[string]string)
  734. m["name"] = clusterName
  735. m["provider"] = "AWS"
  736. return m, nil
  737. }
  738. maybeClusterId := os.Getenv(ClusterIdEnvVar)
  739. if len(maybeClusterId) != 0 {
  740. return makeStructure(maybeClusterId)
  741. }
  742. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  743. clusterIdRx := regexp.MustCompile("^kubernetes\\.io/cluster/([^/]+)")
  744. nodeList, err := awsProvider.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  745. if err != nil {
  746. return nil, err
  747. }
  748. for _, n := range nodeList.Items {
  749. region := ""
  750. instanceId := ""
  751. providerId := n.Spec.ProviderID
  752. for matchNum, group := range provIdRx.FindStringSubmatch(providerId) {
  753. if matchNum == 1 {
  754. region = group
  755. } else if matchNum == 2 {
  756. instanceId = group
  757. }
  758. }
  759. if len(instanceId) == 0 {
  760. klog.V(2).Infof("Unable to decode Node.ProviderID \"%s\", skipping it", providerId)
  761. continue
  762. }
  763. c := &aws.Config{
  764. Region: aws.String(region),
  765. }
  766. s := session.Must(session.NewSession(c))
  767. ec2Svc := ec2.New(s)
  768. di, diErr := ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{
  769. InstanceIds: []*string{
  770. aws.String(instanceId),
  771. },
  772. })
  773. if diErr != nil {
  774. // maybe log this?
  775. continue
  776. }
  777. if len(di.Reservations) != 1 {
  778. klog.V(2).Infof("Expected 1 Reservation back from DescribeInstances(%s), received %d", instanceId, len(di.Reservations))
  779. continue
  780. }
  781. res := di.Reservations[0]
  782. if len(res.Instances) != 1 {
  783. klog.V(2).Infof("Expected 1 Instance back from DescribeInstances(%s), received %d", instanceId, len(res.Instances))
  784. continue
  785. }
  786. inst := res.Instances[0]
  787. for _, tag := range inst.Tags {
  788. tagKey := *tag.Key
  789. for matchNum, group := range clusterIdRx.FindStringSubmatch(tagKey) {
  790. if matchNum != 1 {
  791. continue
  792. }
  793. return makeStructure(group)
  794. }
  795. }
  796. }
  797. klog.V(2).Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", ClusterIdEnvVar)
  798. return makeStructure(defaultClusterName)
  799. }
  800. // AddServiceKey adds an AWS service key, useful for pulling down out-of-cluster costs. Optional-- the container this runs in can be directly authorized.
  801. func (*AWS) AddServiceKey(formValues url.Values) error {
  802. keyID := formValues.Get("access_key_ID")
  803. key := formValues.Get("secret_access_key")
  804. m := make(map[string]string)
  805. m["access_key_ID"] = keyID
  806. m["secret_access_key"] = key
  807. result, err := json.Marshal(m)
  808. if err != nil {
  809. return err
  810. }
  811. return ioutil.WriteFile("/var/configs/key.json", result, 0644)
  812. }
  813. // 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.
  814. func (*AWS) GetDisks() ([]byte, error) {
  815. jsonFile, err := os.Open("/var/configs/key.json")
  816. if err == nil {
  817. byteValue, _ := ioutil.ReadAll(jsonFile)
  818. var result map[string]string
  819. err := json.Unmarshal([]byte(byteValue), &result)
  820. if err != nil {
  821. return nil, err
  822. }
  823. err = os.Setenv(awsAccessKeyIDEnvVar, result["access_key_ID"])
  824. if err != nil {
  825. return nil, err
  826. }
  827. err = os.Setenv(awsAccessKeySecretEnvVar, result["secret_access_key"])
  828. if err != nil {
  829. return nil, err
  830. }
  831. } else if os.IsNotExist(err) {
  832. klog.V(2).Infof("Using Default Credentials")
  833. } else {
  834. return nil, err
  835. }
  836. defer jsonFile.Close()
  837. clusterConfig, err := os.Open("/var/configs/cluster.json")
  838. if err != nil {
  839. return nil, err
  840. }
  841. defer clusterConfig.Close()
  842. b, err := ioutil.ReadAll(clusterConfig)
  843. if err != nil {
  844. return nil, err
  845. }
  846. var clusterConf map[string]string
  847. err = json.Unmarshal([]byte(b), &clusterConf)
  848. if err != nil {
  849. return nil, err
  850. }
  851. region := aws.String(clusterConf["region"])
  852. c := &aws.Config{
  853. Region: region,
  854. }
  855. s := session.Must(session.NewSession(c))
  856. ec2Svc := ec2.New(s)
  857. input := &ec2.DescribeVolumesInput{}
  858. volumeResult, err := ec2Svc.DescribeVolumes(input)
  859. if err != nil {
  860. if aerr, ok := err.(awserr.Error); ok {
  861. switch aerr.Code() {
  862. default:
  863. return nil, aerr
  864. }
  865. } else {
  866. return nil, err
  867. }
  868. }
  869. return json.Marshal(volumeResult)
  870. }
  871. // ConvertToGlueColumnFormat takes a string and runs through various regex
  872. // and string replacement statements to convert it to a format compatible
  873. // with AWS Glue and Athena column names.
  874. // Following guidance from AWS provided here ('Column Names' section):
  875. // https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/run-athena-sql.html
  876. // It returns a string containing the column name in proper column name format and length.
  877. func ConvertToGlueColumnFormat(column_name string) string {
  878. klog.V(5).Infof("Converting string \"%s\" to proper AWS Glue column name.", column_name)
  879. // An underscore is added in front of uppercase letters
  880. capital_underscore := regexp.MustCompile(`[A-Z]`)
  881. final := capital_underscore.ReplaceAllString(column_name, `_$0`)
  882. // Any non-alphanumeric characters are replaced with an underscore
  883. no_space_punc := regexp.MustCompile(`[\s]{1,}|[^A-Za-z0-9]`)
  884. final = no_space_punc.ReplaceAllString(final, "_")
  885. // Duplicate underscores are removed
  886. no_dup_underscore := regexp.MustCompile(`_{2,}`)
  887. final = no_dup_underscore.ReplaceAllString(final, "_")
  888. // Any leading and trailing underscores are removed
  889. no_front_end_underscore := regexp.MustCompile(`(^\_|\_$)`)
  890. final = no_front_end_underscore.ReplaceAllString(final, "")
  891. // Uppercase to lowercase
  892. final = strings.ToLower(final)
  893. // Longer column name than expected - remove _ left to right
  894. allowed_col_len := 128
  895. undersc_to_remove := len(final) - allowed_col_len
  896. if undersc_to_remove > 0 {
  897. final = strings.Replace(final, "_", "", undersc_to_remove)
  898. }
  899. // If removing all of the underscores still didn't
  900. // make the column name < 128 characters, trim it!
  901. if len(final) > allowed_col_len {
  902. final = final[:allowed_col_len]
  903. }
  904. klog.V(5).Infof("Column name being returned: \"%s\". Length: \"%d\".", final, len(final))
  905. return final
  906. }
  907. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  908. // "start" and "end" are dates of the format YYYY-MM-DD
  909. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  910. func (a *AWS) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  911. customPricing, err := a.GetConfig()
  912. if err != nil {
  913. return nil, err
  914. }
  915. aggregator_column_name := "resource_tags_user_kubernetes_" + aggregator
  916. aggregator_column_name = ConvertToGlueColumnFormat(aggregator_column_name)
  917. query := fmt.Sprintf(`SELECT
  918. CAST(line_item_usage_start_date AS DATE) as start_date,
  919. %s,
  920. line_item_product_code,
  921. SUM(line_item_blended_cost) as blended_cost
  922. FROM %s as cost_data
  923. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  924. GROUP BY 1,2,3`, aggregator_column_name, customPricing.AthenaTable, start, end)
  925. if customPricing.ServiceKeyName != "" {
  926. err = os.Setenv(awsAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  927. if err != nil {
  928. return nil, err
  929. }
  930. err = os.Setenv(awsAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  931. if err != nil {
  932. return nil, err
  933. }
  934. }
  935. region := aws.String(customPricing.AthenaRegion)
  936. resultsBucket := customPricing.AthenaBucketName
  937. database := customPricing.AthenaDatabase
  938. c := &aws.Config{
  939. Region: region,
  940. }
  941. s := session.Must(session.NewSession(c))
  942. svc := athena.New(s)
  943. var e athena.StartQueryExecutionInput
  944. var r athena.ResultConfiguration
  945. r.SetOutputLocation(resultsBucket)
  946. e.SetResultConfiguration(&r)
  947. e.SetQueryString(query)
  948. var q athena.QueryExecutionContext
  949. q.SetDatabase(database)
  950. e.SetQueryExecutionContext(&q)
  951. res, err := svc.StartQueryExecution(&e)
  952. if err != nil {
  953. return nil, err
  954. }
  955. klog.V(2).Infof("StartQueryExecution result:")
  956. klog.V(2).Infof(res.GoString())
  957. var qri athena.GetQueryExecutionInput
  958. qri.SetQueryExecutionId(*res.QueryExecutionId)
  959. var qrop *athena.GetQueryExecutionOutput
  960. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  961. for {
  962. qrop, err = svc.GetQueryExecution(&qri)
  963. if err != nil {
  964. return nil, err
  965. }
  966. if *qrop.QueryExecution.Status.State != "RUNNING" {
  967. break
  968. }
  969. time.Sleep(duration)
  970. }
  971. var oocAllocs []*OutOfClusterAllocation
  972. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  973. var ip athena.GetQueryResultsInput
  974. ip.SetQueryExecutionId(*res.QueryExecutionId)
  975. op, err := svc.GetQueryResults(&ip)
  976. if err != nil {
  977. return nil, err
  978. }
  979. for _, r := range op.ResultSet.Rows[1:(len(op.ResultSet.Rows) - 1)] {
  980. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  981. if err != nil {
  982. return nil, err
  983. }
  984. ooc := &OutOfClusterAllocation{
  985. Aggregator: aggregator,
  986. Environment: *r.Data[1].VarCharValue,
  987. Service: *r.Data[2].VarCharValue,
  988. Cost: cost,
  989. }
  990. oocAllocs = append(oocAllocs, ooc)
  991. }
  992. }
  993. return oocAllocs, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  994. }
  995. // QuerySQL can query a properly configured Athena database.
  996. // Used to fetch billing data.
  997. // Requires a json config in /var/configs with key region, output, and database.
  998. func (a *AWS) QuerySQL(query string) ([]byte, error) {
  999. customPricing, err := a.GetConfig()
  1000. if err != nil {
  1001. return nil, err
  1002. }
  1003. if customPricing.ServiceKeyName != "" {
  1004. err = os.Setenv(awsAccessKeyIDEnvVar, customPricing.ServiceKeyName)
  1005. if err != nil {
  1006. return nil, err
  1007. }
  1008. err = os.Setenv(awsAccessKeySecretEnvVar, customPricing.ServiceKeySecret)
  1009. if err != nil {
  1010. return nil, err
  1011. }
  1012. }
  1013. athenaConfigs, err := os.Open("/var/configs/athena.json")
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. defer athenaConfigs.Close()
  1018. b, err := ioutil.ReadAll(athenaConfigs)
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. var athenaConf map[string]string
  1023. json.Unmarshal([]byte(b), &athenaConf)
  1024. region := aws.String(customPricing.AthenaRegion)
  1025. resultsBucket := customPricing.AthenaBucketName
  1026. database := customPricing.AthenaDatabase
  1027. c := &aws.Config{
  1028. Region: region,
  1029. }
  1030. s := session.Must(session.NewSession(c))
  1031. svc := athena.New(s)
  1032. var e athena.StartQueryExecutionInput
  1033. var r athena.ResultConfiguration
  1034. r.SetOutputLocation(resultsBucket)
  1035. e.SetResultConfiguration(&r)
  1036. e.SetQueryString(query)
  1037. var q athena.QueryExecutionContext
  1038. q.SetDatabase(database)
  1039. e.SetQueryExecutionContext(&q)
  1040. res, err := svc.StartQueryExecution(&e)
  1041. if err != nil {
  1042. return nil, err
  1043. }
  1044. klog.V(2).Infof("StartQueryExecution result:")
  1045. klog.V(2).Infof(res.GoString())
  1046. var qri athena.GetQueryExecutionInput
  1047. qri.SetQueryExecutionId(*res.QueryExecutionId)
  1048. var qrop *athena.GetQueryExecutionOutput
  1049. duration := time.Duration(2) * time.Second // Pause for 2 seconds
  1050. for {
  1051. qrop, err = svc.GetQueryExecution(&qri)
  1052. if err != nil {
  1053. return nil, err
  1054. }
  1055. if *qrop.QueryExecution.Status.State != "RUNNING" {
  1056. break
  1057. }
  1058. time.Sleep(duration)
  1059. }
  1060. if *qrop.QueryExecution.Status.State == "SUCCEEDED" {
  1061. var ip athena.GetQueryResultsInput
  1062. ip.SetQueryExecutionId(*res.QueryExecutionId)
  1063. op, err := svc.GetQueryResults(&ip)
  1064. if err != nil {
  1065. return nil, err
  1066. }
  1067. b, err := json.Marshal(op.ResultSet)
  1068. if err != nil {
  1069. return nil, err
  1070. }
  1071. return b, nil
  1072. }
  1073. return nil, fmt.Errorf("Error getting query results : %s", *qrop.QueryExecution.Status.State)
  1074. }
  1075. type spotInfo struct {
  1076. Timestamp string `csv:"Timestamp"`
  1077. UsageType string `csv:"UsageType"`
  1078. Operation string `csv:"Operation"`
  1079. InstanceID string `csv:"InstanceID"`
  1080. MyBidID string `csv:"MyBidID"`
  1081. MyMaxPrice string `csv:"MyMaxPrice"`
  1082. MarketPrice string `csv:"MarketPrice"`
  1083. Charge string `csv:"Charge"`
  1084. Version string `csv:"Version"`
  1085. }
  1086. type fnames []*string
  1087. func (f fnames) Len() int {
  1088. return len(f)
  1089. }
  1090. func (f fnames) Swap(i, j int) {
  1091. f[i], f[j] = f[j], f[i]
  1092. }
  1093. func (f fnames) Less(i, j int) bool {
  1094. key1 := strings.Split(*f[i], ".")
  1095. key2 := strings.Split(*f[j], ".")
  1096. t1, err := time.Parse("2006-01-02-15", key1[1])
  1097. if err != nil {
  1098. klog.V(1).Info("Unable to parse timestamp" + key1[1])
  1099. return false
  1100. }
  1101. t2, err := time.Parse("2006-01-02-15", key2[1])
  1102. if err != nil {
  1103. klog.V(1).Info("Unable to parse timestamp" + key2[1])
  1104. return false
  1105. }
  1106. return t1.Before(t2)
  1107. }
  1108. func parseSpotData(bucket string, prefix string, projectID string, region string, accessKeyID string, accessKeySecret string) (map[string]*spotInfo, error) {
  1109. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1110. err := os.Setenv(awsAccessKeyIDEnvVar, accessKeyID)
  1111. if err != nil {
  1112. return nil, err
  1113. }
  1114. err = os.Setenv(awsAccessKeySecretEnvVar, accessKeySecret)
  1115. if err != nil {
  1116. return nil, err
  1117. }
  1118. }
  1119. s3Prefix := projectID
  1120. if len(prefix) != 0 {
  1121. s3Prefix = prefix + "/" + s3Prefix
  1122. }
  1123. c := aws.NewConfig().WithRegion(region)
  1124. s := session.Must(session.NewSession(c))
  1125. s3Svc := s3.New(s)
  1126. downloader := s3manager.NewDownloaderWithClient(s3Svc)
  1127. tNow := time.Now()
  1128. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1129. ls := &s3.ListObjectsInput{
  1130. Bucket: aws.String(bucket),
  1131. Prefix: aws.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1132. }
  1133. ls2 := &s3.ListObjectsInput{
  1134. Bucket: aws.String(bucket),
  1135. Prefix: aws.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1136. }
  1137. lso, err := s3Svc.ListObjects(ls)
  1138. if err != nil {
  1139. return nil, err
  1140. }
  1141. lsoLen := len(lso.Contents)
  1142. klog.V(2).Infof("Found %d spot data files from yesterday", lsoLen)
  1143. if lsoLen == 0 {
  1144. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1145. }
  1146. lso2, err := s3Svc.ListObjects(ls2)
  1147. if err != nil {
  1148. return nil, err
  1149. }
  1150. lso2Len := len(lso2.Contents)
  1151. klog.V(2).Infof("Found %d spot data files from today", lso2Len)
  1152. if lso2Len == 0 {
  1153. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1154. }
  1155. var keys []*string
  1156. for _, obj := range lso.Contents {
  1157. keys = append(keys, obj.Key)
  1158. }
  1159. for _, obj := range lso2.Contents {
  1160. keys = append(keys, obj.Key)
  1161. }
  1162. versionRx := regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  1163. header, err := csvutil.Header(spotInfo{}, "csv")
  1164. if err != nil {
  1165. return nil, err
  1166. }
  1167. fieldsPerRecord := len(header)
  1168. spots := make(map[string]*spotInfo)
  1169. for _, key := range keys {
  1170. getObj := &s3.GetObjectInput{
  1171. Bucket: aws.String(bucket),
  1172. Key: key,
  1173. }
  1174. buf := aws.NewWriteAtBuffer([]byte{})
  1175. _, err := downloader.Download(buf, getObj)
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. r := bytes.NewReader(buf.Bytes())
  1180. gr, err := gzip.NewReader(r)
  1181. if err != nil {
  1182. return nil, err
  1183. }
  1184. csvReader := csv.NewReader(gr)
  1185. csvReader.Comma = '\t'
  1186. csvReader.FieldsPerRecord = fieldsPerRecord
  1187. dec, err := csvutil.NewDecoder(csvReader, header...)
  1188. if err != nil {
  1189. return nil, err
  1190. }
  1191. var foundVersion string
  1192. for {
  1193. spot := spotInfo{}
  1194. err := dec.Decode(&spot)
  1195. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1196. if err == io.EOF {
  1197. break
  1198. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1199. rec := dec.Record()
  1200. // the first two "Record()" will be the comment lines
  1201. // and they show up as len() == 1
  1202. // the first of which is "#Version"
  1203. // the second of which is "#Fields: "
  1204. if len(rec) != 1 {
  1205. klog.V(2).Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1206. continue
  1207. }
  1208. if len(foundVersion) == 0 {
  1209. spotFeedVersion := rec[0]
  1210. klog.V(3).Infof("Spot feed version is \"%s\"", spotFeedVersion)
  1211. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  1212. if matches != nil {
  1213. foundVersion = matches[1]
  1214. if foundVersion != supportedSpotFeedVersion {
  1215. klog.V(2).Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  1216. break
  1217. }
  1218. }
  1219. continue
  1220. } else if strings.Index(rec[0], "#") == 0 {
  1221. continue
  1222. } else {
  1223. klog.V(3).Infof("skipping non-TSV line: %s", rec)
  1224. continue
  1225. }
  1226. } else if err != nil {
  1227. klog.V(2).Infof("Error during spot info decode: %+v", err)
  1228. continue
  1229. }
  1230. klog.V(3).Infof("Found spot info %+v", spot)
  1231. spots[spot.InstanceID] = &spot
  1232. }
  1233. gr.Close()
  1234. }
  1235. return spots, nil
  1236. }