awsprovider.go 69 KB

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