provider.go 75 KB

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