forked from nianticlabs/modron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodron.go
599 lines (556 loc) · 20.4 KB
/
modron.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// Binary modron is a Cloud auditing tool.
// Modron compares the existing state with a set of predefined rules
// and provides ways to crowd source the resolution of issues
// to resource owners.
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/nianticlabs/modron/src/acl/fakeacl"
"github.com/nianticlabs/modron/src/acl/gcpacl"
"github.com/nianticlabs/modron/src/collector/gcpcollector"
"github.com/nianticlabs/modron/src/constants"
"github.com/nianticlabs/modron/src/engine"
"github.com/nianticlabs/modron/src/engine/rules"
"github.com/nianticlabs/modron/src/lognotifier"
"github.com/nianticlabs/modron/src/model"
"github.com/nianticlabs/modron/src/nagatha"
"github.com/nianticlabs/modron/src/pb"
"github.com/nianticlabs/modron/src/statemanager/reqdepstatemanager"
"github.com/nianticlabs/modron/src/storage/bigquerystorage"
"github.com/nianticlabs/modron/src/storage/memstorage"
"github.com/golang/glog"
"github.com/google/uuid"
"github.com/improbable-eng/grpc-web/go/grpcweb"
"golang.org/x/exp/maps"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/timestamppb"
)
const (
adminGroupsEnvVar = "ADMIN_GROUPS"
collectorEnvVar = "COLLECTOR"
datasetIdEnvVar = "DATASET_ID"
environmentEnvVar = "ENVIRONMENT"
gcpProjectIdEnvVar = "GCP_PROJECT_ID"
notificationSvcAddrEnvVar = "NOTIFICATION_SERVICE"
observationTableIdEnvVar = "OBSERVATION_TABLE_ID"
operationTableIdEnvVar = "OPERATION_TABLE_ID"
portEnvVar = "PORT"
resourceTableIdEnvVar = "RESOURCE_TABLE_ID"
storageEnvVar = "STORAGE"
fakeCollectorEnvironment = "FAKE"
productionEnvironment = "PRODUCTION"
e2eGrpcTestEnvironment = "E2E_GRPC_TESTING"
memStorageEnvironment = "MEM"
collectAndScanInterval = "COLLECT_AND_SCAN_INTERVAL" //given as a parsable duration string
defaultCollectAndScanInterval = "12h"
)
var (
port int64
adminGroups = []string{}
orgSuffix string
requiredEnvVars = []string{datasetIdEnvVar, gcpProjectIdEnvVar, observationTableIdEnvVar, resourceTableIdEnvVar, notificationSvcAddrEnvVar}
)
// TODO: Implement paginated API
type modronService struct {
storage model.Storage
ruleEngine model.RuleEngine
collector model.Collector
checker model.Checker
stateManager model.StateManager
notificationSvc model.NotificationService
// Required
pb.UnimplementedModronServiceServer
pb.UnimplementedNotificationServiceServer
}
func (modron *modronService) validateResourceGroupNames(ctx context.Context, resourceGroupNames []string) ([]string, error) {
ownedResourceGroups, err := modron.checker.ListResourceGroupNamesOwned(ctx)
if err != nil {
return nil, status.Error(codes.Unauthenticated, "failed authenticating request")
}
if len(resourceGroupNames) == 0 {
for k := range ownedResourceGroups {
resourceGroupNames = append(resourceGroupNames, k)
}
} else {
for _, rsgName := range resourceGroupNames {
if _, ok := ownedResourceGroups[rsgName]; !ok {
return nil, status.Error(codes.Internal, "resource group(s) is inaccessible")
}
}
}
return resourceGroupNames, nil
}
func (modron *modronService) scan(ctx context.Context, resourceGroupNames []string, scanId string) error {
filteredGroups := modron.stateManager.AddScan(scanId, resourceGroupNames)
if len(filteredGroups) != 0 {
glog.Infof("starting scan %s", scanId)
modron.logScanStatus(ctx, scanId, filteredGroups, model.OperationStarted)
obs, err := modron.ruleEngine.CheckRules(ctx, scanId, filteredGroups)
if err != nil {
glog.Errorf("scanId %s: %v", scanId, err)
}
modron.stateManager.EndScan(scanId, filteredGroups)
modron.logScanStatus(ctx, scanId, filteredGroups, model.OperationCompleted)
glog.Infof("scan %s completed", scanId)
if err := modron.storage.FlushOpsLog(ctx); err != nil {
glog.Warningf("flush ops log: %v", err)
}
for _, o := range obs {
notifications, err := modron.notificationsFromObservation(ctx, o)
if err != nil {
return fmt.Errorf("notifications: %v", err)
}
for _, n := range notifications {
_, err := modron.notificationSvc.CreateNotification(ctx, n)
if err != nil {
if s, ok := status.FromError(err); !ok {
glog.Warningf("notification creation: %v", err)
} else {
if s.Code() == codes.AlreadyExists {
continue
} else {
glog.Warningf("notification creation: %s: %s, %v", s.Code(), s.Message(), s.Err())
}
}
}
}
}
}
return nil
}
func (modron *modronService) collect(ctx context.Context, resourceGroupNames []string, collectId string) error {
filteredGroups := modron.stateManager.AddCollect(collectId, resourceGroupNames)
if len(filteredGroups) != 0 {
glog.Infof("collect start id: %v for %v", collectId, filteredGroups)
if err := modron.collector.CollectAndStoreAllResourceGroupResources(ctx, collectId, filteredGroups); len(err) != 0 {
return fmt.Errorf("error collecting for collectId %v, err: %v", collectId, strings.ReplaceAll(fmt.Sprintf("%v", err), "\n", " "))
}
glog.Infof("collect done %v", collectId)
modron.stateManager.EndCollect(collectId, filteredGroups)
}
return nil
}
func (modron *modronService) CollectAndScan(ctx context.Context, in *pb.CollectAndScanRequest) (*pb.CollectAndScanResponse, error) {
modronCtx := context.Background()
resourceGroupNames, err := modron.validateResourceGroupNames(ctx, in.ResourceGroupNames)
if err != nil {
return nil, status.Errorf(codes.FailedPrecondition, "resource group validation: %v", err)
}
collectId, scanId := uuid.NewString(), uuid.NewString()
go func(resourceGroupNames []string) {
if err := modron.collect(modronCtx, resourceGroupNames, collectId); err != nil {
glog.Error(err)
// Do not fail the scan if the collection failed.
}
if err := modron.scan(modronCtx, resourceGroupNames, scanId); err != nil {
glog.Error(err)
}
}(resourceGroupNames)
return &pb.CollectAndScanResponse{
CollectId: collectId,
ScanId: scanId,
}, nil
}
func (modron *modronService) scheduledRunner(ctx context.Context) {
intervalS := os.Getenv(collectAndScanInterval)
interval, err := time.ParseDuration(intervalS)
if err != nil || interval < time.Hour { // enforce a minimum of 1 hour interval
interval, _ = time.ParseDuration(defaultCollectAndScanInterval)
glog.Errorf("CollectAndScan Scheduler: error while getting interval from env: %v . Keeping default value: %s", err, interval)
}
for {
glog.Infof("CollectAndScan Scheduler: starting")
if ctx.Err() != nil {
glog.Errorf("CollectAndScan Scheduler: %v", ctx.Err())
return
}
if r, err := modron.CollectAndScan(ctx, &pb.CollectAndScanRequest{ResourceGroupNames: []string{}}); err != nil {
glog.Errorf("CollectAndScan Scheduler: %v", err)
} else {
glog.Infof("CollectAndScan Scheduler done: collectionID: %s, scanID: %s", r.CollectId, r.ScanId)
}
time.Sleep(interval)
}
}
func (modron *modronService) ListObservations(ctx context.Context, in *pb.ListObservationsRequest) (*pb.ListObservationsResponse, error) {
modronCtx := context.Background()
groups, err := modron.validateResourceGroupNames(ctx, in.ResourceGroupNames)
if err != nil {
return nil, err
}
obsByGroupByRules := map[string]map[string][]*pb.Observation{}
obs, err := modron.storage.ListObservations(modronCtx, model.StorageFilter{
ResourceGroupNames: &groups,
})
if err != nil {
return nil, status.Error(codes.Internal, "failed listing observations")
}
for _, group := range groups {
obsByGroupByRules[group] = map[string][]*pb.Observation{}
for _, rule := range rules.GetRules() {
obsByGroupByRules[group][rule.Info().Name] = []*pb.Observation{}
}
}
for _, ob := range obs {
group := ob.Resource.ResourceGroupName
rule := ob.Name
obsByGroupByRules[group][rule] = append(
obsByGroupByRules[group][rule],
ob,
)
}
res := []*pb.ResourceGroupObservationsPair{}
for name, ruleObs := range obsByGroupByRules {
val := []*pb.RuleObservationPair{}
for rule, obs := range ruleObs {
val = append(val, &pb.RuleObservationPair{
Rule: rule,
Observations: obs,
})
}
res = append(res, &pb.ResourceGroupObservationsPair{
ResourceGroupName: name,
RulesObservations: val,
})
}
return &pb.ListObservationsResponse{
ResourceGroupsObservations: res,
}, nil
}
func (modron *modronService) CreateObservation(ctx context.Context, in *pb.CreateObservationRequest) (*pb.Observation, error) {
if in.Observation == nil {
return nil, status.Error(codes.InvalidArgument, "observation is nil")
}
if in.Observation.Name == "" {
return nil, status.Error(codes.InvalidArgument, "observation does not have a name")
}
if in.Observation.Resource == nil {
return nil, status.Error(codes.InvalidArgument, "resource to link observation with not defined")
}
if in.Observation.Remediation == nil || in.Observation.Remediation.Recommendation == "" {
return nil, status.Error(codes.InvalidArgument, "cannot create an observation without recommendation")
}
in.Observation.Timestamp = timestamppb.Now()
res, err := modron.storage.ListResources(ctx, model.StorageFilter{ResourceNames: &[]string{in.Observation.Resource.Name}})
if err != nil {
return nil, status.Errorf(codes.NotFound, "resource to link observation to not found: %v", err)
}
if len(res) != 1 {
return nil, status.Errorf(codes.FailedPrecondition, "found %d resources matching %+v", len(res), in.Observation.Resource)
}
in.Observation.Resource = res[0]
if obs, err := modron.storage.BatchCreateObservations(ctx, []*pb.Observation{in.Observation}); err != nil {
return nil, status.Error(codes.Internal, err.Error())
} else {
if len(obs) != 1 {
return nil, status.Errorf(codes.Internal, "creation returned %d items", len(obs))
} else {
return obs[0], nil
}
}
}
func (modron *modronService) GetStatusCollectAndScan(ctx context.Context, in *pb.GetStatusCollectAndScanRequest) (*pb.GetStatusCollectAndScanResponse, error) {
collectStatus := modron.stateManager.GetCollectState(in.CollectId)
scanStatus := modron.stateManager.GetScanState(in.ScanId)
return &pb.GetStatusCollectAndScanResponse{
CollectStatus: collectStatus,
ScanStatus: scanStatus,
}, nil
}
func (modron *modronService) GetNotificationException(ctx context.Context, req *pb.GetNotificationExceptionRequest) (*pb.NotificationException, error) {
ex, err := modron.validateUserAndGetException(ctx, req.Uuid)
if err != nil {
return nil, err
}
return ex.ToProto(), err
}
func (modron *modronService) CreateNotificationException(ctx context.Context, req *pb.CreateNotificationExceptionRequest) (*pb.NotificationException, error) {
if userEmail, err := modron.checker.GetValidatedUser(ctx); err != nil {
return nil, status.Error(codes.Unauthenticated, "failed authenticating request")
} else {
req.Exception.UserEmail = userEmail
}
ex, err := modron.notificationSvc.CreateException(ctx, model.ExceptionFromProto(req.Exception))
return ex.ToProto(), err
}
func (modron *modronService) UpdateNotificationException(ctx context.Context, req *pb.UpdateNotificationExceptionRequest) (*pb.NotificationException, error) {
if ex, err := modron.validateUserAndGetException(ctx, req.Exception.Uuid); err != nil {
return nil, err
} else {
req.Exception.UserEmail = ex.UserEmail
}
ex, err := modron.notificationSvc.UpdateException(ctx, model.ExceptionFromProto(req.Exception))
return ex.ToProto(), err
}
func (modron *modronService) DeleteNotificationException(ctx context.Context, req *pb.DeleteNotificationExceptionRequest) (*emptypb.Empty, error) {
if _, err := modron.validateUserAndGetException(ctx, req.Uuid); err != nil {
return nil, err
}
return &emptypb.Empty{}, modron.notificationSvc.DeleteException(ctx, req.Uuid)
}
func (modron *modronService) ListNotificationExceptions(ctx context.Context, req *pb.ListNotificationExceptionsRequest) (*pb.ListNotificationExceptionsResponse, error) {
if userEmail, err := modron.checker.GetValidatedUser(ctx); err != nil {
return nil, status.Error(codes.Unauthenticated, "failed authenticating request")
} else {
req.UserEmail = userEmail
}
ex, err := modron.notificationSvc.ListExceptions(ctx, req.UserEmail, req.PageSize, req.PageToken)
exList := []*pb.NotificationException{}
for _, e := range ex {
exList = append(exList, e.ToProto())
}
return &pb.ListNotificationExceptionsResponse{Exceptions: exList}, err
}
func (modron *modronService) logScanStatus(ctx context.Context, scanId string, resourceGroups []string, status model.OperationStatus) {
ops := []model.Operation{}
for _, resourceGroup := range resourceGroups {
ops = append(ops, model.Operation{ID: scanId, ResourceGroup: resourceGroup, OpsType: "scan", StatusTime: time.Now(), Status: status})
}
if err := modron.storage.AddOperationLog(ctx, ops); err != nil {
glog.Warningf("log operation: %v", err)
}
}
// TODO: Allow security admins to bypass the checks
func (modron *modronService) validateUserAndGetException(ctx context.Context, notificationUuid string) (model.Exception, error) {
userEmail, err := modron.checker.GetValidatedUser(ctx)
if err != nil {
return model.Exception{}, status.Error(codes.Unauthenticated, "failed authenticating request")
}
if ex, err := modron.notificationSvc.GetException(ctx, notificationUuid); err != nil {
return model.Exception{}, err
} else if ex.UserEmail != userEmail {
return model.Exception{}, status.Error(codes.Unauthenticated, "failed authenticating request")
} else {
return ex, nil
}
}
func (modron *modronService) notificationsFromObservation(ctx context.Context, ob *pb.Observation) ([]model.Notification, error) {
rg, err := modron.storage.ListResources(ctx, model.StorageFilter{ResourceNames: &[]string{ob.Resource.ResourceGroupName}})
if err != nil {
return nil, err
}
if len(rg) < 1 {
return nil, fmt.Errorf("no resource found %+v", ob.Resource.Uid)
}
if len(rg) > 1 {
glog.Warningf("multiple resources found for %+v, using the first one", ob.Resource.Uid)
}
if rg[0].IamPolicy == nil {
glog.Warningf("no iam policy found for %s", rg[0].Name)
}
// We can have the same contacts in owners and labels, de-duplicate.
uniqueContacts := make(map[string]struct{}, 0)
for _, b := range rg[0].IamPolicy.Permissions {
for r := range constants.AdminRoles {
if strings.EqualFold(b.Role, r) {
for _, m := range b.Principals {
if strings.HasSuffix(m, orgSuffix) {
uniqueContacts[strings.TrimPrefix(m, "user:")] = struct{}{}
}
}
}
}
}
contacts := maps.Keys(uniqueContacts)
if len(contacts) < 1 {
return nil, fmt.Errorf("no contacts found for observation %q, resource group: %q", ob.Uid, ob.Resource.ResourceGroupName)
}
notifications := make([]model.Notification, 0)
for _, c := range contacts {
notifications = append(notifications,
model.Notification{
SourceSystem: "modron",
Name: ob.Name,
Recipient: c,
Content: ob.Remediation.Recommendation,
Interval: time.Duration(7 * time.Hour * 24),
})
}
return notifications, nil
}
func newServer(ctx context.Context) (*modronService, error) {
var storage model.Storage
var err error
if useMemStorage() {
storage = memstorage.New()
} else {
storage, err = bigquerystorage.New(
ctx,
os.Getenv(gcpProjectIdEnvVar),
os.Getenv(datasetIdEnvVar),
os.Getenv(resourceTableIdEnvVar),
os.Getenv(observationTableIdEnvVar),
os.Getenv(operationTableIdEnvVar),
)
if err != nil {
return nil, fmt.Errorf("bigquerystorage creation error: %v", err)
}
}
ruleEngine := engine.New(storage, rules.GetRules())
var collector model.Collector
if useFakeCollector() {
collector = gcpcollector.NewFake(ctx, storage)
} else {
var err error
if collector, err = gcpcollector.New(ctx, storage); err != nil {
return nil, fmt.Errorf("NewGCPCollector error: %v", err)
}
}
var checker model.Checker
if useFakeCollector() {
checker = fakeacl.New()
} else {
var err error
if checker, err = gcpacl.New(ctx, collector, gcpacl.Config{AdminGroups: adminGroups, CacheTimeout: 20 * time.Second}); err != nil {
return nil, fmt.Errorf("NewGcpChecker error: %v", err)
}
}
stateManager, err := reqdepstatemanager.New()
if err != nil {
return nil, fmt.Errorf("creating reqdepstatemanager error: %v", err)
}
var notificationSvc model.NotificationService
if isProduction() {
notificationSvc, err = nagatha.New(ctx, os.Getenv(notificationSvcAddrEnvVar))
if err != nil {
return nil, fmt.Errorf("nagatha service: %v", err)
}
} else {
notificationSvc = lognotifier.New()
}
return &modronService{
storage: storage,
ruleEngine: ruleEngine,
collector: collector,
checker: checker,
stateManager: stateManager,
notificationSvc: notificationSvc,
}, nil
}
func isProduction() bool {
return os.Getenv(environmentEnvVar) == productionEnvironment
}
func isE2eGrpcTest() bool {
return os.Getenv(environmentEnvVar) == e2eGrpcTestEnvironment
}
func useFakeCollector() bool {
return os.Getenv(collectorEnvVar) == fakeCollectorEnvironment
}
func useMemStorage() bool {
return os.Getenv(storageEnvVar) == memStorageEnvironment
}
func validateEnvironment() (errs []error) {
if isProduction() {
for _, v := range requiredEnvVars {
if os.Getenv(v) == "" {
errs = append(errs, fmt.Errorf("%s can't be empty", v))
}
}
if useFakeCollector() {
errs = append(errs, fmt.Errorf("cannot use fake collector in production"))
}
if useMemStorage() {
errs = append(errs, fmt.Errorf("cannot use memstorage in production"))
}
adminGroups = strings.Split(os.Getenv(adminGroupsEnvVar), ",")
if len(adminGroups) < 1 {
errs = append(errs, fmt.Errorf("%q has no entries, add at least one admin group", adminGroupsEnvVar))
}
}
if orgSuffixEnv := os.Getenv(constants.OrgSuffixEnvVar); orgSuffixEnv == "" {
errs = append(errs, fmt.Errorf("environment variable %q is not set", constants.OrgSuffixEnvVar))
} else {
orgSuffix = orgSuffixEnv
}
portStr := os.Getenv(portEnvVar)
var err error
port, err = strconv.ParseInt(portStr, 10, 32)
if err != nil {
errs = append(errs, fmt.Errorf("%s contains an invalid port number %s: %v", portEnvVar, portStr, err))
}
if len(errs) > 0 {
fmt.Println("invalid environment:")
for _, e := range errs {
fmt.Println(e)
}
os.Exit(2)
}
return
}
func withCors() []grpcweb.Option {
return []grpcweb.Option{
grpcweb.WithOriginFunc(func(origin string) bool {
return true
}),
grpcweb.WithAllowedRequestHeaders([]string{"*"}),
}
}
func main() {
flag.Parse()
validateEnvironment()
ctx, cancel := context.WithCancel(context.Background())
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
glog.Errorf("failed to listen: %v", err)
os.Exit(1)
}
// Handle SIGINT (for Ctrl+C) and SIGTERM (for Cloud Run) signals
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-c
glog.Infof("received signal: %+v", sig)
cancel()
}()
go func() {
glog.Infof("server starting on port %d", port)
// Use insecure credentials since communication is encrypted and authenticated via
// HTTPS end-to-end (i.e., from client to Cloud Run ingress).
var opts []grpc.ServerOption = []grpc.ServerOption{
grpc.Creds(insecure.NewCredentials()),
}
grpcServer := grpc.NewServer(opts...) // nosemgrep: go.grpc.security.grpc-server-insecure-connection.grpc-server-insecure-connection
srv, err := newServer(ctx)
if err != nil {
glog.Errorf("server creation: %v", err)
os.Exit(3)
}
pb.RegisterModronServiceServer(grpcServer, srv)
pb.RegisterNotificationServiceServer(grpcServer, srv)
if isE2eGrpcTest() {
// TODO: Unfortunately we need this as the GRPC-Web is different from the GRPC protocol.
// This is used only in the integration test that doesn't have a GRPC-Web client.
// We should look into https://github.com/improbable-eng/grpc-web and check how we can implement a golang GRPC-web client.
if err := grpcServer.Serve(lis); err != nil {
glog.Errorf("error while listening: %v", err)
os.Exit(2)
}
} else {
grpcWebServer := grpcweb.WrapServer(grpcServer, withCors()...)
if err := http.Serve(lis, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
grpcWebServer.ServeHTTP(w, req)
})); err != nil {
glog.Errorf("error while listening: %v", err)
os.Exit(2)
}
}
// Start recurring scans
srv.scheduledRunner(ctx)
}()
<-ctx.Done()
glog.Infof("server stopped")
}