provider.go 74 KB

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