provider.go 75 KB

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