/
cpolr.go
336 lines (283 loc) · 10.3 KB
/
cpolr.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
package api
import (
"context"
"fmt"
"slices"
"strconv"
"github.com/kyverno/reports-server/pkg/storage"
errorpkg "github.com/pkg/errors"
"k8s.io/apimachinery/pkg/api/errors"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/klog/v2"
"sigs.k8s.io/wg-policy-prototypes/policy-report/pkg/api/wgpolicyk8s.io/v1alpha2"
)
type cpolrStore struct {
broadcaster *watch.Broadcaster
store storage.Interface
}
func ClusterPolicyReportStore(store storage.Interface) API {
broadcaster := watch.NewBroadcaster(1000, watch.WaitIfChannelFull)
return &cpolrStore{
broadcaster: broadcaster,
store: store,
}
}
func (c *cpolrStore) New() runtime.Object {
return &v1alpha2.ClusterPolicyReport{}
}
func (c *cpolrStore) Destroy() {
}
func (c *cpolrStore) Kind() string {
return "ClusterPolicyReport"
}
func (c *cpolrStore) NewList() runtime.Object {
return &v1alpha2.ClusterPolicyReportList{}
}
func (c *cpolrStore) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
labelSelector := labels.Everything()
// fieldSelector := fields.Everything() // TODO: Field selectors
if options != nil {
if options.LabelSelector != nil {
labelSelector = options.LabelSelector
}
// if options.FieldSelector != nil {
// fieldSelector = options.FieldSelector
// }
}
klog.Infof("listing all cluster policy reports")
list, err := c.listCpolr()
if err != nil {
return nil, errors.NewBadRequest("failed to list resource clusterpolicyreport")
}
// if labelSelector.String() == labels.Everything().String() {
// return list, nil
// }
cpolrList := &v1alpha2.ClusterPolicyReportList{
Items: make([]v1alpha2.ClusterPolicyReport, 0),
}
for _, cpolr := range list.Items {
if cpolr.Labels == nil {
return list, nil
}
if labelSelector.Matches(labels.Set(cpolr.Labels)) {
cpolrList.Items = append(cpolrList.Items, cpolr)
}
}
return cpolrList, nil
}
func (c *cpolrStore) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
klog.Infof("fetching cluster policy report name=%s", name)
report, err := c.getCpolr(name)
if err != nil || report == nil {
return nil, errors.NewNotFound(v1alpha2.Resource("clusterpolicyreports"), name)
}
return report, nil
}
func (c *cpolrStore) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
isDryRun := slices.Contains(options.DryRun, "All")
err := createValidation(ctx, obj)
if err != nil {
switch options.FieldValidation {
case "Ignore":
case "Warn":
// return &admissionv1.AdmissionResponse{
// Allowed: false,
// Warnings: []string{err.Error()},
// }, nil
case "Strict":
return nil, err
}
}
cpolr, ok := obj.(*v1alpha2.ClusterPolicyReport)
if !ok {
return nil, errors.NewBadRequest("failed to validate cluster policy report")
}
klog.Infof("creating cluster policy report name=%s", cpolr.Name)
if !isDryRun {
if err := c.createCpolr(cpolr); err != nil {
return nil, errors.NewBadRequest(fmt.Sprintf("cannot create cluster policy report: %s", err.Error()))
}
if err := c.broadcaster.Action(watch.Added, obj); err != nil {
klog.ErrorS(err, "failed to broadcast event")
}
}
return obj, nil
}
func (c *cpolrStore) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
isDryRun := slices.Contains(options.DryRun, "All")
if forceAllowCreate {
oldObj, _ := c.getCpolr(name)
updatedObject, _ := objInfo.UpdatedObject(ctx, oldObj)
cpolr := updatedObject.(*v1alpha2.ClusterPolicyReport)
if err := c.updateCpolr(cpolr, true); err != nil {
klog.ErrorS(err, "failed to update resource")
}
if err := c.broadcaster.Action(watch.Added, updatedObject); err != nil {
klog.ErrorS(err, "failed to broadcast event")
}
return updatedObject, true, nil
}
oldObj, err := c.getCpolr(name)
if err != nil {
return nil, false, err
}
updatedObject, err := objInfo.UpdatedObject(ctx, oldObj)
if err != nil {
return nil, false, err
}
err = updateValidation(ctx, updatedObject, oldObj)
if err != nil {
switch options.FieldValidation {
case "Ignore":
case "Warn":
// return &admissionv1.AdmissionResponse{
// Allowed: false,
// Warnings: []string{err.Error()},
// }, nil
case "Strict":
return nil, false, err
}
}
cpolr, ok := updatedObject.(*v1alpha2.ClusterPolicyReport)
if !ok {
return nil, false, errors.NewBadRequest("failed to validate cluster policy report")
}
klog.Infof("updating cluster policy report name=%s", cpolr.Name)
if !isDryRun {
if err := c.updateCpolr(cpolr, false); err != nil {
return nil, false, errors.NewBadRequest(fmt.Sprintf("cannot create cluster policy report: %s", err.Error()))
}
if err := c.broadcaster.Action(watch.Modified, updatedObject); err != nil {
klog.ErrorS(err, "failed to broadcast event")
}
}
return updatedObject, true, nil
}
func (c *cpolrStore) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {
isDryRun := slices.Contains(options.DryRun, "All")
cpolr, err := c.getCpolr(name)
if err != nil {
klog.ErrorS(err, "Failed to find cpolrs", "name", name)
return nil, false, errors.NewNotFound(v1alpha2.Resource("clusterpolicyreports"), name)
}
err = deleteValidation(ctx, cpolr)
if err != nil {
klog.ErrorS(err, "invalid resource", "name", name)
return nil, false, errors.NewBadRequest(fmt.Sprintf("invalid resource: %s", err.Error()))
}
klog.Infof("deleting cluster policy report name=%s", cpolr.Name)
if !isDryRun {
if err = c.deleteCpolr(cpolr); err != nil {
klog.ErrorS(err, "failed to delete cpolr", "name", name)
return nil, false, errors.NewBadRequest(fmt.Sprintf("failed to delete clusterpolicyreport: %s", err.Error()))
}
if err := c.broadcaster.Action(watch.Deleted, cpolr); err != nil {
klog.ErrorS(err, "failed to broadcast event")
}
}
return cpolr, true, nil // TODO: Add protobuf in wgpolicygroup
}
func (c *cpolrStore) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) {
isDryRun := slices.Contains(options.DryRun, "All")
obj, err := c.List(ctx, listOptions)
if err != nil {
klog.ErrorS(err, "Failed to find cpolrs")
return nil, errors.NewBadRequest("Failed to find cluster policy reports")
}
cpolrList, ok := obj.(*v1alpha2.ClusterPolicyReportList)
if !ok {
klog.ErrorS(err, "Failed to parse cpolrs")
return nil, errors.NewBadRequest("Failed to parse cluster policy reports")
}
if !isDryRun {
for _, cpolr := range cpolrList.Items {
obj, isDeleted, err := c.Delete(ctx, cpolr.GetName(), deleteValidation, options)
if !isDeleted {
klog.ErrorS(err, "Failed to delete cpolr", "name", cpolr.GetName())
return nil, errors.NewBadRequest(fmt.Sprintf("Failed to delete cluster policy report: %s", cpolr.GetName()))
}
if err := c.broadcaster.Action(watch.Deleted, obj); err != nil {
klog.ErrorS(err, "failed to broadcast event")
}
}
}
return cpolrList, nil
}
func (c *cpolrStore) Watch(ctx context.Context, _ *metainternalversion.ListOptions) (watch.Interface, error) {
return c.broadcaster.Watch()
}
func (c *cpolrStore) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1beta1.Table, error) {
var table metav1beta1.Table
switch t := object.(type) {
case *v1alpha2.ClusterPolicyReport:
table.ResourceVersion = t.ResourceVersion
table.SelfLink = t.SelfLink //nolint:staticcheck // keep deprecated field to be backward compatible
addClusterPolicyReportToTable(&table, *t)
case *v1alpha2.ClusterPolicyReportList:
table.ResourceVersion = t.ResourceVersion
table.SelfLink = t.SelfLink //nolint:staticcheck // keep deprecated field to be backward compatible
table.Continue = t.Continue
addClusterPolicyReportToTable(&table, t.Items...)
default:
}
return &table, nil
}
func (c *cpolrStore) NamespaceScoped() bool {
return false
}
func (c *cpolrStore) GetSingularName() string {
return "clusterpolicyreport"
}
func (c *cpolrStore) ShortNames() []string {
return []string{"cpolr"}
}
func (c *cpolrStore) getCpolr(name string) (*v1alpha2.ClusterPolicyReport, error) {
val, err := c.store.ClusterPolicyReports().Get(context.TODO(), name)
if err != nil {
return nil, errorpkg.Wrapf(err, "could not find cluster policy report in store")
}
return val.DeepCopy(), nil
}
func (c *cpolrStore) listCpolr() (*v1alpha2.ClusterPolicyReportList, error) {
valList, err := c.store.ClusterPolicyReports().List(context.TODO())
if err != nil {
return nil, errorpkg.Wrapf(err, "could not find cluster policy report in store")
}
reportList := &v1alpha2.ClusterPolicyReportList{
Items: valList,
}
klog.Infof("value found of length:%d", len(reportList.Items))
return reportList, nil
}
func (c *cpolrStore) createCpolr(report *v1alpha2.ClusterPolicyReport) error {
report.ResourceVersion = fmt.Sprint(1)
report.UID = uuid.NewUUID()
report.CreationTimestamp = metav1.Now()
return c.store.ClusterPolicyReports().Create(context.TODO(), *report)
}
func (c *cpolrStore) updateCpolr(report *v1alpha2.ClusterPolicyReport, force bool) error {
if !force {
oldReport, err := c.getCpolr(report.GetName())
if err != nil {
return errorpkg.Wrapf(err, "old cluster policy report not found")
}
oldRV, err := strconv.ParseInt(oldReport.ResourceVersion, 10, 64)
if err != nil {
return errorpkg.Wrapf(err, "could not parse resource version")
}
report.ResourceVersion = fmt.Sprint(oldRV + 1)
} else {
report.ResourceVersion = "1"
}
return c.store.ClusterPolicyReports().Update(context.TODO(), *report)
}
func (c *cpolrStore) deleteCpolr(report *v1alpha2.ClusterPolicyReport) error {
return c.store.ClusterPolicyReports().Delete(context.TODO(), report.Name)
}