provider.go 74 KB

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