provider.go 79 KB

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