forked from neuvector/neuvector
/
registry.go
1557 lines (1348 loc) · 45.5 KB
/
registry.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
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package scan
import (
"context"
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/neuvector/neuvector/controller/access"
"github.com/neuvector/neuvector/controller/api"
"github.com/neuvector/neuvector/controller/common"
"github.com/neuvector/neuvector/controller/scheduler"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/cluster"
"github.com/neuvector/neuvector/share/httptrace"
scanUtils "github.com/neuvector/neuvector/share/scan"
"github.com/neuvector/neuvector/share/utils"
)
const (
registryErrMsgConnect = "Failed to connect to the registry"
registryErrMsgImage = "Failed to get scanning image list"
registryErrMsgAuth = "Authentication error"
scanReqTimeout = time.Minute * 20
scanReqSafetyTimeOut = time.Minute * 30 // Should be longer than scanReqTimeout
scanPersistImageExtra = 32
registryRepoScanName = "_repo_scan"
)
type scanContext struct {
ctx context.Context
cancel context.CancelFunc
scheduling bool
}
type pollContext struct {
ctx context.Context
cancel context.CancelFunc
}
// This structure is derived from image summary and scan report. Mostly used for admisssion control
type imageInfoCache struct {
highVuls int
medVuls int
highVulsWithFix int
vulScore float32
vulTraits []*common.VulTrait
vulInfo map[string]map[string]share.CLUSScannedVulInfo // 1st key is "high"/"medium". 2nd key is "{vul_name}::{package_name}"
lowVulInfo []share.CLUSScannedVulInfoSimple
layers []string
envs []string
labels map[string]string
secrets []share.ScanSecretLog
setIDPerm []share.ScanSetIdPermLog
filteredTime time.Time
}
type Registry struct {
public bool
config *share.CLUSRegistryConfig
state *share.CLUSRegistryState
summary map[string]*share.CLUSRegistryImageSummary
cache map[string]*imageInfoCache
image2ID map[share.CLUSImage]string
digest2ID map[string]string
taskQueue utils.Set
sctx *scanContext
pctx *pollContext
// Keep driver in registry so it doesn't login for every scan
driver registryDriver // TODO: add the idle logout logic
backupDrv registryDriver
errDetail string
stateMux sync.Mutex
}
var repoScanRegistry *Registry
var regMap map[string]*Registry = make(map[string]*Registry)
var regMux sync.RWMutex
// aquire regLock first, and then stateLock
func regLock() {
smd.mutexLog.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("Acquire ...")
regMux.Lock()
}
func regUnlock() {
regMux.Unlock()
smd.mutexLog.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("Released ...")
}
func regReadLock() {
smd.mutexLog.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("Acquire ...")
regMux.RLock()
}
func regReadUnlock() {
regMux.RUnlock()
smd.mutexLog.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("Released ...")
}
func (rs *Registry) stateLock() {
smd.mutexLog.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("Acquire ...")
rs.stateMux.Lock()
}
func (rs *Registry) stateUnlock() {
rs.stateMux.Unlock()
smd.mutexLog.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("Released ...")
}
func regMapToArray() []*Registry {
regReadLock()
defer regReadUnlock()
rss := make([]*Registry, len(regMap))
i := 0
for _, rs := range regMap {
rss[i] = rs
i++
}
return rss
}
func regMapLookup(name string) (*Registry, bool) {
regReadLock()
defer regReadUnlock()
rs, ok := regMap[name]
return rs, ok
}
var regScher *scheduler.Schd
func registryInit() {
if regScher == nil {
regScher = &scheduler.Schd{}
regScher.Init()
}
// Get all registry config first. We will get notified again.
newRepoScanRegistry()
configs := clusHelper.GetAllRegistry()
for _, config := range configs {
regLock()
regMap[config.Name] = newRegistry(config)
regUnlock()
}
}
func becomeScanner() {
log.Debug()
regs := regMapToArray()
for _, reg := range regs {
reg.stateLock()
if reg.state.Status == api.RegistryStatusScanning {
reg.resumeScan()
} else if reg.config.Schedule == api.ScanSchAuto {
reg.resumeScan()
}
if reg.config.Schedule == api.ScanSchPeriodical {
ctx, cancel := context.WithCancel(context.Background())
reg.pctx = &pollContext{ctx: ctx, cancel: cancel}
go reg.polling(ctx)
}
reg.stateUnlock()
}
}
func RegistryConfigHandler(nType cluster.ClusterNotifyType, key string, value []byte) {
log.WithFields(log.Fields{"type": cluster.ClusterNotifyName[nType], "key": key}).Debug()
name := share.CLUSKeyNthToken(key, 3)
switch nType {
case cluster.ClusterNotifyAdd, cluster.ClusterNotifyModify:
var config share.CLUSRegistryConfig
json.Unmarshal(value, &config)
var oldFilters []string
oldSchedule := api.ScanSchManual
var credChanged bool
reg, ok := regMapLookup(config.Name)
if ok && reg.config.Name != "" {
oldSchedule = reg.config.Schedule
oldFilters = reg.config.Filters
oldCfg := reg.config
reg.config = &config
// Clear last error if configuration is changed.
reg.state.ErrMsg = ""
public := isPublicRegistry(&config)
reg.driver.SetConfig(&config)
reg.backupDrv.SetConfig(&config)
if oldCfg.Registry != config.Registry || oldCfg.AuthWithToken != config.AuthWithToken ||
(oldCfg.AuthWithToken && oldCfg.AuthToken != config.AuthToken) ||
(!oldCfg.AuthWithToken && (oldCfg.Username != config.Username || oldCfg.Password != config.Password)) ||
public != reg.public {
// URL or credential changed, stop scan and force logout
credChanged = true
reg.driver.Logout(true)
reg.backupDrv.Logout(true)
// if the public change, need to renew the driver type.
if public != reg.public {
reg.public = public
reg.driver = newRegistryDriver(reg.config, reg.public, new(httptrace.NopTracer))
}
if isScanner() {
reg.stateLock()
if reg.state.Status == api.RegistryStatusScanning {
// stopScan() will be called
state := share.CLUSRegistryState{Status: api.RegistryStatusIdle, StartedAt: reg.state.StartedAt}
clusHelper.PutRegistryState(reg.config.Name, &state)
}
reg.stateUnlock()
}
}
if isScanner() {
if oldCfg.Schedule == api.ScanSchPeriodical &&
config.Schedule != api.ScanSchPeriodical && reg.pctx != nil {
reg.pctx.cancel()
reg.pctx = nil
} else if oldCfg.Schedule != api.ScanSchPeriodical &&
config.Schedule == api.ScanSchPeriodical {
ctx, cancel := context.WithCancel(context.Background())
reg.pctx = &pollContext{ctx: ctx, cancel: cancel}
go reg.polling(ctx)
} else if config.Schedule == api.ScanSchPeriodical &&
oldCfg.PollPeriod != config.PollPeriod && reg.pctx != nil {
reg.pctx.cancel()
ctx, cancel := context.WithCancel(context.Background())
reg.pctx = &pollContext{ctx: ctx, cancel: cancel}
go reg.polling(ctx)
}
}
// Assume that state is always created way after config is created, so no check
// of state here.
} else {
oldFilters = make([]string, 0)
reg = newRegistry(&config)
// put recovery images summary into new created registry
if oldReg, ok := regMapLookup(config.Name); ok && len(oldReg.summary) > 0 {
reg.summary = oldReg.summary
reg.image2ID = oldReg.image2ID
reg.digest2ID = oldReg.digest2ID
}
if isScanner() && reg.config.Schedule == api.ScanSchPeriodical {
ctx, cancel := context.WithCancel(context.Background())
reg.pctx = &pollContext{ctx: ctx, cancel: cancel}
go reg.polling(ctx)
}
regLock()
regMap[config.Name] = reg
regUnlock()
}
if reg.config.Type == share.RegistryTypeOpenShift {
if oldSchedule == api.ScanSchManual && config.Schedule == api.ScanSchAuto {
registerImageBank(api.RegistryImageSourceOpenShift, reg.config.Name)
} else if oldSchedule == api.ScanSchAuto && config.Schedule == api.ScanSchManual {
deregisterImageBank(api.RegistryImageSourceOpenShift, reg.config.Name)
}
}
if credChanged {
return
}
if isScanner() {
if oldSchedule == api.ScanSchManual && config.Schedule == api.ScanSchAuto {
reg.stateLock()
if reg.state.Status == api.RegistryStatusIdle {
// Start scanning if not
state := share.CLUSRegistryState{Status: api.RegistryStatusScanning, StartedAt: time.Now().Unix()}
clusHelper.PutRegistryState(reg.config.Name, &state)
}
reg.stateUnlock()
} else if config.Schedule == api.ScanSchAuto && !reflect.DeepEqual(oldFilters, config.Filters) {
// Filter changes (including order change) with auto-scan enabled
/*
if reg.state.Status == api.RegistryStatusIdle {
// Start scanning if not
state := share.CLUSRegistryState{Status: api.RegistryStatusScanning, StartedAt: time.Now().Unix()}
clusHelper.PutRegistryState(reg.config.Name, &state)
} else if reg.sctx != nil && !reg.sctx.refreshing {
// We don't want to block config change handler for too long, but if filters keeps changing, we don't want
// them to run in parallel. Use a flag to discard later changes. We could use another context to cancel
// the current and keep last one.
reg.sctx.refreshing = true
go reg.imageScanRefresh(false)
}
*/
}
}
case cluster.ClusterNotifyDelete:
regLock()
reg, ok := regMap[name]
if ok {
// It's possible that new scan get kicked in, we just cancel it here.
if reg.sctx != nil {
reg.sctx.cancel()
reg.sctx = nil
reg.driver.Logout(true)
}
if reg.pctx != nil {
reg.pctx.cancel()
reg.pctx = nil
}
// It's possible backupDrv never logged in
reg.backupDrv.Logout(true)
delete(regMap, name)
}
regUnlock()
if ok && isScanner() {
reg.cleanup()
if reg.config.Schedule == api.ScanSchAuto {
if reg.config.Type == share.RegistryTypeOpenShift {
deregisterImageBank(api.RegistryImageSourceOpenShift, reg.config.Name)
}
}
}
}
}
// Allow manual start/stop scan even if auto-scan is enabled, scan can be restarted manually or when
// new images added
func RegistryStateUpdate(name string, state *share.CLUSRegistryState) {
// Assume that state is always created way after config is created, so ignore if config doesn't exist
reg, ok := regMapLookup(name)
if ok {
smd.scanLog.WithFields(log.Fields{"registry": name, "old-state": reg.state, "state": state}).Debug("")
reg.stateLock()
defer reg.stateUnlock()
oldStatus := reg.state.Status
reg.state = state
if isScanner() {
if oldStatus == api.RegistryStatusIdle && state.Status == api.RegistryStatusScanning {
// If sctx is not nil, scan is running, this happens when scan is triggered by new images.
// Must create context here so we can cancel it.
if reg.sctx == nil {
reg.startScan()
} else {
smd.scanLog.WithFields(log.Fields{"registry": name}).Debug("skip start - scanning")
}
} else if oldStatus == api.RegistryStatusScanning && state.Status == api.RegistryStatusIdle {
// sctx could be nil if scan failed to start
if reg.sctx != nil {
reg.stopScan()
} else {
smd.scanLog.WithFields(log.Fields{"registry": name}).Debug("skip stop - not scanning")
}
}
}
}
}
func RegistryImageStateUpdate(name, id string, sum *share.CLUSRegistryImageSummary, vpf common.VPFInterface) (utils.Set, []string, []string) {
smd.scanLog.WithFields(log.Fields{"registry": name, "id": id}).Debug()
var rs *Registry
// We assume that report is always created way after config is created, so ignore if config doesn't exist
if name == registryRepoScanName {
rs = repoScanRegistry
} else if rs, _ = regMapLookup(name); rs == nil {
return nil, nil, nil
}
var c *imageInfoCache
var highs, meds []string
var alives utils.Set // vul names that are not filtered
if sum != nil && sum.Status == api.ScanStatusFinished {
key := share.CLUSRegistryImageDataKey(name, id)
if report := clusHelper.GetScanReport(key); report != nil {
c = &imageInfoCache{}
// Filter the vulnerabilities
c.filteredTime = time.Now()
c.vulTraits = common.ExtractVulnerability(report.Vuls)
if vpf != nil {
alives = vpf.FilterVulTraits(c.vulTraits, images2IDNames(rs, sum))
} else {
alives = utils.NewSet()
for _, t := range c.vulTraits {
alives.Add(t.Name)
}
}
highs, meds, c.highVulsWithFix, c.vulScore, c.vulInfo, c.lowVulInfo = countVuln(report.Vuls, alives)
c.highVuls = len(highs)
c.medVuls = len(meds)
c.envs = report.Envs
c.labels = report.Labels
c.layers = make([]string, len(report.Layers))
for i, l := range report.Layers {
c.layers[i] = l.Digest
}
if report.Secrets != nil {
c.secrets = make([]share.ScanSecretLog, len(report.Secrets.Logs))
for i, s := range report.Secrets.Logs {
c.secrets[i] = *s
}
}
c.setIDPerm = make([]share.ScanSetIdPermLog, len(report.SetIdPerms))
for i, s := range report.SetIdPerms {
c.setIDPerm[i] = *s
}
}
}
rs.stateLock()
defer rs.stateUnlock()
if sum != nil {
for _, image := range sum.Images {
rs.image2ID[image] = id
}
rs.digest2ID[sum.Digest] = id
rs.summary[id] = sum
if c != nil {
rs.cache[id] = c
}
} else if sum, ok := rs.summary[id]; ok {
for _, image := range sum.Images {
delete(rs.image2ID, image)
}
delete(rs.digest2ID, sum.Digest)
delete(rs.summary, id)
delete(rs.cache, id)
}
return alives, highs, meds
}
func RegistryScanCacheRefresh(ctx context.Context, vpf common.VPFInterface) {
log.Debug()
regs := regMapToArray()
for _, rs := range regs {
rs.stateLock()
for id, sum := range rs.summary {
if sum.Status == api.ScanStatusFinished {
if c, ok := rs.cache[id]; ok {
refreshScanCache(rs, id, sum, c, vpf)
}
}
select {
case <-ctx.Done():
rs.stateUnlock()
smd.scanLog.Debug("Canceled")
return
default:
// not canceled, continue
}
}
rs.stateUnlock()
}
}
func isPublicRegistry(cfg *share.CLUSRegistryConfig) bool {
return strings.Contains(cfg.Registry, ".docker.com") || strings.Contains(cfg.Registry, ".docker.io") ||
cfg.Type == share.RegistryTypeRedhat
}
func newRegistryDriver(cfg *share.CLUSRegistryConfig, public bool, tracer httptrace.HTTPTrace) registryDriver {
baseDriver := base{
regURL: cfg.Registry,
proxy: GetProxy(cfg.Registry),
scanLayers: cfg.ScanLayers,
scanSecrets: !cfg.DisableFiles,
tracer: tracer,
}
if cfg.Type == share.RegistryTypeJFrog {
return &jfrog{base: baseDriver, mode: cfg.JfrogMode, aql: cfg.JfrogAQL}
} else if cfg.Type == share.RegistryTypeOpenShift {
return &openshift{base: baseDriver}
} else if cfg.Type == share.RegistryTypeAWSECR {
return &awsDriver{base: baseDriver}
} else if cfg.Type == share.RegistryTypeDocker && public {
return &dockerhub{base: baseDriver}
} else if cfg.Type == share.RegistryTypeGCR {
return &gcrDriver{base: baseDriver}
} else if cfg.Type == share.RegistryTypeGitlab {
return &gitlab{base: baseDriver}
} else if cfg.Type == share.RegistryTypeIBMCloud {
return &ibmcloud{base: baseDriver}
} else {
return &baseDriver
}
}
func newRegistry(config *share.CLUSRegistryConfig) *Registry {
smd.scanLog.WithFields(log.Fields{"registry": config.Name}).Debug("")
rs := &Registry{
config: config,
state: &share.CLUSRegistryState{Status: api.RegistryStatusIdle},
summary: make(map[string]*share.CLUSRegistryImageSummary),
cache: make(map[string]*imageInfoCache),
image2ID: make(map[share.CLUSImage]string),
digest2ID: make(map[string]string),
taskQueue: utils.NewSet(),
public: isPublicRegistry(config),
}
rs.driver = newRegistryDriver(rs.config, rs.public, new(httptrace.NopTracer))
rs.backupDrv = newRegistryDriver(rs.config, rs.public, new(httptrace.NopTracer))
return rs
}
func newRepoScanRegistry() {
repoScanRegistry = &Registry{
config: &share.CLUSRegistryConfig{Name: registryRepoScanName, Type: share.RegistryTypeDocker},
state: &share.CLUSRegistryState{Status: api.RegistryStatusIdle},
summary: make(map[string]*share.CLUSRegistryImageSummary),
cache: make(map[string]*imageInfoCache),
image2ID: make(map[share.CLUSImage]string),
digest2ID: make(map[string]string),
taskQueue: utils.NewSet(),
}
}
func (rs *Registry) newScanContext() (*scanContext, error) {
if err, msg := rs.driver.Login(rs.config); err != nil {
rs.errDetail = msg
return nil, err
} else {
ctx, cancel := context.WithCancel(context.Background())
return &scanContext{ctx: ctx, cancel: cancel}, nil
}
}
// no lock
func (rs *Registry) getScanImages(sctx *scanContext, drv registryDriver, dryrun bool) (map[string]utils.Set, int, error) {
sctx.scheduling = true
defer func() { sctx.scheduling = false }()
rs.driver.GetTracer().SetPhase("Get all images")
// not all driver support this
allImages, err := drv.GetAllImages()
if sctx.ctx != nil {
select {
case <-sctx.ctx.Done():
smd.scanLog.Debug("Registry scan canceled")
return nil, 0, err
default:
// not canceled, continue
}
}
rs.driver.GetTracer().SetPhase("Get registry repository list")
// Get a list of repository. Tag is not expanded yet.
// Different filter might give the same repo list, but their tag filter could be different,
// so repos cannot be merged until tags are expanded.
err = nil
imageTagFilters := make([]*share.CLUSImage, 0)
for _, filter := range rs.config.ParsedFilters {
smd.scanLog.WithFields(log.Fields{"filter": filter}).Debug("")
var limit int
if rs.public {
limit = rs.config.RepoLimit
}
var repos []*share.CLUSImage
if allImages != nil {
prefix := fmt.Sprintf("%s/", filter.Org)
matchAll := (filter.Org == "" && filter.Repo == ".*")
for r, _ := range allImages {
if matchAll || (filter.Org != "" && strings.HasPrefix(r.Repo, prefix)) {
// create a new CLUSImage because &r points one same location
repos = append(repos, &share.CLUSImage{Repo: r.Repo, RegMod: r.RegMod})
}
}
} else {
repos, err = drv.GetRepoList(filter.Org, filter.Repo, limit)
}
if err != nil {
smd.scanLog.WithFields(log.Fields{"error": err}).Error("Failed to get repository list")
continue
}
// for docker hub single repo
if rs.config.Type == share.RegistryTypeDocker && rs.public &&
filter.Org == "" && !strings.Contains(filter.Repo, "*") {
filter.Org = "library"
}
var filteredRepos []*share.CLUSImage
// Only filter image 'org' by registry creater domains for Openshift registry
if rs.config.Type == share.RegistryTypeOpenShift {
filteredRepos, err = filterRepos(repos, filter, rs.config.CreaterDomains, limit)
} else {
filteredRepos, err = filterRepos(repos, filter, nil, limit)
}
if err != nil {
smd.scanLog.WithFields(log.Fields{"error": err}).Error("Failed to filter repository list")
continue
}
for _, repo := range filteredRepos {
repo.Tag = filter.Tag
imageTagFilters = append(imageTagFilters, repo)
}
if sctx.ctx != nil {
select {
case <-sctx.ctx.Done():
smd.scanLog.Debug("Registry scan canceled")
return nil, 0, err
default:
// not canceled, continue
}
}
}
smd.scanLog.WithFields(log.Fields{"count": len(imageTagFilters)}).Debug("image with tag filter")
if len(imageTagFilters) == 0 && err != nil {
return nil, 0, err
}
rs.driver.GetTracer().SetPhase("Get registry repository tag list")
// expand tags
itfList := make([]*share.CLUSImage, 0)
tagList := make([][]string, 0)
for _, itf := range imageTagFilters {
var tags []string
if allImages != nil {
var ok bool
lookup := share.CLUSImage{Domain: itf.Domain, Repo: itf.Repo, RegMod: itf.RegMod}
if tags, ok = allImages[lookup]; !ok {
err = common.ErrObjectNotFound
}
} else {
tags, err = drv.GetTagList(itf.Domain, itf.Repo, itf.Tag)
}
if err != nil {
smd.scanLog.WithFields(log.Fields{"error": err}).Error("Failed to get repository tag list")
continue
}
var limit int
if rs.public {
limit = rs.config.TagLimit
}
var filteredTags []string
filteredTags, err = filterTags(tags, itf.Tag, limit)
if err != nil {
smd.scanLog.WithFields(log.Fields{"error": err}).Error("Failed to filter repository tag list")
continue
}
itfList = append(itfList, itf)
tagList = append(tagList, filteredTags)
smd.scanLog.WithFields(log.Fields{"image": itf, "tags": len(filteredTags)}).Debug()
if sctx.ctx != nil {
select {
case <-sctx.ctx.Done():
smd.scanLog.Debug("Registry scan canceled")
return nil, 0, err
default:
// not canceled, continue
}
}
}
if !dryrun {
imageMap, total := rs.scheduleScanImages(sctx, drv, itfList, tagList)
smd.scanLog.WithFields(log.Fields{"count": total}).Debug("total images")
return imageMap, total, nil
} else {
rs.driver.GetTracer().SetPhase("Get registry image manifest")
var total int
imageMap := make(map[string]utils.Set)
for i := 0; i < len(itfList); i++ {
itf := itfList[i]
tags := tagList[i]
for _, tag := range tags {
info, errCode := drv.GetImageMeta(sctx.ctx, itf.Domain, itf.Repo, tag)
if errCode != share.ScanErrorCode_ScanErrNone {
smd.scanLog.WithFields(log.Fields{
"repo": itf, "tag": tag, "error": scanUtils.ScanErrorToStr(errCode),
}).Debug("Failed to get image info")
continue
}
image := share.CLUSImage{Domain: itf.Domain, Repo: itf.Repo, Tag: tag, RegMod: itf.RegMod}
if exist, ok := imageMap[info.ID]; ok {
exist.Add(image)
} else {
imageMap[info.ID] = utils.NewSet(image)
}
total++
}
}
return imageMap, total, nil
}
}
func (rs *Registry) checkAndPutImageResult(sctx *scanContext, id string, result *share.ScanResult, retAction scheduler.Action) int {
rs.stateLock()
defer rs.stateUnlock()
if retAction != scheduler.TaskActionRequeue {
rs.taskQueue.Remove(id)
}
// Scan might be stopped and registry might be removed, the task is canceled first, so
// check the context and don't do anything if task is canceled.
select {
case <-sctx.ctx.Done():
return -1
default:
// not canceled, continue
}
if sum, ok := rs.summary[id]; ok {
sum.ScannedAt = time.Now().UTC()
sum.Provider = result.Provider
sum.BaseOS = result.Namespace
sum.Version = result.Version
sum.Result = result.Error
if result.Error == share.ScanErrorCode_ScanErrNone {
sum.Status = api.ScanStatusFinished
} else if result.Error == share.ScanErrorCode_ScanErrNotSupport {
sum.Status = api.ScanStatusFinished
} else if retAction == scheduler.TaskActionRequeue {
sum.Status = api.ScanStatusScheduled
} else {
sum.Status = api.ScanStatusFailed
}
sum.Author = result.Author
sum.Size = result.Size
if sum.Status == api.ScanStatusFinished {
sum.ScanFlags |= share.ScanFlagCVE
if len(result.Layers) != 0 {
sum.ScanFlags |= share.ScanFlagLayers
}
if result.Secrets != nil {
sum.ScanFlags |= share.ScanFlagFiles
}
}
report := share.CLUSScanReport{
ScannedAt: sum.ScannedAt,
ScanResult: *result,
}
if sum.Status == api.ScanStatusFinished {
clusHelper.PutRegistryImageSummaryAndReport(rs.config.Name, id, sum, &report)
if len(rs.summary) > api.ScanPersistImageMax+scanPersistImageExtra {
rs.cleanupOldImages()
}
} else {
clusHelper.PutRegistryImageSummary(rs.config.Name, id, sum)
}
}
count := rs.taskQueue.Cardinality()
if count == 0 && !sctx.scheduling && retAction != scheduler.TaskActionRequeue {
// stopScan() will be called
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name}).Debug("Registry scan done")
state := share.CLUSRegistryState{Status: api.RegistryStatusIdle, StartedAt: rs.state.StartedAt}
clusHelper.PutRegistryState(rs.config.Name, &state)
}
return count
}
// Return if should continue scanning
func (rs *Registry) checkAndPutImageScanning(sctx *scanContext, task *regScanTask) *share.CLUSRegistryImageSummary {
if !isScanner() {
return nil
}
rs.stateLock()
defer rs.stateUnlock()
// Scan might be stopped and registry might be removed, the task is canceled first, so
// check the context and don't do anything if task is canceled.
select {
case <-sctx.ctx.Done():
return nil
default:
// not canceled, continue
}
id := task.imageID
sum, ok := rs.summary[id]
if !ok || len(sum.Images) == 0 {
return nil
}
sum.Status = api.ScanStatusScanning
clusHelper.PutRegistryImageSummary(rs.config.Name, id, sum)
return sum
}
// Return if should continue scanning
func (rs *Registry) checkAndPutRegState(ctx context.Context, errMsg string) bool {
rs.stateLock()
defer rs.stateUnlock()
// Scan might be stopped and registry might be removed, the task is canceled first, so
// check the context and don't do anything if task is canceled.
select {
case <-ctx.Done():
return false
default:
// not canceled, continue
}
if errMsg != "" {
state := share.CLUSRegistryState{
Status: api.RegistryStatusIdle,
ErrMsg: errMsg,
ErrDetail: rs.errDetail,
StartedAt: rs.state.StartedAt,
}
clusHelper.PutRegistryState(rs.config.Name, &state)
return false
}
return true
}
func imageUpdateCallback(name string, img *share.CLUSImage, add bool) {
smd.scanLog.WithFields(log.Fields{"registry": name, "image": *img, "add": add}).Debug()
if isScanner() {
if add {
reg, ok := regMapLookup(name)
if ok {
// Not to start go routine because there could be more images pushed at the same time.
// Probably shouldn't run them parallelly.
reg.imageScanAdd(img)
}
} else {
reg, ok := regMapLookup(name)
if ok {
reg.imageScanDelete(img)
}
}
}
}
func (rs *Registry) imageScanDelete(img *share.CLUSImage) {
rs.stateLock()
defer rs.stateUnlock()
for _, sum := range rs.summary {
for i, e := range sum.Images {
if img.Domain == e.Domain && img.Repo == e.Repo && img.Tag == e.Tag {
if len(sum.Images) == 1 {
rs.cleanupOneImage(sum.ImageID)
// rs.summary will be cleaned up when responding the key removal
} else {
sum.Images = append(sum.Images[:i], sum.Images[i+1:]...)
}
return
}
}
}
}
// no lock
func (rs *Registry) imageScanAdd(img *share.CLUSImage) {
repo := *img // clone img so it's value won't be modified
repos := []*share.CLUSImage{&repo}
tags := []string{img.Tag}
var imageTagFilter *share.CLUSImage
for _, filter := range rs.config.ParsedFilters {
filteredRepos, _ := filterRepos(repos, filter, rs.config.CreaterDomains, 0)
if len(filteredRepos) > 0 {
filteredRepos[0].Tag = filter.Tag
imageTagFilter = filteredRepos[0]
break
}
}
if imageTagFilter == nil {
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name, "image": img}).Error("No repo match - ignored")
return
}
filteredTags, err := filterTags(tags, imageTagFilter.Tag, 0)
if err, _ := rs.backupDrv.Login(rs.config); err != nil {
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name, "error": err}).Error()
return
}
ctx, cancel := context.WithCancel(context.Background())
imageMap, err := getImageMeta(ctx, rs.backupDrv, imageTagFilter, filteredTags)
cancel()
rs.backupDrv.Logout(false)
if err != nil {
smd.scanLog.WithFields(log.Fields{"error": err}).Error("Get image meta fail")
return
}
if len(imageMap) == 0 {
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name, "image": img}).Error("No tag match - ignored")
return
}
rs1, ok := regMapLookup(rs.config.Name)
// Because lock was released, we need check registry still exist and same
if ok && rs1 == rs {
// Because we use 'state' to sync, checking sctx is not enough, as state might have changed but scanStop is not call yet.
rs.stateLock()
state := clusHelper.GetRegistryState(rs.config.Name)
if state != nil && state.Status == api.RegistryStatusScanning && rs.sctx != nil {
// Scanning, schedule the image
rs.scheduleScanImagesOnDemand(rs.sctx, imageMap)
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name, "image": img}).Debug("New image scheduled")
} else {
// Not scanning, start scan
state = &share.CLUSRegistryState{Status: api.RegistryStatusScanning, StartedAt: time.Now().Unix()}
clusHelper.PutRegistryState(rs.config.Name, state)
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name, "image": img}).Debug("Start scan")
}
rs.stateUnlock()
} else {
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name, "image": img}).Error("Registry changed - ignored")
}
return
}
// no lock
func (rs *Registry) imageScanStart(sctx *scanContext) {
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name}).Debug("")
imageMap, total, err := rs.getScanImages(sctx, rs.driver, false)
if err == context.Canceled {
return
} else if err != nil && total == 0 {
msg := registryErrMsgImage
if strings.Contains(err.Error(), "UNAUTHORIZED") {
msg = registryErrMsgAuth
}
rs.checkAndPutRegState(sctx.ctx, msg)
return
}
if !rs.checkAndPutRegState(sctx.ctx, "") {
smd.scanLog.WithFields(log.Fields{"registry": rs.config.Name}).Debug("Registry scan canceled")
return
}
rs.stateLock()
rs.cleanupImages(sctx, imageMap)
// No need to cleanup taskQueue() because stopScan must be called in the path