provider.go 75 KB

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