awsprovider.go 63 KB

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