-
Notifications
You must be signed in to change notification settings - Fork 2
/
core.go
523 lines (499 loc) · 19 KB
/
core.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package listgroupmembers
import (
"context"
"encoding/json"
"fmt"
"log"
"strings"
"sync"
"time"
"github.com/BrunoReboul/ram/utilities/aut"
"github.com/BrunoReboul/ram/utilities/cai"
"github.com/BrunoReboul/ram/utilities/ffo"
"github.com/BrunoReboul/ram/utilities/gfs"
"github.com/BrunoReboul/ram/utilities/glo"
"github.com/BrunoReboul/ram/utilities/gps"
"github.com/BrunoReboul/ram/utilities/solution"
"github.com/google/uuid"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"cloud.google.com/go/firestore"
"cloud.google.com/go/functions/metadata"
"cloud.google.com/go/pubsub"
admin "google.golang.org/api/admin/directory/v1"
)
const waitSecOnQuotaExceeded = 70
// Global variable to deal with GroupsListCall Pages constraint: no possible to pass variable to the function in pages()
// https://pkg.go.dev/google.golang.org/api/admin/directory/v1?tab=doc#GroupsListCall.Pages
var ancestors []string
var ancestryPath string
var ctx context.Context
var environment string
var groupAssetName string
var groupEmail string
var instanceName string
var logEventEveryXPubSubMsg uint64
var microserviceName string
var origin string
var outputTopicName string
var pubSubClient *pubsub.Client
var pubSubErrNumber uint64
var pubSubID string
var pubSubMsgNumber uint64
var stepStack glo.Steps
// Global structure for global variables to optimize the cloud function performances
type Global struct {
collectionID string
ctx context.Context
dirAdminService *admin.Service
environment string
firestoreClient *firestore.Client
instanceName string
logEventEveryXPubSubMsg uint64
maxResultsPerPage int64 // API Max = 200
microserviceName string
outputTopicName string
projectID string
pubSubClient *pubsub.Client
PubSubID string
retryTimeOutSeconds int64
step glo.Step
stepStack glo.Steps
}
// Initialize is to be executed in the init() function of the cloud function to optimize the cold start
func Initialize(ctx context.Context, global *Global) (err error) {
log.SetFlags(0)
global.ctx = ctx
var instanceDeployment InstanceDeployment
var clientOption option.ClientOption
var ok bool
initID := fmt.Sprintf("%v", uuid.New())
err = ffo.ReadUnmarshalYAML(solution.PathToFunctionCode+solution.SettingsFileName, &instanceDeployment)
if err != nil {
log.Println(glo.Entry{
Severity: "CRITICAL",
Message: "init_failed",
Description: fmt.Sprintf("ReadUnmarshalYAML %s %v", solution.SettingsFileName, err),
InitID: initID,
})
}
global.environment = instanceDeployment.Core.EnvironmentName
global.instanceName = instanceDeployment.Core.InstanceName
global.microserviceName = instanceDeployment.Core.ServiceName
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "NOTICE",
Message: "coldstart",
InitID: initID,
})
gciAdminUserToImpersonate := instanceDeployment.Settings.Instance.GCI.SuperAdminEmail
global.collectionID = instanceDeployment.Core.SolutionSettings.Hosting.FireStore.CollectionIDs.Assets
global.logEventEveryXPubSubMsg = instanceDeployment.Settings.Service.LogEventEveryXPubSubMsg
global.outputTopicName = instanceDeployment.Core.SolutionSettings.Hosting.Pubsub.TopicNames.GCIGroupMembers
global.maxResultsPerPage = instanceDeployment.Settings.Service.MaxResultsPerPage
global.projectID = instanceDeployment.Core.SolutionSettings.Hosting.ProjectID
global.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds
projectID := instanceDeployment.Core.SolutionSettings.Hosting.ProjectID
keyJSONFilePath := solution.PathToFunctionCode + instanceDeployment.Settings.Service.KeyJSONFileName
serviceAccountEmail := fmt.Sprintf("%s@%s.iam.gserviceaccount.com",
instanceDeployment.Core.ServiceName,
instanceDeployment.Core.SolutionSettings.Hosting.ProjectID)
global.firestoreClient, err = firestore.NewClient(global.ctx, global.projectID)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "init_failed",
Description: fmt.Sprintf("firestore.NewClient %v", err),
InitID: initID,
})
return err
}
serviceAccountKeyNames, err := gfs.ListKeyNames(ctx, global.firestoreClient, instanceDeployment.Core.ServiceName)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "init_failed",
Description: fmt.Sprintf("gfs.ListKeyNames %v", err),
InitID: initID,
})
return err
}
if clientOption, ok = aut.GetClientOptionAndCleanKeys(ctx,
serviceAccountEmail,
keyJSONFilePath,
instanceDeployment.Core.SolutionSettings.Hosting.ProjectID,
gciAdminUserToImpersonate,
[]string{admin.AdminDirectoryGroupMemberReadonlyScope},
serviceAccountKeyNames,
initID,
global.microserviceName,
global.instanceName,
global.environment); !ok {
return fmt.Errorf("aut.GetClientOptionAndCleanKeys")
}
global.dirAdminService, err = admin.NewService(ctx, clientOption)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "init_failed",
Description: fmt.Sprintf("admin.NewService %v", err),
InitID: initID,
})
return err
}
global.pubSubClient, err = pubsub.NewClient(ctx, projectID)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "init_failed",
Description: fmt.Sprintf("pubsub.NewClient %v", err),
InitID: initID,
})
return err
}
return nil
}
// EntryPoint is the function to be executed for each cloud function occurence
func EntryPoint(ctxEvent context.Context, PubSubMessage gps.PubSubMessage, global *Global) error {
// log.Println(string(PubSubMessage.Data))
metadata, err := metadata.FromContext(ctxEvent)
if err != nil {
// Assume an error on the function invoker and try again.
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "redo_on_transient",
Description: fmt.Sprintf("pubsub_id no available metadata.FromContext: %v", err),
TriggeringPubsubID: global.PubSubID,
})
return err
}
global.stepStack = nil
global.PubSubID = metadata.EventID
parts := strings.Split(metadata.Resource.Name, "/")
global.step = glo.Step{
StepID: fmt.Sprintf("%s/%s", parts[len(parts)-1], global.PubSubID),
StepTimestamp: metadata.Timestamp,
}
now := time.Now()
d := now.Sub(metadata.Timestamp)
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "NOTICE",
Message: "start",
TriggeringPubsubID: global.PubSubID,
TriggeringPubsubAgeSeconds: d.Seconds(),
TriggeringPubsubTimestamp: &metadata.Timestamp,
Now: &now,
})
if d.Seconds() > float64(global.retryTimeOutSeconds) {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "noretry",
Description: "Pubsub message too old",
TriggeringPubsubID: global.PubSubID,
TriggeringPubsubAgeSeconds: d.Seconds(),
TriggeringPubsubTimestamp: &metadata.Timestamp,
Now: &now,
})
return nil
}
// Pass data to global variables to deal with func browseGroup
ctx = global.ctx
logEventEveryXPubSubMsg = global.logEventEveryXPubSubMsg
pubSubClient = global.pubSubClient
outputTopicName = global.outputTopicName
pubSubID = global.PubSubID
microserviceName = global.microserviceName
instanceName = global.instanceName
environment = global.environment
var feedMessageGroup cai.FeedMessageGroup
err = json.Unmarshal(PubSubMessage.Data, &feedMessageGroup)
if err != nil {
log.Printf("pubsub_id %s NORETRY_ERROR json.Unmarshal(pubSubMessage.Data, &feedMessageGroup)", global.PubSubID)
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "noretry",
Description: fmt.Sprintf("json.Unmarshal(pubSubMessage.Data, &feedMessageGroup) %v %v", PubSubMessage.Data, err),
TriggeringPubsubID: global.PubSubID,
})
return nil
}
if feedMessageGroup.StepStack != nil {
global.stepStack = append(feedMessageGroup.StepStack, global.step)
} else {
global.stepStack = append(global.stepStack, global.step)
}
stepStack = global.stepStack
pubSubMsgNumber = 0
pubSubErrNumber = 0
groupAssetName = feedMessageGroup.Asset.Name
groupEmail = feedMessageGroup.Asset.Resource.Email
ancestors = feedMessageGroup.Asset.Ancestors
ancestryPath = feedMessageGroup.Asset.AncestryPath
origin = feedMessageGroup.Origin
if feedMessageGroup.Deleted {
// retreive members from cache
err = browseFeedMessageGroupMembersFromCache(global)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "redo_on_transient",
Description: fmt.Sprintf("browseFeedMessageGroupMembersFromCache(global) %v", err),
TriggeringPubsubID: global.PubSubID,
})
return err
}
} else {
// retreive members from admin SDK
// pages function except just the name of the callback function. Not an invocation of the function
err = global.dirAdminService.Members.List(feedMessageGroup.Asset.Resource.Id).MaxResults(global.maxResultsPerPage).Pages(ctx, browseMembers)
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "quota") {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "WARNING",
Message: fmt.Sprintf("waiting_on_quota_exceeded"),
Description: fmt.Sprintf("ListGroupMembers quota is gone, wait for %d seconds then retry", waitSecOnQuotaExceeded),
TriggeringPubsubID: global.PubSubID,
})
time.Sleep(waitSecOnQuotaExceeded * time.Second)
return err
}
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "redo_on_transient",
Description: fmt.Sprintf("dirAdminService.Members.List %v", err),
TriggeringPubsubID: global.PubSubID,
})
return err
}
}
if pubSubMsgNumber > 0 {
now = time.Now()
latency := now.Sub(global.step.StepTimestamp)
latencyE2E := now.Sub(global.stepStack[0].StepTimestamp)
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "NOTICE",
Message: fmt.Sprintf("finish %s %d members", feedMessageGroup.Asset.Resource.Email, pubSubMsgNumber),
Description: fmt.Sprintf("Group %s %s isDeleted %v Number of members published to pubsub topic %s: %d", feedMessageGroup.Asset.Resource.Email, feedMessageGroup.Asset.Resource.Id, feedMessageGroup.Deleted, outputTopicName, pubSubMsgNumber),
Now: &now,
TriggeringPubsubID: global.PubSubID,
OriginEventTimestamp: &global.stepStack[0].StepTimestamp,
LatencySeconds: latency.Seconds(),
LatencyE2ESeconds: latencyE2E.Seconds(),
StepStack: global.stepStack,
AssetInventoryOrigin: feedMessageGroup.Origin,
})
} else {
now = time.Now()
latency := now.Sub(global.step.StepTimestamp)
latencyE2E := now.Sub(global.stepStack[0].StepTimestamp)
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "NOTICE",
Message: "cancel",
Description: fmt.Sprintf("empty group %s", feedMessageGroup.Asset.Resource.Email),
Now: &now,
TriggeringPubsubID: global.PubSubID,
OriginEventTimestamp: &global.stepStack[0].StepTimestamp,
LatencySeconds: latency.Seconds(),
LatencyE2ESeconds: latencyE2E.Seconds(),
StepStack: global.stepStack,
})
}
return nil
}
func browseFeedMessageGroupMembersFromCache(global *Global) (err error) {
var waitgroup sync.WaitGroup
var documentSnap *firestore.DocumentSnapshot
var feedMessageMember cai.FeedMessageMember
topic := pubSubClient.Topic(outputTopicName)
assets := global.firestoreClient.Collection(global.collectionID)
query := assets.Where(
"asset.assetType", "==", "www.googleapis.com/admin/directory/members").Where(
"asset.resource.groupEmail", "==", strings.ToLower(groupEmail))
iter := query.Documents(global.ctx)
defer iter.Stop()
for {
documentSnap, err = iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "WARNING",
Message: "browseFeedMessageGroupMembersFromCache",
Description: fmt.Sprintf("log and move to next iter.Next() %v", err),
TriggeringPubsubID: global.PubSubID,
})
} else {
if documentSnap.Exists() {
err = documentSnap.DataTo(&feedMessageMember)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "WARNING",
Message: "browseFeedMessageGroupMembersFromCache",
Description: fmt.Sprintf("log and move to next documentSnap.DataTo %v", err),
TriggeringPubsubID: global.PubSubID,
})
} else {
feedMessageMember.Deleted = true
feedMessageMember.Window.StartTime = time.Now()
feedMessageMember.Origin = origin
feedMessageMemberJSON, err := json.Marshal(feedMessageMember)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "WARNING",
Message: "browseFeedMessageGroupMembersFromCache",
Description: fmt.Sprintf("log and move to next %s json.Marshal(feedMessageMember) %v", feedMessageMember.Asset.Name, err),
TriggeringPubsubID: global.PubSubID,
})
} else {
pubSubMessage := &pubsub.Message{
Data: feedMessageMemberJSON,
}
publishResult := topic.Publish(ctx, pubSubMessage)
waitgroup.Add(1)
go gps.GetPublishCallResult(ctx,
publishResult,
&waitgroup,
feedMessageMember.Asset.Name,
&pubSubErrNumber,
&pubSubMsgNumber,
logEventEveryXPubSubMsg,
pubSubID,
microserviceName,
instanceName,
environment)
}
}
} else {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "WARNING",
Message: "browseFeedMessageGroupMembersFromCache",
Description: fmt.Sprintf("log and move to next document does not exists %s", documentSnap.Ref.Path),
TriggeringPubsubID: global.PubSubID,
})
}
}
}
waitgroup.Wait()
return nil
}
// browseMembers is executed for each page returning a set of members
// A non-nil error returned will halt the iteration
// the only accepted parameter is groups: https://pkg.go.dev/google.golang.org/api/admin/directory/v1?tab=doc#GroupsListCall.Pages
// so, it use global variables to this package
func browseMembers(members *admin.Members) error {
var waitgroup sync.WaitGroup
topic := pubSubClient.Topic(outputTopicName)
for _, member := range members.Members {
var feedMessageMember cai.FeedMessageMember
feedMessageMember.Window.StartTime = time.Now()
feedMessageMember.Origin = origin
feedMessageMember.Asset.Ancestors = ancestors
feedMessageMember.Asset.AncestryPath = ancestryPath
feedMessageMember.Asset.AssetType = "www.googleapis.com/admin/directory/members"
feedMessageMember.Asset.Name = groupAssetName + "/members/" + member.Id
feedMessageMember.Asset.Resource.GroupEmail = groupEmail
feedMessageMember.Asset.Resource.MemberEmail = member.Email
feedMessageMember.Asset.Resource.ID = member.Id
feedMessageMember.Asset.Resource.Kind = member.Kind
feedMessageMember.Asset.Resource.Role = member.Role
feedMessageMember.Asset.Resource.Type = member.Type
feedMessageMember.StepStack = stepStack
feedMessageMemberJSON, err := json.Marshal(feedMessageMember)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: microserviceName,
InstanceName: instanceName,
Environment: environment,
Severity: "WARNING",
Message: "browseMembers",
Description: fmt.Sprintf("log and move to next %s json.Marshal(feedMessageMember) %v", member.Email, err),
TriggeringPubsubID: pubSubID,
})
} else {
pubSubMessage := &pubsub.Message{
Data: feedMessageMemberJSON,
}
publishResult := topic.Publish(ctx, pubSubMessage)
waitgroup.Add(1)
go gps.GetPublishCallResult(ctx,
publishResult, &waitgroup,
groupAssetName+"/"+member.Email,
&pubSubErrNumber,
&pubSubMsgNumber,
logEventEveryXPubSubMsg,
pubSubID,
microserviceName,
instanceName,
environment)
}
}
waitgroup.Wait()
return nil
}