-
Notifications
You must be signed in to change notification settings - Fork 30
/
controller.go
205 lines (178 loc) · 8.08 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
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
/*
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 watcher
import (
"context"
"errors"
"fmt"
apimetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
machineryruntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"github.com/kyma-project/lifecycle-manager/api/shared"
"github.com/kyma-project/lifecycle-manager/api/v1beta2"
"github.com/kyma-project/lifecycle-manager/internal/event"
"github.com/kyma-project/lifecycle-manager/internal/istio"
"github.com/kyma-project/lifecycle-manager/pkg/log"
"github.com/kyma-project/lifecycle-manager/pkg/queue"
"github.com/kyma-project/lifecycle-manager/pkg/status"
"github.com/kyma-project/lifecycle-manager/pkg/util"
)
const (
addFinalizerFailure event.Reason = "AddFinalizerErr"
updateFinalizerFailure event.Reason = "WatcherFinalizerErr"
gatewayNotFoundFailure event.Reason = "WatcherGatewayNotFound"
watcherStatusUpdateFailure event.Reason = "WatcherStatusUpdate"
)
var (
errFinalizerRemove = errors.New("error removing finalizer")
errFinalizerAdd = errors.New("error adding finalizer")
errGateway = errors.New("gateway for the VirtualService not found")
)
type Reconciler struct {
client.Client
event.Event
IstioClient *istio.Client
VirtualServiceFactory istio.VirtualServiceFactory
RestConfig *rest.Config
Scheme *machineryruntime.Scheme
IstioGatewayNamespace string
queue.RequeueIntervals
}
// +kubebuilder:rbac:groups=operator.kyma-project.io,resources=watchers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=operator.kyma-project.io,resources=watchers/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=operator.kyma-project.io,resources=watchers/finalizers,verbs=update
// +kubebuilder:rbac:groups=networking.istio.io,resources=virtualservices,verbs=get;list;create;update;delete
// +kubebuilder:rbac:groups=networking.istio.io,resources=gateways,verbs=list;get;
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;delete
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := logf.FromContext(ctx).WithName(req.NamespacedName.String())
logger.V(log.DebugLevel).Info("Reconciliation loop starting")
watcher := &v1beta2.Watcher{}
if err := r.Get(ctx, client.ObjectKey{Name: req.Name, Namespace: req.Namespace}, watcher); err != nil {
logger.V(log.DebugLevel).Info("Failed to get reconciliation object")
if !util.IsNotFound(err) {
return ctrl.Result{}, fmt.Errorf("watcherController: %w", err)
}
return ctrl.Result{Requeue: false}, nil
}
if !watcher.DeletionTimestamp.IsZero() && watcher.Status.State != shared.StateDeleting {
return r.updateWatcherState(ctx, watcher, shared.StateDeleting, nil)
}
if !controllerutil.ContainsFinalizer(watcher, shared.WatcherFinalizer) {
if !controllerutil.AddFinalizer(watcher, shared.WatcherFinalizer) {
r.Event.Warning(watcher, addFinalizerFailure, errFinalizerAdd)
return ctrl.Result{}, errFinalizerAdd
}
return ctrl.Result{Requeue: true}, r.updateFinalizer(ctx, watcher)
}
watcher.InitializeConditions()
return r.stateHandling(ctx, watcher)
}
func (r *Reconciler) updateFinalizer(ctx context.Context, watcher *v1beta2.Watcher) error {
err := r.Client.Update(ctx, watcher)
if err != nil {
r.Event.Warning(watcher, updateFinalizerFailure, err)
return fmt.Errorf("failed to update finalizer: %w", err)
}
return nil
}
func (r *Reconciler) stateHandling(ctx context.Context, watcher *v1beta2.Watcher) (ctrl.Result, error) {
switch watcher.Status.State {
case "":
return r.updateWatcherState(ctx, watcher, shared.StateProcessing, nil)
case shared.StateProcessing:
return r.handleProcessingState(ctx, watcher)
case shared.StateDeleting:
return r.handleDeletingState(ctx, watcher)
case shared.StateError:
return r.handleProcessingState(ctx, watcher)
case shared.StateReady, shared.StateWarning:
return r.handleProcessingState(ctx, watcher)
case shared.StateUnmanaged:
return ctrl.Result{}, nil // no requeue of invalid state
}
return ctrl.Result{Requeue: false}, nil
}
func (r *Reconciler) handleDeletingState(ctx context.Context, watcher *v1beta2.Watcher) (ctrl.Result, error) {
err := r.IstioClient.DeleteVirtualService(ctx, watcher.GetName(), watcher.GetNamespace())
if err != nil && !util.IsNotFound(err) {
vsConfigDelErr := fmt.Errorf("failed to delete virtual service (config): %w", err)
return r.updateWatcherState(ctx, watcher, shared.StateError, vsConfigDelErr)
}
finalizerRemoved := controllerutil.RemoveFinalizer(watcher, shared.WatcherFinalizer)
if !finalizerRemoved {
return r.updateWatcherState(ctx, watcher, shared.StateError, errFinalizerRemove)
}
return ctrl.Result{Requeue: true}, r.updateFinalizer(ctx, watcher)
}
func (r *Reconciler) handleProcessingState(ctx context.Context, watcherCR *v1beta2.Watcher) (ctrl.Result, error) {
gateways, err := r.IstioClient.ListGatewaysByLabelSelector(ctx, &watcherCR.Spec.Gateway.LabelSelector,
r.IstioGatewayNamespace)
if err != nil || len(gateways.Items) == 0 {
r.Event.Warning(watcherCR, gatewayNotFoundFailure, errGateway)
return r.updateWatcherState(ctx, watcherCR, shared.StateError, err)
}
virtualSvc, err := r.VirtualServiceFactory.NewVirtualService(watcherCR, gateways)
if err != nil {
return r.updateWatcherState(ctx, watcherCR, shared.StateError, err)
}
virtualSvcRemote, err := r.IstioClient.GetVirtualService(ctx, watcherCR.GetName(), watcherCR.GetNamespace())
if client.IgnoreNotFound(err) != nil {
return r.updateWatcherState(ctx, watcherCR, shared.StateError, err)
}
if util.IsNotFound(err) {
err = r.IstioClient.CreateVirtualService(ctx, virtualSvc)
if err != nil {
vsCreateErr := fmt.Errorf("failed to create virtual service: %w", err)
return r.updateWatcherState(ctx, watcherCR, shared.StateError, vsCreateErr)
}
return r.updateWatcherState(ctx, watcherCR, shared.StateReady, nil)
}
err = r.IstioClient.UpdateVirtualService(ctx, virtualSvc, virtualSvcRemote)
if err != nil {
vsUpdateErr := fmt.Errorf("failed to update virtual service: %w", err)
return r.updateWatcherState(ctx, watcherCR, shared.StateError, vsUpdateErr)
}
return r.updateWatcherState(ctx, watcherCR, shared.StateReady, nil)
}
func (r *Reconciler) updateWatcherState(ctx context.Context, watcher *v1beta2.Watcher, state shared.State,
err error,
) (ctrl.Result, error) {
watcher.Status.State = state
if state == shared.StateReady {
watcher.UpdateWatcherConditionStatus(v1beta2.WatcherConditionTypeVirtualService, apimetav1.ConditionTrue)
} else if state == shared.StateError {
watcher.UpdateWatcherConditionStatus(v1beta2.WatcherConditionTypeVirtualService, apimetav1.ConditionFalse)
}
if err != nil {
r.Event.Warning(watcher, watcherStatusUpdateFailure, err)
}
requeueInterval := queue.DetermineRequeueInterval(state, r.RequeueIntervals)
return ctrl.Result{RequeueAfter: requeueInterval}, r.updateWatcherStatusUsingSSA(ctx, watcher)
}
func (r *Reconciler) updateWatcherStatusUsingSSA(ctx context.Context, watcher *v1beta2.Watcher) error {
watcher.ManagedFields = nil
err := r.Client.Status().Patch(ctx, watcher, client.Apply, client.FieldOwner(shared.OperatorName),
status.SubResourceOpts(client.ForceOwnership))
if err != nil {
err = fmt.Errorf("watcher status update failed: %w", err)
r.Event.Warning(watcher, watcherStatusUpdateFailure, err)
return err
}
return nil
}