provider.go 74 KB

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