awsprovider.go 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. package cloud
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "context"
  6. "encoding/csv"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "k8s.io/klog"
  17. "github.com/kubecost/cost-model/pkg/clustercache"
  18. "github.com/kubecost/cost-model/pkg/env"
  19. "github.com/kubecost/cost-model/pkg/errors"
  20. "github.com/kubecost/cost-model/pkg/log"
  21. "github.com/kubecost/cost-model/pkg/util"
  22. "github.com/kubecost/cost-model/pkg/util/fileutil"
  23. "github.com/kubecost/cost-model/pkg/util/json"
  24. awsSDK "github.com/aws/aws-sdk-go-v2/aws"
  25. "github.com/aws/aws-sdk-go-v2/config"
  26. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  27. "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
  28. "github.com/aws/aws-sdk-go-v2/service/athena"
  29. athenaTypes "github.com/aws/aws-sdk-go-v2/service/athena/types"
  30. "github.com/aws/aws-sdk-go-v2/service/ec2"
  31. ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
  32. "github.com/aws/aws-sdk-go-v2/service/s3"
  33. "github.com/aws/aws-sdk-go-v2/service/sts"
  34. "github.com/jszwec/csvutil"
  35. v1 "k8s.io/api/core/v1"
  36. )
  37. const supportedSpotFeedVersion = "1"
  38. const SpotInfoUpdateType = "spotinfo"
  39. const AthenaInfoUpdateType = "athenainfo"
  40. const PreemptibleType = "preemptible"
  41. const APIPricingSource = "Public API"
  42. const SpotPricingSource = "Spot Data Feed"
  43. const ReservedInstancePricingSource = "Savings Plan, Reserved Instance, and Out-Of-Cluster"
  44. func (aws *AWS) PricingSourceStatus() map[string]*PricingSource {
  45. sources := make(map[string]*PricingSource)
  46. sps := &PricingSource{
  47. Name: SpotPricingSource,
  48. }
  49. sps.Error = ""
  50. if aws.SpotPricingError != nil {
  51. sps.Error = aws.SpotPricingError.Error()
  52. }
  53. if sps.Error != "" {
  54. sps.Available = false
  55. } else if len(aws.SpotPricingByInstanceID) > 0 {
  56. sps.Available = true
  57. } else {
  58. sps.Error = "No spot instances detected"
  59. }
  60. sources[SpotPricingSource] = sps
  61. rps := &PricingSource{
  62. Name: ReservedInstancePricingSource,
  63. }
  64. rps.Error = ""
  65. if aws.RIPricingError != nil {
  66. rps.Error = aws.RIPricingError.Error()
  67. }
  68. if rps.Error != "" {
  69. rps.Available = false
  70. } else {
  71. rps.Available = true
  72. }
  73. sources[ReservedInstancePricingSource] = rps
  74. return sources
  75. }
  76. // How often spot data is refreshed
  77. const SpotRefreshDuration = 15 * time.Minute
  78. const defaultConfigPath = "/var/configs/"
  79. var awsRegions = []string{
  80. "us-east-2",
  81. "us-east-1",
  82. "us-west-1",
  83. "us-west-2",
  84. "ap-east-1",
  85. "ap-south-1",
  86. "ap-northeast-3",
  87. "ap-northeast-2",
  88. "ap-southeast-1",
  89. "ap-southeast-2",
  90. "ap-northeast-1",
  91. "ap-southeast-3",
  92. "ca-central-1",
  93. "cn-north-1",
  94. "cn-northwest-1",
  95. "eu-central-1",
  96. "eu-west-1",
  97. "eu-west-2",
  98. "eu-west-3",
  99. "eu-north-1",
  100. "eu-south-1",
  101. "me-south-1",
  102. "sa-east-1",
  103. "af-south-1",
  104. "us-gov-east-1",
  105. "us-gov-west-1",
  106. }
  107. // AWS represents an Amazon Provider
  108. type AWS struct {
  109. Pricing map[string]*AWSProductTerms
  110. SpotPricingByInstanceID map[string]*spotInfo
  111. SpotPricingUpdatedAt *time.Time
  112. SpotRefreshRunning bool
  113. SpotPricingLock sync.RWMutex
  114. SpotPricingError error
  115. RIPricingByInstanceID map[string]*RIData
  116. RIPricingError error
  117. RIDataRunning bool
  118. RIDataLock sync.RWMutex
  119. SavingsPlanDataByInstanceID map[string]*SavingsPlanData
  120. SavingsPlanDataRunning bool
  121. SavingsPlanDataLock sync.RWMutex
  122. ValidPricingKeys map[string]bool
  123. Clientset clustercache.ClusterCache
  124. BaseCPUPrice string
  125. BaseRAMPrice string
  126. BaseGPUPrice string
  127. BaseSpotCPUPrice string
  128. BaseSpotRAMPrice string
  129. BaseSpotGPUPrice string
  130. SpotLabelName string
  131. SpotLabelValue string
  132. SpotDataRegion string
  133. SpotDataBucket string
  134. SpotDataPrefix string
  135. ProjectID string
  136. DownloadPricingDataLock sync.RWMutex
  137. Config *ProviderConfig
  138. serviceAccountChecks *ServiceAccountChecks
  139. clusterManagementPrice float64
  140. clusterAccountId string
  141. clusterRegion string
  142. clusterProvisioner string
  143. *CustomProvider
  144. }
  145. // AWSAccessKey holds AWS credentials and fulfils the awsV2.CredentialsProvider interface
  146. type AWSAccessKey struct {
  147. AccessKeyID string `json:"aws_access_key_id"`
  148. SecretAccessKey string `json:"aws_secret_access_key"`
  149. }
  150. // Retrieve returns a set of awsV2 credentials using the AWSAccessKey's key and secret.
  151. // This fulfils the awsV2.CredentialsProvider interface contract.
  152. func (accessKey AWSAccessKey) Retrieve(ctx context.Context) (awsSDK.Credentials, error) {
  153. return awsSDK.Credentials{
  154. AccessKeyID: accessKey.AccessKeyID,
  155. SecretAccessKey: accessKey.SecretAccessKey,
  156. }, nil
  157. }
  158. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains for the provided region
  159. func (accessKey AWSAccessKey) CreateConfig(region string) (awsSDK.Config, error) {
  160. var cfg awsSDK.Config
  161. var err error
  162. // If accessKey values have not been provided, attempt to load cfg from service key annotations
  163. if accessKey.AccessKeyID == "" && accessKey.SecretAccessKey == "" {
  164. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
  165. if err != nil {
  166. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region from annotation %s: %s", region, err)
  167. }
  168. } else {
  169. // The AWS SDK v2 requires an object fulfilling the CredentialsProvider interface, which cloud.AWSAccessKey does
  170. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(accessKey), config.WithRegion(region))
  171. if err != nil {
  172. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region %s: %s", region, err)
  173. }
  174. }
  175. return cfg, nil
  176. }
  177. // AWSPricing maps a k8s node to an AWS Pricing "product"
  178. type AWSPricing struct {
  179. Products map[string]*AWSProduct `json:"products"`
  180. Terms AWSPricingTerms `json:"terms"`
  181. }
  182. // AWSProduct represents a purchased SKU
  183. type AWSProduct struct {
  184. Sku string `json:"sku"`
  185. Attributes AWSProductAttributes `json:"attributes"`
  186. }
  187. // AWSProductAttributes represents metadata about the product used to map to a node.
  188. type AWSProductAttributes struct {
  189. Location string `json:"location"`
  190. InstanceType string `json:"instanceType"`
  191. Memory string `json:"memory"`
  192. Storage string `json:"storage"`
  193. VCpu string `json:"vcpu"`
  194. UsageType string `json:"usagetype"`
  195. OperatingSystem string `json:"operatingSystem"`
  196. PreInstalledSw string `json:"preInstalledSw"`
  197. InstanceFamily string `json:"instanceFamily"`
  198. CapacityStatus string `json:"capacitystatus"`
  199. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  200. }
  201. // AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
  202. type AWSPricingTerms struct {
  203. OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
  204. Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
  205. }
  206. // AWSOfferTerm is a sku extension used to pay for the node.
  207. type AWSOfferTerm struct {
  208. Sku string `json:"sku"`
  209. PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
  210. }
  211. func (ot *AWSOfferTerm) String() string {
  212. var strs []string
  213. for k, rc := range ot.PriceDimensions {
  214. strs = append(strs, fmt.Sprintf("%s:%s", k, rc.String()))
  215. }
  216. return fmt.Sprintf("%s:%s", ot.Sku, strings.Join(strs, ","))
  217. }
  218. // AWSRateCode encodes data about the price of a product
  219. type AWSRateCode struct {
  220. Unit string `json:"unit"`
  221. PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
  222. }
  223. func (rc *AWSRateCode) String() string {
  224. return fmt.Sprintf("{unit: %s, pricePerUnit: %v", rc.Unit, rc.PricePerUnit)
  225. }
  226. // AWSCurrencyCode is the localized currency. (TODO: support non-USD)
  227. type AWSCurrencyCode struct {
  228. USD string `json:"USD,omitempty"`
  229. CNY string `json:"CNY,omitempty"`
  230. }
  231. // AWSProductTerms represents the full terms of the product
  232. type AWSProductTerms struct {
  233. Sku string `json:"sku"`
  234. OnDemand *AWSOfferTerm `json:"OnDemand"`
  235. Reserved *AWSOfferTerm `json:"Reserved"`
  236. Memory string `json:"memory"`
  237. Storage string `json:"storage"`
  238. VCpu string `json:"vcpu"`
  239. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  240. PV *PV `json:"pv"`
  241. }
  242. // ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
  243. const ClusterIdEnvVar = "AWS_CLUSTER_ID"
  244. // OnDemandRateCode is appended to an node sku
  245. const OnDemandRateCode = ".JRTCKXETXF"
  246. const OnDemandRateCodeCn = ".99YE2YK9UR"
  247. // ReservedRateCode is appended to a node sku
  248. const ReservedRateCode = ".38NPMPTW36"
  249. // HourlyRateCode is appended to a node sku
  250. const HourlyRateCode = ".6YS6EN2CT7"
  251. const HourlyRateCodeCn = ".Q7UJUT2CE6"
  252. // volTypes are used to map between AWS UsageTypes and
  253. // EBS volume types, as they would appear in K8s storage class
  254. // name and the EC2 API.
  255. var volTypes = map[string]string{
  256. "EBS:VolumeUsage.gp2": "gp2",
  257. "EBS:VolumeUsage": "standard",
  258. "EBS:VolumeUsage.sc1": "sc1",
  259. "EBS:VolumeP-IOPS.piops": "io1",
  260. "EBS:VolumeUsage.st1": "st1",
  261. "EBS:VolumeUsage.piops": "io1",
  262. "gp2": "EBS:VolumeUsage.gp2",
  263. "standard": "EBS:VolumeUsage",
  264. "sc1": "EBS:VolumeUsage.sc1",
  265. "io1": "EBS:VolumeUsage.piops",
  266. "st1": "EBS:VolumeUsage.st1",
  267. }
  268. // locationToRegion maps AWS region names (As they come from Billing)
  269. // to actual region identifiers
  270. var locationToRegion = map[string]string{
  271. "US East (Ohio)": "us-east-2",
  272. "US East (N. Virginia)": "us-east-1",
  273. "US West (N. California)": "us-west-1",
  274. "US West (Oregon)": "us-west-2",
  275. "Asia Pacific (Hong Kong)": "ap-east-1",
  276. "Asia Pacific (Mumbai)": "ap-south-1",
  277. "Asia Pacific (Osaka)": "ap-northeast-3",
  278. "Asia Pacific (Seoul)": "ap-northeast-2",
  279. "Asia Pacific (Singapore)": "ap-southeast-1",
  280. "Asia Pacific (Sydney)": "ap-southeast-2",
  281. "Asia Pacific (Tokyo)": "ap-northeast-1",
  282. "Asia Pacific (Jakarta)": "ap-southeast-3",
  283. "Canada (Central)": "ca-central-1",
  284. "China (Beijing)": "cn-north-1",
  285. "China (Ningxia)": "cn-northwest-1",
  286. "EU (Frankfurt)": "eu-central-1",
  287. "EU (Ireland)": "eu-west-1",
  288. "EU (London)": "eu-west-2",
  289. "EU (Paris)": "eu-west-3",
  290. "EU (Stockholm)": "eu-north-1",
  291. "EU (Milan)": "eu-south-1",
  292. "South America (Sao Paulo)": "sa-east-1",
  293. "Africa (Cape Town)": "af-south-1",
  294. "AWS GovCloud (US-East)": "us-gov-east-1",
  295. "AWS GovCloud (US-West)": "us-gov-west-1",
  296. }
  297. var regionToBillingRegionCode = map[string]string{
  298. "us-east-2": "USE2",
  299. "us-east-1": "",
  300. "us-west-1": "USW1",
  301. "us-west-2": "USW2",
  302. "ap-east-1": "APE1",
  303. "ap-south-1": "APS3",
  304. "ap-northeast-3": "APN3",
  305. "ap-northeast-2": "APN2",
  306. "ap-southeast-1": "APS1",
  307. "ap-southeast-2": "APS2",
  308. "ap-northeast-1": "APN1",
  309. "ap-southeast-3": "APS4",
  310. "ca-central-1": "CAN1",
  311. "cn-north-1": "",
  312. "cn-northwest-1": "",
  313. "eu-central-1": "EUC1",
  314. "eu-west-1": "EU",
  315. "eu-west-2": "EUW2",
  316. "eu-west-3": "EUW3",
  317. "eu-north-1": "EUN1",
  318. "eu-south-1": "EUS1",
  319. "sa-east-1": "SAE1",
  320. "af-south-1": "AFS1",
  321. "us-gov-east-1": "UGE1",
  322. "us-gov-west-1": "UGW1",
  323. }
  324. var loadedAWSSecret bool = false
  325. var awsSecret *AWSAccessKey = nil
  326. func (aws *AWS) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  327. return ""
  328. }
  329. // KubeAttrConversion maps the k8s labels for region to an aws region
  330. func (aws *AWS) KubeAttrConversion(location, instanceType, operatingSystem string) string {
  331. operatingSystem = strings.ToLower(operatingSystem)
  332. region := locationToRegion[location]
  333. return region + "," + instanceType + "," + operatingSystem
  334. }
  335. // AwsSpotFeedInfo contains configuration for spot feed integration
  336. type AwsSpotFeedInfo struct {
  337. BucketName string `json:"bucketName"`
  338. Prefix string `json:"prefix"`
  339. Region string `json:"region"`
  340. AccountID string `json:"projectID"`
  341. ServiceKeyName string `json:"serviceKeyName"`
  342. ServiceKeySecret string `json:"serviceKeySecret"`
  343. SpotLabel string `json:"spotLabel"`
  344. SpotLabelValue string `json:"spotLabelValue"`
  345. }
  346. // AwsAthenaInfo contains configuration for CUR integration
  347. type AwsAthenaInfo struct {
  348. AthenaBucketName string `json:"athenaBucketName"`
  349. AthenaRegion string `json:"athenaRegion"`
  350. AthenaDatabase string `json:"athenaDatabase"`
  351. AthenaTable string `json:"athenaTable"`
  352. ServiceKeyName string `json:"serviceKeyName"`
  353. ServiceKeySecret string `json:"serviceKeySecret"`
  354. AccountID string `json:"projectID"`
  355. MasterPayerARN string `json:"masterPayerARN"`
  356. }
  357. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains
  358. func (aai *AwsAthenaInfo) CreateConfig() (awsSDK.Config, error) {
  359. keyProvider := AWSAccessKey{AccessKeyID: aai.ServiceKeyName, SecretAccessKey: aai.ServiceKeySecret}
  360. cfg, err := keyProvider.CreateConfig(aai.AthenaRegion)
  361. if err != nil {
  362. return cfg, err
  363. }
  364. if aai.MasterPayerARN != "" {
  365. // Create the credentials from AssumeRoleProvider to assume the role
  366. // referenced by the roleARN.
  367. stsSvc := sts.NewFromConfig(cfg)
  368. creds := stscreds.NewAssumeRoleProvider(stsSvc, aai.MasterPayerARN)
  369. cfg.Credentials = awsSDK.NewCredentialsCache(creds)
  370. }
  371. return cfg, nil
  372. }
  373. func (aws *AWS) GetManagementPlatform() (string, error) {
  374. nodes := aws.Clientset.GetAllNodes()
  375. if len(nodes) > 0 {
  376. n := nodes[0]
  377. version := n.Status.NodeInfo.KubeletVersion
  378. if strings.Contains(version, "eks") {
  379. return "eks", nil
  380. }
  381. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  382. return "kops", nil
  383. }
  384. }
  385. return "", nil
  386. }
  387. func (aws *AWS) GetConfig() (*CustomPricing, error) {
  388. c, err := aws.Config.GetCustomPricingData()
  389. if err != nil {
  390. return nil, err
  391. }
  392. if c.Discount == "" {
  393. c.Discount = "0%"
  394. }
  395. if c.NegotiatedDiscount == "" {
  396. c.NegotiatedDiscount = "0%"
  397. }
  398. if c.ShareTenancyCosts == "" {
  399. c.ShareTenancyCosts = defaultShareTenancyCost
  400. }
  401. return c, nil
  402. }
  403. // GetAWSAccessKey generate an AWSAccessKey object from the config
  404. func (aws *AWS) GetAWSAccessKey() (*AWSAccessKey, error) {
  405. config, err := aws.GetConfig()
  406. if err != nil {
  407. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  408. }
  409. err = aws.ConfigureAuthWith(config)
  410. if err != nil {
  411. return nil, fmt.Errorf("error configuring Cloud Provider %s", err)
  412. }
  413. //Look for service key values in env if not present in config
  414. if config.ServiceKeyName == "" {
  415. config.ServiceKeyName = env.GetAWSAccessKeyID()
  416. }
  417. if config.ServiceKeySecret == "" {
  418. config.ServiceKeySecret = env.GetAWSAccessKeySecret()
  419. }
  420. if config.ServiceKeyName == "" && config.ServiceKeySecret == "" {
  421. log.DedupedInfof(1, "missing service key values for AWS cloud integration attempting to use service account integration")
  422. }
  423. return &AWSAccessKey{AccessKeyID: config.ServiceKeyName, SecretAccessKey: config.ServiceKeySecret}, nil
  424. }
  425. // GetAWSAthenaInfo generate an AWSAthenaInfo object from the config
  426. func (aws *AWS) GetAWSAthenaInfo() (*AwsAthenaInfo, error) {
  427. config, err := aws.GetConfig()
  428. if err != nil {
  429. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  430. }
  431. aak, err := aws.GetAWSAccessKey()
  432. if err != nil {
  433. return nil, err
  434. }
  435. return &AwsAthenaInfo{
  436. AthenaBucketName: config.AthenaBucketName,
  437. AthenaRegion: config.AthenaRegion,
  438. AthenaDatabase: config.AthenaDatabase,
  439. AthenaTable: config.AthenaTable,
  440. ServiceKeyName: aak.AccessKeyID,
  441. ServiceKeySecret: aak.SecretAccessKey,
  442. AccountID: config.AthenaProjectID,
  443. MasterPayerARN: config.MasterPayerARN,
  444. }, nil
  445. }
  446. func (aws *AWS) UpdateConfigFromConfigMap(cm map[string]string) (*CustomPricing, error) {
  447. return aws.Config.UpdateFromMap(cm)
  448. }
  449. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  450. return aws.Config.Update(func(c *CustomPricing) error {
  451. if updateType == SpotInfoUpdateType {
  452. asfi := AwsSpotFeedInfo{}
  453. err := json.NewDecoder(r).Decode(&asfi)
  454. if err != nil {
  455. return err
  456. }
  457. c.ServiceKeyName = asfi.ServiceKeyName
  458. if asfi.ServiceKeySecret != "" {
  459. c.ServiceKeySecret = asfi.ServiceKeySecret
  460. }
  461. c.SpotDataPrefix = asfi.Prefix
  462. c.SpotDataBucket = asfi.BucketName
  463. c.ProjectID = asfi.AccountID
  464. c.SpotDataRegion = asfi.Region
  465. c.SpotLabel = asfi.SpotLabel
  466. c.SpotLabelValue = asfi.SpotLabelValue
  467. } else if updateType == AthenaInfoUpdateType {
  468. aai := AwsAthenaInfo{}
  469. err := json.NewDecoder(r).Decode(&aai)
  470. if err != nil {
  471. return err
  472. }
  473. c.AthenaBucketName = aai.AthenaBucketName
  474. c.AthenaRegion = aai.AthenaRegion
  475. c.AthenaDatabase = aai.AthenaDatabase
  476. c.AthenaTable = aai.AthenaTable
  477. c.ServiceKeyName = aai.ServiceKeyName
  478. if aai.ServiceKeySecret != "" {
  479. c.ServiceKeySecret = aai.ServiceKeySecret
  480. }
  481. if aai.MasterPayerARN != "" {
  482. c.MasterPayerARN = aai.MasterPayerARN
  483. }
  484. c.AthenaProjectID = aai.AccountID
  485. } else {
  486. a := make(map[string]interface{})
  487. err := json.NewDecoder(r).Decode(&a)
  488. if err != nil {
  489. return err
  490. }
  491. for k, v := range a {
  492. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  493. vstr, ok := v.(string)
  494. if ok {
  495. err := SetCustomPricingField(c, kUpper, vstr)
  496. if err != nil {
  497. return err
  498. }
  499. } else {
  500. return fmt.Errorf("type error while updating config for %s", kUpper)
  501. }
  502. }
  503. }
  504. if env.IsRemoteEnabled() {
  505. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  506. if err != nil {
  507. return err
  508. }
  509. }
  510. return nil
  511. })
  512. }
  513. type awsKey struct {
  514. SpotLabelName string
  515. SpotLabelValue string
  516. Labels map[string]string
  517. ProviderID string
  518. }
  519. func (k *awsKey) GPUType() string {
  520. return ""
  521. }
  522. func (k *awsKey) ID() string {
  523. provIdRx := regexp.MustCompile("aws:///([^/]+)/([^/]+)") // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  524. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  525. if matchNum == 2 {
  526. return group
  527. }
  528. }
  529. klog.V(3).Infof("Could not find instance ID in \"%s\"", k.ProviderID)
  530. return ""
  531. }
  532. func (k *awsKey) Features() string {
  533. instanceType, _ := util.GetInstanceType(k.Labels)
  534. operatingSystem, _ := util.GetOperatingSystem(k.Labels)
  535. region, _ := util.GetRegion(k.Labels)
  536. key := region + "," + instanceType + "," + operatingSystem
  537. usageType := PreemptibleType
  538. spotKey := key + "," + usageType
  539. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  540. return spotKey
  541. }
  542. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  543. return spotKey
  544. }
  545. return key
  546. }
  547. func (aws *AWS) PVPricing(pvk PVKey) (*PV, error) {
  548. pricing, ok := aws.Pricing[pvk.Features()]
  549. if !ok {
  550. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  551. return &PV{}, nil
  552. }
  553. return pricing.PV, nil
  554. }
  555. type awsPVKey struct {
  556. Labels map[string]string
  557. StorageClassParameters map[string]string
  558. StorageClassName string
  559. Name string
  560. DefaultRegion string
  561. ProviderID string
  562. }
  563. func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  564. providerID := ""
  565. if pv.Spec.AWSElasticBlockStore != nil {
  566. providerID = pv.Spec.AWSElasticBlockStore.VolumeID
  567. } else if pv.Spec.CSI != nil {
  568. providerID = pv.Spec.CSI.VolumeHandle
  569. }
  570. return &awsPVKey{
  571. Labels: pv.Labels,
  572. StorageClassName: pv.Spec.StorageClassName,
  573. StorageClassParameters: parameters,
  574. Name: pv.Name,
  575. DefaultRegion: defaultRegion,
  576. ProviderID: providerID,
  577. }
  578. }
  579. func (key *awsPVKey) ID() string {
  580. return key.ProviderID
  581. }
  582. func (key *awsPVKey) GetStorageClass() string {
  583. return key.StorageClassName
  584. }
  585. func (key *awsPVKey) Features() string {
  586. storageClass := key.StorageClassParameters["type"]
  587. if storageClass == "standard" {
  588. storageClass = "gp2"
  589. }
  590. // Storage class names are generally EBS volume types (gp2)
  591. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  592. // Converts between the 2
  593. region, ok := util.GetRegion(key.Labels)
  594. if !ok {
  595. region = key.DefaultRegion
  596. }
  597. class, ok := volTypes[storageClass]
  598. if !ok {
  599. klog.V(4).Infof("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  600. }
  601. return region + "," + class
  602. }
  603. // GetKey maps node labels to information needed to retrieve pricing data
  604. func (aws *AWS) GetKey(labels map[string]string, n *v1.Node) Key {
  605. return &awsKey{
  606. SpotLabelName: aws.SpotLabelName,
  607. SpotLabelValue: aws.SpotLabelValue,
  608. Labels: labels,
  609. ProviderID: labels["providerID"],
  610. }
  611. }
  612. func (aws *AWS) isPreemptible(key string) bool {
  613. s := strings.Split(key, ",")
  614. if len(s) == 4 && s[3] == PreemptibleType {
  615. return true
  616. }
  617. return false
  618. }
  619. func (aws *AWS) ClusterManagementPricing() (string, float64, error) {
  620. return aws.clusterProvisioner, aws.clusterManagementPrice, nil
  621. }
  622. // Use the pricing data from the current region. Fall back to using all region data if needed.
  623. func (aws *AWS) getRegionPricing(nodeList []*v1.Node) (*http.Response, string, error) {
  624. pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/"
  625. region := ""
  626. multiregion := false
  627. for _, n := range nodeList {
  628. labels := n.GetLabels()
  629. currentNodeRegion := ""
  630. if r, ok := util.GetRegion(labels); ok {
  631. currentNodeRegion = r
  632. // Switch to Chinese endpoint for regions with the Chinese prefix
  633. if strings.HasPrefix(currentNodeRegion, "cn-") {
  634. pricingURL = "https://pricing.cn-north-1.amazonaws.com.cn/offers/v1.0/cn/AmazonEC2/current/"
  635. }
  636. } else {
  637. multiregion = true // We weren't able to detect the node's region, so pull all data.
  638. break
  639. }
  640. if region == "" { // We haven't set a region yet
  641. region = currentNodeRegion
  642. } else if region != "" && currentNodeRegion != region { // If two nodes have different regions here, we'll need to fetch all pricing data.
  643. multiregion = true
  644. break
  645. }
  646. }
  647. // Chinese multiregion endpoint only contains data for Chinese regions and Chinese regions are excluded from other endpoint
  648. if region != "" && !multiregion {
  649. pricingURL += region + "/"
  650. }
  651. pricingURL += "index.json"
  652. klog.V(2).Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  653. resp, err := http.Get(pricingURL)
  654. if err != nil {
  655. klog.V(2).Infof("Bogus fetch of \"%s\": %v", pricingURL, err)
  656. return nil, pricingURL, err
  657. }
  658. return resp, pricingURL, err
  659. }
  660. // DownloadPricingData fetches data from the AWS Pricing API
  661. func (aws *AWS) DownloadPricingData() error {
  662. aws.DownloadPricingDataLock.Lock()
  663. defer aws.DownloadPricingDataLock.Unlock()
  664. c, err := aws.Config.GetCustomPricingData()
  665. if err != nil {
  666. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  667. }
  668. aws.BaseCPUPrice = c.CPU
  669. aws.BaseRAMPrice = c.RAM
  670. aws.BaseGPUPrice = c.GPU
  671. aws.BaseSpotCPUPrice = c.SpotCPU
  672. aws.BaseSpotRAMPrice = c.SpotRAM
  673. aws.BaseSpotGPUPrice = c.SpotGPU
  674. aws.SpotLabelName = c.SpotLabel
  675. aws.SpotLabelValue = c.SpotLabelValue
  676. aws.SpotDataBucket = c.SpotDataBucket
  677. aws.SpotDataPrefix = c.SpotDataPrefix
  678. aws.ProjectID = c.ProjectID
  679. aws.SpotDataRegion = c.SpotDataRegion
  680. aws.ConfigureAuthWith(c) // load aws authentication from configuration or secret
  681. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  682. klog.V(1).Infof("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  683. }
  684. nodeList := aws.Clientset.GetAllNodes()
  685. inputkeys := make(map[string]bool)
  686. for _, n := range nodeList {
  687. if _, ok := n.Labels["eks.amazonaws.com/nodegroup"]; ok {
  688. aws.clusterManagementPrice = 0.10
  689. aws.clusterProvisioner = "EKS"
  690. } else if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  691. aws.clusterProvisioner = "KOPS"
  692. }
  693. labels := n.GetObjectMeta().GetLabels()
  694. key := aws.GetKey(labels, n)
  695. inputkeys[key.Features()] = true
  696. }
  697. pvList := aws.Clientset.GetAllPersistentVolumes()
  698. storageClasses := aws.Clientset.GetAllStorageClasses()
  699. storageClassMap := make(map[string]map[string]string)
  700. for _, storageClass := range storageClasses {
  701. params := storageClass.Parameters
  702. storageClassMap[storageClass.ObjectMeta.Name] = params
  703. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  704. storageClassMap["default"] = params
  705. storageClassMap[""] = params
  706. }
  707. }
  708. pvkeys := make(map[string]PVKey)
  709. for _, pv := range pvList {
  710. params, ok := storageClassMap[pv.Spec.StorageClassName]
  711. if !ok {
  712. klog.V(2).Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  713. continue
  714. }
  715. key := aws.GetPVKey(pv, params, "")
  716. pvkeys[key.Features()] = key
  717. }
  718. // RIDataRunning establishes the existance of the goroutine. Since it's possible we
  719. // run multiple downloads, we don't want to create multiple go routines if one already exists
  720. if !aws.RIDataRunning && c.AthenaBucketName != "" {
  721. err = aws.GetReservationDataFromAthena() // Block until one run has completed.
  722. if err != nil {
  723. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  724. } else { // If we make one successful run, check on new reservation data every hour
  725. go func() {
  726. defer errors.HandlePanic()
  727. aws.RIDataRunning = true
  728. for {
  729. klog.Infof("Reserved Instance watcher running... next update in 1h")
  730. time.Sleep(time.Hour)
  731. err := aws.GetReservationDataFromAthena()
  732. if err != nil {
  733. klog.Infof("Error updating RI data: %s", err.Error())
  734. }
  735. }
  736. }()
  737. }
  738. }
  739. if !aws.SavingsPlanDataRunning && c.AthenaBucketName != "" {
  740. err = aws.GetSavingsPlanDataFromAthena()
  741. if err != nil {
  742. klog.V(1).Infof("Failed to lookup savings plan data: %s", err.Error())
  743. } else {
  744. go func() {
  745. defer errors.HandlePanic()
  746. aws.SavingsPlanDataRunning = true
  747. for {
  748. klog.Infof("Savings Plan watcher running... next update in 1h")
  749. time.Sleep(time.Hour)
  750. err := aws.GetSavingsPlanDataFromAthena()
  751. if err != nil {
  752. klog.Infof("Error updating Savings Plan data: %s", err.Error())
  753. }
  754. }
  755. }()
  756. }
  757. }
  758. aws.Pricing = make(map[string]*AWSProductTerms)
  759. aws.ValidPricingKeys = make(map[string]bool)
  760. skusToKeys := make(map[string]string)
  761. resp, pricingURL, err := aws.getRegionPricing(nodeList)
  762. if err != nil {
  763. return err
  764. }
  765. dec := json.NewDecoder(resp.Body)
  766. for {
  767. t, err := dec.Token()
  768. if err == io.EOF {
  769. klog.V(2).Infof("done loading \"%s\"\n", pricingURL)
  770. break
  771. } else if err != nil {
  772. klog.V(2).Infof("error parsing response json %v", resp.Body)
  773. break
  774. }
  775. if t == "products" {
  776. _, err := dec.Token() // this should parse the opening "{""
  777. if err != nil {
  778. return err
  779. }
  780. for dec.More() {
  781. _, err := dec.Token() // the sku token
  782. if err != nil {
  783. return err
  784. }
  785. product := &AWSProduct{}
  786. err = dec.Decode(&product)
  787. if err != nil {
  788. klog.V(1).Infof("Error parsing response from \"%s\": %v", pricingURL, err.Error())
  789. break
  790. }
  791. if product.Attributes.PreInstalledSw == "NA" &&
  792. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) &&
  793. product.Attributes.CapacityStatus == "Used" {
  794. key := aws.KubeAttrConversion(product.Attributes.Location, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  795. spotKey := key + ",preemptible"
  796. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  797. productTerms := &AWSProductTerms{
  798. Sku: product.Sku,
  799. Memory: product.Attributes.Memory,
  800. Storage: product.Attributes.Storage,
  801. VCpu: product.Attributes.VCpu,
  802. GPU: product.Attributes.GPU,
  803. }
  804. aws.Pricing[key] = productTerms
  805. aws.Pricing[spotKey] = productTerms
  806. skusToKeys[product.Sku] = key
  807. }
  808. aws.ValidPricingKeys[key] = true
  809. aws.ValidPricingKeys[spotKey] = true
  810. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  811. // UsageTypes may be prefixed with a region code - we're removing this when using
  812. // volTypes to keep lookups generic
  813. usageTypeRegx := regexp.MustCompile(".*(-|^)(EBS.+)")
  814. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  815. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  816. key := locationToRegion[product.Attributes.Location] + "," + usageTypeNoRegion
  817. spotKey := key + ",preemptible"
  818. pv := &PV{
  819. Class: volTypes[usageTypeNoRegion],
  820. Region: locationToRegion[product.Attributes.Location],
  821. }
  822. productTerms := &AWSProductTerms{
  823. Sku: product.Sku,
  824. PV: pv,
  825. }
  826. aws.Pricing[key] = productTerms
  827. aws.Pricing[spotKey] = productTerms
  828. skusToKeys[product.Sku] = key
  829. aws.ValidPricingKeys[key] = true
  830. aws.ValidPricingKeys[spotKey] = true
  831. }
  832. }
  833. }
  834. if t == "terms" {
  835. _, err := dec.Token() // this should parse the opening "{""
  836. if err != nil {
  837. return err
  838. }
  839. termType, err := dec.Token()
  840. if err != nil {
  841. return err
  842. }
  843. if termType == "OnDemand" {
  844. _, err := dec.Token()
  845. if err != nil { // again, should parse an opening "{"
  846. return err
  847. }
  848. for dec.More() {
  849. sku, err := dec.Token()
  850. if err != nil {
  851. return err
  852. }
  853. _, err = dec.Token() // another opening "{"
  854. if err != nil {
  855. return err
  856. }
  857. skuOnDemand, err := dec.Token()
  858. if err != nil {
  859. return err
  860. }
  861. offerTerm := &AWSOfferTerm{}
  862. err = dec.Decode(&offerTerm)
  863. if err != nil {
  864. klog.V(1).Infof("Error decoding AWS Offer Term: " + err.Error())
  865. }
  866. key, ok := skusToKeys[sku.(string)]
  867. spotKey := key + ",preemptible"
  868. if ok {
  869. aws.Pricing[key].OnDemand = offerTerm
  870. aws.Pricing[spotKey].OnDemand = offerTerm
  871. var cost string
  872. if sku.(string)+OnDemandRateCode == skuOnDemand {
  873. cost = offerTerm.PriceDimensions[sku.(string)+OnDemandRateCode+HourlyRateCode].PricePerUnit.USD
  874. } else if sku.(string)+OnDemandRateCodeCn == skuOnDemand {
  875. cost = offerTerm.PriceDimensions[sku.(string)+OnDemandRateCodeCn+HourlyRateCodeCn].PricePerUnit.CNY
  876. }
  877. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  878. // If the specific UsageType is the per IO cost used on io1 volumes
  879. // we need to add the per IO cost to the io1 PV cost
  880. // Add the per IO cost to the PV object for the io1 volume type
  881. aws.Pricing[key].PV.CostPerIO = cost
  882. } else if strings.Contains(key, "EBS:Volume") {
  883. // If volume, we need to get hourly cost and add it to the PV object
  884. costFloat, _ := strconv.ParseFloat(cost, 64)
  885. hourlyPrice := costFloat / 730
  886. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  887. }
  888. }
  889. _, err = dec.Token()
  890. if err != nil {
  891. return err
  892. }
  893. }
  894. _, err = dec.Token()
  895. if err != nil {
  896. return err
  897. }
  898. }
  899. }
  900. }
  901. klog.V(2).Infof("Finished downloading \"%s\"", pricingURL)
  902. // Always run spot pricing refresh when performing download
  903. aws.refreshSpotPricing(true)
  904. // Only start a single refresh goroutine
  905. if !aws.SpotRefreshRunning {
  906. aws.SpotRefreshRunning = true
  907. go func() {
  908. defer errors.HandlePanic()
  909. for {
  910. klog.Infof("Spot Pricing Refresh scheduled in %.2f minutes.", SpotRefreshDuration.Minutes())
  911. time.Sleep(SpotRefreshDuration)
  912. // Reoccurring refresh checks update times
  913. aws.refreshSpotPricing(false)
  914. }
  915. }()
  916. }
  917. return nil
  918. }
  919. func (aws *AWS) refreshSpotPricing(force bool) {
  920. aws.SpotPricingLock.Lock()
  921. defer aws.SpotPricingLock.Unlock()
  922. now := time.Now().UTC()
  923. updateTime := now.Add(-SpotRefreshDuration)
  924. // Return if there was an update time set and an hour hasn't elapsed
  925. if !force && aws.SpotPricingUpdatedAt != nil && aws.SpotPricingUpdatedAt.After(updateTime) {
  926. return
  927. }
  928. sp, err := aws.parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion)
  929. if err != nil {
  930. klog.V(1).Infof("Skipping AWS spot data download: %s", err.Error())
  931. aws.SpotPricingError = err
  932. return
  933. }
  934. aws.SpotPricingError = nil
  935. // update time last updated
  936. aws.SpotPricingUpdatedAt = &now
  937. aws.SpotPricingByInstanceID = sp
  938. }
  939. // Stubbed NetworkPricing for AWS. Pull directly from aws.json for now
  940. func (aws *AWS) NetworkPricing() (*Network, error) {
  941. cpricing, err := aws.Config.GetCustomPricingData()
  942. if err != nil {
  943. return nil, err
  944. }
  945. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  946. if err != nil {
  947. return nil, err
  948. }
  949. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  950. if err != nil {
  951. return nil, err
  952. }
  953. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  954. if err != nil {
  955. return nil, err
  956. }
  957. return &Network{
  958. ZoneNetworkEgressCost: znec,
  959. RegionNetworkEgressCost: rnec,
  960. InternetNetworkEgressCost: inec,
  961. }, nil
  962. }
  963. func (aws *AWS) LoadBalancerPricing() (*LoadBalancer, error) {
  964. fffrc := 0.025
  965. afrc := 0.010
  966. lbidc := 0.008
  967. numForwardingRules := 1.0
  968. dataIngressGB := 0.0
  969. var totalCost float64
  970. if numForwardingRules < 5 {
  971. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  972. } else {
  973. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  974. }
  975. return &LoadBalancer{
  976. Cost: totalCost,
  977. }, nil
  978. }
  979. // AllNodePricing returns all the billing data fetched.
  980. func (aws *AWS) AllNodePricing() (interface{}, error) {
  981. aws.DownloadPricingDataLock.RLock()
  982. defer aws.DownloadPricingDataLock.RUnlock()
  983. return aws.Pricing, nil
  984. }
  985. func (aws *AWS) spotPricing(instanceID string) (*spotInfo, bool) {
  986. aws.SpotPricingLock.RLock()
  987. defer aws.SpotPricingLock.RUnlock()
  988. info, ok := aws.SpotPricingByInstanceID[instanceID]
  989. return info, ok
  990. }
  991. func (aws *AWS) reservedInstancePricing(instanceID string) (*RIData, bool) {
  992. aws.RIDataLock.RLock()
  993. defer aws.RIDataLock.RUnlock()
  994. data, ok := aws.RIPricingByInstanceID[instanceID]
  995. return data, ok
  996. }
  997. func (aws *AWS) savingsPlanPricing(instanceID string) (*SavingsPlanData, bool) {
  998. aws.SavingsPlanDataLock.RLock()
  999. defer aws.SavingsPlanDataLock.RUnlock()
  1000. data, ok := aws.SavingsPlanDataByInstanceID[instanceID]
  1001. return data, ok
  1002. }
  1003. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k Key) (*Node, error) {
  1004. key := k.Features()
  1005. if spotInfo, ok := aws.spotPricing(k.ID()); ok {
  1006. var spotcost string
  1007. log.DedupedInfof(5, "Looking up spot data from feed for node %s", k.ID())
  1008. arr := strings.Split(spotInfo.Charge, " ")
  1009. if len(arr) == 2 {
  1010. spotcost = arr[0]
  1011. } else {
  1012. klog.V(2).Infof("Spot data for node %s is missing", k.ID())
  1013. }
  1014. return &Node{
  1015. Cost: spotcost,
  1016. VCPU: terms.VCpu,
  1017. RAM: terms.Memory,
  1018. GPU: terms.GPU,
  1019. Storage: terms.Storage,
  1020. BaseCPUPrice: aws.BaseCPUPrice,
  1021. BaseRAMPrice: aws.BaseRAMPrice,
  1022. BaseGPUPrice: aws.BaseGPUPrice,
  1023. UsageType: PreemptibleType,
  1024. }, nil
  1025. } else if aws.isPreemptible(key) { // Preemptible but we don't have any data in the pricing report.
  1026. log.DedupedWarningf(5, "Node %s marked preemptible but we have no data in spot feed", k.ID())
  1027. return &Node{
  1028. VCPU: terms.VCpu,
  1029. VCPUCost: aws.BaseSpotCPUPrice,
  1030. RAM: terms.Memory,
  1031. GPU: terms.GPU,
  1032. Storage: terms.Storage,
  1033. BaseCPUPrice: aws.BaseCPUPrice,
  1034. BaseRAMPrice: aws.BaseRAMPrice,
  1035. BaseGPUPrice: aws.BaseGPUPrice,
  1036. UsageType: PreemptibleType,
  1037. }, nil
  1038. } else if sp, ok := aws.savingsPlanPricing(k.ID()); ok {
  1039. strCost := fmt.Sprintf("%f", sp.EffectiveCost)
  1040. return &Node{
  1041. Cost: strCost,
  1042. VCPU: terms.VCpu,
  1043. RAM: terms.Memory,
  1044. GPU: terms.GPU,
  1045. Storage: terms.Storage,
  1046. BaseCPUPrice: aws.BaseCPUPrice,
  1047. BaseRAMPrice: aws.BaseRAMPrice,
  1048. BaseGPUPrice: aws.BaseGPUPrice,
  1049. UsageType: usageType,
  1050. }, nil
  1051. } else if ri, ok := aws.reservedInstancePricing(k.ID()); ok {
  1052. strCost := fmt.Sprintf("%f", ri.EffectiveCost)
  1053. return &Node{
  1054. Cost: strCost,
  1055. VCPU: terms.VCpu,
  1056. RAM: terms.Memory,
  1057. GPU: terms.GPU,
  1058. Storage: terms.Storage,
  1059. BaseCPUPrice: aws.BaseCPUPrice,
  1060. BaseRAMPrice: aws.BaseRAMPrice,
  1061. BaseGPUPrice: aws.BaseGPUPrice,
  1062. UsageType: usageType,
  1063. }, nil
  1064. }
  1065. var cost string
  1066. c, ok := terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCode+HourlyRateCode]
  1067. if ok {
  1068. cost = c.PricePerUnit.USD
  1069. } else {
  1070. // Check for Chinese pricing before throwing error
  1071. c, ok = terms.OnDemand.PriceDimensions[terms.Sku+OnDemandRateCodeCn+HourlyRateCodeCn]
  1072. if ok {
  1073. cost = c.PricePerUnit.CNY
  1074. } else {
  1075. return nil, fmt.Errorf("Could not fetch data for \"%s\"", k.ID())
  1076. }
  1077. }
  1078. return &Node{
  1079. Cost: cost,
  1080. VCPU: terms.VCpu,
  1081. RAM: terms.Memory,
  1082. GPU: terms.GPU,
  1083. Storage: terms.Storage,
  1084. BaseCPUPrice: aws.BaseCPUPrice,
  1085. BaseRAMPrice: aws.BaseRAMPrice,
  1086. BaseGPUPrice: aws.BaseGPUPrice,
  1087. UsageType: usageType,
  1088. }, nil
  1089. }
  1090. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  1091. func (aws *AWS) NodePricing(k Key) (*Node, error) {
  1092. aws.DownloadPricingDataLock.RLock()
  1093. defer aws.DownloadPricingDataLock.RUnlock()
  1094. key := k.Features()
  1095. usageType := "ondemand"
  1096. if aws.isPreemptible(key) {
  1097. usageType = PreemptibleType
  1098. }
  1099. terms, ok := aws.Pricing[key]
  1100. if ok {
  1101. return aws.createNode(terms, usageType, k)
  1102. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  1103. aws.DownloadPricingDataLock.RUnlock()
  1104. err := aws.DownloadPricingData()
  1105. aws.DownloadPricingDataLock.RLock()
  1106. if err != nil {
  1107. return &Node{
  1108. Cost: aws.BaseCPUPrice,
  1109. BaseCPUPrice: aws.BaseCPUPrice,
  1110. BaseRAMPrice: aws.BaseRAMPrice,
  1111. BaseGPUPrice: aws.BaseGPUPrice,
  1112. UsageType: usageType,
  1113. UsesBaseCPUPrice: true,
  1114. }, err
  1115. }
  1116. terms, termsOk := aws.Pricing[key]
  1117. if !termsOk {
  1118. return &Node{
  1119. Cost: aws.BaseCPUPrice,
  1120. BaseCPUPrice: aws.BaseCPUPrice,
  1121. BaseRAMPrice: aws.BaseRAMPrice,
  1122. BaseGPUPrice: aws.BaseGPUPrice,
  1123. UsageType: usageType,
  1124. UsesBaseCPUPrice: true,
  1125. }, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  1126. }
  1127. return aws.createNode(terms, usageType, k)
  1128. } else { // Fall back to base pricing if we can't find the key. Base pricing is handled at the costmodel level.
  1129. return nil, fmt.Errorf("Invalid Pricing Key \"%s\"", key)
  1130. }
  1131. }
  1132. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  1133. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  1134. defaultClusterName := "AWS Cluster #1"
  1135. c, err := awsProvider.GetConfig()
  1136. if err != nil {
  1137. return nil, err
  1138. }
  1139. remoteEnabled := env.IsRemoteEnabled()
  1140. makeStructure := func(clusterName string) (map[string]string, error) {
  1141. m := make(map[string]string)
  1142. m["name"] = clusterName
  1143. m["provider"] = "AWS"
  1144. m["account"] = c.AthenaProjectID // this value requires configuration but is unavailable else where
  1145. m["region"] = awsProvider.clusterRegion
  1146. m["id"] = env.GetClusterID()
  1147. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1148. m["provisioner"] = awsProvider.clusterProvisioner
  1149. return m, nil
  1150. }
  1151. if c.ClusterName != "" {
  1152. return makeStructure(c.ClusterName)
  1153. }
  1154. maybeClusterId := env.GetAWSClusterID()
  1155. if len(maybeClusterId) != 0 {
  1156. klog.V(2).Infof("Returning \"%s\" as ClusterName", maybeClusterId)
  1157. return makeStructure(maybeClusterId)
  1158. }
  1159. klog.V(2).Infof("Unable to sniff out cluster ID, perhaps set $%s to force one", env.AWSClusterIDEnvVar)
  1160. return makeStructure(defaultClusterName)
  1161. }
  1162. // updates the authentication to the latest values (via config or secret)
  1163. func (aws *AWS) ConfigureAuth() error {
  1164. c, err := aws.Config.GetCustomPricingData()
  1165. if err != nil {
  1166. klog.V(1).Infof("Error downloading default pricing data: %s", err.Error())
  1167. }
  1168. return aws.ConfigureAuthWith(c)
  1169. }
  1170. // updates the authentication to the latest values (via config or secret)
  1171. func (aws *AWS) ConfigureAuthWith(config *CustomPricing) error {
  1172. accessKeyID, accessKeySecret := aws.getAWSAuth(false, config)
  1173. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1174. err := env.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1175. if err != nil {
  1176. return err
  1177. }
  1178. err = env.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1179. if err != nil {
  1180. return err
  1181. }
  1182. }
  1183. return nil
  1184. }
  1185. // Gets the aws key id and secret
  1186. func (aws *AWS) getAWSAuth(forceReload bool, cp *CustomPricing) (string, string) {
  1187. // 1. Check config values first (set from frontend UI)
  1188. if cp.ServiceKeyName != "" && cp.ServiceKeySecret != "" {
  1189. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1190. Message: "AWS ServiceKey exists",
  1191. Status: true,
  1192. })
  1193. return cp.ServiceKeyName, cp.ServiceKeySecret
  1194. }
  1195. // 2. Check for secret
  1196. s, _ := aws.loadAWSAuthSecret(forceReload)
  1197. if s != nil && s.AccessKeyID != "" && s.SecretAccessKey != "" {
  1198. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1199. Message: "AWS ServiceKey exists",
  1200. Status: true,
  1201. })
  1202. return s.AccessKeyID, s.SecretAccessKey
  1203. }
  1204. // 3. Fall back to env vars
  1205. if env.GetAWSAccessKeyID() == "" || env.GetAWSAccessKeyID() == "" {
  1206. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1207. Message: "AWS ServiceKey exists",
  1208. Status: false,
  1209. })
  1210. } else {
  1211. aws.serviceAccountChecks.set("hasKey", &ServiceAccountCheck{
  1212. Message: "AWS ServiceKey exists",
  1213. Status: true,
  1214. })
  1215. }
  1216. return env.GetAWSAccessKeyID(), env.GetAWSAccessKeySecret()
  1217. }
  1218. // Load once and cache the result (even on failure). This is an install time secret, so
  1219. // we don't expect the secret to change. If it does, however, we can force reload using
  1220. // the input parameter.
  1221. func (aws *AWS) loadAWSAuthSecret(force bool) (*AWSAccessKey, error) {
  1222. if !force && loadedAWSSecret {
  1223. return awsSecret, nil
  1224. }
  1225. loadedAWSSecret = true
  1226. exists, err := fileutil.FileExists(authSecretPath)
  1227. if !exists || err != nil {
  1228. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  1229. }
  1230. result, err := ioutil.ReadFile(authSecretPath)
  1231. if err != nil {
  1232. return nil, err
  1233. }
  1234. var ak AWSAccessKey
  1235. err = json.Unmarshal(result, &ak)
  1236. if err != nil {
  1237. return nil, err
  1238. }
  1239. awsSecret = &ak
  1240. return awsSecret, nil
  1241. }
  1242. func (aws *AWS) getAddressesForRegion(ctx context.Context, region string) (*ec2.DescribeAddressesOutput, error) {
  1243. aak, err := aws.GetAWSAccessKey()
  1244. if err != nil {
  1245. return nil, err
  1246. }
  1247. cfg, err := aak.CreateConfig(region)
  1248. if err != nil {
  1249. return nil, err
  1250. }
  1251. cli := ec2.NewFromConfig(cfg)
  1252. return cli.DescribeAddresses(ctx, &ec2.DescribeAddressesInput{})
  1253. }
  1254. // GetAddresses retrieves EC2 addresses
  1255. func (aws *AWS) GetAddresses() ([]byte, error) {
  1256. aws.ConfigureAuth() // load authentication data into env vars
  1257. addressCh := make(chan *ec2.DescribeAddressesOutput, len(awsRegions))
  1258. errorCh := make(chan error, len(awsRegions))
  1259. var wg sync.WaitGroup
  1260. wg.Add(len(awsRegions))
  1261. // Get volumes from each AWS region
  1262. for _, r := range awsRegions {
  1263. // Fetch IP address response and send results and errors to their
  1264. // respective channels
  1265. go func(region string) {
  1266. defer wg.Done()
  1267. defer errors.HandlePanic()
  1268. // Query for first page of volume results
  1269. resp, err := aws.getAddressesForRegion(context.TODO(), region)
  1270. if err != nil {
  1271. errorCh <- err
  1272. return
  1273. }
  1274. addressCh <- resp
  1275. }(r)
  1276. }
  1277. // Close the result channels after everything has been sent
  1278. go func() {
  1279. defer errors.HandlePanic()
  1280. wg.Wait()
  1281. close(errorCh)
  1282. close(addressCh)
  1283. }()
  1284. var addresses []*ec2Types.Address
  1285. for adds := range addressCh {
  1286. for _, add := range adds.Addresses {
  1287. a := add // duplicate to avoid pointer to iterator
  1288. addresses = append(addresses, &a)
  1289. }
  1290. }
  1291. var errs []error
  1292. for err := range errorCh {
  1293. log.DedupedWarningf(5, "unable to get addresses: %s", err)
  1294. errs = append(errs, err)
  1295. }
  1296. // Return error if no addresses are returned
  1297. if len(errs) > 0 && len(addresses) == 0 {
  1298. return nil, fmt.Errorf("%d error(s) retrieving addresses: %v", len(errs), errs)
  1299. }
  1300. // Format the response this way to match the JSON-encoded formatting of a single response
  1301. // from DescribeAddresss, so that consumers can always expect AWS disk responses to have
  1302. // a "Addresss" key at the top level.
  1303. return json.Marshal(map[string][]*ec2Types.Address{
  1304. "Addresses": addresses,
  1305. })
  1306. }
  1307. func (aws *AWS) getDisksForRegion(ctx context.Context, region string, maxResults int32, nextToken *string) (*ec2.DescribeVolumesOutput, error) {
  1308. aak, err := aws.GetAWSAccessKey()
  1309. if err != nil {
  1310. return nil, err
  1311. }
  1312. cfg, err := aak.CreateConfig(region)
  1313. if err != nil {
  1314. return nil, err
  1315. }
  1316. cli := ec2.NewFromConfig(cfg)
  1317. return cli.DescribeVolumes(ctx, &ec2.DescribeVolumesInput{
  1318. MaxResults: &maxResults,
  1319. NextToken: nextToken,
  1320. })
  1321. }
  1322. // 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.
  1323. func (aws *AWS) GetDisks() ([]byte, error) {
  1324. aws.ConfigureAuth() // load authentication data into env vars
  1325. volumeCh := make(chan *ec2.DescribeVolumesOutput, len(awsRegions))
  1326. errorCh := make(chan error, len(awsRegions))
  1327. var wg sync.WaitGroup
  1328. wg.Add(len(awsRegions))
  1329. // Get volumes from each AWS region
  1330. for _, r := range awsRegions {
  1331. // Fetch volume response and send results and errors to their
  1332. // respective channels
  1333. go func(region string) {
  1334. defer wg.Done()
  1335. defer errors.HandlePanic()
  1336. // Query for first page of volume results
  1337. resp, err := aws.getDisksForRegion(context.TODO(), region, 1000, nil)
  1338. if err != nil {
  1339. errorCh <- err
  1340. return
  1341. }
  1342. volumeCh <- resp
  1343. // A NextToken indicates more pages of results. Keep querying
  1344. // until all pages are retrieved.
  1345. for resp.NextToken != nil {
  1346. resp, err = aws.getDisksForRegion(context.TODO(), region, 100, resp.NextToken)
  1347. if err != nil {
  1348. errorCh <- err
  1349. return
  1350. }
  1351. volumeCh <- resp
  1352. }
  1353. }(r)
  1354. }
  1355. // Close the result channels after everything has been sent
  1356. go func() {
  1357. defer errors.HandlePanic()
  1358. wg.Wait()
  1359. close(errorCh)
  1360. close(volumeCh)
  1361. }()
  1362. var volumes []*ec2Types.Volume
  1363. for vols := range volumeCh {
  1364. for _, vol := range vols.Volumes {
  1365. v := vol // duplicate to avoid pointer to iterator
  1366. volumes = append(volumes, &v)
  1367. }
  1368. }
  1369. var errs []error
  1370. for err := range errorCh {
  1371. log.DedupedWarningf(5, "unable to get disks: %s", err)
  1372. errs = append(errs, err)
  1373. }
  1374. // Return error if no volumes are returned
  1375. if len(errs) > 0 && len(volumes) == 0 {
  1376. return nil, fmt.Errorf("%d error(s) retrieving volumes: %v", len(errs), errs)
  1377. }
  1378. // Format the response this way to match the JSON-encoded formatting of a single response
  1379. // from DescribeVolumes, so that consumers can always expect AWS disk responses to have
  1380. // a "Volumes" key at the top level.
  1381. return json.Marshal(map[string][]*ec2Types.Volume{
  1382. "Volumes": volumes,
  1383. })
  1384. }
  1385. // QueryAthenaPaginated executes athena query and processes results.
  1386. func (aws *AWS) QueryAthenaPaginated(ctx context.Context, query string, fn func(*athena.GetQueryResultsOutput) bool) error {
  1387. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  1388. if err != nil {
  1389. return err
  1390. }
  1391. if awsAthenaInfo.AthenaDatabase == "" || awsAthenaInfo.AthenaTable == "" || awsAthenaInfo.AthenaRegion == "" ||
  1392. awsAthenaInfo.AthenaBucketName == "" || awsAthenaInfo.AccountID == "" {
  1393. return fmt.Errorf("QueryAthenaPaginated: athena configuration incomplete")
  1394. }
  1395. queryExecutionCtx := &athenaTypes.QueryExecutionContext{
  1396. Database: awsSDK.String(awsAthenaInfo.AthenaDatabase),
  1397. }
  1398. resultConfiguration := &athenaTypes.ResultConfiguration{
  1399. OutputLocation: awsSDK.String(awsAthenaInfo.AthenaBucketName),
  1400. }
  1401. startQueryExecutionInput := &athena.StartQueryExecutionInput{
  1402. QueryString: awsSDK.String(query),
  1403. QueryExecutionContext: queryExecutionCtx,
  1404. ResultConfiguration: resultConfiguration,
  1405. }
  1406. // Create Athena Client
  1407. cfg, err := awsAthenaInfo.CreateConfig()
  1408. if err != nil {
  1409. log.Errorf("Could not retrieve Athena Configuration: %s", err.Error())
  1410. }
  1411. cli := athena.NewFromConfig(cfg)
  1412. // Query Athena
  1413. startQueryExecutionOutput, err := cli.StartQueryExecution(ctx, startQueryExecutionInput)
  1414. if err != nil {
  1415. log.Errorf(err.Error())
  1416. }
  1417. waitForQueryToComplete(ctx, cli, startQueryExecutionOutput.QueryExecutionId)
  1418. queryResultsInput := &athena.GetQueryResultsInput{
  1419. QueryExecutionId: startQueryExecutionOutput.QueryExecutionId,
  1420. }
  1421. getQueryResultsPaginator := athena.NewGetQueryResultsPaginator(cli, queryResultsInput)
  1422. for getQueryResultsPaginator.HasMorePages() {
  1423. pg, err := getQueryResultsPaginator.NextPage(ctx)
  1424. if err != nil {
  1425. log.Errorf("QueryAthenaPaginated: NextPage error: %s", err.Error())
  1426. continue
  1427. }
  1428. fn(pg)
  1429. }
  1430. return nil
  1431. }
  1432. func waitForQueryToComplete(ctx context.Context, client *athena.Client, queryExecutionID *string) {
  1433. inp := &athena.GetQueryExecutionInput{
  1434. QueryExecutionId: queryExecutionID,
  1435. }
  1436. isQueryStillRunning := true
  1437. for isQueryStillRunning {
  1438. qe, _ := client.GetQueryExecution(ctx, inp)
  1439. if qe.QueryExecution.Status.State == "SUCCEEDED" {
  1440. isQueryStillRunning = false
  1441. }
  1442. time.Sleep(2 * time.Second)
  1443. }
  1444. }
  1445. type SavingsPlanData struct {
  1446. ResourceID string
  1447. EffectiveCost float64
  1448. SavingsPlanARN string
  1449. MostRecentDate string
  1450. }
  1451. func (aws *AWS) GetSavingsPlanDataFromAthena() error {
  1452. cfg, err := aws.GetConfig()
  1453. if err != nil {
  1454. return err
  1455. }
  1456. if cfg.AthenaBucketName == "" {
  1457. return fmt.Errorf("No Athena Bucket configured")
  1458. }
  1459. if aws.SavingsPlanDataByInstanceID == nil {
  1460. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData)
  1461. }
  1462. tNow := time.Now()
  1463. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1464. start := tOneDayAgo.Format("2006-01-02")
  1465. end := tNow.Format("2006-01-02")
  1466. // Use Savings Plan Effective Rate as an estimation for cost, assuming the 1h most recent period got a fully loaded savings plan.
  1467. //
  1468. q := `SELECT
  1469. line_item_usage_start_date,
  1470. savings_plan_savings_plan_a_r_n,
  1471. line_item_resource_id,
  1472. savings_plan_savings_plan_rate
  1473. FROM %s as cost_data
  1474. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1475. AND line_item_line_item_type = 'SavingsPlanCoveredUsage' ORDER BY
  1476. line_item_usage_start_date DESC`
  1477. page := 0
  1478. processResults := func(op *athena.GetQueryResultsOutput) bool {
  1479. if op == nil {
  1480. log.Errorf("GetSavingsPlanDataFromAthena: Athena page is nil")
  1481. return false
  1482. } else if op.ResultSet == nil {
  1483. log.Errorf("GetSavingsPlanDataFromAthena: Athena page.ResultSet is nil")
  1484. return false
  1485. }
  1486. aws.SavingsPlanDataLock.Lock()
  1487. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData) // Clean out the old data and only report a savingsplan price if its in the most recent run.
  1488. mostRecentDate := ""
  1489. iter := op.ResultSet.Rows
  1490. if page == 0 && len(iter) > 0 {
  1491. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  1492. }
  1493. page++
  1494. for _, r := range iter {
  1495. d := *r.Data[0].VarCharValue
  1496. if mostRecentDate == "" {
  1497. mostRecentDate = d
  1498. } else if mostRecentDate != d { // Get all most recent assignments
  1499. break
  1500. }
  1501. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1502. if err != nil {
  1503. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1504. }
  1505. r := &SavingsPlanData{
  1506. ResourceID: *r.Data[2].VarCharValue,
  1507. EffectiveCost: cost,
  1508. SavingsPlanARN: *r.Data[1].VarCharValue,
  1509. MostRecentDate: d,
  1510. }
  1511. aws.SavingsPlanDataByInstanceID[r.ResourceID] = r
  1512. }
  1513. klog.V(1).Infof("Found %d savings plan applied instances", len(aws.SavingsPlanDataByInstanceID))
  1514. for k, r := range aws.SavingsPlanDataByInstanceID {
  1515. log.DedupedInfof(5, "Savings Plan Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1516. }
  1517. aws.SavingsPlanDataLock.Unlock()
  1518. return true
  1519. }
  1520. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1521. klog.V(3).Infof("Running Query: %s", query)
  1522. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  1523. if err != nil {
  1524. return fmt.Errorf("Error fetching Savings Plan Data: %s", err)
  1525. }
  1526. return nil
  1527. }
  1528. type RIData struct {
  1529. ResourceID string
  1530. EffectiveCost float64
  1531. ReservationARN string
  1532. MostRecentDate string
  1533. }
  1534. func (aws *AWS) GetReservationDataFromAthena() error {
  1535. cfg, err := aws.GetConfig()
  1536. if err != nil {
  1537. return err
  1538. }
  1539. if cfg.AthenaBucketName == "" {
  1540. return fmt.Errorf("No Athena Bucket configured")
  1541. }
  1542. // Query for all column names in advance in order to validate configured
  1543. // label columns
  1544. columns, _ := aws.fetchColumns()
  1545. if !columns["reservation_reservation_a_r_n"] || !columns["reservation_effective_cost"] {
  1546. klog.Infof("No reserved data available in Athena")
  1547. aws.RIPricingError = nil
  1548. }
  1549. if aws.RIPricingByInstanceID == nil {
  1550. aws.RIPricingByInstanceID = make(map[string]*RIData)
  1551. }
  1552. tNow := time.Now()
  1553. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1554. start := tOneDayAgo.Format("2006-01-02")
  1555. end := tNow.Format("2006-01-02")
  1556. q := `SELECT
  1557. line_item_usage_start_date,
  1558. reservation_reservation_a_r_n,
  1559. line_item_resource_id,
  1560. reservation_effective_cost
  1561. FROM %s as cost_data
  1562. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1563. AND reservation_reservation_a_r_n <> '' ORDER BY
  1564. line_item_usage_start_date DESC`
  1565. page := 0
  1566. processResults := func(op *athena.GetQueryResultsOutput) bool {
  1567. if op == nil {
  1568. log.Errorf("GetReservationDataFromAthena: Athena page is nil")
  1569. return false
  1570. } else if op.ResultSet == nil {
  1571. log.Errorf("GetReservationDataFromAthena: Athena page.ResultSet is nil")
  1572. return false
  1573. }
  1574. aws.RIDataLock.Lock()
  1575. aws.RIPricingByInstanceID = make(map[string]*RIData) // Clean out the old data and only report a RI price if its in the most recent run.
  1576. mostRecentDate := ""
  1577. iter := op.ResultSet.Rows
  1578. if page == 0 && len(iter) > 0 {
  1579. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  1580. }
  1581. page++
  1582. for _, r := range iter {
  1583. d := *r.Data[0].VarCharValue
  1584. if mostRecentDate == "" {
  1585. mostRecentDate = d
  1586. } else if mostRecentDate != d { // Get all most recent assignments
  1587. break
  1588. }
  1589. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  1590. if err != nil {
  1591. klog.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  1592. }
  1593. r := &RIData{
  1594. ResourceID: *r.Data[2].VarCharValue,
  1595. EffectiveCost: cost,
  1596. ReservationARN: *r.Data[1].VarCharValue,
  1597. MostRecentDate: d,
  1598. }
  1599. aws.RIPricingByInstanceID[r.ResourceID] = r
  1600. }
  1601. klog.V(1).Infof("Found %d reserved instances", len(aws.RIPricingByInstanceID))
  1602. for k, r := range aws.RIPricingByInstanceID {
  1603. log.DedupedInfof(5, "Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  1604. }
  1605. aws.RIDataLock.Unlock()
  1606. return true
  1607. }
  1608. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  1609. klog.V(3).Infof("Running Query: %s", query)
  1610. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  1611. if err != nil {
  1612. aws.RIPricingError = err
  1613. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  1614. }
  1615. aws.RIPricingError = nil
  1616. return nil
  1617. }
  1618. // fetchColumns returns a list of the names of all columns in the configured
  1619. // Athena tables
  1620. func (aws *AWS) fetchColumns() (map[string]bool, error) {
  1621. columnSet := map[string]bool{}
  1622. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  1623. if err != nil {
  1624. return nil, err
  1625. }
  1626. // This Query is supported by Athena tables and views
  1627. q := `SELECT column_name FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s'`
  1628. query := fmt.Sprintf(q, awsAthenaInfo.AthenaDatabase, awsAthenaInfo.AthenaTable)
  1629. pageNum := 0
  1630. athenaErr := aws.QueryAthenaPaginated(context.TODO(), query, func(page *athena.GetQueryResultsOutput) bool {
  1631. if page == nil {
  1632. log.Errorf("fetchColumns: Athena page is nil")
  1633. return false
  1634. } else if page.ResultSet == nil {
  1635. log.Errorf("fetchColumns: Athena page.ResultSet is nil")
  1636. return false
  1637. }
  1638. // remove header row 'column_name'
  1639. rows := page.ResultSet.Rows[1:]
  1640. for _, row := range rows {
  1641. columnSet[*row.Data[0].VarCharValue] = true
  1642. }
  1643. pageNum++
  1644. return true
  1645. })
  1646. if athenaErr != nil {
  1647. return columnSet, athenaErr
  1648. }
  1649. if len(columnSet) == 0 {
  1650. log.Infof("No columns retrieved from Athena")
  1651. }
  1652. return columnSet, nil
  1653. }
  1654. type spotInfo struct {
  1655. Timestamp string `csv:"Timestamp"`
  1656. UsageType string `csv:"UsageType"`
  1657. Operation string `csv:"Operation"`
  1658. InstanceID string `csv:"InstanceID"`
  1659. MyBidID string `csv:"MyBidID"`
  1660. MyMaxPrice string `csv:"MyMaxPrice"`
  1661. MarketPrice string `csv:"MarketPrice"`
  1662. Charge string `csv:"Charge"`
  1663. Version string `csv:"Version"`
  1664. }
  1665. func (aws *AWS) parseSpotData(bucket string, prefix string, projectID string, region string) (map[string]*spotInfo, error) {
  1666. aws.ConfigureAuth() // configure aws api authentication by setting env vars
  1667. s3Prefix := projectID
  1668. if len(prefix) != 0 {
  1669. s3Prefix = prefix + "/" + s3Prefix
  1670. }
  1671. aak, err := aws.GetAWSAccessKey()
  1672. if err != nil {
  1673. return nil, err
  1674. }
  1675. cfg, err := aak.CreateConfig(region)
  1676. if err != nil {
  1677. return nil, err
  1678. }
  1679. cli := s3.NewFromConfig(cfg)
  1680. downloader := manager.NewDownloader(cli)
  1681. tNow := time.Now()
  1682. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1683. ls := &s3.ListObjectsInput{
  1684. Bucket: awsSDK.String(bucket),
  1685. Prefix: awsSDK.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  1686. }
  1687. ls2 := &s3.ListObjectsInput{
  1688. Bucket: awsSDK.String(bucket),
  1689. Prefix: awsSDK.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  1690. }
  1691. lso, err := cli.ListObjects(context.TODO(), ls)
  1692. if err != nil {
  1693. aws.serviceAccountChecks.set("bucketList", &ServiceAccountCheck{
  1694. Message: "Bucket List Permissions Available",
  1695. Status: false,
  1696. AdditionalInfo: err.Error(),
  1697. })
  1698. return nil, err
  1699. } else {
  1700. aws.serviceAccountChecks.set("bucketList", &ServiceAccountCheck{
  1701. Message: "Bucket List Permissions Available",
  1702. Status: true,
  1703. })
  1704. }
  1705. lsoLen := len(lso.Contents)
  1706. klog.V(2).Infof("Found %d spot data files from yesterday", lsoLen)
  1707. if lsoLen == 0 {
  1708. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  1709. }
  1710. lso2, err := cli.ListObjects(context.TODO(), ls2)
  1711. if err != nil {
  1712. return nil, err
  1713. }
  1714. lso2Len := len(lso2.Contents)
  1715. klog.V(2).Infof("Found %d spot data files from today", lso2Len)
  1716. if lso2Len == 0 {
  1717. klog.V(5).Infof("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  1718. }
  1719. // TODO: Worth it to use LastModifiedDate to determine if we should reparse the spot data?
  1720. var keys []*string
  1721. for _, obj := range lso.Contents {
  1722. keys = append(keys, obj.Key)
  1723. }
  1724. for _, obj := range lso2.Contents {
  1725. keys = append(keys, obj.Key)
  1726. }
  1727. versionRx := regexp.MustCompile("^#Version: (\\d+)\\.\\d+$")
  1728. header, err := csvutil.Header(spotInfo{}, "csv")
  1729. if err != nil {
  1730. return nil, err
  1731. }
  1732. fieldsPerRecord := len(header)
  1733. spots := make(map[string]*spotInfo)
  1734. for _, key := range keys {
  1735. getObj := &s3.GetObjectInput{
  1736. Bucket: awsSDK.String(bucket),
  1737. Key: key,
  1738. }
  1739. buf := manager.NewWriteAtBuffer([]byte{})
  1740. _, err := downloader.Download(context.TODO(), buf, getObj)
  1741. if err != nil {
  1742. aws.serviceAccountChecks.set("objectList", &ServiceAccountCheck{
  1743. Message: "Object Get Permissions Available",
  1744. Status: false,
  1745. AdditionalInfo: err.Error(),
  1746. })
  1747. return nil, err
  1748. } else {
  1749. aws.serviceAccountChecks.set("objectList", &ServiceAccountCheck{
  1750. Message: "Object Get Permissions Available",
  1751. Status: true,
  1752. })
  1753. }
  1754. r := bytes.NewReader(buf.Bytes())
  1755. gr, err := gzip.NewReader(r)
  1756. if err != nil {
  1757. return nil, err
  1758. }
  1759. csvReader := csv.NewReader(gr)
  1760. csvReader.Comma = '\t'
  1761. csvReader.FieldsPerRecord = fieldsPerRecord
  1762. dec, err := csvutil.NewDecoder(csvReader, header...)
  1763. if err != nil {
  1764. return nil, err
  1765. }
  1766. var foundVersion string
  1767. for {
  1768. spot := spotInfo{}
  1769. err := dec.Decode(&spot)
  1770. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  1771. if err == io.EOF {
  1772. break
  1773. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  1774. rec := dec.Record()
  1775. // the first two "Record()" will be the comment lines
  1776. // and they show up as len() == 1
  1777. // the first of which is "#Version"
  1778. // the second of which is "#Fields: "
  1779. if len(rec) != 1 {
  1780. klog.V(2).Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  1781. continue
  1782. }
  1783. if len(foundVersion) == 0 {
  1784. spotFeedVersion := rec[0]
  1785. klog.V(4).Infof("Spot feed version is \"%s\"", spotFeedVersion)
  1786. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  1787. if matches != nil {
  1788. foundVersion = matches[1]
  1789. if foundVersion != supportedSpotFeedVersion {
  1790. klog.V(2).Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  1791. break
  1792. }
  1793. }
  1794. continue
  1795. } else if strings.Index(rec[0], "#") == 0 {
  1796. continue
  1797. } else {
  1798. klog.V(3).Infof("skipping non-TSV line: %s", rec)
  1799. continue
  1800. }
  1801. } else if err != nil {
  1802. klog.V(2).Infof("Error during spot info decode: %+v", err)
  1803. continue
  1804. }
  1805. log.DedupedInfof(5, "Found spot info for: %s", spot.InstanceID)
  1806. spots[spot.InstanceID] = &spot
  1807. }
  1808. gr.Close()
  1809. }
  1810. return spots, nil
  1811. }
  1812. // ApplyReservedInstancePricing TODO
  1813. func (aws *AWS) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1814. }
  1815. func (aws *AWS) ServiceAccountStatus() *ServiceAccountStatus {
  1816. return aws.serviceAccountChecks.getStatus()
  1817. }
  1818. func (aws *AWS) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1819. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1820. }
  1821. // Regions returns a predefined list of AWS regions
  1822. func (aws *AWS) Regions() []string {
  1823. return awsRegions
  1824. }