-
Notifications
You must be signed in to change notification settings - Fork 2
/
core.go
345 lines (321 loc) · 12.8 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
// 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 getgroupsettings
import (
"context"
"encoding/json"
"fmt"
"log"
"strings"
"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/groupssettings/v1"
"google.golang.org/api/option"
"cloud.google.com/go/firestore"
"cloud.google.com/go/functions/metadata"
pubsub "cloud.google.com/go/pubsub/apiv1"
pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1"
)
const waitSecOnQuotaExceeded = 70
// Global structure for global variables to optimize the cloud function performances
type Global struct {
ctx context.Context
environment string
firestoreClient *firestore.Client
groupsSettingsService *groupssettings.Service
instanceName string
microserviceName string
outputTopicName string
projectID string
PubSubID string
pubsubPublisherClient *pubsub.PublisherClient
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,
})
return err
}
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.outputTopicName = instanceDeployment.Core.SolutionSettings.Hosting.Pubsub.TopicNames.GCIGroupSettings
global.projectID = instanceDeployment.Core.SolutionSettings.Hosting.ProjectID
global.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds
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{"https://www.googleapis.com/auth/apps.groups.settings"},
serviceAccountKeyNames,
initID,
global.microserviceName,
global.instanceName,
global.environment); !ok {
return fmt.Errorf("aut.GetClientOptionAndCleanKeys")
}
global.groupsSettingsService, err = groupssettings.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("groupssettings.NewService %v", err),
InitID: initID,
})
return err
}
global.pubsubPublisherClient, err = pubsub.NewPublisherClient(global.ctx)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "init_failed",
Description: fmt.Sprintf("global.pubsubPublisherClient %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
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)
}
var feedMessageGroupSettings cai.FeedMessageGroupSettings
feedMessageGroupSettings.Window.StartTime = metadata.Timestamp
feedMessageGroupSettings.Origin = feedMessageGroup.Origin
feedMessageGroupSettings.Asset.Ancestors = feedMessageGroup.Asset.Ancestors
feedMessageGroupSettings.Asset.AncestryPath = feedMessageGroup.Asset.AncestryPath
feedMessageGroupSettings.Asset.AssetType = "groupssettings.googleapis.com/groupSettings"
feedMessageGroupSettings.Asset.Name = feedMessageGroup.Asset.Name + "/groupSettings"
feedMessageGroupSettings.Deleted = feedMessageGroup.Deleted
if !feedMessageGroup.Deleted {
groupSettings, err := global.groupsSettingsService.Groups.Get(feedMessageGroup.Asset.Resource.Email).Do()
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("GetGroupSettings 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("groupsSettingsService.Groups.Get %v", err),
TriggeringPubsubID: global.PubSubID,
})
return err
}
feedMessageGroupSettings.Asset.Resource = groupSettings
}
feedMessageGroupSettings.StepStack = global.stepStack
feedMessageGroupSettingsJSON, err := json.Marshal(feedMessageGroupSettings)
if err != nil {
log.Println(glo.Entry{
MicroserviceName: global.microserviceName,
InstanceName: global.instanceName,
Environment: global.environment,
Severity: "CRITICAL",
Message: "noretry",
Description: fmt.Sprintf("json.Marshal(feedMessageGroupSettings) %v %v", feedMessageGroupSettings, err),
TriggeringPubsubID: global.PubSubID,
})
return nil
}
var pubSubMessage pubsubpb.PubsubMessage
pubSubMessage.Data = feedMessageGroupSettingsJSON
var pubsubMessages []*pubsubpb.PubsubMessage
pubsubMessages = append(pubsubMessages, &pubSubMessage)
var publishRequest pubsubpb.PublishRequest
publishRequest.Topic = fmt.Sprintf("projects/%s/topics/%s", global.projectID, global.outputTopicName)
publishRequest.Messages = pubsubMessages
pubsubResponse, err := global.pubsubPublisherClient.Publish(global.ctx, &publishRequest)
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("global.pubsubPublisherClient.Publish %v %v", &publishRequest, err),
TriggeringPubsubID: global.PubSubID,
})
return err
}
now = time.Now()
latency := now.Sub(metadata.Timestamp)
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", feedMessageGroup.Asset.Resource.Email),
Description: fmt.Sprintf("groupSettings published to pubsub %s (isdeleted status=%v) %s topic %s ids %v %s", feedMessageGroup.Asset.Resource.Email, feedMessageGroup.Deleted, feedMessageGroup.Asset.Resource.Id, global.outputTopicName, pubsubResponse.MessageIds, string(feedMessageGroupSettingsJSON)),
Now: &now,
TriggeringPubsubID: global.PubSubID,
OriginEventTimestamp: &metadata.Timestamp,
LatencySeconds: latency.Seconds(),
LatencyE2ESeconds: latencyE2E.Seconds(),
StepStack: global.stepStack,
AssetInventoryOrigin: feedMessageGroup.Origin,
})
return nil
}