/
inmemorychannel.go
280 lines (238 loc) · 11 KB
/
inmemorychannel.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
/*
Copyright 2019 The Knative Authors
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 controller
import (
"context"
"errors"
"fmt"
"reflect"
"time"
"go.uber.org/zap"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
appsv1listers "k8s.io/client-go/listers/apps/v1"
corev1listers "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"knative.dev/eventing/pkg/apis/messaging/v1alpha1"
listers "knative.dev/eventing/pkg/client/listers/messaging/v1alpha1"
"knative.dev/eventing/pkg/logging"
"knative.dev/eventing/pkg/reconciler"
"knative.dev/eventing/pkg/reconciler/inmemorychannel/controller/resources"
"knative.dev/eventing/pkg/utils"
"knative.dev/pkg/apis"
"knative.dev/pkg/controller"
)
const (
// Name of the corev1.Events emitted from the reconciliation process.
reconciled = "Reconciled"
reconcileFailed = "ReconcileFailed"
updateStatusFailed = "UpdateStatusFailed"
)
type Reconciler struct {
*reconciler.Base
dispatcherNamespace string
dispatcherDeploymentName string
dispatcherServiceName string
inmemorychannelLister listers.InMemoryChannelLister
inmemorychannelInformer cache.SharedIndexInformer
deploymentLister appsv1listers.DeploymentLister
serviceLister corev1listers.ServiceLister
endpointsLister corev1listers.EndpointsLister
impl *controller.Impl
}
var deploymentGVK = appsv1.SchemeGroupVersion.WithKind("Deployment")
var serviceGVK = corev1.SchemeGroupVersion.WithKind("Service")
// Check that our Reconciler implements controller.Reconciler.
var _ controller.Reconciler = (*Reconciler)(nil)
// Check that our Reconciler implements cache.ResourceEventHandler
var _ cache.ResourceEventHandler = (*Reconciler)(nil)
// cache.ResourceEventHandler implementation.
// These 3 functions just cause a Global Resync of the channels, because any changes here
// should be reflected onto the channels.
func (r *Reconciler) OnAdd(obj interface{}) {
r.impl.GlobalResync(r.inmemorychannelInformer)
}
func (r *Reconciler) OnUpdate(old, new interface{}) {
r.impl.GlobalResync(r.inmemorychannelInformer)
}
func (r *Reconciler) OnDelete(obj interface{}) {
r.impl.GlobalResync(r.inmemorychannelInformer)
}
// Reconcile compares the actual state with the desired, and attempts to
// converge the two. It then updates the Status block of the InMemoryChannel resource
// with the current status of the resource.
func (r *Reconciler) Reconcile(ctx context.Context, key string) error {
// Convert the namespace/name string into a distinct namespace and name.
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
logging.FromContext(ctx).Error("invalid resource key")
return nil
}
// Get the InMemoryChannel resource with this namespace/name.
original, err := r.inmemorychannelLister.InMemoryChannels(namespace).Get(name)
if apierrs.IsNotFound(err) {
// The resource may no longer exist, in which case we stop processing.
logging.FromContext(ctx).Error("InMemoryChannel key in work queue no longer exists")
return nil
} else if err != nil {
return err
}
// Don't modify the informers copy.
channel := original.DeepCopy()
// Reconcile this copy of the InMemoryChannel and then write back any status updates regardless of
// whether the reconcile error out.
reconcileErr := r.reconcile(ctx, channel)
if reconcileErr != nil {
logging.FromContext(ctx).Error("Error reconciling InMemoryChannel", zap.Error(reconcileErr))
r.Recorder.Eventf(channel, corev1.EventTypeWarning, reconcileFailed, "InMemoryChannel reconciliation failed: %v", reconcileErr)
} else {
logging.FromContext(ctx).Debug("InMemoryChannel reconciled")
r.Recorder.Event(channel, corev1.EventTypeNormal, reconciled, "InMemoryChannel reconciled")
}
// Since the reconciler took a crack at this, make sure it's reflected
// in the status correctly.
channel.Status.ObservedGeneration = original.Generation
if _, updateStatusErr := r.updateStatus(ctx, channel); updateStatusErr != nil {
logging.FromContext(ctx).Error("Failed to update InMemoryChannel status", zap.Error(updateStatusErr))
r.Recorder.Eventf(channel, corev1.EventTypeWarning, updateStatusFailed, "Failed to update InMemoryChannel's status: %v", err)
return updateStatusErr
}
// Requeue if the resource is not ready
return reconcileErr
}
func (r *Reconciler) reconcile(ctx context.Context, imc *v1alpha1.InMemoryChannel) error {
imc.Status.InitializeConditions()
if imc.DeletionTimestamp != nil {
// Everything is cleaned up by the garbage collector.
return nil
}
// We reconcile the status of the Channel by looking at:
// 1. Dispatcher Deployment for it's readiness.
// 2. Dispatcher k8s Service for it's existence.
// 3. Dispatcher endpoints to ensure that there's something backing the Service.
// 4. k8s service representing the channel that will use ExternalName to point to the Dispatcher k8s service
// Get the Dispatcher Deployment and propagate the status to the Channel
d, err := r.deploymentLister.Deployments(r.dispatcherNamespace).Get(r.dispatcherDeploymentName)
if err != nil {
if apierrs.IsNotFound(err) {
imc.Status.MarkDispatcherFailed("DispatcherDeploymentDoesNotExist", "Dispatcher Deployment does not exist")
} else {
logging.FromContext(ctx).Error("Unable to get the dispatcher Deployment", zap.Error(err))
imc.Status.MarkDispatcherUnknown("DispatcherDeploymentGetFailed", "Failed to get dispatcher Deployment")
}
return err
}
imc.Status.PropagateDispatcherStatus(&d.Status)
// Get the Dispatcher Service and propagate the status to the Channel in case it does not exist.
// We don't do anything with the service because it's status contains nothing useful, so just do
// an existence check. Then below we check the endpoints targeting it.
_, err = r.serviceLister.Services(r.dispatcherNamespace).Get(r.dispatcherServiceName)
if err != nil {
if apierrs.IsNotFound(err) {
imc.Status.MarkServiceFailed("DispatcherServiceDoesNotExist", "Dispatcher Service does not exist")
} else {
logging.FromContext(ctx).Error("Unable to get the dispatcher service", zap.Error(err))
imc.Status.MarkServiceUnknown("DispatcherServiceGetFailed", "Failed to get dispatcher service")
}
return err
}
imc.Status.MarkServiceTrue()
// Get the Dispatcher Service Endpoints and propagate the status to the Channel
// endpoints has the same name as the service, so not a bug.
e, err := r.endpointsLister.Endpoints(r.dispatcherNamespace).Get(r.dispatcherServiceName)
if err != nil {
if apierrs.IsNotFound(err) {
imc.Status.MarkEndpointsFailed("DispatcherEndpointsDoesNotExist", "Dispatcher Endpoints does not exist")
} else {
logging.FromContext(ctx).Error("Unable to get the dispatcher endpoints", zap.Error(err))
imc.Status.MarkEndpointsUnknown("DispatcherEndpointsGetFailed", "Failed to get dispatcher endpoints")
}
return err
}
if len(e.Subsets) == 0 {
logging.FromContext(ctx).Error("No endpoints found for Dispatcher service", zap.Error(err))
imc.Status.MarkEndpointsFailed("DispatcherEndpointsNotReady", "There are no endpoints ready for Dispatcher service")
return errors.New("there are no endpoints ready for Dispatcher service")
}
imc.Status.MarkEndpointsTrue()
// Reconcile the k8s service representing the actual Channel. It points to the Dispatcher service via
// ExternalName
svc, err := r.reconcileChannelService(ctx, imc)
if err != nil {
return err
}
imc.Status.MarkChannelServiceTrue()
imc.Status.SetAddress(&apis.URL{
Scheme: "http",
Host: fmt.Sprintf("%s.%s.svc.%s", svc.Name, svc.Namespace, utils.GetClusterDomainName()),
})
// Ok, so now the Dispatcher Deployment & Service have been created, we're golden since the
// dispatcher watches the Channel and where it needs to dispatch events to.
return nil
}
func (r *Reconciler) reconcileChannelService(ctx context.Context, imc *v1alpha1.InMemoryChannel) (*corev1.Service, error) {
// Get the Service and propagate the status to the Channel in case it does not exist.
// We don't do anything with the service because it's status contains nothing useful, so just do
// an existence check. Then below we check the endpoints targeting it.
// We may change this name later, so we have to ensure we use proper addressable when resolving these.
svc, err := r.serviceLister.Services(imc.Namespace).Get(resources.CreateChannelServiceName(imc.Name))
if err != nil {
if apierrs.IsNotFound(err) {
svc, err = resources.NewK8sService(imc, resources.ExternalService(r.dispatcherNamespace, r.dispatcherServiceName))
if err != nil {
logging.FromContext(ctx).Error("failed to create the channel service object", zap.Error(err))
imc.Status.MarkChannelServiceFailed("ChannelServiceFailed", fmt.Sprintf("Channel Service failed: %s", err))
return nil, err
}
svc, err = r.KubeClientSet.CoreV1().Services(imc.Namespace).Create(svc)
if err != nil {
logging.FromContext(ctx).Error("failed to create the channel service", zap.Error(err))
imc.Status.MarkChannelServiceFailed("ChannelServiceFailed", fmt.Sprintf("Channel Service failed: %s", err))
return nil, err
}
return svc, nil
}
logging.FromContext(ctx).Error("Unable to get the channel service", zap.Error(err))
imc.Status.MarkChannelServiceUnknown("ChannelServiceGetFailed", fmt.Sprintf("Unable to get the channel service: %s", err))
return nil, err
}
// Check to make sure that our IMC owns this service and if not, complain.
if !metav1.IsControlledBy(svc, imc) {
err := fmt.Errorf("inmemorychannel: %s/%s does not own Service: %q", imc.Namespace, imc.Name, svc.Name)
imc.Status.MarkChannelServiceFailed("ChannelServiceFailed", fmt.Sprintf("Channel Service failed: %s", err))
return nil, err
}
return svc, nil
}
func (r *Reconciler) updateStatus(ctx context.Context, desired *v1alpha1.InMemoryChannel) (*v1alpha1.InMemoryChannel, error) {
imc, err := r.inmemorychannelLister.InMemoryChannels(desired.Namespace).Get(desired.Name)
if err != nil {
return nil, err
}
if reflect.DeepEqual(imc.Status, desired.Status) {
return imc, nil
}
becomesReady := desired.Status.IsReady() && !imc.Status.IsReady()
// Don't modify the informers copy.
existing := imc.DeepCopy()
existing.Status = desired.Status
new, err := r.EventingClientSet.MessagingV1alpha1().InMemoryChannels(desired.Namespace).UpdateStatus(existing)
if err == nil && becomesReady {
duration := time.Since(new.ObjectMeta.CreationTimestamp.Time)
r.Logger.Infof("InMemoryChannel %q became ready after %v", imc.Name, duration)
r.StatsReporter.ReportReady("InMemoryChannel", imc.Namespace, imc.Name, duration)
}
return new, err
}