awsprovider.go 66 KB

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