provider.go 73 KB

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