-
Notifications
You must be signed in to change notification settings - Fork 201
/
io.go
90 lines (73 loc) · 2.34 KB
/
io.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
package vulnerabilityreport
import (
"context"
"github.com/aquasecurity/trivy-operator/pkg/apis/aquasecurity/v1alpha1"
"github.com/aquasecurity/trivy-operator/pkg/kube"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// Writer is the interface that wraps the basic Write method.
//
// Write creates or updates the given slice of v1alpha1.VulnerabilityReport
// instances.
type Writer interface {
Write(context.Context, []v1alpha1.VulnerabilityReport) error
}
// Reader is the interface that wraps methods for finding v1alpha1.VulnerabilityReport objects.
//
// FindByOwner returns the slice of v1alpha1.VulnerabilityReport instances
// owned by the given kube.ObjectRef or an empty slice if the reports are not found.
type Reader interface {
FindByOwner(context.Context, kube.ObjectRef) ([]v1alpha1.VulnerabilityReport, error)
}
type ReadWriter interface {
Reader
Writer
}
type readWriter struct {
*kube.ObjectResolver
}
// NewReadWriter constructs a new ReadWriter which is using the client package
// provided by the controller-runtime libraries for interacting with the
// Kubernetes API server.
func NewReadWriter(objectResolver *kube.ObjectResolver) ReadWriter {
return &readWriter{
ObjectResolver: objectResolver,
}
}
func (r *readWriter) Write(ctx context.Context, reports []v1alpha1.VulnerabilityReport) error {
for _, report := range reports {
err := r.createOrUpdate(ctx, report)
if err != nil {
return err
}
}
return nil
}
func (r *readWriter) createOrUpdate(ctx context.Context, report v1alpha1.VulnerabilityReport) error {
var existing v1alpha1.VulnerabilityReport
err := r.Get(ctx, types.NamespacedName{
Name: report.Name,
Namespace: report.Namespace,
}, &existing)
if err == nil {
copied := existing.DeepCopy()
copied.Labels = report.Labels
copied.Report = report.Report
return r.Update(ctx, copied)
}
if errors.IsNotFound(err) {
return r.Create(ctx, &report)
}
return err
}
func (r *readWriter) FindByOwner(ctx context.Context, owner kube.ObjectRef) ([]v1alpha1.VulnerabilityReport, error) {
var list v1alpha1.VulnerabilityReportList
labels := client.MatchingLabels(kube.ObjectRefToLabels(owner))
err := r.List(ctx, &list, labels, client.InNamespace(owner.Namespace))
if err != nil {
return nil, err
}
return list.DeepCopy().Items, nil
}