provider.go 80 KB

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