provider.go 73 KB

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