awsprovider.go 40 KB

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