forked from kyma-project/kyma
/
reconcile.go
311 lines (280 loc) · 14 KB
/
reconcile.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
package subscription
import (
"context"
eventingv1alpha1 "github.com/kyma-project/kyma/components/event-bus/api/push/eventing.kyma-project.io/v1alpha1"
"github.com/kyma-project/kyma/components/event-bus/internal/knative/metrics"
"github.com/kyma-project/kyma/components/event-bus/internal/knative/subscription/opts"
"github.com/kyma-project/kyma/components/event-bus/internal/knative/util"
eventBusUtil "github.com/kyma-project/kyma/components/event-bus/pkg/util"
"github.com/prometheus/client_golang/prometheus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
const (
// Name of the corev1.Events emitted from the reconciliation process
subReconciled = "SubscriptionReconciled"
subReconcileFailed = "SubscriptionReconcileFailed"
// Finalizer for deleting Knative Subscriptions
finalizerName = "subscription.finalizers.kyma-project.io"
subscriptionSourceID = "kyma-source-id"
subscriptionEventType = "kyma-event-type"
subscriptionEventTypeVersion = "kyma-event-type-version"
)
type reconciler struct {
client client.Client
recorder record.EventRecorder
knativeLib util.KnativeAccessLib
opts *opts.Options
time util.CurrentTime
}
// Verify the struct implements reconcile.Reconciler
var _ reconcile.Reconciler = &reconciler{}
func (r *reconciler) InjectClient(c client.Client) error {
r.client = c
return nil
}
func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) {
log.Info("Reconcile: ", "request", request)
ctx := context.TODO()
// Fetch the Subscription instance
subscription := &eventingv1alpha1.Subscription{}
KymaSubscriptionsGauge := metrics.KymaSubscriptionsGaugeObj
err := r.client.Get(ctx, request.NamespacedName, subscription)
// The Subscription may have been deleted since it was added to the work queue. If
// so, there is nothing to be done.
if errors.IsNotFound(err) {
log.Info("Could not find Subscription: ", "err", err)
return reconcile.Result{}, nil
}
// Any other error should be retried in another reconciliation.
if err != nil {
log.Error(err, "Unable to Get Subscription object")
return reconcile.Result{}, err
}
log.Info("Reconciling Subscription", "UID", string(subscription.ObjectMeta.UID))
subscription = subscription.DeepCopy()
requeue, reconcileErr := r.reconcile(ctx, subscription, KymaSubscriptionsGauge)
if reconcileErr != nil {
log.Error(reconcileErr, "Reconciling Subscription")
if err := util.SetNotReadySubscription(ctx, r.client, subscription, r.time); err != nil {
log.Error(err, "SetNotReadySubscription() failed for the subscription:", "subscription", subscription)
}
r.recorder.Eventf(subscription, corev1.EventTypeWarning, subReconcileFailed, "Subscription reconciliation failed: %v", err)
} else if !requeue {
// the work was done without errors
if !subscription.ObjectMeta.DeletionTimestamp.IsZero() {
// subscription is marked for deletion, all the work was done
r.recorder.Eventf(subscription, corev1.EventTypeNormal, subReconciled,
"Subscription reconciled and deleted, name: %q; namespace: %q", subscription.Name, subscription.Namespace)
} else if util.IsSubscriptionActivated(subscription) {
// reconcile finished with no errors
if err := util.SetReadySubscription(ctx, r.client, subscription, "", r.time); err != nil {
log.Error(err, "SetReadySubscription() failed for the subscription:", "subscription", subscription)
reconcileErr = err
} else {
KymaSubscriptionsGauge.DeleteKymaSubscriptionsGaugeLabelValues(subscription.Namespace, subscription.Name)
KymaSubscriptionsGauge.Metric.With(prometheus.Labels{
metrics.Namespace: subscription.Namespace,
metrics.Name: subscription.Name,
metrics.Ready: "true"}).Set(1)
log.Info("Subscription reconciled")
r.recorder.Eventf(subscription, corev1.EventTypeNormal, subReconciled,
"Subscription reconciled, name: %q; namespace: %q", subscription.Name, subscription.Namespace)
}
} else {
// reconcile finished with no errors, but subscription is not activated
if err := util.SetNotReadySubscription(ctx, r.client, subscription, r.time); err != nil {
log.Error(err, "SetNotReadySubscription() failed for the subscription:", "subscription", subscription)
reconcileErr = err
} else {
KymaSubscriptionsGauge.DeleteKymaSubscriptionsGaugeLabelValues(subscription.Namespace, subscription.Name)
KymaSubscriptionsGauge.Metric.With(prometheus.Labels{metrics.Namespace: subscription.Namespace,
metrics.Name: subscription.Name,
metrics.Ready: "false"}).Set(1)
log.Info("Subscription reconciled")
r.recorder.Eventf(subscription, corev1.EventTypeNormal, subReconciled,
"Subscription reconciled, name: %q; namespace: %q", subscription.Name, subscription.Namespace)
}
}
}
return reconcile.Result{
Requeue: requeue,
}, reconcileErr
}
func (r *reconciler) reconcile(ctx context.Context, subscription *eventingv1alpha1.Subscription,
KymaSubscriptionsGauge *metrics.SubscriptionsGauge) (bool, error) {
knativeSubscriptionsGauge := metrics.KnativeSubscriptionsGaugeObj
knativeChannelGauge := metrics.KnativeChanelGaugeObj
knativeSubsName := util.GetKnSubscriptionName(&subscription.Name, &subscription.Namespace)
knativeSubsNamespace := util.GetDefaultChannelNamespace()
knativeSubsURI := subscription.Endpoint
knativeChannelName := eventBusUtil.GetChannelName(&subscription.SourceID, &subscription.EventType, &subscription.EventTypeVersion)
knativeChannelProvisioner := "natss"
timeout := r.opts.ChannelTimeout
if subscription.ObjectMeta.DeletionTimestamp.IsZero() {
// The object is not being deleted, so if it does not have our finalizer,
// then lets add the finalizer and update the object.
if !util.ContainsString(&subscription.ObjectMeta.Finalizers, finalizerName) {
subscription.ObjectMeta.Finalizers = append(subscription.ObjectMeta.Finalizers, finalizerName)
err := util.WriteSubscription(context.Background(), r.client, subscription)
if err == nil {
return true, nil
}
return false, err
}
} else {
// The object is being deleted
KymaSubscriptionsGauge.DeleteKymaSubscriptionsGaugeLabelValues(subscription.Namespace, subscription.Name)
if util.ContainsString(&subscription.ObjectMeta.Finalizers, finalizerName) {
// our finalizer is present, so lets handle our external dependency
if err := r.deleteExternalDependency(ctx, knativeSubsName, knativeChannelName, knativeSubsNamespace,
subscription.Name, knativeSubscriptionsGauge, knativeChannelGauge); err != nil {
// if fail to delete the external dependency here, return with error
// so that it can be retried
return false, err
}
// remove our finalizer from the list and update it.
subscription.ObjectMeta.Finalizers = util.RemoveString(&subscription.ObjectMeta.Finalizers, finalizerName)
if err := util.WriteSubscription(context.Background(), r.client, subscription); err != nil {
return false, err
}
}
// Our finalizer has finished, so the reconciler can do nothing.
return false, nil
}
// Check if Kyma Subscription has events-activated condition.
if subscription.HasCondition(eventingv1alpha1.SubscriptionCondition{Type: eventingv1alpha1.EventsActivated, Status: eventingv1alpha1.ConditionTrue}) {
// Check if Knative Channel already exists, create if not.
_, err := r.knativeLib.GetChannel(knativeChannelName, knativeSubsNamespace)
if err != nil && !errors.IsNotFound(err) {
return false, err
} else if errors.IsNotFound(err) {
//Adding the event-metadata as channel labels
knativeChannelLabels := make(map[string]string)
knativeChannelLabels[subscriptionSourceID] = subscription.SourceID
knativeChannelLabels[subscriptionEventType] = subscription.EventType
knativeChannelLabels[subscriptionEventTypeVersion] = subscription.EventTypeVersion
knativeChannel, err := r.knativeLib.CreateChannel(knativeChannelProvisioner, knativeChannelName,
knativeSubsNamespace, &knativeChannelLabels, timeout)
if err != nil {
return false, err
}
log.Info("Knative Channel is created", "Channel", knativeChannel)
}
knativeChannelGauge.Metric.With(prometheus.Labels{metrics.Name: subscription.Name}).Set(1)
log.Info("Knative channel gauge is created:", "subscription", subscription.Name)
// Check if Knative Subscription already exists, if not create one.
sub, err := r.knativeLib.GetSubscription(knativeSubsName, knativeSubsNamespace)
if err != nil && !errors.IsNotFound(err) {
return false, err
} else if errors.IsNotFound(err) {
err = r.knativeLib.CreateSubscription(knativeSubsName, knativeSubsNamespace, knativeChannelName, &knativeSubsURI)
if err != nil {
return false, err
}
knativeSubscriptionsGauge.DeleteKnativeSubscriptionsGaugeLabelValues(subscription.Namespace, subscription.Name)
knativeSubscriptionsGauge.Metric.With(prometheus.Labels{
metrics.Namespace: subscription.Namespace,
metrics.Name: subscription.Name,
metrics.Ready: "true"}).Set(1)
log.Info("Knative Subscription is created", "Subscription", knativeSubsName)
} else {
// In case there is a change in Channel name or URI, delete and re-create Knative Subscription because update does not work.
if knativeChannelName != sub.Spec.Channel.Name || knativeSubsURI != *sub.Spec.Subscriber.DNSName {
err = r.knativeLib.DeleteSubscription(knativeSubsName, knativeSubsNamespace)
if err != nil {
return false, err
}
log.Info("Knative Subscription is deleted", "Subscription", knativeSubsName)
err = r.knativeLib.CreateSubscription(knativeSubsName, knativeSubsNamespace, knativeChannelName, &knativeSubsURI)
if err != nil {
return false, err
}
knativeSubscriptionsGauge.DeleteKnativeSubscriptionsGaugeLabelValues(subscription.Namespace, subscription.Name)
knativeSubscriptionsGauge.Metric.With(prometheus.Labels{
metrics.Namespace: subscription.Namespace,
metrics.Name: subscription.Name,
metrics.Ready: "false"}).Set(1)
log.Info("Knative Subscription is re-created", "Subscription", knativeSubsName)
}
}
} else if util.CheckIfEventActivationExistForSubscription(ctx, r.client, subscription) {
// In case Kyma Subscription does not have events-activated condition, but there is an EventActivation for it.
// Activate subscription
if err := util.ActivateSubscriptions(ctx, r.client, []*eventingv1alpha1.Subscription{subscription}, log, r.time); err != nil {
log.Error(err, "ActivateSubscriptions() failed")
return false, err
}
log.Info("Kyma Subscription is activated", "Subscription", subscription.Name)
return true, nil
} else {
// In case Kyma Subscription does not have events-activated condition and there is no EventActivation, delete Knative Subscription & Channel if exist.
knativeSub, err := r.knativeLib.GetSubscription(knativeSubsName, knativeSubsNamespace)
if err != nil && !errors.IsNotFound(err) {
return false, err
} else if err == nil && knativeSub != nil {
err = r.knativeLib.DeleteSubscription(knativeSubsName, knativeSubsNamespace)
if err != nil {
return false, err
}
knativeSubscriptionsGauge.DeleteKnativeSubscriptionsGaugeLabelValues(subscription.Namespace, subscription.Name)
log.Info("Knative Subscription is deleted", "Subscription", knativeSubsName)
knativeChannelGauge.DeleteKnativeChannelGaugeLabelValues(subscription.Name)
log.Info("Knative Channel Gauge is deleted", "subscription", subscription.Name)
}
// Check if Channel has any other Subscription, if not, delete it.
knativeChannel, err := r.knativeLib.GetChannel(knativeChannelName, knativeSubsNamespace)
if err != nil && !errors.IsNotFound(err) {
return false, err
} else if err == nil && knativeChannel != nil {
if knativeChannel.Spec.Subscribable == nil || len(knativeChannel.Spec.Subscribable.Subscribers) == 0 ||
(len(knativeChannel.Spec.Subscribable.Subscribers) == 1 && knativeChannel.Spec.Subscribable.Subscribers[0].SubscriberURI == subscription.Endpoint) {
err = r.knativeLib.DeleteChannel(knativeChannelName, knativeSubsNamespace)
if err != nil {
return false, err
}
log.Info("Knative Channel is deleted", "Channel", knativeChannel)
knativeChannelGauge.DeleteKnativeChannelGaugeLabelValues(subscription.Name)
log.Info("Knative Channel Gauge is deleted", "subscription", subscription.Name)
}
}
}
return false, nil
}
func (r *reconciler) deleteExternalDependency(ctx context.Context, knativeSubsName string, channelName string,
namespace string, kymaSubscriptionName string, knativeSubscriptionsGauge *metrics.SubscriptionsGauge,
knativeChannelGauge *metrics.SubscriptionsGauge) error {
log.Info("Deleting the external dependencies")
// In case Knative Subscription exists, delete it.
knativeSubs, err := r.knativeLib.GetSubscription(knativeSubsName, namespace)
if err != nil && !errors.IsNotFound(err) {
return err
} else if err == nil {
err = r.knativeLib.DeleteSubscription(knativeSubs.Name, knativeSubs.Namespace)
if err != nil {
return err
}
knativeSubscriptionsGauge.DeleteKnativeSubscriptionsGaugeLabelValues(namespace, kymaSubscriptionName)
log.Info("Knative Subscription is deleted", "Subscription", knativeSubs.Name)
}
// Check if Channel has any other Subscription, if not, delete it.
knativeChannel, err := r.knativeLib.GetChannel(channelName, namespace)
if err != nil && !errors.IsNotFound(err) {
return err
} else if err == nil {
if knativeChannel.Spec.Subscribable == nil || (len(knativeChannel.Spec.Subscribable.Subscribers) == 1 && knativeSubs != nil &&
knativeChannel.Spec.Subscribable.Subscribers[0].SubscriberURI == *knativeSubs.Spec.Subscriber.DNSName) {
err = r.knativeLib.DeleteChannel(channelName, namespace)
if err != nil {
return err
}
log.Info("Knative Channel is deleted", "Channel", knativeChannel)
knativeChannelGauge.DeleteKnativeChannelGaugeLabelValues(kymaSubscriptionName)
log.Info("Knative Channel gauge is deleted", "subscription", kymaSubscriptionName)
}
}
return nil
}