provider.go 75 KB

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