provider.go 76 KB

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