-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathreprocessor.go
More file actions
927 lines (812 loc) · 31.9 KB
/
reprocessor.go
File metadata and controls
927 lines (812 loc) · 31.9 KB
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
package reprocessor
import (
"context"
"time"
"github.com/pkg/errors"
administrationEvents "github.com/stackrox/rox/central/administration/events"
deploymentDatastore "github.com/stackrox/rox/central/deployment/datastore"
"github.com/stackrox/rox/central/enrichment"
imageDatastore "github.com/stackrox/rox/central/image/datastore"
imageV2Datastore "github.com/stackrox/rox/central/imagev2/datastore"
"github.com/stackrox/rox/central/metrics"
nodeDatastore "github.com/stackrox/rox/central/node/datastore"
"github.com/stackrox/rox/central/risk/manager"
"github.com/stackrox/rox/central/sensor/service/connection"
watchedImageDataStore "github.com/stackrox/rox/central/watchedimage/datastore"
v1 "github.com/stackrox/rox/generated/api/v1"
"github.com/stackrox/rox/generated/internalapi/central"
"github.com/stackrox/rox/generated/storage"
"github.com/stackrox/rox/pkg/centralsensor"
"github.com/stackrox/rox/pkg/concurrency"
"github.com/stackrox/rox/pkg/env"
"github.com/stackrox/rox/pkg/features"
imageEnricher "github.com/stackrox/rox/pkg/images/enricher"
"github.com/stackrox/rox/pkg/images/utils"
"github.com/stackrox/rox/pkg/logging"
"github.com/stackrox/rox/pkg/maputil"
nodeEnricher "github.com/stackrox/rox/pkg/nodes/enricher"
"github.com/stackrox/rox/pkg/sac"
"github.com/stackrox/rox/pkg/sac/resources"
"github.com/stackrox/rox/pkg/search"
"github.com/stackrox/rox/pkg/search/options/deployments"
imageMapping "github.com/stackrox/rox/pkg/search/options/images"
"github.com/stackrox/rox/pkg/set"
"github.com/stackrox/rox/pkg/sync"
"github.com/stackrox/rox/pkg/uuid"
"go.uber.org/atomic"
"golang.org/x/sync/semaphore"
)
const (
imageReprocessorSemaphoreSize = int64(5)
)
var (
log = logging.LoggerForModule(administrationEvents.EnableAdministrationEvents())
riskDedupeNamespace = uuid.NewV4()
once sync.Once
loop Loop
allAccessCtx = sac.WithAllAccess(context.Background())
emptyCtx = context.Background()
delegateScanCtx = sac.WithGlobalAccessScopeChecker(
context.Background(),
sac.AllowFixedScopes(
sac.AccessModeScopeKeys(storage.Access_READ_ACCESS),
sac.ResourceScopeKeys(resources.Image),
),
)
imageClusterIDFieldPath = imageMapping.ImageDeploymentOptions.MustGet(search.ClusterID.String()).GetFieldPath()
allImagesQuery = search.NewQueryBuilder().AddStringsHighlighted(search.ClusterID, search.WildcardString).
ProtoQuery()
// allV2ImagesQuery selects all deployment containers with a non-null and non-empty ImageID (V2 image ID).
allV2ImagesQuery = search.NewQueryBuilder().AddRegexes(search.ImageID, ".+").ProtoQuery()
imagesWithSignaturesQuery = search.NewQueryBuilder().
// We take all images into account irrespective whether they have a cluster associated with them
// or not. The reason is that we want to reprocess those in case e.g. a previous signature
// verification failure lead to an enforcement, which would make the image not have any cluster
// associated with it.
AddTimeRangeField(search.ImageSignatureFetchedTime,
// Could potentially miss images that _just_ fetched signatures so creating a small jitter
// to include those as well.
time.Unix(0, 0), time.Now().Add(10*time.Second)).
ProtoQuery()
)
// Singleton returns the singleton reprocessor loop
func Singleton() Loop {
once.Do(func() {
loop = NewLoop(connection.ManagerSingleton(), enrichment.ImageEnricherSingleton(), enrichment.ImageEnricherV2Singleton(),
enrichment.NodeEnricherSingleton(), deploymentDatastore.Singleton(), imageDatastore.Singleton(),
imageV2Datastore.Singleton(), nodeDatastore.Singleton(), manager.Singleton(), watchedImageDataStore.Singleton())
})
return loop
}
// Loop combines periodically (every 4 hours by default) runs enrichment and detection.
//
//go:generate mockgen-wrapper
type Loop interface {
Start()
ShortCircuit()
Stop()
ReprocessRiskForDeployments(deploymentIDs ...string)
ReprocessSignatureVerifications(firstIntegration bool)
}
// NewLoop returns a new instance of a Loop.
func NewLoop(connManager connection.Manager, imageEnricher imageEnricher.ImageEnricher, imageEnricherV2 imageEnricher.ImageEnricherV2,
nodeEnricher nodeEnricher.NodeEnricher, deployments deploymentDatastore.DataStore, images imageDatastore.DataStore,
imagesV2 imageV2Datastore.DataStore, nodes nodeDatastore.DataStore, risk manager.Manager,
watchedImages watchedImageDataStore.DataStore) Loop {
return newLoopWithDuration(
connManager, imageEnricher, imageEnricherV2, nodeEnricher, deployments, images, imagesV2, nodes, risk,
watchedImages, env.ReprocessInterval.DurationSetting(), env.RiskReprocessInterval.DurationSetting())
}
// newLoopWithDuration returns a loop that ticks at the given duration.
// It is NOT exported, since we don't want clients to control the duration; it only exists as a separate function
// to enable testing.
func newLoopWithDuration(connManager connection.Manager, imageEnricher imageEnricher.ImageEnricher, imageEnricherV2 imageEnricher.ImageEnricherV2,
nodeEnricher nodeEnricher.NodeEnricher, deployments deploymentDatastore.DataStore, images imageDatastore.DataStore,
imagesV2 imageV2Datastore.DataStore, nodes nodeDatastore.DataStore, risk manager.Manager,
watchedImages watchedImageDataStore.DataStore, enrichAndDetectDuration, deploymentRiskDuration time.Duration) *loopImpl {
return &loopImpl{
enrichAndDetectTickerDuration: enrichAndDetectDuration,
deploymentRiskTickerDuration: deploymentRiskDuration,
imageEnricher: imageEnricher,
imageEnricherV2: imageEnricherV2,
images: images,
imagesV2: imagesV2,
risk: risk,
watchedImages: watchedImages,
deployments: deployments,
deploymentRiskSet: set.NewStringSet(),
nodeEnricher: nodeEnricher,
nodes: nodes,
shortCircuitSig: concurrency.NewSignal(),
stopSig: concurrency.NewSignal(),
enrichmentStopped: concurrency.NewSignal(),
riskStopped: concurrency.NewSignal(),
signatureVerificationSig: concurrency.NewSignal(),
connManager: connManager,
injectMessageTimeoutDur: env.ReprocessInjectMessageTimeout.DurationSetting(),
}
}
// imageReprocessingFunc represents the function used for image reprocessing. This enables us to specifically exclude
// some parts of the enrichment, i.e. when only wanting to re-fetch signature verification results.
// TODO(ROX-30117): Remove this function after ImageV2 model is fully rolled out
type imageReprocessingFunc func(ctx context.Context, enrichCtx imageEnricher.EnrichmentContext,
image *storage.Image) (imageEnricher.EnrichmentResult, error)
// imageReprocessingFuncV2 represents the function used for imageV2 reprocessing. This enables us to specifically exclude
// some parts of the enrichment, i.e. when only wanting to re-fetch signature verification results.
type imageReprocessingFuncV2 func(ctx context.Context, enrichCtx imageEnricher.EnrichmentContext,
image *storage.ImageV2) (imageEnricher.EnrichmentResult, error)
type loopImpl struct {
enrichAndDetectTickerDuration time.Duration
enrichAndDetectTicker *time.Ticker
images imageDatastore.DataStore
imagesV2 imageV2Datastore.DataStore
risk manager.Manager
imageEnricher imageEnricher.ImageEnricher
imageEnricherV2 imageEnricher.ImageEnricherV2
watchedImages watchedImageDataStore.DataStore
deployments deploymentDatastore.DataStore
deploymentRiskSet set.StringSet
deploymentRiskLock sync.Mutex
deploymentRiskTicker *time.Ticker
deploymentRiskTickerDuration time.Duration
nodes nodeDatastore.DataStore
nodeEnricher nodeEnricher.NodeEnricher
shortCircuitSig concurrency.Signal
stopSig concurrency.Signal
riskStopped concurrency.Signal
enrichmentStopped concurrency.Signal
signatureVerificationSig concurrency.Signal
firstSignatureIntegration concurrency.Flag
reprocessingInProgress concurrency.Flag
connManager connection.Manager
injectMessageTimeoutDur time.Duration
}
func (l *loopImpl) ReprocessRiskForDeployments(deploymentIDs ...string) {
l.deploymentRiskLock.Lock()
defer l.deploymentRiskLock.Unlock()
l.deploymentRiskSet.AddAll(deploymentIDs...)
}
// Start starts the enrich and detect loop.
func (l *loopImpl) Start() {
l.enrichAndDetectTicker = time.NewTicker(l.enrichAndDetectTickerDuration)
l.deploymentRiskTicker = time.NewTicker(l.deploymentRiskTickerDuration)
go l.riskLoop()
go l.enrichLoop()
}
// Stop stops the enrich and detect loop.
func (l *loopImpl) Stop() {
l.stopSig.Signal()
l.riskStopped.Wait()
l.enrichmentStopped.Wait()
}
func (l *loopImpl) ShortCircuit() {
// Signal that we should run a short circuited reprocessing. If the signal is already triggered, then the current
// signal is effectively deduped
l.shortCircuitSig.Signal()
}
func (l *loopImpl) ReprocessSignatureVerifications(firstIntegration bool) {
// Signal that we should reprocess signature verifications for all images. This will only trigger a reprocess with
// refetch of signature verification results.
// If the signal is already triggered, then the current signal is effectively deduped.
l.firstSignatureIntegration.Set(firstIntegration)
l.signatureVerificationSig.Signal()
}
func (l *loopImpl) sendDeployments(deploymentIDs []string) {
query := search.NewQueryBuilder().AddStringsHighlighted(search.ClusterID, search.WildcardString)
if len(deploymentIDs) > 0 {
query = query.AddDocIDs(deploymentIDs...)
}
results, err := l.deployments.SearchDeployments(allAccessCtx, query.ProtoQuery())
if err != nil {
log.Errorw("Error getting results for deployment reprocessing", logging.Err(err))
return
}
path, ok := deployments.OptionsMap.Get(search.ClusterID.String())
if !ok {
panic("No Cluster ID option for deployments")
}
for _, r := range results {
clusterIDs := r.GetFieldToMatches()[path.GetFieldPath()].GetValues()
if len(clusterIDs) == 0 {
log.Error("no cluster id found in fields")
continue
}
conn := l.connManager.GetConnection(clusterIDs[0])
if conn == nil {
continue
}
dedupeKey := uuid.NewV5(riskDedupeNamespace, r.GetId()).String()
msg := ¢ral.MsgFromSensor{
HashKey: r.GetId(),
DedupeKey: dedupeKey,
Msg: ¢ral.MsgFromSensor_Event{
Event: ¢ral.SensorEvent{
Resource: ¢ral.SensorEvent_ReprocessDeployment{
ReprocessDeployment: ¢ral.ReprocessDeploymentRisk{
DeploymentId: r.GetId(),
},
},
},
},
}
conn.InjectMessageIntoQueue(msg)
}
}
func (l *loopImpl) runReprocessingForObjects(entityType string, getIDsFunc func() ([]string, error), individualReprocessFunc func(id string) bool) {
if l.stopSig.IsDone() {
return
}
ids, err := getIDsFunc()
if err != nil {
log.Errorw("Failed to retrieve active IDs for entity", logging.String("entity", entityType),
logging.Err(err))
return
}
log.Infof("Found %d %ss to scan", len(ids), entityType)
sema := semaphore.NewWeighted(5)
wg := concurrency.NewWaitGroup(0)
nReprocessed := atomic.NewInt32(0)
for _, id := range ids {
wg.Add(1)
if err := sema.Acquire(concurrency.AsContext(&l.stopSig), 1); err != nil {
log.Errorw("Reprocessing stopped", logging.Err(err))
return
}
go func(id string) {
defer sema.Release(1)
defer wg.Add(-1)
if individualReprocessFunc(id) {
nReprocessed.Inc()
}
}(id)
}
select {
case <-wg.Done():
case <-l.stopSig.Done():
log.Info("Stopping reprocessing due to stop signal")
return
}
log.Infof("Successfully reprocessed %d/%d %ss", nReprocessed.Load(), len(ids), entityType)
}
// TODO(ROX-30117): Remove this function after ImageV2 model is fully rolled out
func (l *loopImpl) reprocessImage(id string, fetchOpt imageEnricher.FetchOption,
reprocessingFunc imageReprocessingFunc) (*storage.Image, bool) {
image, exists, err := l.images.GetImage(allAccessCtx, id)
if err != nil {
log.Errorw("Error fetching image from database", logging.ImageID(id), logging.Err(err))
return nil, false
}
if !exists || image.GetNotPullable() || image.GetIsClusterLocal() {
return nil, false
}
result, err := reprocessingFunc(emptyCtx, imageEnricher.EnrichmentContext{
FetchOpt: fetchOpt,
}, image)
if err != nil {
log.Errorw("Error enriching image", logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()), logging.Err(err))
return nil, false
}
if result.ImageUpdated {
if err := l.risk.CalculateRiskAndUpsertImage(image); err != nil {
log.Errorw("Error upserting image into datastore",
logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()), logging.Err(err))
return nil, false
}
// We need to fetch the image again to make sure all fields are populated.
// GetImage will internally call a Merge function which will use the CVEEdges table to enrich fields like
// FirstImageOccurrence and FirstSystemOccurrence.
newImage, exists, err := l.images.GetImage(allAccessCtx, id)
if err != nil {
log.Errorw("Error fetching image from database", logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()), logging.Err(err))
return nil, false
}
if !exists {
log.Errorw("The image was not found after enrichement", logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()))
return nil, false
}
return newImage, true
}
return image, true
}
// TODO(ROX-30117): Remove this function after ImageV2 model is fully rolled out
func (l *loopImpl) reprocessImagesAndResyncDeployments(fetchOpt imageEnricher.FetchOption,
imgReprocessingFunc imageReprocessingFunc, imageQuery *v1.Query) {
if l.stopSig.IsDone() {
return
}
results, err := l.images.Search(allAccessCtx, imageQuery)
if err != nil {
log.Errorw("Error searching for active image IDs", logging.Err(err))
return
}
log.Infof("Found %d images to scan", len(results))
if len(results) == 0 {
return
}
sema := semaphore.NewWeighted(imageReprocessorSemaphoreSize)
wg := concurrency.NewWaitGroup(0)
nReprocessed := atomic.NewInt32(0)
skipClusterIDs := maputil.NewSyncMap[string, struct{}]()
for _, result := range results {
wg.Add(1)
if err := sema.Acquire(concurrency.AsContext(&l.stopSig), 1); err != nil {
log.Errorw("Reprocessing stopped", logging.Err(err))
return
}
// Duplicates can exist if the image is within multiple deployments
clusterIDSet := set.NewStringSet(result.Matches[imageClusterIDFieldPath]...)
go func(id string, clusterIDs set.StringSet) {
defer sema.Release(1)
defer wg.Add(-1)
image, successfullyProcessed := l.reprocessImage(id, fetchOpt, imgReprocessingFunc)
if !successfullyProcessed {
return
}
nReprocessed.Inc()
utils.FilterSuppressedCVEsNoClone(image)
utils.StripCVEDescriptionsNoClone(image)
// Send the updated image to relevant clusters.
for clusterID := range clusterIDs {
conn := l.connManager.GetConnection(clusterID)
if conn == nil {
continue
}
msg := ¢ral.MsgToSensor{
Msg: ¢ral.MsgToSensor_UpdatedImage{
UpdatedImage: image,
},
}
// If were prior errors, do not attempt to send a message to this cluster.
if skipClusterIDs.Contains(clusterID) {
metrics.IncrementMsgToSensorNotSentCounter(clusterID, msg, metrics.NotSentSkip)
log.Debugw("Not sending updated image to cluster due to prior errors",
logging.ImageID(image.GetId()),
logging.ImageName(image.GetName().GetFullName()),
logging.String("dst_cluster", clusterID),
)
continue
}
err := l.injectMessage(concurrency.AsContext(&l.stopSig), conn, msg)
if err != nil {
skipClusterIDs.Store(clusterID, struct{}{})
log.Errorw("Error sending updated image to cluster, skipping cluster until next reprocessing cycle",
logging.ImageName(image.GetName().GetFullName()),
logging.ImageID(image.GetId()), logging.Err(err),
// Not using logging.ClusterID() to avoid "duplicate resource ID field found" panic
logging.String("dst_cluster", clusterID),
)
}
}
}(result.ID, clusterIDSet)
}
select {
case <-wg.Done():
case <-l.stopSig.Done():
log.Info("Stopping reprocessing due to stop signal")
return
}
log.Infof("Successfully reprocessed %d/%d images", nReprocessed.Load(), len(results))
log.Info("Resyncing deployments now that images have been reprocessed...")
l.sendReprocessDeployments(skipClusterIDs)
}
func (l *loopImpl) reprocessImageV2(id string, digest string, fetchOpt imageEnricher.FetchOption,
reprocessingFunc imageReprocessingFuncV2) (*storage.ImageV2, bool) {
image, exists, err := l.imagesV2.GetImage(allAccessCtx, id)
if err != nil {
log.Errorw("Error fetching image from database", logging.ImageID(id), logging.Err(err))
return nil, false
}
migrateToV2 := false
if !exists {
// The image was not found in ImageV2 store, but it might be in the legacy ImageV1 store
var legacyImage *storage.Image
legacyImage, exists, err = l.images.GetImageMetadata(allAccessCtx, digest)
if err != nil {
log.Errorw("Error fetching legacy image from database", logging.ImageID(id), logging.Err(err))
return nil, false
}
if !exists {
return nil, false
}
image = utils.ConvertToV2(legacyImage)
migrateToV2 = true
}
if image == nil {
return nil, false
}
if image.GetNotPullable() || image.GetIsClusterLocal() {
// Skip reprocessing. Sensor will handle cluster-local images. But we still need to migrate the image to V2.
if migrateToV2 {
if err := l.imagesV2.UpsertImage(allAccessCtx, image); err != nil {
log.Errorw("Error migrating image to imageV2 store", logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()), logging.Err(err))
return nil, false
}
}
return nil, false
}
result, err := reprocessingFunc(emptyCtx, imageEnricher.EnrichmentContext{
FetchOpt: fetchOpt,
}, image)
if err != nil {
log.Errorw("Error enriching image", logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()), logging.Err(err))
return nil, false
}
if result.ImageUpdated {
if err := l.risk.CalculateRiskAndUpsertImageV2(image); err != nil {
log.Errorw("Error upserting image into datastore",
logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()), logging.Err(err))
return nil, false
}
// We need to fetch the image again to make sure all fields are populated.
// GetImage will internally call a Merge function which will use the CVEEdges table to enrich fields like
// FirstImageOccurrence and FirstSystemOccurrence.
newImage, exists, err := l.imagesV2.GetImage(allAccessCtx, id)
if err != nil {
log.Errorw("Error fetching image from database", logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()), logging.Err(err))
return nil, false
}
if !exists {
log.Errorw("The image was not found after enrichement", logging.ImageName(image.GetName().GetFullName()), logging.ImageID(image.GetId()))
return nil, false
}
return newImage, true
}
return image, true
}
func (l *loopImpl) reprocessImagesV2AndResyncDeployments(fetchOpt imageEnricher.FetchOption,
imgReprocessingFunc imageReprocessingFuncV2, imageQuery *v1.Query) {
if l.stopSig.IsDone() {
return
}
results, err := l.deployments.GetContainerImageViews(allAccessCtx, imageQuery)
if err != nil {
log.Errorw("Error searching for active image IDs", logging.Err(err))
return
}
log.Infof("Found %d images to scan", len(results))
if len(results) == 0 {
return
}
sema := semaphore.NewWeighted(imageReprocessorSemaphoreSize)
wg := concurrency.NewWaitGroup(0)
nReprocessed := atomic.NewInt32(0)
skipClusterIDs := maputil.NewSyncMap[string, struct{}]()
for _, result := range results {
wg.Add(1)
if err := sema.Acquire(concurrency.AsContext(&l.stopSig), 1); err != nil {
log.Errorw("Reprocessing stopped", logging.Err(err))
return
}
clusterIDSet := set.NewStringSet(result.GetClusterIDs()...)
go func(id string, digest string, clusterIDs set.StringSet) {
defer sema.Release(1)
defer wg.Add(-1)
image, successfullyProcessed := l.reprocessImageV2(id, digest, fetchOpt, imgReprocessingFunc)
if !successfullyProcessed {
return
}
nReprocessed.Inc()
utils.FilterSuppressedCVEsNoCloneV2(image)
utils.StripCVEDescriptionsNoCloneV2(image)
// Gather all known image names with the same SHA to ensure backward compatibility
// with sensors that don't have the FlattenImageData capability.
// Skip if all sensors have the capability.
var allNames []*storage.ImageName
if !l.connManager.AllSensorsHaveCapability(centralsensor.FlattenImageData) {
var err error
allNames, err = l.imagesV2.GetImageNames(allAccessCtx, image.GetDigest())
if err != nil {
log.Warnw("Failed to retrieve image names by digest",
logging.ImageName(image.GetName().GetFullName()),
logging.ImageID(image.GetId()),
logging.String("digest", image.GetDigest()),
logging.Err(err),
)
}
}
convertedImage := utils.ConvertToV1(image, allNames...)
// Send the updated image to relevant clusters.
for clusterID := range clusterIDs {
conn := l.connManager.GetConnection(clusterID)
if conn == nil {
continue
}
msg := ¢ral.MsgToSensor{
Msg: ¢ral.MsgToSensor_UpdatedImage{
UpdatedImage: convertedImage,
},
}
// If were prior errors, do not attempt to send a message to this cluster.
if skipClusterIDs.Contains(clusterID) {
metrics.IncrementMsgToSensorNotSentCounter(clusterID, msg, metrics.NotSentSkip)
log.Debugw("Not sending updated image to cluster due to prior errors",
logging.ImageID(image.GetId()),
logging.ImageName(image.GetName().GetFullName()),
logging.String("dst_cluster", clusterID),
)
continue
}
err := l.injectMessage(concurrency.AsContext(&l.stopSig), conn, msg)
if err != nil {
skipClusterIDs.Store(clusterID, struct{}{})
log.Errorw("Error sending updated image to cluster, skipping cluster until next reprocessing cycle",
logging.ImageName(image.GetName().GetFullName()),
logging.ImageID(image.GetId()), logging.Err(err),
// Not using logging.ClusterID() to avoid "duplicate resource ID field found" panic
logging.String("dst_cluster", clusterID),
)
}
}
}(result.GetImageID(), result.GetImageDigest(), clusterIDSet)
}
select {
case <-wg.Done():
case <-l.stopSig.Done():
log.Info("Stopping reprocessing due to stop signal")
return
}
log.Infof("Successfully reprocessed %d/%d images", nReprocessed.Load(), len(results))
log.Info("Resyncing deployments now that images have been reprocessed...")
l.sendReprocessDeployments(skipClusterIDs)
}
// sendReprocessDeployments sends a reprocess deployments message to every connected
// secured cluster.
func (l *loopImpl) sendReprocessDeployments(skipClusterIDs maputil.SyncMap[string, struct{}]) {
// Once the images have been rescanned, then reprocess the deployments.
// This should not take a particularly long period of time.
if !l.stopSig.IsDone() {
msg := ¢ral.MsgToSensor{
Msg: ¢ral.MsgToSensor_ReprocessDeployments{
ReprocessDeployments: ¢ral.ReprocessDeployments{},
},
}
ctx := concurrency.AsContext(&l.stopSig)
// Calculate the delay between sending reprocess messages to secured clusters.
conns := l.connManager.GetActiveConnections()
delay := env.ReprocessDeploymentsMsgDelay.DurationSetting()
if delay > 0 {
log.Infof("Sending reprocess deployments messages to %d clusters with %s delay between each message", len(conns), delay)
}
firstMessage := true
for i, conn := range conns {
clusterID := conn.ClusterID()
if skipClusterIDs.Contains(clusterID) {
metrics.IncrementMsgToSensorNotSentCounter(clusterID, msg, metrics.NotSentSkip)
log.Errorw("Not sending reprocess deployments to cluster due to prior errors",
logging.ClusterID(clusterID),
)
continue
}
// Sleep before sending if it is not the first message and a delay is specified.
if !firstMessage && delay > 0 {
log.Infof("Sleeping %s before sending reprocess deployments message to cluster %q [%d/%d]", delay, clusterID, i+1, len(conns))
select {
case <-time.After(delay):
case <-l.stopSig.Done():
log.Infof("Caught stop signal while waiting to send reprocess deployments to cluster %q", clusterID)
return
}
}
firstMessage = false
err := l.injectMessage(ctx, conn, msg)
if err != nil {
log.Errorw("Error sending reprocess deployments message to cluster",
logging.ClusterID(clusterID),
logging.Err(err),
)
}
}
}
log.Info("Done sending reprocess deployments messages")
}
// injectMessage will inject a message onto connection, an error will be returned if the
// injection fails for any reason, including timeout.
func (l *loopImpl) injectMessage(ctx context.Context, conn connection.SensorConnection, msg *central.MsgToSensor) error {
if l.injectMessageTimeoutDur > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, l.injectMessageTimeoutDur)
defer cancel()
}
err := conn.InjectMessage(ctx, msg)
if err != nil {
return errors.Wrap(err, "injecting message to sensor")
}
return nil
}
func (l *loopImpl) reprocessNode(id string) bool {
node, exists, err := l.nodes.GetNode(allAccessCtx, id)
if err != nil {
log.Errorw("Error fetching node from the database", logging.NodeID(id), logging.Err(err))
return false
}
if !exists {
log.Warnw("Error fetching non-existing node from the database", logging.NodeID(id))
return false
}
if nodeEnricher.SupportsNodeScanning(node) {
log.Infof("node %s is host-scanned: skipping reprocess", nodeDatastore.NodeString(node))
// False signals there was no writes to the database and no actual reprocessing.
return false
}
err = l.nodeEnricher.EnrichNode(node)
if err != nil {
log.Errorw("Error enriching node", logging.String("node", nodeDatastore.NodeString(node)), logging.Err(err))
return false
}
if err := l.risk.CalculateRiskAndUpsertNode(node); err != nil {
log.Error(err)
return false
}
return true
}
func (l *loopImpl) reprocessNodes() {
l.runReprocessingForObjects("node", func() ([]string, error) {
results, err := l.nodes.Search(allAccessCtx, search.EmptyQuery())
if err != nil {
return nil, err
}
return search.ResultsToIDs(results), nil
}, l.reprocessNode)
}
func (l *loopImpl) reprocessWatchedImage(name string) bool {
enrichmentCtx := imageEnricher.EnrichmentContext{
FetchOpt: imageEnricher.IgnoreExistingImages,
}
ctx := emptyCtx
if features.DelegateWatchedImageReprocessing.Enabled() {
ctx = delegateScanCtx
enrichmentCtx.Delegable = true
}
img, err := imageEnricher.EnrichImageByName(ctx, l.imageEnricher, enrichmentCtx, name)
if err != nil {
log.Errorw("Error enriching watched image", logging.ImageName(name), logging.Err(err))
return false
}
// Save the image
img.Id = utils.GetSHA(img)
if img.GetId() == "" {
return false
}
if err := l.risk.CalculateRiskAndUpsertImage(img); err != nil {
log.Errorw("Error upserting watched image after enriching", logging.ImageName(name), logging.ImageID(img.GetId()), logging.Err(err))
return false
}
return true
}
func (l *loopImpl) reprocessWatchedImageV2(name string) bool {
enrichmentCtx := imageEnricher.EnrichmentContext{
FetchOpt: imageEnricher.IgnoreExistingImages,
}
ctx := emptyCtx
if features.DelegateWatchedImageReprocessing.Enabled() {
ctx = delegateScanCtx
enrichmentCtx.Delegable = true
}
img, err := imageEnricher.EnrichImageV2ByName(ctx, l.imageEnricherV2, enrichmentCtx, name)
if err != nil {
log.Errorw("Error enriching watched image", logging.ImageName(name), logging.Err(err))
return false
}
// Save the image
img.Digest = utils.GetSHAV2(img)
img.Id, err = utils.GetImageV2ID(img)
if err != nil {
log.Errorw("Error getting enriched image ID", logging.ImageName(name), logging.Err(err))
return false
}
if img.GetId() == "" {
return false
}
if err := l.risk.CalculateRiskAndUpsertImageV2(img); err != nil {
log.Errorw("Error upserting watched image after enriching", logging.ImageName(name), logging.ImageID(img.GetId()), logging.Err(err))
return false
}
return true
}
func (l *loopImpl) reprocessWatchedImages() {
var reprocessFunc func(name string) bool
if features.FlattenImageData.Enabled() {
reprocessFunc = l.reprocessWatchedImageV2
} else {
reprocessFunc = l.reprocessWatchedImage
}
l.runReprocessingForObjects("watched image", func() ([]string, error) {
watchedImages, err := l.watchedImages.GetAllWatchedImages(allAccessCtx)
if err != nil {
return nil, err
}
imageNames := make([]string, 0, len(watchedImages))
for _, img := range watchedImages {
imageNames = append(imageNames, img.GetName())
}
return imageNames, nil
}, reprocessFunc)
}
func (l *loopImpl) runReprocessing(imageFetchOpt imageEnricher.FetchOption) {
// In case the current reprocessing run takes longer than the ticker (i.e. > 4 hours when using a high number of
// images), we shouldn't trigger a parallel reprocessing run.
if l.reprocessingInProgress.TestAndSet(true) {
return
}
defer metrics.SetReprocessorDuration(time.Now())
l.reprocessNodes()
l.reprocessWatchedImages()
if features.FlattenImageData.Enabled() {
l.reprocessImagesV2AndResyncDeployments(imageFetchOpt, l.enrichImageV2, allV2ImagesQuery)
} else {
l.reprocessImagesAndResyncDeployments(imageFetchOpt, l.enrichImage, allImagesQuery)
}
l.reprocessingInProgress.Set(false)
}
func (l *loopImpl) runSignatureVerificationReprocessing() {
defer metrics.SetSignatureVerificationReprocessorDuration(time.Now())
l.reprocessWatchedImages()
query := imagesWithSignaturesQuery
// If we have reprocessed when the _first_ signature integration is added, then take into account all images.
if l.firstSignatureIntegration.Get() {
query = allImagesQuery
}
if features.FlattenImageData.Enabled() {
l.reprocessImagesV2AndResyncDeployments(imageEnricher.ForceRefetchSignaturesOnly,
l.forceEnrichImageSignatureVerificationResultsV2, allV2ImagesQuery)
} else {
l.reprocessImagesAndResyncDeployments(imageEnricher.ForceRefetchSignaturesOnly,
l.forceEnrichImageSignatureVerificationResults, query)
}
l.firstSignatureIntegration.Set(false)
}
func (l *loopImpl) forceEnrichImageSignatureVerificationResults(ctx context.Context, _ imageEnricher.EnrichmentContext,
image *storage.Image) (imageEnricher.EnrichmentResult, error) {
return l.imageEnricher.EnrichWithSignatureVerificationData(ctx, image)
}
func (l *loopImpl) forceEnrichImageSignatureVerificationResultsV2(ctx context.Context, _ imageEnricher.EnrichmentContext,
image *storage.ImageV2) (imageEnricher.EnrichmentResult, error) {
return l.imageEnricherV2.EnrichWithSignatureVerificationData(ctx, image)
}
func (l *loopImpl) enrichImage(ctx context.Context, enrichCtx imageEnricher.EnrichmentContext,
image *storage.Image) (imageEnricher.EnrichmentResult, error) {
return l.imageEnricher.EnrichImage(ctx, enrichCtx, image)
}
func (l *loopImpl) enrichImageV2(ctx context.Context, enrichCtx imageEnricher.EnrichmentContext,
image *storage.ImageV2) (imageEnricher.EnrichmentResult, error) {
return l.imageEnricherV2.EnrichImage(ctx, enrichCtx, image)
}
func (l *loopImpl) enrichLoop() {
defer l.enrichAndDetectTicker.Stop()
defer l.enrichmentStopped.Signal()
// Call runReprocessing with ForceRefetch on start to ensure that the image metadata reflects any changes
// in the proto and to ensure that the images and nodes are pulling new scans on <= the reprocessing interval
l.runReprocessing(imageEnricher.ForceRefetch)
for !l.stopSig.IsDone() {
select {
case <-l.stopSig.Done():
return
case <-l.shortCircuitSig.Done():
l.shortCircuitSig.Reset()
l.runReprocessing(imageEnricher.UseCachesIfPossible)
case <-l.signatureVerificationSig.Done():
l.signatureVerificationSig.Reset()
l.runSignatureVerificationReprocessing()
case <-l.enrichAndDetectTicker.C:
l.runReprocessing(imageEnricher.ForceRefetchCachedValuesOnly)
}
}
}
func (l *loopImpl) riskLoop() {
defer l.riskStopped.Signal()
defer l.deploymentRiskTicker.Stop()
for !l.stopSig.IsDone() {
select {
case <-l.stopSig.Done():
return
case <-l.deploymentRiskTicker.C:
concurrency.WithLock(&l.deploymentRiskLock, func() {
if l.deploymentRiskSet.Cardinality() > 0 {
// goroutine to ensure this is non-blocking.
go l.sendDeployments(l.deploymentRiskSet.AsSlice())
l.deploymentRiskSet.Clear()
}
})
}
}
}