provider.go 74 KB

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