provider.go 80 KB

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