/
tokenupload_controller.go
296 lines (251 loc) · 11.2 KB
/
tokenupload_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
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
/*
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"errors"
"fmt"
"time"
"github.com/redhat-appstudio/remote-secret/pkg/metrics"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
kuberrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
api "github.com/redhat-appstudio/remote-secret/api/v1beta1"
"github.com/redhat-appstudio/remote-secret/controllers/remotesecretstorage"
"github.com/redhat-appstudio/remote-secret/pkg/commaseparated"
"github.com/redhat-appstudio/remote-secret/pkg/logs"
)
var uploadSecretSelector = metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: api.UploadSecretLabel,
Values: []string{"remotesecret"},
Operator: metav1.LabelSelectorOpIn,
},
},
}
var remoteSecretDoesntExist = errors.New("remote secret does not exist")
var remoteSecretNilNoError = errors.New("unexpected state: both remote secret and error is nil")
var metricOperationNameLabel = "secret_data_upload"
//+kubebuilder:rbac:groups="",resources=events,verbs=get;list;watch;create;update;delete
//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;watch;create;update;list;delete
//+kubebuilder:rbac:groups=appstudio.redhat.com,resources=remotesecrets,verbs=get;list;watch;create;update;patch;delete
// TokenUploadReconciler reconciles a Secret object
type TokenUploadReconciler struct {
client.Client
Scheme *runtime.Scheme
RemoteSecretStorage remotesecretstorage.RemoteSecretStorage
}
// SetupWithManager sets up the controller with the Manager.
func (r *TokenUploadReconciler) SetupWithManager(mgr ctrl.Manager) error {
pred, err := predicate.LabelSelectorPredicate(uploadSecretSelector)
if err != nil {
return fmt.Errorf("failed to construct the predicate for matching secrets. This should not happen: %w", err)
}
if err := ctrl.NewControllerManagedBy(mgr).
For(&corev1.Secret{}, builder.WithPredicates(pred)).
Complete(r); err != nil {
err = fmt.Errorf("failed to build the controller manager: %w", err)
return err
}
return nil
}
func (r *TokenUploadReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lg := log.FromContext(ctx)
lg.V(logs.DebugLevel).Info("starting reconciliation")
defer logs.TimeTrackWithLazyLogger(func() logr.Logger { return lg }, time.Now(), "Reconcile Upload Secret")
uploadSecret := &corev1.Secret{}
if err := r.Get(ctx, req.NamespacedName, uploadSecret); err != nil {
if kuberrors.IsNotFound(err) {
lg.V(logs.DebugLevel).Info("upload secret already gone from the cluster. skipping reconciliation")
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to load the upload secret from the cluster: %w", err)
}
if uploadSecret.DeletionTimestamp != nil {
lg.V(logs.DebugLevel).Info("upload secret is being deleted. skipping reconciliation")
return ctrl.Result{}, nil
}
// We first find/create the RemoteSecret since we need it to store the data. Only after we have stored the data
// in secretStorage can we delete the uploadSecret. The deletion triggers RS reconciliation in which the data is
// fetched from the storage and propagated to the targets by RS controller.
err := r.reconcileRemoteSecret(ctx, uploadSecret)
// we immediately delete the Secret
delErr := r.Delete(ctx, uploadSecret)
if delErr != nil {
// We failed to delete the secret, so we error out so that we can try again in the next reconciliation round.
// We therefore also DON'T create the error event in this case like we do later on in this method.
return ctrl.Result{}, fmt.Errorf("cannot delete the Secret: %w", err)
}
// NOTE: it is useless to return any error to the controller runtime after this point, because we just
// deleted the secret that is being reconciled and so its repeated reconciliation would short-circuit
// on the non-nil DeletionTimestamp. Therefore, in case of errors, we just create the error event and
// return a "success" to the controller runtime.
if err != nil {
r.createErrorEvent(ctx, uploadSecret, err, lg)
} else {
r.tryDeleteEvent(ctx, uploadSecret.Name, req.Namespace, lg)
}
return ctrl.Result{}, nil
}
func (r *TokenUploadReconciler) reconcileRemoteSecret(ctx context.Context, uploadSecret *corev1.Secret) error {
_, partialUpdate := uploadSecret.Annotations[api.RemoteSecretPartialUpdateAnnotation]
auditLog := logs.AuditLog(ctx).WithValues("partialUpdate", partialUpdate)
auditLog.Info("reconciling upload secret")
remoteSecret, err := r.findRemoteSecret(ctx, uploadSecret)
if err != nil {
metrics.UploadRejectionsCounter.WithLabelValues(metricOperationNameLabel, "find_remote_secret_failed").Inc()
return fmt.Errorf("attempt to find the remote secret failed: %w", err)
}
if !partialUpdate && remoteSecret == nil {
remoteSecret, err = r.createRemoteSecret(ctx, uploadSecret)
if err != nil {
metrics.UploadRejectionsCounter.WithLabelValues(metricOperationNameLabel, "create_remote_secret_failed").Inc()
return fmt.Errorf("failed to create the remote secret: %w", err)
}
}
// When we're doing the full upload, the remote secret is created if it doesn't exist.
// When we're doing a partial update, the remote secret is not created though, and therefore
// we need to check that we have a remote secret to work with here before continuing.
if remoteSecret == nil {
return remoteSecretDoesntExist
}
auditLog = auditLog.WithValues("remoteSecret", client.ObjectKeyFromObject(remoteSecret))
if partialUpdate {
auditLog.Info("manual secret partial update initiated", "action", "UPDATE")
keysToDelete := commaseparated.Value(uploadSecret.Annotations[api.RemoteSecretDeletedKeysAnnotation]).Values()
if err = r.RemoteSecretStorage.PartialUpdate(ctx, remoteSecret, &uploadSecret.Data, keysToDelete); err != nil {
err = fmt.Errorf("failed to partially update the secret data: %w", err)
auditLog.Error(err, "manual secret partial update failed")
return err
}
auditLog.Info("manual secret partial update completed")
} else {
err = remoteSecret.ValidateUploadSecret(uploadSecret)
if err != nil {
auditLog.Info("manual secret upload not started because of invalid upload secret")
metrics.UploadRejectionsCounter.WithLabelValues(metricOperationNameLabel, "invalid_upload_secret").Inc()
return fmt.Errorf("validation of upload secret failed: %w ", err)
}
auditLog.Info("manual secret upload initiated", "action", "UPDATE")
if err = r.RemoteSecretStorage.Store(ctx, remoteSecret, &uploadSecret.Data); err != nil {
err = fmt.Errorf("failed to store the remote secret data: %w", err)
metrics.UploadRejectionsCounter.WithLabelValues(metricOperationNameLabel, "storage_write_failed").Inc()
auditLog.Error(err, "manual secret upload failed")
return err
}
auditLog.Info("manual secret upload completed")
}
return nil
}
// reports error in both Log and Event in current Namespace
func (r *TokenUploadReconciler) createErrorEvent(ctx context.Context, secret *corev1.Secret, err error, lg logr.Logger) {
r.tryDeleteEvent(ctx, secret.Name, secret.Namespace, lg)
secretErrEvent := &corev1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: secret.Name,
Namespace: secret.Namespace,
},
Message: err.Error(),
Reason: "cannot process upload secret",
InvolvedObject: corev1.ObjectReference{Namespace: secret.Namespace, Name: secret.Name, Kind: secret.Kind, APIVersion: secret.APIVersion},
Type: "Error",
LastTimestamp: metav1.NewTime(time.Now()),
}
err = r.Create(ctx, secretErrEvent)
if err != nil {
lg.Error(err, "event creation failed for upload secret")
}
}
// Contract: having exactly one event if upload failed and no events if uploaded.
// For this need to delete the event every attempt
func (r *TokenUploadReconciler) tryDeleteEvent(ctx context.Context, secretName string, ns string, lg logr.Logger) {
stored := &corev1.Event{}
err := r.Get(ctx, types.NamespacedName{Name: secretName, Namespace: ns}, stored)
if err == nil {
lg.V(logs.DebugLevel).Info("event found and will be deleted", "event.name", stored.Name)
err = r.Delete(ctx, stored)
if err != nil {
lg.Error(err, "can not delete event")
}
}
}
func (r *TokenUploadReconciler) findRemoteSecret(ctx context.Context, uploadSecret *corev1.Secret) (*api.RemoteSecret, error) {
lg := log.FromContext(ctx)
remoteSecretName := uploadSecret.Annotations[api.RemoteSecretNameAnnotation]
if remoteSecretName == "" {
lg.V(logs.DebugLevel).Info("No remoteSecretName found, will try to create with generated ")
return nil, nil
}
remoteSecret := api.RemoteSecret{}
err := r.Get(ctx, types.NamespacedName{Name: remoteSecretName, Namespace: uploadSecret.Namespace}, &remoteSecret)
if err != nil {
if kuberrors.IsNotFound(err) {
lg.V(logs.DebugLevel).Info("RemoteSecret NOT found, will try to create ", "RemoteSecret.name", remoteSecret.Name)
return nil, nil
} else {
return nil, fmt.Errorf("can not find RemoteSecret %s: %w ", remoteSecretName, err)
}
} else {
lg.V(logs.DebugLevel).Info("RemoteSecret found : ", "RemoteSecret.name", remoteSecret.Name)
return &remoteSecret, nil
}
}
func (r *TokenUploadReconciler) createRemoteSecret(ctx context.Context, uploadSecret *corev1.Secret) (*api.RemoteSecret, error) {
lg := log.FromContext(ctx)
remoteSecret := api.RemoteSecret{
ObjectMeta: metav1.ObjectMeta{
Namespace: uploadSecret.Namespace,
},
Spec: api.RemoteSecretSpec{},
}
targetName, ok := uploadSecret.Annotations[api.TargetNamespaceAnnotation]
if ok {
targetSpec := api.RemoteSecretTarget{}
targetSpec.Namespace = targetName
remoteSecret.Spec.Targets = []api.RemoteSecretTarget{targetSpec}
}
remoteSecretName := uploadSecret.Annotations[api.RemoteSecretNameAnnotation]
if remoteSecretName == "" {
remoteSecret.GenerateName = "generated-"
} else {
remoteSecret.Name = remoteSecretName
}
err := r.Create(ctx, &remoteSecret)
if err == nil {
lg.V(logs.DebugLevel).Info("RemoteSecret created : ", "RemoteSecret.name", remoteSecret.Name, "targetName", targetName)
return &remoteSecret, nil
} else {
if kuberrors.IsAlreadyExists(err) {
rs, findErr := r.findRemoteSecret(ctx, uploadSecret)
if rs == nil {
if findErr != nil {
return nil, fmt.Errorf("can not find existing RemoteSecret %s. Reason: %w", remoteSecret.Name, findErr)
} else {
return nil, fmt.Errorf("RemoteSecret: %s. Reason: %w", remoteSecret.Name, remoteSecretNilNoError)
}
} else {
return rs, nil
}
}
return nil, fmt.Errorf("can not create RemoteSecret %s. Reason: %w", remoteSecret.Name, err)
}
}