provider.go 71 KB

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