-
Notifications
You must be signed in to change notification settings - Fork 25
/
main.go
286 lines (254 loc) · 8.06 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package awsets
import (
ctx2 "context"
"fmt"
"reflect"
"runtime/debug"
"strings"
"sync"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/trek10inc/awsets/context"
"github.com/trek10inc/awsets/lister"
"github.com/trek10inc/awsets/resource"
)
type ListerName string
// Types applies a filter to all supported AWS resources types and returns a
// slice of the ones that match. It first builds a list of all resources types
// that match any of the prefixes defined in `include`, and then removes any
// resource types that match any of the prefixes defined in `exclude`
func Types(include []string, exclude []string) []resource.ResourceType {
filteredListers := Listers(include, exclude)
typeMap := make(map[resource.ResourceType]struct{})
for _, v := range filteredListers {
for _, l := range lister.AllListers() {
if v == ListerName(reflect.TypeOf(l).Name()) {
for _, t := range l.Types() {
typeMap[t] = struct{}{}
}
}
}
}
ret := make([]resource.ResourceType, 0)
for k := range typeMap {
ret = append(ret, k)
}
return ret
}
// Listers applies an include/exclude filter to all implemented listers and
// returns a slice of the Lister names that match. The filter is processed
// against the resource types handled by each Lister.
func Listers(include []string, exclude []string) []ListerName {
listerMap := make(map[ListerName]struct{}, 0)
if len(include) == 0 {
for _, v := range lister.AllListers() {
listerMap[ListerName(reflect.TypeOf(v).Name())] = struct{}{}
}
} else {
for _, name := range include {
for _, v := range lister.AllListers() {
for _, t := range v.Types() {
if strings.HasPrefix(t.String(), name) {
listerMap[ListerName(reflect.TypeOf(v).Name())] = struct{}{}
}
}
}
}
}
for _, name := range exclude {
if len(name) == 0 {
continue
}
for _, v := range lister.AllListers() {
for _, t := range v.Types() {
if strings.HasPrefix(t.String(), name) {
delete(listerMap, ListerName(reflect.TypeOf(v).Name()))
}
}
}
}
ret := make([]ListerName, 0)
for v := range listerMap {
ret = append(ret, v)
}
return ret
}
// GetByName finds the Lister that matches the name of the input argument. It
// returns an error if no match is found.
func GetByName(name ListerName) (lister.Lister, error) {
for _, v := range lister.AllListers() {
if name == ListerName(reflect.TypeOf(v).Name()) {
return v, nil
}
}
return nil, fmt.Errorf("no Lister found for %s", name)
}
// GetByType finds the Lister that processes the ResourceType given as an
// argument. It returns an error if no match is found.
func GetByType(kind resource.ResourceType) (lister.Lister, error) {
for _, v := range lister.AllListers() {
for _, t := range v.Types() {
if t == kind {
return v, nil
}
}
}
return nil, fmt.Errorf("no Lister found for %s", kind)
}
// Regions applies a filter to all available AWS regions and returns a list
// of the ones that match. The filtering is done by finding the regions that
// start with any of the prefixes pass in as arguments. If no prefixes are
// given, all available regions are returned.
func Regions(cfg aws.Config, prefixes ...string) ([]string, error) {
// query AWS to find a list of all regions that the given credentials
// have access to
cfg.Region = "us-east-1"
ec2svc := ec2.NewFromConfig(cfg)
regionsRes, err := ec2svc.DescribeRegions(ctx2.Background(), &ec2.DescribeRegionsInput{
AllRegions: aws.Bool(true),
})
if err != nil {
return nil, fmt.Errorf("failed to query regions: %w", err)
}
// remove any AWS regions that are disabled in the current account
regionMap := make(map[string]struct{}, 0)
for _, r := range regionsRes.Regions {
if r.OptInStatus != nil && *r.OptInStatus == "not-opted-in" {
continue
}
if len(prefixes) == 0 {
regionMap[*r.RegionName] = struct{}{}
} else {
for _, p := range prefixes {
if strings.HasPrefix(*r.RegionName, p) {
regionMap[*r.RegionName] = struct{}{}
}
}
}
}
regions := make([]string, 0)
for k := range regionMap {
regions = append(regions, k)
}
return regions, nil
}
// List handles the execution of listers across multiple regions. It creates a
// worker pool to process every Lister/Region combination and aggregates the
// results together before returning them. If a cache is provided, each
// Lister/Region combination will first check for an existing result before
// querying AWS. Any new results will be updated in the cache.
func List(options ...Option) (*resource.Group, error) {
// Create config struct, apply options
awsetsCfg := &config{}
for _, opt := range options {
opt(awsetsCfg)
}
defer awsetsCfg.close()
// Validates config values, defaults them if they are not specified
err := awsetsCfg.validate()
if err != nil {
return nil, fmt.Errorf("failed to validate config: %w", err)
}
// Creates a work queue
jobs := make(chan listjob, 0)
totalJobs := len(awsetsCfg.Regions) * len(awsetsCfg.Listers)
rg := resource.NewGroup()
// Build worker pool
wg := &sync.WaitGroup{}
for i := 0; i < awsetsCfg.WorkerCount; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
for {
select {
case job, more := <-jobs:
if !more {
return
}
// Creates the AWSets context - this also configures the region in the AWS config
workerCtx := createContext(awsetsCfg, id, job, totalJobs)
workerCtx.SendStatus(context.StatusProcessing, "processing")
group, err := processJob(workerCtx, id, job, awsetsCfg.Cache)
if err != nil {
workerCtx.SendStatus(context.StatusCompleteWithError, err.Error())
} else {
// Merge the new results in with the rest
rg.Merge(group)
workerCtx.SendStatus(context.StatusComplete, "")
}
}
}
}(i)
}
// Populate work queue with all Region/ListerName combinations
for _, k := range awsetsCfg.Listers {
for _, r := range awsetsCfg.Regions {
jobs <- listjob{
lister: k,
region: r,
}
}
}
// Closes worker queue so the worker pool knows to stop
close(jobs)
wg.Wait()
return rg, nil
}
// processJob does the actual querying of a particular resource type in a particular region. It catches panics caused by
// both the AWS SDK and also any other issues so that the full processing always completes.
func processJob(awsetsCtx *context.AWSetsCtx, id int, job listjob, cache Cacher) (rg *resource.Group, jobError error) {
defer func() {
if r := recover(); r != nil {
jobError = fmt.Errorf("panicked: %v", r)
awsetsCtx.SendStatus(context.StatusLogError, fmt.Sprintf("%d: stacktrace from panic: %v\n", id, string(debug.Stack())))
}
}()
rg = resource.NewGroup()
// If listing is cached, return it
if cache.IsCached(job.region, job.lister) {
awsetsCtx.SendStatus(context.StatusLogDebug, fmt.Sprintf("%d: cached: %s - %s", id, job.region, job.lister))
rg, jobError = cache.LoadGroup(job.region, job.lister)
if jobError != nil {
jobError = fmt.Errorf("failed to load group from cache: %w", jobError)
}
} else {
awsetsCtx.SendStatus(context.StatusLogDebug, fmt.Sprintf("%d: not cached: %s - %s", id, job.region, job.lister))
// Find the appropriate Lister
l, err := GetByName(job.lister)
if err != nil {
return rg, fmt.Errorf("failed to get lister by name %s: %v", job.lister, err)
}
// Execute listing
rg, jobError = l.List(*awsetsCtx)
if jobError != nil {
// indicates service is not supported in a region
if strings.Contains(jobError.Error(), "no such host") {
jobError = nil
}
return
}
// Update the results in the cache
jobError = cache.SaveGroup(job.lister, rg)
if jobError != nil {
jobError = fmt.Errorf("failed to write resources to cache: %w", jobError)
}
}
return rg, jobError
}
type listjob struct {
lister ListerName
region string
}
func createContext(o *config, id int, job listjob, totalJobs int) *context.AWSetsCtx {
ctx := &context.AWSetsCtx{
AWSCfg: o.AWSCfg.Copy(),
AccountId: o.AccountId,
WorkerId: id,
Context: o.Context,
Lister: string(job.lister),
StatusChan: o.StatusChan,
TotalJobs: totalJobs,
}
ctx.AWSCfg.Region = job.region
return ctx
}