provider.go 75 KB

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