provider.go 74 KB

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