/
controller.go
105 lines (91 loc) · 2.45 KB
/
controller.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
package updater
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"github.com/quay/zlog"
"github.com/quay/claircore/internal/vulnstore"
"github.com/quay/claircore/libvuln/driver"
)
// Controller is the interface that updater Controllers implement.
type Controller interface {
// Run has the Controller execute all the Updaters passed on the channel,
// until it's closed. The method runs synchronously and only returns after
// the channel is closed or the context is canceled.
//
// Any spawned goroutines should inherit the passed-in Context.
//
// A call to Run should be thought of as one execution of the Updaters.
// If a caller wants to call Run in a loop, it should use a new channel on
// each iteration.
Run(context.Context, <-chan driver.Updater) error
}
// Errmap is a wrapper around a group of errors.
type errmap struct {
sync.Mutex
m map[string]error
}
func (e *errmap) add(name string, err error) {
e.Lock()
defer e.Unlock()
e.m[name] = err
}
func (e *errmap) len() int {
e.Lock()
defer e.Unlock()
return len(e.m)
}
func (e *errmap) error() error {
e.Lock()
defer e.Unlock()
var b strings.Builder
b.WriteString("updating errors:\n")
for n, err := range e.m {
fmt.Fprintf(&b, "\t%s: %v\n", n, err)
}
return errors.New(b.String())
}
// DriveUpdater drives the updater.
//
// The caller is expected to handle any locking or concurrency control needed.
func driveUpdater(ctx context.Context, u driver.Updater, s vulnstore.Updater) error {
zlog.Debug(ctx).Msg("start")
defer zlog.Debug(ctx).Msg("done")
name := u.Name()
var prevFP driver.Fingerprint
// Get previous fingerprint, if present.
// A fingerprint being missing is not an error.
opmap, err := s.GetUpdateOperations(ctx, driver.VulnerabilityKind, name)
if err != nil {
return err
}
if s := opmap[name]; len(s) > 0 {
prevFP = s[0].Fingerprint
}
vulnDB, newFP, err := u.Fetch(ctx, prevFP)
if vulnDB != nil {
defer vulnDB.Close()
}
switch {
case err == nil:
case errors.Is(err, driver.Unchanged):
zlog.Info(ctx).Msg("vulnerability database unchanged")
return nil
default:
return err
}
vulns, err := u.Parse(ctx, vulnDB)
if err != nil {
return fmt.Errorf("failed to parse the fetched vulnerability database: %v", err)
}
ref, err := s.UpdateVulnerabilities(ctx, name, newFP, vulns)
if err != nil {
return fmt.Errorf("failed to update vulnerabilities: %v", err)
}
zlog.Info(ctx).
Str("ref", ref.String()).
Msg("successful update")
return nil
}