-
Notifications
You must be signed in to change notification settings - Fork 26
/
clustercatalog_controller.go
266 lines (239 loc) · 10.4 KB
/
clustercatalog_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
/*
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 core
import (
"context" // #nosec
"errors"
"fmt"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apimacherrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/wait"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log"
"github.com/operator-framework/catalogd/api/core/v1alpha1"
"github.com/operator-framework/catalogd/internal/source"
catalogderrors "github.com/operator-framework/catalogd/pkg/errors"
"github.com/operator-framework/catalogd/pkg/storage"
)
const (
fbcDeletionFinalizer = "catalogd.operatorframework.io/delete-server-cache"
// CatalogSources are polled if PollInterval is mentioned, in intervals of wait.Jitter(pollDuration, maxFactor)
// wait.Jitter returns a time.Duration between pollDuration and pollDuration + maxFactor * pollDuration.
requeueJitterMaxFactor = 0.01
)
// ClusterCatalogReconciler reconciles a Catalog object
type ClusterCatalogReconciler struct {
client.Client
Unpacker source.Unpacker
Storage storage.Instance
}
//+kubebuilder:rbac:groups=catalogd.operatorframework.io,resources=clustercatalogs,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=catalogd.operatorframework.io,resources=clustercatalogs/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=catalogd.operatorframework.io,resources=clustercatalogs/finalizers,verbs=update
//+kubebuilder:rbac:groups=core,resources=pods,verbs=create;update;patch;delete;get;list;watch
//+kubebuilder:rbac:groups=core,resources=pods/log,verbs=get;list;watch
//+kubebuilder:rbac:groups=core,namespace=system,resources=secrets,verbs=get;
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.11.0/pkg/reconcile
func (r *ClusterCatalogReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
// TODO: Where and when should we be logging errors and at which level?
_ = log.FromContext(ctx).WithName("catalogd-controller")
existingCatsrc := v1alpha1.ClusterCatalog{}
if err := r.Client.Get(ctx, req.NamespacedName, &existingCatsrc); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
reconciledCatsrc := existingCatsrc.DeepCopy()
res, reconcileErr := r.reconcile(ctx, reconciledCatsrc)
var unrecov *catalogderrors.Unrecoverable
if errors.As(reconcileErr, &unrecov) {
reconcileErr = nil
}
// Update the status subresource before updating the main object. This is
// necessary because, in many cases, the main object update will remove the
// finalizer, which will cause the core Kubernetes deletion logic to
// complete. Therefore, we need to make the status update prior to the main
// object update to ensure that the status update can be processed before
// a potential deletion.
if !equality.Semantic.DeepEqual(existingCatsrc.Status, reconciledCatsrc.Status) {
if updateErr := r.Client.Status().Update(ctx, reconciledCatsrc); updateErr != nil {
return res, apimacherrors.NewAggregate([]error{reconcileErr, updateErr})
}
}
existingCatsrc.Status, reconciledCatsrc.Status = v1alpha1.ClusterCatalogStatus{}, v1alpha1.ClusterCatalogStatus{}
if !equality.Semantic.DeepEqual(existingCatsrc, reconciledCatsrc) {
if updateErr := r.Client.Update(ctx, reconciledCatsrc); updateErr != nil {
return res, apimacherrors.NewAggregate([]error{reconcileErr, updateErr})
}
}
return res, reconcileErr
}
// SetupWithManager sets up the controller with the Manager.
func (r *ClusterCatalogReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.ClusterCatalog{}).
Owns(&corev1.Pod{}).
Complete(r)
}
// Note: This function always returns ctrl.Result{}. The linter
// fusses about this as we could instead just return error. This was
// discussed in https://github.com/operator-framework/rukpak/pull/635#discussion_r1229859464
// and the consensus was that it is better to keep the ctrl.Result return
// type so that if we do end up needing to return something else we don't forget
// to add the ctrl.Result type back as a return value. Adding a comment to ignore
// linting from the linter that was fussing about this.
// nolint:unparam
func (r *ClusterCatalogReconciler) reconcile(ctx context.Context, catalog *v1alpha1.ClusterCatalog) (ctrl.Result, error) {
if catalog.DeletionTimestamp.IsZero() && !controllerutil.ContainsFinalizer(catalog, fbcDeletionFinalizer) {
controllerutil.AddFinalizer(catalog, fbcDeletionFinalizer)
return ctrl.Result{}, nil
}
if !catalog.DeletionTimestamp.IsZero() {
if err := r.Storage.Delete(catalog.Name); err != nil {
return ctrl.Result{}, updateStatusStorageDeleteError(&catalog.Status, err)
}
if err := r.Unpacker.Cleanup(ctx, catalog); err != nil {
return ctrl.Result{}, updateStatusStorageDeleteError(&catalog.Status, err)
}
controllerutil.RemoveFinalizer(catalog, fbcDeletionFinalizer)
return ctrl.Result{}, nil
}
// if ResolvedSource is not nil, it indicates that this is not the first time we're
// unpacking this catalog.
if catalog.Status.ResolvedSource != nil {
if !unpackAgain(catalog) {
return ctrl.Result{}, nil
}
}
unpackResult, err := r.Unpacker.Unpack(ctx, catalog)
if err != nil {
return ctrl.Result{}, updateStatusUnpackFailing(&catalog.Status, fmt.Errorf("source bundle content: %v", err))
}
switch unpackResult.State {
case source.StatePending:
updateStatusUnpackPending(&catalog.Status, unpackResult)
return ctrl.Result{}, nil
case source.StateUnpacking:
updateStatusUnpacking(&catalog.Status, unpackResult)
return ctrl.Result{}, nil
case source.StateUnpacked:
contentURL := ""
// TODO: We should check to see if the unpacked result has the same content
// as the already unpacked content. If it does, we should skip this rest
// of the unpacking steps.
err := r.Storage.Store(ctx, catalog.Name, unpackResult.FS)
if err != nil {
return ctrl.Result{}, updateStatusStorageError(&catalog.Status, fmt.Errorf("error storing fbc: %v", err))
}
contentURL = r.Storage.ContentURL(catalog.Name)
updateStatusUnpacked(&catalog.Status, unpackResult, contentURL, catalog.Generation)
var requeueAfter time.Duration
switch catalog.Spec.Source.Type {
case v1alpha1.SourceTypeImage:
if catalog.Spec.Source.Image.PollInterval != nil {
requeueAfter = wait.Jitter(catalog.Spec.Source.Image.PollInterval.Duration, requeueJitterMaxFactor)
}
}
return ctrl.Result{RequeueAfter: requeueAfter}, nil
default:
return ctrl.Result{}, updateStatusUnpackFailing(&catalog.Status, fmt.Errorf("unknown unpack state %q: %v", unpackResult.State, err))
}
}
func updateStatusUnpackPending(status *v1alpha1.ClusterCatalogStatus, result *source.Result) {
status.ResolvedSource = nil
status.Phase = v1alpha1.PhasePending
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: v1alpha1.TypeUnpacked,
Status: metav1.ConditionFalse,
Reason: v1alpha1.ReasonUnpackPending,
Message: result.Message,
})
}
func updateStatusUnpacking(status *v1alpha1.ClusterCatalogStatus, result *source.Result) {
status.ResolvedSource = nil
status.Phase = v1alpha1.PhaseUnpacking
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: v1alpha1.TypeUnpacked,
Status: metav1.ConditionFalse,
Reason: v1alpha1.ReasonUnpacking,
Message: result.Message,
})
}
func updateStatusUnpacked(status *v1alpha1.ClusterCatalogStatus, result *source.Result, contentURL string, generation int64) {
status.ResolvedSource = result.ResolvedSource
status.ContentURL = contentURL
status.Phase = v1alpha1.PhaseUnpacked
status.ObservedGeneration = generation
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: v1alpha1.TypeUnpacked,
Status: metav1.ConditionTrue,
Reason: v1alpha1.ReasonUnpackSuccessful,
Message: result.Message,
})
}
func updateStatusUnpackFailing(status *v1alpha1.ClusterCatalogStatus, err error) error {
status.ResolvedSource = nil
status.Phase = v1alpha1.PhaseFailing
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: v1alpha1.TypeUnpacked,
Status: metav1.ConditionFalse,
Reason: v1alpha1.ReasonUnpackFailed,
Message: err.Error(),
})
return err
}
func updateStatusStorageError(status *v1alpha1.ClusterCatalogStatus, err error) error {
status.ResolvedSource = nil
status.Phase = v1alpha1.PhaseFailing
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: v1alpha1.TypeUnpacked,
Status: metav1.ConditionFalse,
Reason: v1alpha1.ReasonStorageFailed,
Message: fmt.Sprintf("failed to store bundle: %s", err.Error()),
})
return err
}
func updateStatusStorageDeleteError(status *v1alpha1.ClusterCatalogStatus, err error) error {
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: v1alpha1.TypeDelete,
Status: metav1.ConditionFalse,
Reason: v1alpha1.ReasonStorageDeleteFailed,
Message: fmt.Sprintf("failed to delete storage: %s", err.Error()),
})
return err
}
func unpackAgain(catalog *v1alpha1.ClusterCatalog) bool {
// if the spec.Source.Image.Ref was changed, unpack the new ref
if catalog.Spec.Source.Image.Ref != catalog.Status.ResolvedSource.Image.Ref {
return true
}
// if pollInterval is nil, don't unpack again
if catalog.Spec.Source.Image.PollInterval == nil {
return false
}
// if it's not time to poll yet, and the CR wasn't changed don't unpack again
nextPoll := catalog.Status.ResolvedSource.Image.LastPollAttempt.Add(catalog.Spec.Source.Image.PollInterval.Duration)
if nextPoll.After(time.Now()) && catalog.Generation == catalog.Status.ObservedGeneration {
return false
}
// time to unpack
return true
}