provider.go 75 KB

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