provider.go 76 KB

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