provider.go 74 KB

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