provider.go 75 KB

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