/
client.go
493 lines (402 loc) · 14.3 KB
/
client.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package gcp
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
foundation "github.com/estafette/estafette-foundation"
"github.com/rs/zerolog/log"
"golang.org/x/oauth2/google"
crmv1 "google.golang.org/api/cloudresourcemanager/v1"
computev1 "google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
iamv1 "google.golang.org/api/iam/v1"
)
var (
// ErrAPIForbidden is returned when the api returns a 401
ErrAPIForbidden = wrapError{msg: "The api is not allowed for the current service account"}
// ErrAPINotEnabled is returned when an api is not enabled
ErrAPINotEnabled = wrapError{msg: "The api is not enabled"}
// ErrUnknownProjectID is returned when an api throws 'googleapi: Error 400: Unknown project id: 0, invalid'
ErrUnknownProjectID = wrapError{msg: "The project id is unknown"}
// ErrProjectNotFound is returned when an api throws 'googleapi: Error 404: The requested project was not found., notFound'
ErrProjectNotFound = wrapError{msg: "The project is not found"}
// ErrEntityNotFound is returned when pubsub topics return html with a 404
ErrEntityNotFound = wrapError{msg: "Entity is not found"}
// ErrEntityNotActive is returned when cloud sql instance is not running and its databases cannot be fetched
ErrEntityNotActive = wrapError{msg: "Entity is not runactivening"}
)
//go:generate mockgen -package=gcp -destination ./mock.go -source=client.go
type Client interface {
GetProjectByLabels(ctx context.Context, filters []string) (projects []*crmv1.Project, err error)
GetProjectNetworks(ctx context.Context, projects []*crmv1.Project) (networks []*computev1.Network, err error)
GetProjectSubnetworks(ctx context.Context, projects []*crmv1.Project) (subnetworks []*computev1.Subnetwork, err error)
GetProjectRoutes(ctx context.Context, projects []*crmv1.Project) (routes []*computev1.Route, err error)
}
// NewClient returns a new gcp.Client
func NewClient(ctx context.Context, concurrency int) (Client, error) {
// use service account to authenticate against gcp apis
googleClient, err := google.DefaultClient(ctx, iamv1.CloudPlatformScope)
if err != nil {
return nil, err
}
computev1Service, err := computev1.New(googleClient)
if err != nil {
return nil, err
}
crmv1Service, err := crmv1.New(googleClient)
if err != nil {
return nil, err
}
return &client{
computev1Service: computev1Service,
crmv1Service: crmv1Service,
concurrency: concurrency,
}, nil
}
type client struct {
computev1Service *computev1.Service
crmv1Service *crmv1.Service
concurrency int
}
func (c *client) GetProjectByLabels(ctx context.Context, filters []string) (projects []*crmv1.Project, err error) {
filters = append(filters, "lifecycleState:ACTIVE")
log.Info().Msgf("Retrieving projects for filters %v...", filters)
projects = make([]*crmv1.Project, 0)
nextPageToken := ""
for {
// retrieving projects matching labels (by page)
var resp *crmv1.ListProjectsResponse
err = c.substituteErrorsWithPredefinedErrors(foundation.Retry(func() error {
listCall := c.crmv1Service.Projects.List()
if nextPageToken != "" {
listCall.PageToken(nextPageToken)
}
// set filter
listCall.Filter(strings.Join(filters, " "))
resp, err = listCall.Context(ctx).Do()
if err != nil {
return err
}
return nil
}, c.getRetryOptions()...))
if err != nil {
return projects, fmt.Errorf("Can't get projects by filters %v: %w", filters, err)
}
projects = append(projects, resp.Projects...)
if resp.NextPageToken == "" {
break
}
nextPageToken = resp.NextPageToken
}
log.Debug().Msgf("Retrieved %v projects for filters %v", len(projects), filters)
return
}
func (c *client) getProjectNetworks(ctx context.Context, projectID string) (networks []*computev1.Network, err error) {
if projectID == "" {
return nil, fmt.Errorf("GetProjectNetworks argument projectID is empty")
}
log.Debug().Msgf("Retrieving networks for project %v...", projectID)
nextPageToken := ""
for {
var resp *computev1.NetworkList
err = c.substituteErrorsWithPredefinedErrors(foundation.Retry(func() error {
listCall := c.computev1Service.Networks.List(projectID)
if nextPageToken != "" {
listCall.PageToken(nextPageToken)
}
resp, err = listCall.Context(ctx).Do()
if err != nil {
return err
}
return nil
}, c.getRetryOptions()...))
if err != nil && !errors.Is(err, ErrAPIForbidden) {
return networks, fmt.Errorf("Can't get project networks for project id %v: %w", projectID, err)
}
if err != nil && errors.Is(err, ErrAPIForbidden) {
return networks, nil
}
networks = append(networks, resp.Items...)
if resp.NextPageToken == "" {
break
}
nextPageToken = resp.NextPageToken
}
log.Debug().Msgf("Retrieved %v networks for project %v", len(networks), projectID)
return
}
func (c *client) GetProjectNetworks(ctx context.Context, projects []*crmv1.Project) (networks []*computev1.Network, err error) {
// http://jmoiron.net/blog/limiting-concurrency-in-go/
semaphore := make(chan bool, c.concurrency)
cancelled := false
resultChannel := make(chan struct {
Networks []*computev1.Network
Err error
}, len(projects))
for _, p := range projects {
select {
// try to fill semaphore up to it's full size otherwise wait for a routine to finish
case semaphore <- true:
go func(ctx context.Context, p *crmv1.Project) {
// lower semaphore once the routine's finished, making room for another one to start
defer func() { <-semaphore }()
networks, err := c.getProjectNetworks(ctx, p.ProjectId)
resultChannel <- struct {
Networks []*computev1.Network
Err error
}{networks, err}
}(ctx, p)
case <-ctx.Done():
log.Info().Msg("User has canceled execution, stopping retrieval of networks...")
cancelled = true
}
if cancelled {
log.Info().Msg("User has canceled execution, waiting for pending retrieval of networks to finish...")
break
}
}
// try to fill semaphore up to it's full size which only succeeds if all routines have finished or execution has been canceled
for i := 0; i < cap(semaphore); i++ {
semaphore <- true
}
if cancelled {
log.Info().Msg("User has canceled execution, checking retrieved networks...")
}
// check for errors and aggregate all networks
close(resultChannel)
for r := range resultChannel {
if r.Err != nil {
err = r.Err
return
}
networks = append(networks, r.Networks...)
}
return
}
func (c *client) getProjectSubnetworks(ctx context.Context, projectID string) (subnetworks []*computev1.Subnetwork, err error) {
log.Info().Msgf("Retrieving subnetworks for project %v...", projectID)
nextPageToken := ""
for {
var resp *computev1.SubnetworkAggregatedList
err = c.substituteErrorsWithPredefinedErrors(foundation.Retry(func() error {
listCall := c.computev1Service.Subnetworks.AggregatedList(projectID)
if nextPageToken != "" {
listCall.PageToken(nextPageToken)
}
resp, err = listCall.Context(ctx).Do()
if err != nil {
return err
}
return nil
}, c.getRetryOptions()...))
if err != nil && !errors.Is(err, ErrAPIForbidden) {
return subnetworks, fmt.Errorf("Can't get project subnetworks for project id %v: %w", projectID, err)
}
if err != nil && errors.Is(err, ErrAPIForbidden) {
return subnetworks, nil
}
for _, v := range resp.Items {
if v.Subnetworks != nil && len(v.Subnetworks) > 0 {
subnetworks = append(subnetworks, v.Subnetworks...)
}
}
if resp.NextPageToken == "" {
break
}
nextPageToken = resp.NextPageToken
}
log.Debug().Msgf("Retrieved %v subnetworks for project %v", len(subnetworks), projectID)
return
}
func (c *client) GetProjectSubnetworks(ctx context.Context, projects []*crmv1.Project) (subnetworks []*computev1.Subnetwork, err error) {
// http://jmoiron.net/blog/limiting-concurrency-in-go/
semaphore := make(chan bool, c.concurrency)
cancelled := false
resultChannel := make(chan struct {
Subnetworks []*computev1.Subnetwork
Err error
}, len(projects))
for _, p := range projects {
select {
// try to fill semaphore up to it's full size otherwise wait for a routine to finish
case semaphore <- true:
go func(ctx context.Context, p *crmv1.Project) {
// lower semaphore once the routine's finished, making room for another one to start
defer func() { <-semaphore }()
subnetworks, err := c.getProjectSubnetworks(ctx, p.ProjectId)
resultChannel <- struct {
Subnetworks []*computev1.Subnetwork
Err error
}{subnetworks, err}
}(ctx, p)
case <-ctx.Done():
log.Info().Msg("User has canceled execution, stopping retrieval of subnetworks...")
cancelled = true
}
if cancelled {
log.Info().Msg("User has canceled execution, waiting for pending retrieval of subnetworks to finish...")
break
}
}
// try to fill semaphore up to it's full size which only succeeds if all routines have finished or execution has been canceled
for i := 0; i < cap(semaphore); i++ {
semaphore <- true
}
if cancelled {
log.Info().Msg("User has canceled execution, checking retrieved subnetworks...")
}
// check for errors and aggregate all subnetworks
close(resultChannel)
for r := range resultChannel {
if r.Err != nil {
err = r.Err
return
}
subnetworks = append(subnetworks, r.Subnetworks...)
}
return
}
func (c *client) getProjectRoutes(ctx context.Context, projectID string) (routes []*computev1.Route, err error) {
log.Info().Msgf("Retrieving routes for project %v...", projectID)
nextPageToken := ""
for {
var resp *computev1.RouteList
err = c.substituteErrorsWithPredefinedErrors(foundation.Retry(func() error {
listCall := c.computev1Service.Routes.List(projectID)
if nextPageToken != "" {
listCall.PageToken(nextPageToken)
}
resp, err = listCall.Context(ctx).Do()
if err != nil {
return err
}
return nil
}, c.getRetryOptions()...))
if err != nil && !errors.Is(err, ErrAPIForbidden) {
return routes, fmt.Errorf("Can't get project routes for project id %v: %w", projectID, err)
}
if err != nil && errors.Is(err, ErrAPIForbidden) {
return routes, nil
}
routes = append(routes, resp.Items...)
if resp.NextPageToken == "" {
break
}
nextPageToken = resp.NextPageToken
}
log.Debug().Msgf("Retrieved %v routes for project %v", len(routes), projectID)
return
}
func (c *client) GetProjectRoutes(ctx context.Context, projects []*crmv1.Project) (routes []*computev1.Route, err error) {
// http://jmoiron.net/blog/limiting-concurrency-in-go/
semaphore := make(chan bool, c.concurrency)
cancelled := false
resultChannel := make(chan struct {
Routes []*computev1.Route
Err error
}, len(projects))
for _, p := range projects {
select {
// try to fill semaphore up to it's full size otherwise wait for a routine to finish
case semaphore <- true:
go func(ctx context.Context, p *crmv1.Project) {
// lower semaphore once the routine's finished, making room for another one to start
defer func() { <-semaphore }()
routes, err := c.getProjectRoutes(ctx, p.ProjectId)
resultChannel <- struct {
Routes []*computev1.Route
Err error
}{routes, err}
}(ctx, p)
case <-ctx.Done():
log.Info().Msg("User has canceled execution, stopping retrieval of routes...")
cancelled = true
}
if cancelled {
log.Info().Msg("User has canceled execution, waiting for pending retrieval of routes to finish...")
break
}
}
// try to fill semaphore up to it's full size which only succeeds if all routines have finished or execution has been canceled
for i := 0; i < cap(semaphore); i++ {
semaphore <- true
}
if cancelled {
log.Info().Msg("User has canceled execution, checking retrieved routes...")
}
// check for errors and aggregate all routes
close(resultChannel)
for r := range resultChannel {
if r.Err != nil {
err = r.Err
return
}
routes = append(routes, r.Routes...)
}
return
}
func (c *client) isRetryableErrorCustomOption() foundation.RetryOption {
return func(c *foundation.RetryConfig) {
c.IsRetryableError = func(err error) bool {
switch e := err.(type) {
case *googleapi.Error:
// Retry on 429 and 5xx, according to
// https://cloud.google.com/storage/docs/exponential-backoff.
return e.Code == http.StatusTooManyRequests || (e.Code >= 500 && e.Code < 600)
case *url.Error:
// Retry socket-level errors ECONNREFUSED and ENETUNREACH (from syscall).
// Unfortunately the error type is unexported, so we resort to string
// matching.
retriable := []string{"connection refused", "connection reset"}
for _, s := range retriable {
if strings.Contains(e.Error(), s) {
return true
}
}
return false
case interface{ Temporary() bool }:
return e.Temporary()
default:
return false
}
}
}
}
func (c *client) substituteErrorsWithPredefinedErrors(err error) error {
if err == nil {
return nil
}
if googleapiErr, ok := err.(*googleapi.Error); ok && googleapiErr.Code == http.StatusForbidden {
return ErrAPIForbidden.wrap(err)
}
if googleapiErr, ok := err.(*googleapi.Error); ok && googleapiErr.Code == http.StatusBadRequest && err.Error() == "googleapi: Error 400: Unknown project id: 0, invalid" {
return ErrUnknownProjectID.wrap(err)
}
if googleapiErr, ok := err.(*googleapi.Error); ok && googleapiErr.Code == http.StatusBadRequest && strings.HasSuffix(err.Error(), "has not enabled BigQuery., invalid") {
return ErrAPINotEnabled.wrap(err)
}
if googleapiErr, ok := err.(*googleapi.Error); ok && googleapiErr.Code == http.StatusBadRequest && strings.HasSuffix(err.Error(), "Invalid request: Invalid request since instance is not running., invalid") {
return ErrEntityNotActive.wrap(err)
}
if googleapiErr, ok := err.(*googleapi.Error); ok && googleapiErr.Code == http.StatusNotFound && err.Error() == "googleapi: Error 404: The requested project was not found., notFound" {
return ErrProjectNotFound.wrap(err)
}
if googleapiErr, ok := err.(*googleapi.Error); ok && googleapiErr.Code == http.StatusNotFound {
return ErrEntityNotFound.wrap(err)
}
if googleapiErr, ok := err.(*googleapi.Error); ok && googleapiErr.Code == http.StatusNoContent {
return ErrEntityNotFound.wrap(err)
}
return err
}
func (c *client) getRetryOptions() []foundation.RetryOption {
return []foundation.RetryOption{
c.isRetryableErrorCustomOption(),
foundation.LastErrorOnly(true),
foundation.Attempts(5),
foundation.DelayMillisecond(1000),
}
}