provider.go 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636
  1. package aws
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "context"
  6. "encoding/csv"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/aws/smithy-go"
  18. "github.com/opencost/opencost/pkg/cloud/httputil"
  19. "github.com/opencost/opencost/pkg/cloud/models"
  20. "github.com/opencost/opencost/pkg/cloud/utils"
  21. "github.com/opencost/opencost/core/pkg/clustercache"
  22. coreenv "github.com/opencost/opencost/core/pkg/env"
  23. errs "github.com/opencost/opencost/core/pkg/errors"
  24. "github.com/opencost/opencost/core/pkg/log"
  25. "github.com/opencost/opencost/core/pkg/opencost"
  26. "github.com/opencost/opencost/core/pkg/util"
  27. "github.com/opencost/opencost/core/pkg/util/fileutil"
  28. "github.com/opencost/opencost/core/pkg/util/json"
  29. "github.com/opencost/opencost/core/pkg/util/timeutil"
  30. "github.com/opencost/opencost/pkg/env"
  31. awsSDK "github.com/aws/aws-sdk-go-v2/aws"
  32. "github.com/aws/aws-sdk-go-v2/config"
  33. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  34. "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
  35. "github.com/aws/aws-sdk-go-v2/service/athena"
  36. athenaTypes "github.com/aws/aws-sdk-go-v2/service/athena/types"
  37. "github.com/aws/aws-sdk-go-v2/service/ec2"
  38. ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
  39. "github.com/aws/aws-sdk-go-v2/service/s3"
  40. "github.com/aws/aws-sdk-go-v2/service/sts"
  41. "github.com/jszwec/csvutil"
  42. )
  43. const (
  44. supportedSpotFeedVersion = "1"
  45. SpotInfoUpdateType = "spotinfo"
  46. AthenaInfoUpdateType = "athenainfo"
  47. PreemptibleType = "preemptible"
  48. APIPricingSource = "Public API"
  49. SpotPricingSource = "Spot Data Feed"
  50. SpotPriceHistorySource = "Spot Price History"
  51. ReservedInstancePricingSource = "Savings Plan, Reserved Instance, and Out-Of-Cluster"
  52. FargatePricingSource = "Fargate"
  53. InUseState = "in-use"
  54. AttachedState = "attached"
  55. AWSHourlyPublicIPCost = 0.005
  56. EKSCapacityTypeLabel = "eks.amazonaws.com/capacityType"
  57. EKSCapacitySpotTypeValue = "SPOT"
  58. // relevant to pricing url
  59. awsPricingBaseURL = "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/"
  60. awsChinaPricingBaseURL = "https://pricing.cn-north-1.amazonaws.com.cn/offers/v1.0/cn/"
  61. pricingCurrentPath = "/current/"
  62. pricingIndexFile = "index.json"
  63. chinaRegionPrefix = "cn-"
  64. )
  65. var (
  66. // It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
  67. provIdRx = regexp.MustCompile("aws:///([^/]+)/([^/]+)")
  68. usageTypeRegx = regexp.MustCompile(".*(-|^)(EBS.+)")
  69. versionRx = regexp.MustCompile(`^#Version: (\\d+)\\.\\d+$`)
  70. regionRx = regexp.MustCompile("([a-z]+-[a-z]+-[0-9])")
  71. ErrNoAthenaBucket = errors.New("No Athena Bucket configured")
  72. // StorageClassProvisionerDefaults specifies the default storage class types depending upon the provisioner
  73. StorageClassProvisionerDefaults = map[string]string{
  74. "kubernetes.io/aws-ebs": "gp2",
  75. "ebs.csi.aws.com": "gp3",
  76. // TODO: add efs provisioner
  77. }
  78. )
  79. func (aws *AWS) PricingSourceStatus() map[string]*models.PricingSource {
  80. sources := make(map[string]*models.PricingSource)
  81. sps := &models.PricingSource{
  82. Name: SpotPricingSource,
  83. Enabled: true,
  84. }
  85. if aws.SpotFeedRefreshEnabled() {
  86. sps.Error = ""
  87. if aws.SpotPricingError != nil {
  88. sps.Error = aws.SpotPricingError.Error()
  89. }
  90. if sps.Error != "" {
  91. sps.Available = false
  92. } else if len(aws.SpotPricingByInstanceID) > 0 {
  93. sps.Available = true
  94. } else {
  95. sps.Error = "No spot instances detected"
  96. }
  97. } else {
  98. sps.Available = false
  99. sps.Error = "Spot instances not set up"
  100. sps.Enabled = false
  101. }
  102. sources[SpotPricingSource] = sps
  103. sphs := &models.PricingSource{
  104. Name: SpotPriceHistorySource,
  105. Enabled: true,
  106. }
  107. if aws.SpotPriceHistoryError != nil {
  108. sphs.Error = aws.SpotPriceHistoryError.Error()
  109. sphs.Available = false
  110. } else if aws.SpotPriceHistoryCache == nil {
  111. sphs.Error = "Not yet initialized"
  112. sphs.Available = false
  113. } else {
  114. sphs.Available = true
  115. }
  116. sources[SpotPriceHistorySource] = sphs
  117. rps := &models.PricingSource{
  118. Name: ReservedInstancePricingSource,
  119. Enabled: true,
  120. }
  121. rps.Error = ""
  122. if aws.RIPricingError != nil {
  123. rps.Error = aws.RIPricingError.Error()
  124. }
  125. if rps.Error != "" {
  126. rps.Available = false
  127. } else {
  128. rps.Available = true
  129. }
  130. sources[ReservedInstancePricingSource] = rps
  131. fs := &models.PricingSource{
  132. Name: FargatePricingSource,
  133. Enabled: true,
  134. Available: true,
  135. }
  136. if aws.FargatePricingError != nil {
  137. fs.Error = aws.FargatePricingError.Error()
  138. fs.Available = false
  139. }
  140. sources[FargatePricingSource] = fs
  141. return sources
  142. }
  143. // SpotRefreshDuration represents how much time must pass before we refresh
  144. const SpotRefreshDuration = 15 * time.Minute
  145. var awsRegions = []string{
  146. "us-east-2",
  147. "us-east-1",
  148. "us-west-1",
  149. "us-west-2",
  150. "ap-east-1",
  151. "ap-south-1",
  152. "ap-northeast-3",
  153. "ap-northeast-2",
  154. "ap-southeast-1",
  155. "ap-southeast-2",
  156. "ap-northeast-1",
  157. "ap-southeast-3",
  158. "ca-central-1",
  159. "cn-north-1",
  160. "cn-northwest-1",
  161. "eu-central-1",
  162. "eu-west-1",
  163. "eu-west-2",
  164. "eu-west-3",
  165. "eu-north-1",
  166. "eu-south-1",
  167. "me-south-1",
  168. "sa-east-1",
  169. "af-south-1",
  170. "us-gov-east-1",
  171. "us-gov-west-1",
  172. "me-central-1",
  173. }
  174. // AWS represents an Amazon Provider
  175. type AWS struct {
  176. Pricing map[string]*AWSProductTerms
  177. SpotPricingByInstanceID map[string]*spotInfo
  178. SpotPricingUpdatedAt *time.Time
  179. SpotRefreshRunning bool
  180. SpotPricingLock sync.RWMutex
  181. SpotPricingError error
  182. SpotPriceHistoryCache *SpotPriceHistoryCache
  183. SpotPriceHistoryError error
  184. RIPricingByInstanceID map[string]*RIData
  185. RIPricingError error
  186. RIDataRunning bool
  187. RIDataLock sync.RWMutex
  188. SavingsPlanDataByInstanceID map[string]*SavingsPlanData
  189. SavingsPlanDataRunning bool
  190. SavingsPlanDataLock sync.RWMutex
  191. FargatePricing *FargatePricing
  192. FargatePricingError error
  193. ValidPricingKeys map[string]bool
  194. Clientset clustercache.ClusterCache
  195. BaseCPUPrice string
  196. BaseRAMPrice string
  197. BaseGPUPrice string
  198. BaseSpotCPUPrice string
  199. BaseSpotRAMPrice string
  200. BaseSpotGPUPrice string
  201. SpotLabelName string
  202. SpotLabelValue string
  203. SpotDataRegion string
  204. SpotDataBucket string
  205. SpotDataPrefix string
  206. ProjectID string
  207. DownloadPricingDataLock sync.RWMutex
  208. Config models.ProviderConfig
  209. ServiceAccountChecks *models.ServiceAccountChecks
  210. clusterManagementPrice float64
  211. ClusterRegion string
  212. ClusterAccountID string
  213. clusterProvisioner string
  214. }
  215. // AWSAccessKey holds AWS credentials and fulfils the awsV2.CredentialsProvider interface
  216. // Deprecated: v1.104 Use AccessKey instead
  217. type AWSAccessKey struct {
  218. AccessKeyID string `json:"aws_access_key_id"`
  219. SecretAccessKey string `json:"aws_secret_access_key"`
  220. }
  221. // Retrieve returns a set of awsV2 credentials using the AWSAccessKey's key and secret.
  222. // This fulfils the awsV2.CredentialsProvider interface contract.
  223. func (accessKey AWSAccessKey) Retrieve(ctx context.Context) (awsSDK.Credentials, error) {
  224. return awsSDK.Credentials{
  225. AccessKeyID: accessKey.AccessKeyID,
  226. SecretAccessKey: accessKey.SecretAccessKey,
  227. }, nil
  228. }
  229. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains for the provided region
  230. func (accessKey AWSAccessKey) CreateConfig(region string) (awsSDK.Config, error) {
  231. var cfg awsSDK.Config
  232. var err error
  233. // If accessKey values have not been provided, attempt to load cfg from service key annotations
  234. if accessKey.AccessKeyID == "" && accessKey.SecretAccessKey == "" {
  235. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
  236. if err != nil {
  237. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region from annotation %s: %s", region, err)
  238. }
  239. } else {
  240. // The AWS SDK v2 requires an object fulfilling the CredentialsProvider interface, which cloud.AWSAccessKey does
  241. cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(accessKey), config.WithRegion(region))
  242. if err != nil {
  243. return cfg, fmt.Errorf("failed to initialize AWS SDK config for region %s: %s", region, err)
  244. }
  245. }
  246. return cfg, nil
  247. }
  248. // AWSProductTerms represents the full terms of the product
  249. type AWSProductTerms struct {
  250. Sku string `json:"sku"`
  251. OnDemand *PriceListEC2Term `json:"OnDemand"`
  252. Reserved *PriceListEC2Term `json:"Reserved"`
  253. Memory string `json:"memory"`
  254. Storage string `json:"storage"`
  255. VCpu string `json:"vcpu"`
  256. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  257. PV *models.PV `json:"pv"`
  258. LoadBalancer *models.LoadBalancer `json:"load_balancer"`
  259. }
  260. // volTypes are used to map between AWS UsageTypes and
  261. // EBS volume types, as they would appear in K8s storage class
  262. // name and the EC2 API.
  263. var volTypes = map[string]string{
  264. "EBS:VolumeUsage.gp2": "gp2",
  265. "EBS:VolumeUsage.gp3": "gp3",
  266. "EBS:VolumeUsage": "standard",
  267. "EBS:VolumeUsage.sc1": "sc1",
  268. "EBS:VolumeP-IOPS.piops": "io1",
  269. "EBS:VolumeUsage.st1": "st1",
  270. "EBS:VolumeUsage.piops": "io1",
  271. "EBS:VolumeUsage.io2": "io2",
  272. "gp2": "EBS:VolumeUsage.gp2",
  273. "gp3": "EBS:VolumeUsage.gp3",
  274. "standard": "EBS:VolumeUsage",
  275. "sc1": "EBS:VolumeUsage.sc1",
  276. "io1": "EBS:VolumeUsage.piops",
  277. "st1": "EBS:VolumeUsage.st1",
  278. "io2": "EBS:VolumeUsage.io2",
  279. }
  280. var (
  281. loadedAWSSecret bool = false
  282. awsSecret *AWSAccessKey = nil
  283. )
  284. // KubeAttrConversion maps the k8s labels for region to an AWS key
  285. func (aws *AWS) KubeAttrConversion(region, instanceType, operatingSystem string) string {
  286. operatingSystem = strings.ToLower(operatingSystem)
  287. return region + "," + instanceType + "," + operatingSystem
  288. }
  289. // AwsSpotFeedInfo contains configuration for spot feed integration
  290. type AwsSpotFeedInfo struct {
  291. BucketName string `json:"bucketName"`
  292. Prefix string `json:"prefix"`
  293. Region string `json:"region"`
  294. AccountID string `json:"projectID"`
  295. ServiceKeyName string `json:"serviceKeyName"`
  296. ServiceKeySecret string `json:"serviceKeySecret"`
  297. SpotLabel string `json:"spotLabel"`
  298. SpotLabelValue string `json:"spotLabelValue"`
  299. }
  300. // AwsAthenaInfo contains configuration for CUR integration
  301. // Deprecated: v1.104 Use AthenaConfiguration instead
  302. type AwsAthenaInfo struct {
  303. AthenaBucketName string `json:"athenaBucketName"`
  304. AthenaRegion string `json:"athenaRegion"`
  305. AthenaDatabase string `json:"athenaDatabase"`
  306. AthenaCatalog string `json:"athenaCatalog"`
  307. AthenaTable string `json:"athenaTable"`
  308. AthenaWorkgroup string `json:"athenaWorkgroup"`
  309. ServiceKeyName string `json:"serviceKeyName"`
  310. ServiceKeySecret string `json:"serviceKeySecret"`
  311. AccountID string `json:"projectID"`
  312. MasterPayerARN string `json:"masterPayerARN"`
  313. }
  314. // IsEmpty returns true if all fields in config are empty, false if not.
  315. func (aai *AwsAthenaInfo) IsEmpty() bool {
  316. return aai.AthenaBucketName == "" &&
  317. aai.AthenaRegion == "" &&
  318. aai.AthenaDatabase == "" &&
  319. aai.AthenaCatalog == "" &&
  320. aai.AthenaTable == "" &&
  321. aai.AthenaWorkgroup == "" &&
  322. aai.ServiceKeyName == "" &&
  323. aai.ServiceKeySecret == "" &&
  324. aai.AccountID == "" &&
  325. aai.MasterPayerARN == ""
  326. }
  327. // CreateConfig creates an AWS SDK V2 Config for the credentials that it contains
  328. func (aai *AwsAthenaInfo) CreateConfig() (awsSDK.Config, error) {
  329. keyProvider := AWSAccessKey{AccessKeyID: aai.ServiceKeyName, SecretAccessKey: aai.ServiceKeySecret}
  330. cfg, err := keyProvider.CreateConfig(aai.AthenaRegion)
  331. if err != nil {
  332. return cfg, err
  333. }
  334. if aai.MasterPayerARN != "" {
  335. // Create the credentials from AssumeRoleProvider to assume the role
  336. // referenced by the roleARN.
  337. stsSvc := sts.NewFromConfig(cfg)
  338. creds := stscreds.NewAssumeRoleProvider(stsSvc, aai.MasterPayerARN)
  339. cfg.Credentials = awsSDK.NewCredentialsCache(creds)
  340. }
  341. return cfg, nil
  342. }
  343. func (aws *AWS) GetManagementPlatform() (string, error) {
  344. nodes := aws.Clientset.GetAllNodes()
  345. if len(nodes) > 0 {
  346. n := nodes[0]
  347. version := n.Status.NodeInfo.KubeletVersion
  348. if strings.Contains(version, "eks") {
  349. return "eks", nil
  350. }
  351. if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  352. return "kops", nil
  353. }
  354. }
  355. return "", nil
  356. }
  357. func (aws *AWS) GetConfig() (*models.CustomPricing, error) {
  358. c, err := aws.Config.GetCustomPricingData()
  359. if err != nil {
  360. return nil, err
  361. }
  362. if c.Discount == "" {
  363. c.Discount = "0%"
  364. }
  365. if c.NegotiatedDiscount == "" {
  366. c.NegotiatedDiscount = "0%"
  367. }
  368. return c, nil
  369. }
  370. // GetAWSAccessKey generate an AWSAccessKey object from the config
  371. func (aws *AWS) GetAWSAccessKey() (*AWSAccessKey, error) {
  372. config, err := aws.GetConfig()
  373. if err != nil {
  374. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  375. }
  376. err = aws.ConfigureAuthWith(config)
  377. if err != nil {
  378. return nil, fmt.Errorf("error configuring Cloud Provider %s", err)
  379. }
  380. // Look for service key values in env if not present in config
  381. if config.AwsServiceKeyName == "" {
  382. config.AwsServiceKeyName = env.GetAWSAccessKeyID()
  383. }
  384. if config.AwsServiceKeySecret == "" {
  385. config.AwsServiceKeySecret = env.GetAWSAccessKeySecret()
  386. }
  387. if config.AwsServiceKeyName == "" && config.AwsServiceKeySecret == "" {
  388. log.DedupedInfof(1, "missing service key values for AWS cloud integration attempting to use service account integration")
  389. }
  390. return &AWSAccessKey{AccessKeyID: config.AwsServiceKeyName, SecretAccessKey: config.AwsServiceKeySecret}, nil
  391. }
  392. // GetAWSAthenaInfo generate an AWSAthenaInfo object from the config
  393. func (aws *AWS) GetAWSAthenaInfo() (*AwsAthenaInfo, error) {
  394. config, err := aws.GetConfig()
  395. if err != nil {
  396. return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
  397. }
  398. aak, err := aws.GetAWSAccessKey()
  399. if err != nil {
  400. return nil, err
  401. }
  402. return &AwsAthenaInfo{
  403. AthenaBucketName: config.AthenaBucketName,
  404. AthenaRegion: config.AthenaRegion,
  405. AthenaDatabase: config.AthenaDatabase,
  406. AthenaCatalog: config.AthenaCatalog,
  407. AthenaTable: config.AthenaTable,
  408. AthenaWorkgroup: config.AthenaWorkgroup,
  409. ServiceKeyName: aak.AccessKeyID,
  410. ServiceKeySecret: aak.SecretAccessKey,
  411. AccountID: config.AthenaProjectID,
  412. MasterPayerARN: config.MasterPayerARN,
  413. }, nil
  414. }
  415. func (aws *AWS) UpdateConfigFromConfigMap(cm map[string]string) (*models.CustomPricing, error) {
  416. return aws.Config.UpdateFromMap(cm)
  417. }
  418. func configUpdaterWithReaderAndType(r io.Reader, updateType string) func(c *models.CustomPricing) error {
  419. return func(c *models.CustomPricing) error {
  420. switch updateType {
  421. case SpotInfoUpdateType:
  422. asfi := AwsSpotFeedInfo{}
  423. err := json.NewDecoder(r).Decode(&asfi)
  424. if err != nil {
  425. return err
  426. }
  427. c.AwsServiceKeyName = asfi.ServiceKeyName
  428. if asfi.ServiceKeySecret != "" {
  429. c.AwsServiceKeySecret = asfi.ServiceKeySecret
  430. }
  431. c.AwsSpotDataPrefix = asfi.Prefix
  432. c.AwsSpotDataBucket = asfi.BucketName
  433. c.ProjectID = asfi.AccountID
  434. c.AwsSpotDataRegion = asfi.Region
  435. c.SpotLabel = asfi.SpotLabel
  436. c.SpotLabelValue = asfi.SpotLabelValue
  437. case AthenaInfoUpdateType:
  438. aai := AwsAthenaInfo{}
  439. err := json.NewDecoder(r).Decode(&aai)
  440. if err != nil {
  441. return err
  442. }
  443. c.AthenaBucketName = aai.AthenaBucketName
  444. c.AthenaRegion = aai.AthenaRegion
  445. c.AthenaDatabase = aai.AthenaDatabase
  446. c.AthenaCatalog = aai.AthenaCatalog
  447. c.AthenaTable = aai.AthenaTable
  448. c.AthenaWorkgroup = aai.AthenaWorkgroup
  449. c.AwsServiceKeyName = aai.ServiceKeyName
  450. if aai.ServiceKeySecret != "" {
  451. c.AwsServiceKeySecret = aai.ServiceKeySecret
  452. }
  453. if aai.MasterPayerARN != "" {
  454. c.MasterPayerARN = aai.MasterPayerARN
  455. }
  456. c.AthenaProjectID = aai.AccountID
  457. default:
  458. a := make(map[string]any)
  459. err := json.NewDecoder(r).Decode(&a)
  460. if err != nil {
  461. return err
  462. }
  463. for k, v := range a {
  464. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  465. vstr, ok := v.(string)
  466. if ok {
  467. err := models.SetCustomPricingField(c, kUpper, vstr)
  468. if err != nil {
  469. return fmt.Errorf("error setting custom pricing field: %w", err)
  470. }
  471. } else {
  472. return fmt.Errorf("type error while updating config for %s", kUpper)
  473. }
  474. }
  475. }
  476. if env.IsRemoteEnabled() {
  477. err := utils.UpdateClusterMeta(coreenv.GetClusterID(), c.ClusterName)
  478. if err != nil {
  479. return err
  480. }
  481. }
  482. return nil
  483. }
  484. }
  485. func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  486. return aws.Config.Update(configUpdaterWithReaderAndType(r, updateType))
  487. }
  488. type awsKey struct {
  489. Name string
  490. SpotLabelName string
  491. SpotLabelValue string
  492. Labels map[string]string
  493. ProviderID string
  494. }
  495. func (k *awsKey) GPUCount() int {
  496. return 0
  497. }
  498. func (k *awsKey) GPUType() string {
  499. return ""
  500. }
  501. func (k *awsKey) ID() string {
  502. for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
  503. if matchNum == 2 {
  504. return group
  505. }
  506. }
  507. log.Warnf("Could not find instance ID in \"%s\"", k.ProviderID)
  508. return ""
  509. }
  510. // Features will return a comma separated list of features for the given node
  511. // If the node has a spot label, it will be included in the list
  512. // Otherwise, the list include instance type, operating system, and the region
  513. func (k *awsKey) Features() string {
  514. instanceType, _ := util.GetInstanceType(k.Labels)
  515. operatingSystem, _ := util.GetOperatingSystem(k.Labels)
  516. region, _ := util.GetRegion(k.Labels)
  517. key := region + "," + instanceType + "," + operatingSystem
  518. usageType := k.getUsageType(k.Labels)
  519. spotKey := key + "," + usageType
  520. if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
  521. return spotKey
  522. }
  523. if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
  524. return spotKey
  525. }
  526. if usageType == PreemptibleType {
  527. return spotKey
  528. }
  529. return key
  530. }
  531. const eksComputeTypeLabel = "eks.amazonaws.com/compute-type"
  532. func (k *awsKey) isFargateNode() bool {
  533. v := k.Labels[eksComputeTypeLabel]
  534. if v == "fargate" {
  535. return true
  536. }
  537. return false
  538. }
  539. // getUsageType returns the usage type of the instance
  540. // If the instance is a spot instance, it will return PreemptibleType
  541. // Otherwise returns an empty string
  542. func (k *awsKey) getUsageType(labels map[string]string) string {
  543. if kLabel, ok := labels[k.SpotLabelName]; ok && kLabel == k.SpotLabelValue {
  544. return PreemptibleType
  545. }
  546. if eksLabel, ok := labels[EKSCapacityTypeLabel]; ok && eksLabel == EKSCapacitySpotTypeValue {
  547. // We currently write out spot instances as "preemptible" in the pricing data, so these need to match
  548. return PreemptibleType
  549. }
  550. if kLabel, ok := labels[models.KarpenterCapacityTypeLabel]; ok && kLabel == models.KarpenterCapacitySpotTypeValue {
  551. return PreemptibleType
  552. }
  553. return ""
  554. }
  555. func (awsProvider *AWS) GpuPricing(nodeLabels map[string]string) (string, error) {
  556. return "", nil
  557. }
  558. func (aws *AWS) PVPricing(pvk models.PVKey) (*models.PV, error) {
  559. pricing, ok := aws.Pricing[pvk.Features()]
  560. if !ok {
  561. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  562. return &models.PV{}, nil
  563. }
  564. return pricing.PV, nil
  565. }
  566. type awsPVKey struct {
  567. Labels map[string]string
  568. StorageClassParameters map[string]string
  569. StorageClassName string
  570. Name string
  571. DefaultRegion string
  572. ProviderID string
  573. }
  574. func (aws *AWS) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  575. providerID := ""
  576. if pv.Spec.AWSElasticBlockStore != nil {
  577. providerID = pv.Spec.AWSElasticBlockStore.VolumeID
  578. } else if pv.Spec.CSI != nil {
  579. providerID = pv.Spec.CSI.VolumeHandle
  580. }
  581. return &awsPVKey{
  582. Labels: pv.Labels,
  583. StorageClassName: pv.Spec.StorageClassName,
  584. StorageClassParameters: parameters,
  585. Name: pv.Name,
  586. DefaultRegion: defaultRegion,
  587. ProviderID: providerID,
  588. }
  589. }
  590. func (key *awsPVKey) ID() string {
  591. return key.ProviderID
  592. }
  593. func (key *awsPVKey) GetStorageClass() string {
  594. return key.StorageClassName
  595. }
  596. func (key *awsPVKey) Features() string {
  597. storageClass, ok := key.StorageClassParameters["type"]
  598. if !ok {
  599. log.Debugf("storage class %s doesn't have a 'type' parameter", key.Name)
  600. storageClass = getStorageClassTypeFrom(key.StorageClassParameters["provisioner"])
  601. }
  602. if storageClass == "standard" {
  603. storageClass = "gp2"
  604. }
  605. // Storage class names are generally EBS volume types (gp2)
  606. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  607. // Converts between the 2
  608. region, ok := util.GetRegion(key.Labels)
  609. if !ok {
  610. region = key.DefaultRegion
  611. }
  612. class, ok := volTypes[storageClass]
  613. if !ok {
  614. log.Debugf("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  615. }
  616. return region + "," + class
  617. }
  618. // getStorageClassTypeFrom returns the default ebs volume type for a provider provisioner
  619. func getStorageClassTypeFrom(provisioner string) string {
  620. // if there isn't any provided provisioner, return empty volume type
  621. if provisioner == "" {
  622. return ""
  623. }
  624. scType, ok := StorageClassProvisionerDefaults[provisioner]
  625. if ok {
  626. log.Debugf("using default voltype %s for provisioner %s", scType, provisioner)
  627. return scType
  628. }
  629. return ""
  630. }
  631. // GetKey maps node labels to information needed to retrieve pricing data
  632. func (aws *AWS) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  633. return &awsKey{
  634. Name: n.Name,
  635. SpotLabelName: aws.SpotLabelName,
  636. SpotLabelValue: aws.SpotLabelValue,
  637. Labels: labels,
  638. ProviderID: labels["providerID"],
  639. }
  640. }
  641. func (aws *AWS) isPreemptible(key string) bool {
  642. s := strings.Split(key, ",")
  643. if len(s) == 4 && s[3] == PreemptibleType {
  644. return true
  645. }
  646. return false
  647. }
  648. func (aws *AWS) ClusterManagementPricing() (string, float64, error) {
  649. return aws.clusterProvisioner, aws.clusterManagementPrice, nil
  650. }
  651. func getPricingListURL(serviceCode string, nodeList []*clustercache.Node) string {
  652. // See https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/using-the-aws-price-list-bulk-api-fetching-price-list-files-manually.html
  653. region := ""
  654. multiregion := false
  655. isChina := false
  656. for _, n := range nodeList {
  657. r, ok := util.GetRegion(n.Labels)
  658. if !ok {
  659. multiregion = true
  660. break
  661. }
  662. if strings.HasPrefix(r, chinaRegionPrefix) {
  663. isChina = true
  664. }
  665. if region == "" {
  666. region = r
  667. } else if r != region {
  668. multiregion = true
  669. break
  670. }
  671. }
  672. baseURL := awsPricingBaseURL + serviceCode + pricingCurrentPath
  673. if isChina {
  674. // Chinese regions are isolated and use a different pricing endpoint
  675. baseURL = awsChinaPricingBaseURL + serviceCode + pricingCurrentPath
  676. }
  677. if region != "" && !multiregion {
  678. baseURL += region + "/"
  679. }
  680. return baseURL + pricingIndexFile
  681. }
  682. // Use the pricing data from the current region. Fall back to using all region data if needed.
  683. func (aws *AWS) getRegionPricing(nodeList []*clustercache.Node) (*http.Response, string, error) {
  684. var pricingURL string
  685. if env.GetAWSPricingURL() != "" { // Allow override of pricing URL
  686. pricingURL = env.GetAWSPricingURL()
  687. } else {
  688. pricingURL = getPricingListURL("AmazonEC2", nodeList)
  689. }
  690. log.Infof("starting download of \"%s\", which is quite large ...", pricingURL)
  691. // This file is large and can take a while to stream, so the streaming client
  692. // bounds connect/TLS/response-header time but not the total body read - enough
  693. // to bail on a hung endpoint without truncating a legitimate slow download.
  694. resp, err := httputil.StreamingGet(context.Background(), 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. // SpotFeedRefreshEnabled determines whether the required configs to run the spot feed query have been set up
  702. func (aws *AWS) SpotFeedRefreshEnabled() bool {
  703. // Guard against nil receiver
  704. if aws == nil {
  705. return false
  706. }
  707. // Fallback if config is not initialized
  708. if aws.Config == nil {
  709. return len(aws.SpotDataBucket) != 0 ||
  710. len(aws.SpotDataRegion) != 0 ||
  711. len(aws.ProjectID) != 0
  712. }
  713. // Check if spot data feed is explicitly disabled via config
  714. c, err := aws.Config.GetCustomPricingData()
  715. if err == nil && c.SpotDataFeedEnabled == "false" {
  716. return false
  717. }
  718. // Default behavior
  719. return len(aws.SpotDataBucket) != 0 ||
  720. len(aws.SpotDataRegion) != 0 ||
  721. len(aws.ProjectID) != 0
  722. }
  723. // DownloadPricingData fetches data from the AWS Pricing API
  724. func (aws *AWS) DownloadPricingData() error {
  725. aws.DownloadPricingDataLock.Lock()
  726. defer aws.DownloadPricingDataLock.Unlock()
  727. c, err := aws.Config.GetCustomPricingData()
  728. if err != nil {
  729. log.Errorf("Error downloading default pricing data: %s", err.Error())
  730. }
  731. aws.BaseCPUPrice = c.CPU
  732. aws.BaseRAMPrice = c.RAM
  733. aws.BaseGPUPrice = c.GPU
  734. aws.BaseSpotCPUPrice = c.SpotCPU
  735. aws.BaseSpotRAMPrice = c.SpotRAM
  736. aws.BaseSpotGPUPrice = c.SpotGPU
  737. aws.SpotLabelName = c.SpotLabel
  738. aws.SpotLabelValue = c.SpotLabelValue
  739. aws.SpotDataBucket = c.AwsSpotDataBucket
  740. aws.SpotDataPrefix = c.AwsSpotDataPrefix
  741. aws.ProjectID = c.ProjectID
  742. aws.SpotDataRegion = c.AwsSpotDataRegion
  743. aws.ConfigureAuthWith(c) // load aws authentication from configuration or secret
  744. if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
  745. log.Warnf("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
  746. }
  747. nodeList := aws.Clientset.GetAllNodes()
  748. inputkeys := make(map[string]bool)
  749. for _, n := range nodeList {
  750. if _, ok := n.Labels["eks.amazonaws.com/nodegroup"]; ok {
  751. aws.clusterManagementPrice = 0.10
  752. aws.clusterProvisioner = "EKS"
  753. } else if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
  754. aws.clusterProvisioner = "KOPS"
  755. }
  756. labels := n.Labels
  757. key := aws.GetKey(labels, n)
  758. inputkeys[key.Features()] = true
  759. }
  760. pvList := aws.Clientset.GetAllPersistentVolumes()
  761. storageClasses := aws.Clientset.GetAllStorageClasses()
  762. storageClassMap := make(map[string]map[string]string)
  763. for _, storageClass := range storageClasses {
  764. params := storageClass.Parameters
  765. if params != nil {
  766. params["provisioner"] = storageClass.Provisioner
  767. }
  768. storageClassMap[storageClass.Name] = params
  769. if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  770. storageClassMap["default"] = params
  771. storageClassMap[""] = params
  772. }
  773. }
  774. pvkeys := make(map[string]models.PVKey)
  775. for _, pv := range pvList {
  776. params, ok := storageClassMap[pv.Spec.StorageClassName]
  777. if !ok {
  778. log.Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
  779. continue
  780. }
  781. key := aws.GetPVKey(pv, params, "")
  782. pvkeys[key.Features()] = key
  783. }
  784. // RIDataRunning establishes the existence of the goroutine. Since it's possible we
  785. // run multiple downloads, we don't want to create multiple go routines if one already exists
  786. //
  787. // If athenaBucketName is unconfigured, the ReservedInstanceData and SavingsPlanData watchers
  788. // are skipped. Note: These watchers are less commonly used. It is recommended to use the full
  789. // CloudCosts feature via athenaintegration.go.
  790. if !aws.RIDataRunning {
  791. err = aws.GetReservationDataFromAthena() // Block until one run has completed.
  792. if err != nil {
  793. if errors.Is(err, ErrNoAthenaBucket) {
  794. log.Debugf("No \"athenaBucketName\" configured, ReservedInstanceData watcher will not run")
  795. } else {
  796. log.Warnf("Failed to lookup reserved instance data: %s", err.Error())
  797. }
  798. } else { // If we make one successful run, check on new reservation data every hour
  799. go func() {
  800. defer errs.HandlePanic()
  801. aws.RIDataRunning = true
  802. for {
  803. log.Infof("Reserved Instance watcher running... next update in 1h")
  804. time.Sleep(time.Hour)
  805. err := aws.GetReservationDataFromAthena()
  806. if err != nil {
  807. log.Infof("Error updating RI data: %s", err.Error())
  808. }
  809. }
  810. }()
  811. }
  812. }
  813. if !aws.SavingsPlanDataRunning {
  814. err = aws.GetSavingsPlanDataFromAthena()
  815. if err != nil {
  816. if errors.Is(err, ErrNoAthenaBucket) {
  817. log.Debugf("No \"athenaBucketName\" configured, SavingsPlanData watcher will not run")
  818. } else {
  819. log.Errorf("Failed to lookup savings plan data: %s", err.Error())
  820. }
  821. } else {
  822. go func() {
  823. defer errs.HandlePanic()
  824. aws.SavingsPlanDataRunning = true
  825. for {
  826. log.Infof("Savings Plan watcher running... next update in 1h")
  827. time.Sleep(time.Hour)
  828. err := aws.GetSavingsPlanDataFromAthena()
  829. if err != nil {
  830. log.Infof("Error updating Savings Plan data: %s", err.Error())
  831. }
  832. }
  833. }()
  834. }
  835. }
  836. // Initialize fargate pricing if it's not initialized yet
  837. if aws.FargatePricing == nil {
  838. aws.FargatePricing = NewFargatePricing()
  839. aws.FargatePricingError = aws.FargatePricing.Initialize(nodeList)
  840. if aws.FargatePricingError != nil {
  841. log.Errorf("Failed to initialize fargate pricing: %s", aws.FargatePricingError.Error())
  842. }
  843. }
  844. aws.ValidPricingKeys = make(map[string]bool)
  845. resp, pricingURL, err := aws.getRegionPricing(nodeList)
  846. if err != nil {
  847. return err
  848. }
  849. err = aws.populatePricing(resp, inputkeys)
  850. if err != nil {
  851. return err
  852. }
  853. log.Infof("Finished downloading \"%s\"", pricingURL)
  854. // Initialize a spot price history cache if not already initialized.
  855. // Reset error to allow retrying on subsequent DownloadPricingData calls.
  856. if aws.SpotPriceHistoryCache == nil {
  857. aws.SpotPriceHistoryError = nil
  858. aws.SpotPriceHistoryCache, aws.SpotPriceHistoryError = aws.initializeSpotPriceHistoryCache()
  859. if aws.SpotPriceHistoryError != nil {
  860. log.Errorf("Failed to initialize spot price history manager: %v", aws.SpotPriceHistoryError)
  861. }
  862. }
  863. if aws.SpotFeedRefreshEnabled() {
  864. // Always run spot pricing refresh when performing download
  865. aws.refreshSpotPricing(true)
  866. // Only start a single refresh goroutine
  867. if !aws.SpotRefreshRunning {
  868. aws.SpotRefreshRunning = true
  869. go func() {
  870. defer errs.HandlePanic()
  871. for {
  872. log.Infof("Spot Pricing Refresh scheduled in %.2f minutes.", SpotRefreshDuration.Minutes())
  873. time.Sleep(SpotRefreshDuration)
  874. // Reoccurring refresh checks update times
  875. aws.refreshSpotPricing(false)
  876. }
  877. }()
  878. }
  879. }
  880. return nil
  881. }
  882. func (aws *AWS) populatePricing(resp *http.Response, inputkeys map[string]bool) error {
  883. aws.Pricing = make(map[string]*AWSProductTerms)
  884. skusToKeys := make(map[string]string)
  885. dec := json.NewDecoder(resp.Body)
  886. for {
  887. t, err := dec.Token()
  888. if err == io.EOF {
  889. log.Infof("done loading \"%s\"\n", resp.Request.URL.String())
  890. break
  891. } else if err != nil {
  892. log.Errorf("error parsing response json %v", resp.Body)
  893. break
  894. }
  895. if t == "products" {
  896. _, err := dec.Token() // this should parse the opening "{""
  897. if err != nil {
  898. return err
  899. }
  900. for dec.More() {
  901. _, err := dec.Token() // the sku token
  902. if err != nil {
  903. return err
  904. }
  905. product := &PriceListEC2Product{}
  906. err = dec.Decode(&product)
  907. if err != nil {
  908. log.Errorf("Error parsing response from \"%s\": %v", resp.Request.URL.String(), err.Error())
  909. break
  910. }
  911. if product.Attributes.PreInstalledSw == "NA" &&
  912. (strings.HasPrefix(product.Attributes.UsageType, "BoxUsage") || strings.Contains(product.Attributes.UsageType, "-BoxUsage")) &&
  913. product.Attributes.CapacityStatus == "Used" &&
  914. product.Attributes.MarketOption == "OnDemand" {
  915. key := aws.KubeAttrConversion(product.Attributes.RegionCode, product.Attributes.InstanceType, product.Attributes.OperatingSystem)
  916. spotKey := key + ",preemptible"
  917. if inputkeys[key] || inputkeys[spotKey] { // Just grab the sku even if spot, and change the price later.
  918. productTerms := &AWSProductTerms{
  919. Sku: product.Sku,
  920. Memory: product.Attributes.Memory,
  921. Storage: product.Attributes.Storage,
  922. VCpu: product.Attributes.VCpu,
  923. GPU: product.Attributes.GPU,
  924. }
  925. aws.Pricing[key] = productTerms
  926. aws.Pricing[spotKey] = productTerms
  927. skusToKeys[product.Sku] = key
  928. }
  929. aws.ValidPricingKeys[key] = true
  930. aws.ValidPricingKeys[spotKey] = true
  931. } else if strings.Contains(product.Attributes.UsageType, "EBS:Volume") {
  932. // UsageTypes may be prefixed with a region code - we're removing this when using
  933. // volTypes to keep lookups generic
  934. usageTypeMatch := usageTypeRegx.FindStringSubmatch(product.Attributes.UsageType)
  935. usageTypeNoRegion := usageTypeMatch[len(usageTypeMatch)-1]
  936. key := product.Attributes.RegionCode + "," + usageTypeNoRegion
  937. spotKey := key + ",preemptible"
  938. pv := &models.PV{
  939. Class: volTypes[usageTypeNoRegion],
  940. Region: product.Attributes.RegionCode,
  941. }
  942. productTerms := &AWSProductTerms{
  943. Sku: product.Sku,
  944. PV: pv,
  945. }
  946. aws.Pricing[key] = productTerms
  947. aws.Pricing[spotKey] = productTerms
  948. skusToKeys[product.Sku] = key
  949. aws.ValidPricingKeys[key] = true
  950. aws.ValidPricingKeys[spotKey] = true
  951. } else if strings.Contains(product.Attributes.UsageType, "LoadBalancerUsage") && product.Attributes.Operation == "LoadBalancing:Network" {
  952. // since the costmodel is only using services of type LoadBalancer
  953. // (and not ingresses controlled by AWS load balancer controller)
  954. // we can safely filter for Network load balancers only
  955. productTerms := &AWSProductTerms{
  956. Sku: product.Sku,
  957. LoadBalancer: &models.LoadBalancer{},
  958. }
  959. // there is no spot pricing for load balancers
  960. key := product.Attributes.RegionCode + ",LoadBalancerUsage"
  961. aws.Pricing[key] = productTerms
  962. skusToKeys[product.Sku] = key
  963. aws.ValidPricingKeys[key] = true
  964. }
  965. }
  966. }
  967. if t == "terms" {
  968. _, err := dec.Token() // this should parse the opening "{""
  969. if err != nil {
  970. return err
  971. }
  972. termType, err := dec.Token()
  973. if err != nil {
  974. return err
  975. }
  976. if termType == "OnDemand" {
  977. _, err := dec.Token()
  978. if err != nil { // again, should parse an opening "{"
  979. return err
  980. }
  981. for dec.More() {
  982. sku, err := dec.Token()
  983. if err != nil {
  984. return err
  985. }
  986. _, err = dec.Token() // another opening "{"
  987. if err != nil {
  988. return err
  989. }
  990. // SKUOndemand
  991. _, err = dec.Token()
  992. if err != nil {
  993. return err
  994. }
  995. offerTerm := &PriceListEC2Term{}
  996. err = dec.Decode(&offerTerm)
  997. if err != nil {
  998. log.Errorf("Error decoding AWS Offer Term: %s", err.Error())
  999. }
  1000. key, ok := skusToKeys[sku.(string)]
  1001. spotKey := key + ",preemptible"
  1002. if ok {
  1003. aws.Pricing[key].OnDemand = offerTerm
  1004. if _, ok := aws.Pricing[spotKey]; ok {
  1005. aws.Pricing[spotKey].OnDemand = offerTerm
  1006. }
  1007. var cost string
  1008. if _, isMatch := OnDemandRateCodes[offerTerm.OfferTermCode]; isMatch {
  1009. priceDimensionKey := strings.Join([]string{sku.(string), offerTerm.OfferTermCode, HourlyRateCode}, ".")
  1010. dimension, ok := offerTerm.PriceDimensions[priceDimensionKey]
  1011. if ok {
  1012. cost = dimension.PricePerUnit.USD
  1013. } else {
  1014. // this is an edge case seen in AWS CN pricing files, including here just in case
  1015. // if there is only one dimension, use it, even if the key is incorrect, otherwise assume defaults
  1016. if len(offerTerm.PriceDimensions) == 1 {
  1017. for key, backupDimension := range offerTerm.PriceDimensions {
  1018. cost = backupDimension.PricePerUnit.USD
  1019. log.DedupedWarningf(5, "using:%s for a price dimension instead of missing dimension: %s", offerTerm.PriceDimensions[key], priceDimensionKey)
  1020. break
  1021. }
  1022. } else if len(offerTerm.PriceDimensions) == 0 {
  1023. log.DedupedWarningf(5, "populatePricing: no pricing dimension available for: %s.", priceDimensionKey)
  1024. } else {
  1025. log.DedupedWarningf(5, "populatePricing: no assumable pricing dimension available for: %s.", priceDimensionKey)
  1026. }
  1027. }
  1028. } else if _, isMatch := OnDemandRateCodesCn[offerTerm.OfferTermCode]; isMatch {
  1029. priceDimensionKey := strings.Join([]string{sku.(string), offerTerm.OfferTermCode, HourlyRateCodeCn}, ".")
  1030. dimension, ok := offerTerm.PriceDimensions[priceDimensionKey]
  1031. if ok {
  1032. cost = dimension.PricePerUnit.CNY
  1033. } else {
  1034. // fall through logic for handling inconsistencies in AWS CN pricing files
  1035. // if there is only one dimension, use it, even if the key is incorrect, otherwise assume defaults
  1036. if len(offerTerm.PriceDimensions) == 1 {
  1037. for key, backupDimension := range offerTerm.PriceDimensions {
  1038. cost = backupDimension.PricePerUnit.CNY
  1039. log.DedupedWarningf(5, "using:%s for a price dimension instead of missing dimension: %s", offerTerm.PriceDimensions[key], priceDimensionKey)
  1040. break
  1041. }
  1042. } else if len(offerTerm.PriceDimensions) == 0 {
  1043. log.DedupedWarningf(5, "populatePricing: no pricing dimension available for: %s.", priceDimensionKey)
  1044. } else {
  1045. log.DedupedWarningf(5, "populatePricing: no assumable pricing dimension available for: %s.", priceDimensionKey)
  1046. }
  1047. }
  1048. }
  1049. if strings.Contains(key, "EBS:VolumeP-IOPS.piops") {
  1050. // If the specific UsageType is the per IO cost used on io1 volumes
  1051. // we need to add the per IO cost to the io1 PV cost
  1052. // Add the per IO cost to the PV object for the io1 volume type
  1053. aws.Pricing[key].PV.CostPerIO = cost
  1054. } else if strings.Contains(key, "EBS:Volume") {
  1055. // If volume, we need to get hourly cost and add it to the PV object
  1056. costFloat, _ := strconv.ParseFloat(cost, 64)
  1057. hourlyPrice := costFloat / 730
  1058. aws.Pricing[key].PV.Cost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  1059. } else if strings.Contains(key, "LoadBalancerUsage") {
  1060. costFloat, err := strconv.ParseFloat(cost, 64)
  1061. if err != nil {
  1062. return err
  1063. }
  1064. aws.Pricing[key].LoadBalancer.Cost = costFloat
  1065. }
  1066. }
  1067. _, err = dec.Token()
  1068. if err != nil {
  1069. return err
  1070. }
  1071. }
  1072. _, err = dec.Token()
  1073. if err != nil {
  1074. return err
  1075. }
  1076. }
  1077. }
  1078. }
  1079. return nil
  1080. }
  1081. func (aws *AWS) refreshSpotPricing(force bool) {
  1082. aws.SpotPricingLock.Lock()
  1083. defer aws.SpotPricingLock.Unlock()
  1084. now := time.Now().UTC()
  1085. updateTime := now.Add(-SpotRefreshDuration)
  1086. // Return if there was an update time set and an hour hasn't elapsed
  1087. if !force && aws.SpotPricingUpdatedAt != nil && aws.SpotPricingUpdatedAt.After(updateTime) {
  1088. return
  1089. }
  1090. sp, err := aws.parseSpotData(aws.SpotDataBucket, aws.SpotDataPrefix, aws.ProjectID, aws.SpotDataRegion)
  1091. if err != nil {
  1092. log.Warnf("Skipping AWS spot data download: %s", err.Error())
  1093. aws.SpotPricingError = err
  1094. return
  1095. }
  1096. aws.SpotPricingError = nil
  1097. // update time last updated
  1098. aws.SpotPricingUpdatedAt = &now
  1099. aws.SpotPricingByInstanceID = sp
  1100. }
  1101. func (aws *AWS) initializeSpotPriceHistoryCache() (*SpotPriceHistoryCache, error) {
  1102. log.Info("Initializing AWS Spot Price History Manager")
  1103. // Get AWS access key for creating config
  1104. accessKey, err := aws.GetAWSAccessKey()
  1105. if err != nil {
  1106. return nil, fmt.Errorf("getting AWS access key for spot price history: %w", err)
  1107. }
  1108. // Use the cluster region to create the initial AWS config and credentials.
  1109. // The SpotPriceHistoryFetcher itself can query multiple regions by creating
  1110. // region-specific EC2 clients as needed.
  1111. if aws.ClusterRegion == "" {
  1112. return nil, fmt.Errorf("no cluster region configured")
  1113. }
  1114. // Create config for the cluster region
  1115. awsConfig, err := accessKey.CreateConfig(aws.ClusterRegion)
  1116. if err != nil {
  1117. return nil, fmt.Errorf("creating AWS config for spot price history: %w", err)
  1118. }
  1119. return NewSpotPriceHistoryCache(NewAWSSpotPriceHistoryFetcher(awsConfig)), nil
  1120. }
  1121. func (aws *AWS) spotPricingFromHistory(k models.Key) (*SpotPriceHistoryEntry, bool) {
  1122. if aws.SpotPriceHistoryCache == nil {
  1123. return nil, false
  1124. }
  1125. // Extract region, instance type, and availability zone from the key
  1126. awsKey, ok := k.(*awsKey)
  1127. if !ok {
  1128. log.DedupedWarningf(10, "Failed to cast key to awsKey for spot price history lookup: %s", k.ID())
  1129. return nil, false
  1130. }
  1131. region, regionOk := util.GetRegion(awsKey.Labels)
  1132. instanceType, instanceTypeOk := util.GetInstanceType(awsKey.Labels)
  1133. availabilityZone, availabilityZoneOk := util.GetZone(awsKey.Labels)
  1134. // Skip lookup if any required information is missing
  1135. if !regionOk || !instanceTypeOk || !availabilityZoneOk {
  1136. log.DedupedWarningf(10, "Missing required info for spot price history lookup (region: %s, instanceType: %s, zone: %s): %s", region, instanceType, availabilityZone, k.ID())
  1137. return nil, false
  1138. }
  1139. price, err := aws.SpotPriceHistoryCache.GetSpotPrice(region, instanceType, availabilityZone)
  1140. if err != nil {
  1141. log.Debugf("Failed to get spot price history for instance %s: %s", k.ID(), err.Error())
  1142. return nil, false
  1143. }
  1144. return price, true
  1145. }
  1146. // Stubbed NetworkPricing for AWS. Pull directly from aws.json for now
  1147. func (aws *AWS) NetworkPricing() (*models.Network, error) {
  1148. cpricing, err := aws.Config.GetCustomPricingData()
  1149. if err != nil {
  1150. return nil, err
  1151. }
  1152. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1153. if err != nil {
  1154. return nil, err
  1155. }
  1156. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1157. if err != nil {
  1158. return nil, err
  1159. }
  1160. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1161. if err != nil {
  1162. return nil, err
  1163. }
  1164. nge, err := strconv.ParseFloat(cpricing.NatGatewayEgress, 64)
  1165. if err != nil {
  1166. return nil, err
  1167. }
  1168. ngi, err := strconv.ParseFloat(cpricing.NatGatewayIngress, 64)
  1169. if err != nil {
  1170. return nil, err
  1171. }
  1172. return &models.Network{
  1173. ZoneNetworkEgressCost: znec,
  1174. RegionNetworkEgressCost: rnec,
  1175. InternetNetworkEgressCost: inec,
  1176. NatGatewayEgressCost: nge,
  1177. NatGatewayIngressCost: ngi,
  1178. }, nil
  1179. }
  1180. func (aws *AWS) LoadBalancerPricing() (*models.LoadBalancer, error) {
  1181. // TODO: determine key based on function arguments
  1182. // this is something that should be changed in the Provider interface
  1183. key := aws.ClusterRegion + ",LoadBalancerUsage"
  1184. // set default price
  1185. hourlyCost := 0.025
  1186. // use price index when available
  1187. if terms, ok := aws.Pricing[key]; ok {
  1188. hourlyCost = terms.LoadBalancer.Cost
  1189. }
  1190. return &models.LoadBalancer{
  1191. Cost: hourlyCost,
  1192. }, nil
  1193. }
  1194. // AllNodePricing returns all the billing data fetched.
  1195. func (aws *AWS) AllNodePricing() (interface{}, error) {
  1196. aws.DownloadPricingDataLock.RLock()
  1197. defer aws.DownloadPricingDataLock.RUnlock()
  1198. return aws.Pricing, nil
  1199. }
  1200. func (aws *AWS) spotPricing(instanceID string) (*spotInfo, bool) {
  1201. aws.SpotPricingLock.RLock()
  1202. defer aws.SpotPricingLock.RUnlock()
  1203. info, ok := aws.SpotPricingByInstanceID[instanceID]
  1204. return info, ok
  1205. }
  1206. func (aws *AWS) reservedInstancePricing(instanceID string) (*RIData, bool) {
  1207. aws.RIDataLock.RLock()
  1208. defer aws.RIDataLock.RUnlock()
  1209. data, ok := aws.RIPricingByInstanceID[instanceID]
  1210. return data, ok
  1211. }
  1212. func (aws *AWS) savingsPlanPricing(instanceID string) (*SavingsPlanData, bool) {
  1213. aws.SavingsPlanDataLock.RLock()
  1214. defer aws.SavingsPlanDataLock.RUnlock()
  1215. data, ok := aws.SavingsPlanDataByInstanceID[instanceID]
  1216. return data, ok
  1217. }
  1218. func (aws *AWS) createNode(terms *AWSProductTerms, usageType string, k models.Key) (*models.Node, models.PricingMetadata, error) {
  1219. key := k.Features()
  1220. meta := models.PricingMetadata{}
  1221. var cost string
  1222. publicPricingFound := true
  1223. c, ok := terms.OnDemand.PriceDimensions[strings.Join([]string{terms.Sku, terms.OnDemand.OfferTermCode, HourlyRateCode}, ".")]
  1224. if ok {
  1225. cost = c.PricePerUnit.USD
  1226. } else {
  1227. // Check for Chinese pricing
  1228. c, ok = terms.OnDemand.PriceDimensions[strings.Join([]string{terms.Sku, terms.OnDemand.OfferTermCode, HourlyRateCodeCn}, ".")]
  1229. if ok {
  1230. cost = c.PricePerUnit.CNY
  1231. } else {
  1232. publicPricingFound = false
  1233. }
  1234. }
  1235. if spotInfo, ok := aws.spotPricing(k.ID()); ok {
  1236. var spotcost string
  1237. log.DedupedInfof(5, "Looking up spot data from feed for node %s", k.ID())
  1238. arr := strings.Split(spotInfo.Charge, " ")
  1239. if len(arr) == 2 {
  1240. spotcost = arr[0]
  1241. } else {
  1242. log.Infof("Spot data for node %s is missing", k.ID())
  1243. }
  1244. return &models.Node{
  1245. Cost: spotcost,
  1246. VCPU: terms.VCpu,
  1247. RAM: terms.Memory,
  1248. GPU: terms.GPU,
  1249. Storage: terms.Storage,
  1250. BaseCPUPrice: aws.BaseCPUPrice,
  1251. BaseRAMPrice: aws.BaseRAMPrice,
  1252. BaseGPUPrice: aws.BaseGPUPrice,
  1253. UsageType: PreemptibleType,
  1254. }, meta, nil
  1255. } else if aws.isPreemptible(key) { // Preemptible but we don't have any data in the pricing report.
  1256. log.Debugf("Node %s marked preemptible but no spot feed data available; falling back to other pricing sources", k.ID())
  1257. // Try to get spot pricing from DescribeSpotPriceHistory API
  1258. if historyEntry, ok := aws.spotPricingFromHistory(k); ok {
  1259. log.DedupedInfof(5, "Using spot price history data for node %s: $%f", k.ID(), historyEntry.SpotPrice)
  1260. spotHistoryCost := fmt.Sprintf("%f", historyEntry.SpotPrice)
  1261. meta.Source = SpotPriceHistorySource
  1262. return &models.Node{
  1263. Cost: spotHistoryCost,
  1264. VCPU: terms.VCpu,
  1265. RAM: terms.Memory,
  1266. GPU: terms.GPU,
  1267. Storage: terms.Storage,
  1268. BaseCPUPrice: aws.BaseCPUPrice,
  1269. BaseRAMPrice: aws.BaseRAMPrice,
  1270. BaseGPUPrice: aws.BaseGPUPrice,
  1271. UsageType: PreemptibleType,
  1272. }, meta, nil
  1273. }
  1274. if publicPricingFound {
  1275. // return public price if found
  1276. log.Debugf("No spot price history available for %s, falling back to on-demand pricing", k.ID())
  1277. return &models.Node{
  1278. Cost: cost,
  1279. VCPU: terms.VCpu,
  1280. RAM: terms.Memory,
  1281. GPU: terms.GPU,
  1282. Storage: terms.Storage,
  1283. BaseCPUPrice: aws.BaseCPUPrice,
  1284. BaseRAMPrice: aws.BaseRAMPrice,
  1285. BaseGPUPrice: aws.BaseGPUPrice,
  1286. UsageType: PreemptibleType,
  1287. }, meta, nil
  1288. } else {
  1289. // return defaults if public pricing not found
  1290. log.DedupedWarningf(5, "Could not find Node %s's public pricing info, using default configured spot prices instead", k.ID())
  1291. return &models.Node{
  1292. VCPU: terms.VCpu,
  1293. VCPUCost: aws.BaseSpotCPUPrice,
  1294. RAMCost: aws.BaseSpotRAMPrice,
  1295. RAM: terms.Memory,
  1296. GPU: terms.GPU,
  1297. Storage: terms.Storage,
  1298. BaseCPUPrice: aws.BaseCPUPrice,
  1299. BaseRAMPrice: aws.BaseRAMPrice,
  1300. BaseGPUPrice: aws.BaseGPUPrice,
  1301. UsageType: PreemptibleType,
  1302. }, meta, nil
  1303. }
  1304. } else if sp, ok := aws.savingsPlanPricing(k.ID()); ok {
  1305. strCost := fmt.Sprintf("%f", sp.EffectiveCost)
  1306. return &models.Node{
  1307. Cost: strCost,
  1308. VCPU: terms.VCpu,
  1309. RAM: terms.Memory,
  1310. GPU: terms.GPU,
  1311. Storage: terms.Storage,
  1312. BaseCPUPrice: aws.BaseCPUPrice,
  1313. BaseRAMPrice: aws.BaseRAMPrice,
  1314. BaseGPUPrice: aws.BaseGPUPrice,
  1315. UsageType: usageType,
  1316. }, meta, nil
  1317. } else if ri, ok := aws.reservedInstancePricing(k.ID()); ok {
  1318. strCost := fmt.Sprintf("%f", ri.EffectiveCost)
  1319. return &models.Node{
  1320. Cost: strCost,
  1321. VCPU: terms.VCpu,
  1322. RAM: terms.Memory,
  1323. GPU: terms.GPU,
  1324. Storage: terms.Storage,
  1325. BaseCPUPrice: aws.BaseCPUPrice,
  1326. BaseRAMPrice: aws.BaseRAMPrice,
  1327. BaseGPUPrice: aws.BaseGPUPrice,
  1328. UsageType: usageType,
  1329. }, meta, nil
  1330. }
  1331. // Throw error if public price is not found
  1332. if !publicPricingFound {
  1333. return nil, meta, fmt.Errorf("for node \"%s\", cannot find the following key in OnDemand pricing data \"%s\"", k.ID(), k.Features())
  1334. }
  1335. return &models.Node{
  1336. Cost: cost,
  1337. VCPU: terms.VCpu,
  1338. RAM: terms.Memory,
  1339. GPU: terms.GPU,
  1340. Storage: terms.Storage,
  1341. BaseCPUPrice: aws.BaseCPUPrice,
  1342. BaseRAMPrice: aws.BaseRAMPrice,
  1343. BaseGPUPrice: aws.BaseGPUPrice,
  1344. UsageType: usageType,
  1345. }, meta, nil
  1346. }
  1347. func (aws *AWS) getFargatePod(awsKey *awsKey) (*clustercache.Pod, bool) {
  1348. pods := aws.Clientset.GetAllPods()
  1349. for _, pod := range pods {
  1350. if pod.Spec.NodeName == awsKey.Name {
  1351. return pod, true
  1352. }
  1353. }
  1354. return nil, false
  1355. }
  1356. const (
  1357. nodeOSLabel = "kubernetes.io/os"
  1358. nodeArchLabel = "kubernetes.io/arch"
  1359. fargatePodCapacityAnnotation = "CapacityProvisioned"
  1360. )
  1361. // e.g. "0.25vCPU 0.5GB"
  1362. var fargatePodCapacityRegex = regexp.MustCompile("^([0-9.]+)vCPU ([0-9.]+)GB$")
  1363. func (aws *AWS) createFargateNode(awsKey *awsKey, usageType string) (*models.Node, models.PricingMetadata, error) {
  1364. if aws.FargatePricing == nil {
  1365. return nil, models.PricingMetadata{}, fmt.Errorf("fargate pricing not initialized")
  1366. }
  1367. pod, ok := aws.getFargatePod(awsKey)
  1368. if !ok {
  1369. return nil, models.PricingMetadata{}, fmt.Errorf("could not find pod for fargate node %s", awsKey.Name)
  1370. }
  1371. capacity := pod.Annotations[fargatePodCapacityAnnotation]
  1372. match := fargatePodCapacityRegex.FindStringSubmatch(capacity)
  1373. if len(match) == 0 {
  1374. return nil, models.PricingMetadata{}, fmt.Errorf("could not parse pod capacity for fargate node %s", awsKey.Name)
  1375. }
  1376. vCPU, err := strconv.ParseFloat(match[1], 64)
  1377. if err != nil {
  1378. return nil, models.PricingMetadata{}, fmt.Errorf("could not parse vCPU capacity for fargate node %s: %v", awsKey.Name, err)
  1379. }
  1380. memory, err := strconv.ParseFloat(match[2], 64)
  1381. if err != nil {
  1382. return nil, models.PricingMetadata{}, fmt.Errorf("could not parse memory capacity for fargate node %s: %v", awsKey.Name, err)
  1383. }
  1384. region, ok := util.GetRegion(awsKey.Labels)
  1385. if !ok {
  1386. return nil, models.PricingMetadata{}, fmt.Errorf("could not get region for fargate node %s", awsKey.Name)
  1387. }
  1388. nodeOS := awsKey.Labels[nodeOSLabel]
  1389. nodeArch := awsKey.Labels[nodeArchLabel]
  1390. hourlyCPU, hourlyRAM, err := aws.FargatePricing.GetHourlyPricing(region, nodeOS, nodeArch)
  1391. if err != nil {
  1392. return nil, models.PricingMetadata{}, fmt.Errorf("could not get hourly pricing for fargate node %s: %v", awsKey.Name, err)
  1393. }
  1394. cost := hourlyCPU*vCPU + hourlyRAM*memory
  1395. return &models.Node{
  1396. Cost: strconv.FormatFloat(cost, 'f', -1, 64),
  1397. VCPU: strconv.FormatFloat(vCPU, 'f', -1, 64),
  1398. RAM: strconv.FormatFloat(memory, 'f', -1, 64),
  1399. RAMBytes: strconv.FormatFloat(memory*1024*1024*1024, 'f', -1, 64),
  1400. VCPUCost: strconv.FormatFloat(hourlyCPU, 'f', -1, 64),
  1401. RAMCost: strconv.FormatFloat(hourlyRAM, 'f', -1, 64),
  1402. BaseCPUPrice: aws.BaseCPUPrice,
  1403. BaseRAMPrice: aws.BaseRAMPrice,
  1404. BaseGPUPrice: aws.BaseGPUPrice,
  1405. UsageType: usageType,
  1406. }, models.PricingMetadata{}, nil
  1407. }
  1408. // NodePricing takes in a key from GetKey and returns a Node object for use in building the cost model.
  1409. func (aws *AWS) NodePricing(k models.Key) (*models.Node, models.PricingMetadata, error) {
  1410. aws.DownloadPricingDataLock.RLock()
  1411. defer aws.DownloadPricingDataLock.RUnlock()
  1412. key := k.Features()
  1413. usageType := "ondemand"
  1414. if aws.isPreemptible(key) {
  1415. usageType = PreemptibleType
  1416. }
  1417. meta := models.PricingMetadata{}
  1418. terms, ok := aws.Pricing[key]
  1419. if termsStr, err := json.Marshal(terms); err == nil {
  1420. log.Debugf("NodePricing: for key \"%s\" found the following OnDemand data: %s", key, string(termsStr))
  1421. }
  1422. if ok {
  1423. return aws.createNode(terms, usageType, k)
  1424. } else if _, ok := aws.ValidPricingKeys[key]; ok {
  1425. aws.DownloadPricingDataLock.RUnlock()
  1426. err := aws.DownloadPricingData()
  1427. aws.DownloadPricingDataLock.RLock()
  1428. if err != nil {
  1429. return &models.Node{
  1430. Cost: aws.BaseCPUPrice,
  1431. BaseCPUPrice: aws.BaseCPUPrice,
  1432. BaseRAMPrice: aws.BaseRAMPrice,
  1433. BaseGPUPrice: aws.BaseGPUPrice,
  1434. UsageType: usageType,
  1435. UsesBaseCPUPrice: true,
  1436. }, meta, err
  1437. }
  1438. terms, termsOk := aws.Pricing[key]
  1439. if !termsOk {
  1440. return &models.Node{
  1441. Cost: aws.BaseCPUPrice,
  1442. BaseCPUPrice: aws.BaseCPUPrice,
  1443. BaseRAMPrice: aws.BaseRAMPrice,
  1444. BaseGPUPrice: aws.BaseGPUPrice,
  1445. UsageType: usageType,
  1446. UsesBaseCPUPrice: true,
  1447. }, meta, fmt.Errorf("Unable to find any Pricing data for \"%s\"", key)
  1448. }
  1449. return aws.createNode(terms, usageType, k)
  1450. } else if awsKey, ok := k.(*awsKey); ok && awsKey.isFargateNode() {
  1451. // Since Fargate pricing is listed at AmazonECS and is different from AmazonEC2, we handle it separately here
  1452. return aws.createFargateNode(awsKey, usageType)
  1453. } else { // Fall back to base pricing if we can't find the key. Base pricing is handled at the costmodel level.
  1454. // we seem to have an issue where this error gets thrown during app start.
  1455. // somehow the ValidPricingKeys map is being accessed before all the pricing data has been downloaded
  1456. return nil, meta, fmt.Errorf("Invalid Pricing Key \"%s\"", key)
  1457. }
  1458. }
  1459. // ClusterInfo returns an object that represents the cluster. TODO: actually return the name of the cluster. Blocked on cluster federation.
  1460. func (awsProvider *AWS) ClusterInfo() (map[string]string, error) {
  1461. c, err := awsProvider.GetConfig()
  1462. if err != nil {
  1463. return nil, err
  1464. }
  1465. const defaultClusterName = "AWS Cluster #1"
  1466. // Determine cluster name
  1467. clusterName := c.ClusterName
  1468. if clusterName == "" {
  1469. awsClusterID := env.GetAWSClusterID()
  1470. if awsClusterID != "" {
  1471. log.Infof("Returning \"%s\" as ClusterName", awsClusterID)
  1472. clusterName = awsClusterID
  1473. log.Warnf("Warning - %s will be deprecated in a future release. Use %s instead", env.AWSClusterIDEnvVar, coreenv.ClusterIDEnvVar)
  1474. } else if clusterName = coreenv.GetClusterID(); clusterName != "" {
  1475. log.DedupedInfof(5, "Setting cluster name to %s from %s ", clusterName, coreenv.ClusterIDEnvVar)
  1476. } else {
  1477. clusterName = defaultClusterName
  1478. log.DedupedWarningf(5, "Unable to detect cluster name - using default of %s", defaultClusterName)
  1479. log.DedupedWarningf(5, "Please set cluster name through configmap or via %s env var", coreenv.ClusterIDEnvVar)
  1480. }
  1481. }
  1482. // this value requires configuration but is unavailable else where
  1483. clusterAccountID := c.ClusterAccountID
  1484. // Use AthenaProjectID if Cluster Account is not set to support older configs
  1485. if clusterAccountID == "" {
  1486. clusterAccountID = c.AthenaProjectID
  1487. }
  1488. m := make(map[string]string)
  1489. m["name"] = clusterName
  1490. m["provider"] = opencost.AWSProvider
  1491. m["account"] = clusterAccountID
  1492. m["region"] = awsProvider.ClusterRegion
  1493. m["id"] = coreenv.GetClusterID()
  1494. m["remoteReadEnabled"] = strconv.FormatBool(env.IsRemoteEnabled())
  1495. m["provisioner"] = awsProvider.clusterProvisioner
  1496. return m, nil
  1497. }
  1498. // updates the authentication to the latest values (via config or secret)
  1499. func (aws *AWS) ConfigureAuth() error {
  1500. c, err := aws.Config.GetCustomPricingData()
  1501. if err != nil {
  1502. log.Errorf("Error downloading default pricing data: %s", err.Error())
  1503. }
  1504. return aws.ConfigureAuthWith(c)
  1505. }
  1506. // updates the authentication to the latest values (via config or secret)
  1507. func (aws *AWS) ConfigureAuthWith(config *models.CustomPricing) error {
  1508. accessKeyID, accessKeySecret := aws.getAWSAuth(false, config)
  1509. if accessKeyID != "" && accessKeySecret != "" { // credentials may exist on the actual AWS node-- if so, use those. If not, override with the service key
  1510. err := coreenv.Set(env.AWSAccessKeyIDEnvVar, accessKeyID)
  1511. if err != nil {
  1512. return err
  1513. }
  1514. err = coreenv.Set(env.AWSAccessKeySecretEnvVar, accessKeySecret)
  1515. if err != nil {
  1516. return err
  1517. }
  1518. }
  1519. return nil
  1520. }
  1521. // Gets the aws key id and secret
  1522. func (aws *AWS) getAWSAuth(forceReload bool, cp *models.CustomPricing) (string, string) {
  1523. // 1. Check config values first (set from frontend UI)
  1524. if cp.AwsServiceKeyName != "" && cp.AwsServiceKeySecret != "" {
  1525. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1526. Message: "AWS ServiceKey exists",
  1527. Status: true,
  1528. })
  1529. return cp.AwsServiceKeyName, cp.AwsServiceKeySecret
  1530. }
  1531. // 2. Check for secret
  1532. s, _ := aws.loadAWSAuthSecret(forceReload)
  1533. if s != nil && s.AccessKeyID != "" && s.SecretAccessKey != "" {
  1534. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1535. Message: "AWS ServiceKey exists",
  1536. Status: true,
  1537. })
  1538. return s.AccessKeyID, s.SecretAccessKey
  1539. }
  1540. // 3. Fall back to env vars
  1541. if env.GetAWSAccessKeyID() == "" || env.GetAWSAccessKeySecret() == "" {
  1542. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1543. Message: "AWS ServiceKey exists",
  1544. Status: false,
  1545. })
  1546. } else {
  1547. aws.ServiceAccountChecks.Set("hasKey", &models.ServiceAccountCheck{
  1548. Message: "AWS ServiceKey exists",
  1549. Status: true,
  1550. })
  1551. }
  1552. return env.GetAWSAccessKeyID(), env.GetAWSAccessKeySecret()
  1553. }
  1554. // Load once and cache the result (even on failure). This is an install time secret, so
  1555. // we don't expect the secret to change. If it does, however, we can force reload using
  1556. // the input parameter.
  1557. func (aws *AWS) loadAWSAuthSecret(force bool) (*AWSAccessKey, error) {
  1558. if !force && loadedAWSSecret {
  1559. return awsSecret, nil
  1560. }
  1561. loadedAWSSecret = true
  1562. exists, err := fileutil.FileExists(models.AuthSecretPath)
  1563. if !exists || err != nil {
  1564. return nil, fmt.Errorf("Failed to locate service account file: %s", models.AuthSecretPath)
  1565. }
  1566. result, err := os.ReadFile(models.AuthSecretPath)
  1567. if err != nil {
  1568. return nil, err
  1569. }
  1570. var ak AWSAccessKey
  1571. err = json.Unmarshal(result, &ak)
  1572. if err != nil {
  1573. return nil, err
  1574. }
  1575. awsSecret = &ak
  1576. return awsSecret, nil
  1577. }
  1578. func (aws *AWS) getAddressesForRegion(ctx context.Context, region string) (*ec2.DescribeAddressesOutput, error) {
  1579. aak, err := aws.GetAWSAccessKey()
  1580. if err != nil {
  1581. return nil, err
  1582. }
  1583. cfg, err := aak.CreateConfig(region)
  1584. if err != nil {
  1585. return nil, err
  1586. }
  1587. cli := ec2.NewFromConfig(cfg)
  1588. return cli.DescribeAddresses(ctx, &ec2.DescribeAddressesInput{})
  1589. }
  1590. func (aws *AWS) getAllAddresses() ([]*ec2Types.Address, error) {
  1591. aws.ConfigureAuth() // load authentication data into env vars
  1592. regions := aws.Regions()
  1593. addressCh := make(chan *ec2.DescribeAddressesOutput, len(regions))
  1594. errorCh := make(chan error, len(regions))
  1595. var wg sync.WaitGroup
  1596. wg.Add(len(regions))
  1597. // Get volumes from each AWS region
  1598. for _, r := range regions {
  1599. region := r // make a copy of r to avoid capturing loop variable
  1600. // Fetch IP address response and send results and errors to their
  1601. // respective channels
  1602. go func() {
  1603. defer wg.Done()
  1604. defer errs.HandlePanic()
  1605. // Query for first page of volume results
  1606. resp, err := aws.getAddressesForRegion(context.TODO(), region)
  1607. if err != nil {
  1608. var awsErr smithy.APIError
  1609. if errors.As(err, &awsErr) {
  1610. switch awsErr.ErrorCode() {
  1611. case "AuthFailure", "InvalidClientTokenId", "UnauthorizedOperation":
  1612. log.DedupedInfof(5, "Unable to get addresses for region %s due to AWS permissions, error message: %s", region, awsErr.ErrorMessage())
  1613. return
  1614. default:
  1615. errorCh <- err
  1616. return
  1617. }
  1618. } else {
  1619. errorCh <- err
  1620. return
  1621. }
  1622. }
  1623. addressCh <- resp
  1624. }()
  1625. }
  1626. // Close the result channels after everything has been sent
  1627. go func() {
  1628. defer errs.HandlePanic()
  1629. wg.Wait()
  1630. close(errorCh)
  1631. close(addressCh)
  1632. }()
  1633. var addresses []*ec2Types.Address
  1634. for adds := range addressCh {
  1635. for _, add := range adds.Addresses {
  1636. a := add // duplicate to avoid pointer to iterator
  1637. addresses = append(addresses, &a)
  1638. }
  1639. }
  1640. var errs []error
  1641. for err := range errorCh {
  1642. log.DedupedWarningf(5, "unable to get addresses: %s", err)
  1643. errs = append(errs, err)
  1644. }
  1645. // Return error if no addresses are returned
  1646. if len(errs) > 0 && len(addresses) == 0 {
  1647. return nil, fmt.Errorf("%d error(s) retrieving addresses: %v", len(errs), errs)
  1648. }
  1649. return addresses, nil
  1650. }
  1651. // GetAddresses retrieves EC2 addresses
  1652. func (aws *AWS) GetAddresses() ([]byte, error) {
  1653. addresses, err := aws.getAllAddresses()
  1654. if err != nil {
  1655. return nil, err
  1656. }
  1657. // Format the response this way to match the JSON-encoded formatting of a single response
  1658. // from DescribeAddresss, so that consumers can always expect AWS disk responses to have
  1659. // a "Addresss" key at the top level.
  1660. return json.Marshal(map[string][]*ec2Types.Address{
  1661. "Addresses": addresses,
  1662. })
  1663. }
  1664. func (aws *AWS) isAddressOrphaned(address *ec2Types.Address) bool {
  1665. if address.AssociationId != nil {
  1666. return false
  1667. }
  1668. return true
  1669. }
  1670. func (aws *AWS) getDisksForRegion(ctx context.Context, region string, maxResults int32, nextToken *string) (*ec2.DescribeVolumesOutput, error) {
  1671. aak, err := aws.GetAWSAccessKey()
  1672. if err != nil {
  1673. return nil, err
  1674. }
  1675. cfg, err := aak.CreateConfig(region)
  1676. if err != nil {
  1677. return nil, err
  1678. }
  1679. cli := ec2.NewFromConfig(cfg)
  1680. return cli.DescribeVolumes(ctx, &ec2.DescribeVolumesInput{
  1681. MaxResults: &maxResults,
  1682. NextToken: nextToken,
  1683. })
  1684. }
  1685. func (aws *AWS) getAllDisks() ([]*ec2Types.Volume, error) {
  1686. aws.ConfigureAuth() // load authentication data into env vars
  1687. regions := aws.Regions()
  1688. volumeCh := make(chan *ec2.DescribeVolumesOutput, len(regions))
  1689. errorCh := make(chan error, len(regions))
  1690. var wg sync.WaitGroup
  1691. wg.Add(len(regions))
  1692. // Get volumes from each AWS region
  1693. for _, r := range regions {
  1694. // Fetch volume response and send results and errors to their
  1695. // respective channels
  1696. go func(region string) {
  1697. defer wg.Done()
  1698. defer errs.HandlePanic()
  1699. // Query for first page of volume results
  1700. resp, err := aws.getDisksForRegion(context.TODO(), region, 1000, nil)
  1701. if err != nil {
  1702. var awsErr smithy.APIError
  1703. if errors.As(err, &awsErr) {
  1704. switch awsErr.ErrorCode() {
  1705. case "AuthFailure", "InvalidClientTokenId", "UnauthorizedOperation":
  1706. log.DedupedInfof(5, "Unable to get disks for region %s due to AWS permissions, error message: %s", region, awsErr.ErrorMessage())
  1707. return
  1708. default:
  1709. errorCh <- err
  1710. return
  1711. }
  1712. } else {
  1713. errorCh <- err
  1714. return
  1715. }
  1716. }
  1717. volumeCh <- resp
  1718. // A NextToken indicates more pages of results. Keep querying
  1719. // until all pages are retrieved.
  1720. for resp.NextToken != nil {
  1721. resp, err = aws.getDisksForRegion(context.TODO(), region, 100, resp.NextToken)
  1722. if err != nil {
  1723. errorCh <- err
  1724. return
  1725. }
  1726. volumeCh <- resp
  1727. }
  1728. }(r)
  1729. }
  1730. // Close the result channels after everything has been sent
  1731. go func() {
  1732. defer errs.HandlePanic()
  1733. wg.Wait()
  1734. close(errorCh)
  1735. close(volumeCh)
  1736. }()
  1737. var volumes []*ec2Types.Volume
  1738. for vols := range volumeCh {
  1739. for _, vol := range vols.Volumes {
  1740. v := vol // duplicate to avoid pointer to iterator
  1741. volumes = append(volumes, &v)
  1742. }
  1743. }
  1744. var errs []error
  1745. for err := range errorCh {
  1746. log.DedupedWarningf(5, "unable to get disks: %s", err)
  1747. errs = append(errs, err)
  1748. }
  1749. // Return error if no volumes are returned
  1750. if len(errs) > 0 && len(volumes) == 0 {
  1751. return nil, fmt.Errorf("%d error(s) retrieving volumes: %v", len(errs), errs)
  1752. }
  1753. return volumes, nil
  1754. }
  1755. // 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.
  1756. func (aws *AWS) GetDisks() ([]byte, error) {
  1757. volumes, err := aws.getAllDisks()
  1758. if err != nil {
  1759. return nil, err
  1760. }
  1761. // Format the response this way to match the JSON-encoded formatting of a single response
  1762. // from DescribeVolumes, so that consumers can always expect AWS disk responses to have
  1763. // a "Volumes" key at the top level.
  1764. return json.Marshal(map[string][]*ec2Types.Volume{
  1765. "Volumes": volumes,
  1766. })
  1767. }
  1768. func (aws *AWS) isDiskOrphaned(vol *ec2Types.Volume) bool {
  1769. // Do not consider volume orphaned if in use
  1770. if vol.State == InUseState {
  1771. return false
  1772. }
  1773. // Do not consider volume orphaned if volume is attached to any attachments
  1774. if len(vol.Attachments) != 0 {
  1775. for _, attachment := range vol.Attachments {
  1776. if attachment.State == AttachedState {
  1777. return false
  1778. }
  1779. }
  1780. }
  1781. return true
  1782. }
  1783. func (aws *AWS) GetOrphanedResources() ([]models.OrphanedResource, error) {
  1784. volumes, volumesErr := aws.getAllDisks()
  1785. addresses, addressesErr := aws.getAllAddresses()
  1786. // If we have any orphaned resources - prioritize returning them over returning errors
  1787. if len(addresses) == 0 && len(volumes) == 0 {
  1788. if volumesErr != nil {
  1789. return nil, volumesErr
  1790. }
  1791. if addressesErr != nil {
  1792. return nil, addressesErr
  1793. }
  1794. }
  1795. var orphanedResources []models.OrphanedResource
  1796. for _, volume := range volumes {
  1797. if aws.isDiskOrphaned(volume) {
  1798. cost, err := aws.findCostForDisk(volume)
  1799. if err != nil {
  1800. return nil, err
  1801. }
  1802. var volumeSize int64
  1803. if volume.Size != nil {
  1804. volumeSize = int64(*volume.Size)
  1805. }
  1806. // This is turning us-east-1a into us-east-1
  1807. var zone string
  1808. if volume.AvailabilityZone != nil {
  1809. zone = *volume.AvailabilityZone
  1810. }
  1811. var region, url string
  1812. region = regionRx.FindString(zone)
  1813. if region != "" {
  1814. url = "https://console.aws.amazon.com/ec2/home?region=" + region + "#Volumes:sort=desc:createTime"
  1815. } else {
  1816. url = "https://console.aws.amazon.com/ec2/home?#Volumes:sort=desc:createTime"
  1817. }
  1818. // output tags as desc
  1819. tags := map[string]string{}
  1820. for _, tag := range volume.Tags {
  1821. tags[*tag.Key] = *tag.Value
  1822. }
  1823. or := models.OrphanedResource{
  1824. Kind: "disk",
  1825. Region: zone,
  1826. Size: &volumeSize,
  1827. DiskName: *volume.VolumeId,
  1828. Url: url,
  1829. MonthlyCost: cost,
  1830. Description: tags,
  1831. }
  1832. orphanedResources = append(orphanedResources, or)
  1833. }
  1834. }
  1835. for _, address := range addresses {
  1836. if aws.isAddressOrphaned(address) {
  1837. cost := AWSHourlyPublicIPCost * timeutil.HoursPerMonth
  1838. desc := map[string]string{}
  1839. for _, tag := range address.Tags {
  1840. if tag.Key == nil {
  1841. continue
  1842. }
  1843. if tag.Value == nil {
  1844. desc[*tag.Key] = ""
  1845. } else {
  1846. desc[*tag.Key] = *tag.Value
  1847. }
  1848. }
  1849. or := models.OrphanedResource{
  1850. Kind: "address",
  1851. Address: *address.PublicIp,
  1852. Description: desc,
  1853. Url: "http://console.aws.amazon.com/ec2/home?#Addresses",
  1854. MonthlyCost: &cost,
  1855. }
  1856. orphanedResources = append(orphanedResources, or)
  1857. }
  1858. }
  1859. return orphanedResources, nil
  1860. }
  1861. func (aws *AWS) findCostForDisk(disk *ec2Types.Volume) (*float64, error) {
  1862. // todo: use AWS pricing from all regions
  1863. if disk.AvailabilityZone == nil {
  1864. return nil, fmt.Errorf("nil region")
  1865. }
  1866. if disk.Size == nil {
  1867. return nil, fmt.Errorf("nil disk size")
  1868. }
  1869. class := volTypes[string(disk.VolumeType)]
  1870. key := aws.ClusterRegion + "," + class
  1871. pricing, ok := aws.Pricing[key]
  1872. if !ok {
  1873. return nil, fmt.Errorf("no pricing data for key '%s'", key)
  1874. }
  1875. if pricing == nil {
  1876. return nil, fmt.Errorf("nil pricing data for key '%s'", key)
  1877. }
  1878. if pricing.PV == nil {
  1879. return nil, fmt.Errorf("pricing for key '%s' has nil PV", key)
  1880. }
  1881. priceStr := pricing.PV.Cost
  1882. price, err := strconv.ParseFloat(priceStr, 64)
  1883. if err != nil {
  1884. return nil, err
  1885. }
  1886. cost := price * timeutil.HoursPerMonth * float64(*disk.Size)
  1887. return &cost, nil
  1888. }
  1889. // QueryAthenaPaginated executes athena query and processes results.
  1890. func (aws *AWS) QueryAthenaPaginated(ctx context.Context, query string, fn func(*athena.GetQueryResultsOutput) bool) error {
  1891. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  1892. if err != nil {
  1893. return err
  1894. }
  1895. if awsAthenaInfo.AthenaDatabase == "" || awsAthenaInfo.AthenaTable == "" || awsAthenaInfo.AthenaRegion == "" ||
  1896. awsAthenaInfo.AthenaBucketName == "" || awsAthenaInfo.AccountID == "" {
  1897. return fmt.Errorf("QueryAthenaPaginated: athena configuration incomplete")
  1898. }
  1899. queryExecutionCtx := &athenaTypes.QueryExecutionContext{
  1900. Database: awsSDK.String(awsAthenaInfo.AthenaDatabase),
  1901. }
  1902. if awsAthenaInfo.AthenaCatalog != "" {
  1903. queryExecutionCtx.Catalog = awsSDK.String(awsAthenaInfo.AthenaCatalog)
  1904. }
  1905. resultConfiguration := &athenaTypes.ResultConfiguration{
  1906. OutputLocation: awsSDK.String(awsAthenaInfo.AthenaBucketName),
  1907. }
  1908. startQueryExecutionInput := &athena.StartQueryExecutionInput{
  1909. QueryString: awsSDK.String(query),
  1910. QueryExecutionContext: queryExecutionCtx,
  1911. ResultConfiguration: resultConfiguration,
  1912. }
  1913. // Only set if there is a value, the default input is nil which defaults to the 'primary' workgroup
  1914. if awsAthenaInfo.AthenaWorkgroup != "" {
  1915. startQueryExecutionInput.WorkGroup = awsSDK.String(awsAthenaInfo.AthenaWorkgroup)
  1916. }
  1917. // Create Athena Client
  1918. cfg, err := awsAthenaInfo.CreateConfig()
  1919. if err != nil {
  1920. log.Errorf("Could not retrieve Athena Configuration: %s", err.Error())
  1921. }
  1922. cli := athena.NewFromConfig(cfg)
  1923. // Query Athena
  1924. startQueryExecutionOutput, err := cli.StartQueryExecution(ctx, startQueryExecutionInput)
  1925. if err != nil {
  1926. return fmt.Errorf("QueryAthenaPaginated: start query error: %s", err.Error())
  1927. }
  1928. err = waitForQueryToComplete(ctx, cli, startQueryExecutionOutput.QueryExecutionId)
  1929. if err != nil {
  1930. return fmt.Errorf("QueryAthenaPaginated: query execution error: %s", err.Error())
  1931. }
  1932. queryResultsInput := &athena.GetQueryResultsInput{
  1933. QueryExecutionId: startQueryExecutionOutput.QueryExecutionId,
  1934. }
  1935. getQueryResultsPaginator := athena.NewGetQueryResultsPaginator(cli, queryResultsInput)
  1936. for getQueryResultsPaginator.HasMorePages() {
  1937. pg, err := getQueryResultsPaginator.NextPage(ctx)
  1938. if err != nil {
  1939. log.Errorf("QueryAthenaPaginated: NextPage error: %s", err.Error())
  1940. continue
  1941. }
  1942. fn(pg)
  1943. }
  1944. return nil
  1945. }
  1946. type SavingsPlanData struct {
  1947. ResourceID string
  1948. EffectiveCost float64
  1949. SavingsPlanARN string
  1950. MostRecentDate string
  1951. }
  1952. func (aws *AWS) GetSavingsPlanDataFromAthena() error {
  1953. cfg, err := aws.GetConfig()
  1954. if err != nil {
  1955. aws.RIPricingError = err
  1956. return err
  1957. }
  1958. if cfg.AthenaBucketName == "" {
  1959. err = ErrNoAthenaBucket
  1960. aws.RIPricingError = err
  1961. return err
  1962. }
  1963. if aws.SavingsPlanDataByInstanceID == nil {
  1964. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData)
  1965. }
  1966. tNow := time.Now()
  1967. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  1968. start := tOneDayAgo.Format("2006-01-02")
  1969. end := tNow.Format("2006-01-02")
  1970. // Use Savings Plan Effective Rate as an estimation for cost, assuming the 1h most recent period got a fully loaded savings plan.
  1971. //
  1972. q := `SELECT
  1973. line_item_usage_start_date,
  1974. savings_plan_savings_plan_a_r_n,
  1975. line_item_resource_id,
  1976. savings_plan_savings_plan_rate
  1977. FROM %s as cost_data
  1978. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  1979. AND line_item_line_item_type = 'SavingsPlanCoveredUsage' ORDER BY
  1980. line_item_usage_start_date DESC`
  1981. page := 0
  1982. mostRecentDate := ""
  1983. processResults := func(op *athena.GetQueryResultsOutput) bool {
  1984. if op == nil {
  1985. log.Errorf("GetSavingsPlanDataFromAthena: Athena page is nil")
  1986. return false
  1987. } else if op.ResultSet == nil {
  1988. log.Errorf("GetSavingsPlanDataFromAthena: Athena page.ResultSet is nil")
  1989. return false
  1990. }
  1991. aws.SavingsPlanDataLock.Lock()
  1992. defer aws.SavingsPlanDataLock.Unlock()
  1993. if page == 0 {
  1994. aws.SavingsPlanDataByInstanceID = make(map[string]*SavingsPlanData) // Clean out the old data and only report a savingsplan price if its in the most recent run.
  1995. }
  1996. iter := op.ResultSet.Rows
  1997. if page == 0 && len(iter) > 0 {
  1998. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  1999. }
  2000. page++
  2001. for _, r := range iter {
  2002. d := *r.Data[0].VarCharValue
  2003. if mostRecentDate == "" {
  2004. mostRecentDate = d
  2005. } else if mostRecentDate != d { // Get all most recent assignments
  2006. break
  2007. }
  2008. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  2009. if err != nil {
  2010. log.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  2011. }
  2012. r := &SavingsPlanData{
  2013. ResourceID: *r.Data[2].VarCharValue,
  2014. EffectiveCost: cost,
  2015. SavingsPlanARN: *r.Data[1].VarCharValue,
  2016. MostRecentDate: d,
  2017. }
  2018. aws.SavingsPlanDataByInstanceID[r.ResourceID] = r
  2019. }
  2020. log.Debugf("Found %d savings plan applied instances", len(aws.SavingsPlanDataByInstanceID))
  2021. for k, r := range aws.SavingsPlanDataByInstanceID {
  2022. log.DedupedInfof(5, "Savings Plan Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  2023. }
  2024. return true
  2025. }
  2026. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  2027. log.Debugf("Running Query: %s", query)
  2028. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  2029. if err != nil {
  2030. aws.RIPricingError = err
  2031. return fmt.Errorf("Error fetching Savings Plan Data: %s", err)
  2032. }
  2033. return nil
  2034. }
  2035. type RIData struct {
  2036. ResourceID string
  2037. EffectiveCost float64
  2038. ReservationARN string
  2039. MostRecentDate string
  2040. }
  2041. func (aws *AWS) GetReservationDataFromAthena() error {
  2042. cfg, err := aws.GetConfig()
  2043. if err != nil {
  2044. aws.RIPricingError = err
  2045. return err
  2046. }
  2047. if cfg.AthenaBucketName == "" {
  2048. err = ErrNoAthenaBucket
  2049. aws.RIPricingError = err
  2050. return err
  2051. }
  2052. // Query for all column names in advance in order to validate configured
  2053. // label columns
  2054. columns, _ := aws.fetchColumns()
  2055. if !columns["reservation_reservation_a_r_n"] || !columns["reservation_effective_cost"] {
  2056. err = fmt.Errorf("no reservation data available in Athena")
  2057. aws.RIPricingError = err
  2058. return err
  2059. }
  2060. if aws.RIPricingByInstanceID == nil {
  2061. aws.RIPricingByInstanceID = make(map[string]*RIData)
  2062. }
  2063. tNow := time.Now()
  2064. tOneDayAgo := tNow.Add(time.Duration(-25) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  2065. start := tOneDayAgo.Format("2006-01-02")
  2066. end := tNow.Format("2006-01-02")
  2067. q := `SELECT
  2068. line_item_usage_start_date,
  2069. reservation_reservation_a_r_n,
  2070. line_item_resource_id,
  2071. reservation_effective_cost
  2072. FROM %s as cost_data
  2073. WHERE line_item_usage_start_date BETWEEN date '%s' AND date '%s'
  2074. AND reservation_reservation_a_r_n <> '' ORDER BY
  2075. line_item_usage_start_date DESC`
  2076. page := 0
  2077. mostRecentDate := ""
  2078. processResults := func(op *athena.GetQueryResultsOutput) bool {
  2079. if op == nil {
  2080. log.Errorf("GetReservationDataFromAthena: Athena page is nil")
  2081. return false
  2082. } else if op.ResultSet == nil {
  2083. log.Errorf("GetReservationDataFromAthena: Athena page.ResultSet is nil")
  2084. return false
  2085. }
  2086. aws.RIDataLock.Lock()
  2087. defer aws.RIDataLock.Unlock()
  2088. if page == 0 {
  2089. aws.RIPricingByInstanceID = make(map[string]*RIData) // Clean out the old data and only report a RI price if its in the most recent run.
  2090. }
  2091. iter := op.ResultSet.Rows
  2092. if page == 0 && len(iter) > 0 {
  2093. iter = op.ResultSet.Rows[1:len(op.ResultSet.Rows)]
  2094. }
  2095. page++
  2096. for _, r := range iter {
  2097. d := *r.Data[0].VarCharValue
  2098. if mostRecentDate == "" {
  2099. mostRecentDate = d
  2100. } else if mostRecentDate != d { // Get all most recent assignments
  2101. break
  2102. }
  2103. cost, err := strconv.ParseFloat(*r.Data[3].VarCharValue, 64)
  2104. if err != nil {
  2105. log.Infof("Error converting `%s` from float ", *r.Data[3].VarCharValue)
  2106. }
  2107. r := &RIData{
  2108. ResourceID: *r.Data[2].VarCharValue,
  2109. EffectiveCost: cost,
  2110. ReservationARN: *r.Data[1].VarCharValue,
  2111. MostRecentDate: d,
  2112. }
  2113. aws.RIPricingByInstanceID[r.ResourceID] = r
  2114. }
  2115. log.Debugf("Found %d reserved instances", len(aws.RIPricingByInstanceID))
  2116. for k, r := range aws.RIPricingByInstanceID {
  2117. log.DedupedInfof(5, "Reserved Instance Data found for node %s : %f at time %s", k, r.EffectiveCost, r.MostRecentDate)
  2118. }
  2119. return true
  2120. }
  2121. query := fmt.Sprintf(q, cfg.AthenaTable, start, end)
  2122. log.Debugf("Running Query: %s", query)
  2123. err = aws.QueryAthenaPaginated(context.TODO(), query, processResults)
  2124. if err != nil {
  2125. aws.RIPricingError = err
  2126. return fmt.Errorf("Error fetching Reserved Instance Data: %s", err)
  2127. }
  2128. aws.RIPricingError = nil
  2129. return nil
  2130. }
  2131. // fetchColumns returns a list of the names of all columns in the configured
  2132. // Athena tables
  2133. func (aws *AWS) fetchColumns() (map[string]bool, error) {
  2134. columnSet := map[string]bool{}
  2135. awsAthenaInfo, err := aws.GetAWSAthenaInfo()
  2136. if err != nil {
  2137. return nil, err
  2138. }
  2139. // This Query is supported by Athena tables and views
  2140. q := `SELECT column_name FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s'`
  2141. query := fmt.Sprintf(q, awsAthenaInfo.AthenaDatabase, awsAthenaInfo.AthenaTable)
  2142. pageNum := 0
  2143. athenaErr := aws.QueryAthenaPaginated(context.TODO(), query, func(page *athena.GetQueryResultsOutput) bool {
  2144. if page == nil {
  2145. log.Errorf("fetchColumns: Athena page is nil")
  2146. return false
  2147. } else if page.ResultSet == nil {
  2148. log.Errorf("fetchColumns: Athena page.ResultSet is nil")
  2149. return false
  2150. }
  2151. // remove header row 'column_name'
  2152. rows := page.ResultSet.Rows[1:]
  2153. for _, row := range rows {
  2154. columnSet[*row.Data[0].VarCharValue] = true
  2155. }
  2156. pageNum++
  2157. return true
  2158. })
  2159. if athenaErr != nil {
  2160. return columnSet, athenaErr
  2161. }
  2162. if len(columnSet) == 0 {
  2163. log.Infof("No columns retrieved from Athena")
  2164. }
  2165. return columnSet, nil
  2166. }
  2167. type spotInfo struct {
  2168. Timestamp string `csv:"Timestamp"`
  2169. UsageType string `csv:"UsageType"`
  2170. Operation string `csv:"Operation"`
  2171. InstanceID string `csv:"InstanceID"`
  2172. MyBidID string `csv:"MyBidID"`
  2173. MyMaxPrice string `csv:"MyMaxPrice"`
  2174. MarketPrice string `csv:"MarketPrice"`
  2175. Charge string `csv:"Charge"`
  2176. Version string `csv:"Version"`
  2177. }
  2178. func (aws *AWS) parseSpotData(bucket string, prefix string, projectID string, region string) (map[string]*spotInfo, error) {
  2179. aws.ConfigureAuth() // configure aws api authentication by setting env vars
  2180. s3Prefix := projectID
  2181. if len(prefix) != 0 {
  2182. s3Prefix = prefix + "/" + s3Prefix
  2183. }
  2184. aak, err := aws.GetAWSAccessKey()
  2185. if err != nil {
  2186. return nil, err
  2187. }
  2188. cfg, err := aak.CreateConfig(region)
  2189. if err != nil {
  2190. return nil, err
  2191. }
  2192. cli := s3.NewFromConfig(cfg)
  2193. downloader := manager.NewDownloader(cli)
  2194. tNow := time.Now()
  2195. tOneDayAgo := tNow.Add(time.Duration(-24) * time.Hour) // Also get files from one day ago to avoid boundary conditions
  2196. ls := &s3.ListObjectsInput{
  2197. Bucket: awsSDK.String(bucket),
  2198. Prefix: awsSDK.String(s3Prefix + "." + tOneDayAgo.Format("2006-01-02")),
  2199. }
  2200. ls2 := &s3.ListObjectsInput{
  2201. Bucket: awsSDK.String(bucket),
  2202. Prefix: awsSDK.String(s3Prefix + "." + tNow.Format("2006-01-02")),
  2203. }
  2204. lso, err := cli.ListObjects(context.TODO(), ls)
  2205. if err != nil {
  2206. aws.ServiceAccountChecks.Set("bucketList", &models.ServiceAccountCheck{
  2207. Message: "Bucket List Permissions Available",
  2208. Status: false,
  2209. AdditionalInfo: err.Error(),
  2210. })
  2211. return nil, err
  2212. } else {
  2213. aws.ServiceAccountChecks.Set("bucketList", &models.ServiceAccountCheck{
  2214. Message: "Bucket List Permissions Available",
  2215. Status: true,
  2216. })
  2217. }
  2218. lsoLen := len(lso.Contents)
  2219. log.Debugf("Found %d spot data files from yesterday", lsoLen)
  2220. if lsoLen == 0 {
  2221. log.Debugf("ListObjects \"s3://%s/%s\" produced no keys", *ls.Bucket, *ls.Prefix)
  2222. }
  2223. lso2, err := cli.ListObjects(context.TODO(), ls2)
  2224. if err != nil {
  2225. return nil, err
  2226. }
  2227. lso2Len := len(lso2.Contents)
  2228. log.Debugf("Found %d spot data files from today", lso2Len)
  2229. if lso2Len == 0 {
  2230. log.Debugf("ListObjects \"s3://%s/%s\" produced no keys", *ls2.Bucket, *ls2.Prefix)
  2231. }
  2232. // TODO: Worth it to use LastModifiedDate to determine if we should reparse the spot data?
  2233. var keys []*string
  2234. for _, obj := range lso.Contents {
  2235. keys = append(keys, obj.Key)
  2236. }
  2237. for _, obj := range lso2.Contents {
  2238. keys = append(keys, obj.Key)
  2239. }
  2240. header, err := csvutil.Header(spotInfo{}, "csv")
  2241. if err != nil {
  2242. return nil, err
  2243. }
  2244. fieldsPerRecord := len(header)
  2245. spots := make(map[string]*spotInfo)
  2246. for _, key := range keys {
  2247. getObj := &s3.GetObjectInput{
  2248. Bucket: awsSDK.String(bucket),
  2249. Key: key,
  2250. }
  2251. buf := manager.NewWriteAtBuffer([]byte{})
  2252. _, err := downloader.Download(context.TODO(), buf, getObj)
  2253. if err != nil {
  2254. aws.ServiceAccountChecks.Set("objectList", &models.ServiceAccountCheck{
  2255. Message: "Object Get Permissions Available",
  2256. Status: false,
  2257. AdditionalInfo: err.Error(),
  2258. })
  2259. return nil, err
  2260. } else {
  2261. aws.ServiceAccountChecks.Set("objectList", &models.ServiceAccountCheck{
  2262. Message: "Object Get Permissions Available",
  2263. Status: true,
  2264. })
  2265. }
  2266. r := bytes.NewReader(buf.Bytes())
  2267. gr, err := gzip.NewReader(r)
  2268. if err != nil {
  2269. return nil, err
  2270. }
  2271. csvReader := csv.NewReader(gr)
  2272. csvReader.Comma = '\t'
  2273. csvReader.FieldsPerRecord = fieldsPerRecord
  2274. dec, err := csvutil.NewDecoder(csvReader, header...)
  2275. if err != nil {
  2276. return nil, err
  2277. }
  2278. var foundVersion string
  2279. for {
  2280. spot := spotInfo{}
  2281. err := dec.Decode(&spot)
  2282. csvParseErr, isCsvParseErr := err.(*csv.ParseError)
  2283. if err == io.EOF {
  2284. break
  2285. } else if err == csvutil.ErrFieldCount || (isCsvParseErr && csvParseErr.Err == csv.ErrFieldCount) {
  2286. rec := dec.Record()
  2287. // the first two "Record()" will be the comment lines
  2288. // and they show up as len() == 1
  2289. // the first of which is "#Version"
  2290. // the second of which is "#Fields: "
  2291. if len(rec) != 1 {
  2292. log.Infof("Expected %d spot info fields but received %d: %s", fieldsPerRecord, len(rec), rec)
  2293. continue
  2294. }
  2295. if len(foundVersion) == 0 {
  2296. spotFeedVersion := rec[0]
  2297. log.Debugf("Spot feed version is \"%s\"", spotFeedVersion)
  2298. matches := versionRx.FindStringSubmatch(spotFeedVersion)
  2299. if matches != nil {
  2300. foundVersion = matches[1]
  2301. if foundVersion != supportedSpotFeedVersion {
  2302. log.Infof("Unsupported spot info feed version: wanted \"%s\" got \"%s\"", supportedSpotFeedVersion, foundVersion)
  2303. break
  2304. }
  2305. }
  2306. continue
  2307. } else if strings.Index(rec[0], "#") == 0 {
  2308. continue
  2309. } else {
  2310. log.Infof("skipping non-TSV line: %s", rec)
  2311. continue
  2312. }
  2313. } else if err != nil {
  2314. log.Warnf("Error during spot info decode: %+v", err)
  2315. continue
  2316. }
  2317. log.DedupedInfof(5, "Found spot info for: %s", spot.InstanceID)
  2318. spots[spot.InstanceID] = &spot
  2319. }
  2320. gr.Close()
  2321. }
  2322. return spots, nil
  2323. }
  2324. // ApplyReservedInstancePricing TODO
  2325. func (aws *AWS) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  2326. }
  2327. func (aws *AWS) ServiceAccountStatus() *models.ServiceAccountStatus {
  2328. return aws.ServiceAccountChecks.GetStatus()
  2329. }
  2330. func (aws *AWS) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  2331. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  2332. }
  2333. // Regions returns a predefined list of AWS regions
  2334. func (aws *AWS) Regions() []string {
  2335. regionOverrides := env.GetRegionOverrideList()
  2336. if len(regionOverrides) > 0 {
  2337. log.Debugf("Overriding AWS regions with configured region list: %+v", regionOverrides)
  2338. return regionOverrides
  2339. }
  2340. return awsRegions
  2341. }
  2342. // PricingSourceSummary returns the pricing source summary for the provider.
  2343. // The summary represents what was _parsed_ from the pricing source, not
  2344. // everything that was _available_ in the pricing source.
  2345. func (aws *AWS) PricingSourceSummary() interface{} {
  2346. // encode the pricing source summary as a JSON string
  2347. return aws.Pricing
  2348. }