awsprovider.go 71 KB

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