-
Notifications
You must be signed in to change notification settings - Fork 67
/
binding_controller.go
227 lines (195 loc) · 8.23 KB
/
binding_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
/*
RabbitMQ Messaging Topology Kubernetes Operator
Copyright 2021 VMware, Inc.
This product is licensed to you under the Mozilla Public License 2.0 license (the "License"). You may not use this product except in compliance with the Mozilla 2.0 License.
This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file.
*/
package controllers
import (
"context"
"encoding/json"
"errors"
"reflect"
"time"
rabbithole "github.com/michaelklishin/rabbit-hole/v2"
"github.com/rabbitmq/messaging-topology-operator/internal"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/record"
clientretry "k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
topology "github.com/rabbitmq/messaging-topology-operator/api/v1alpha2"
)
const bindingFinalizer = "deletion.finalizers.bindings.rabbitmq.com"
// BindingReconciler reconciles a Binding object
type BindingReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
Recorder record.EventRecorder
RabbitmqClientFactory internal.RabbitMQClientFactory
}
// +kubebuilder:rbac:groups=rabbitmq.com,resources=bindings,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=rabbitmq.com,resources=bindings/status,verbs=get;update;patch
func (r *BindingReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := ctrl.LoggerFrom(ctx)
binding := &topology.Binding{}
if err := r.Get(ctx, req.NamespacedName, binding); err != nil {
return reconcile.Result{}, client.IgnoreNotFound(err)
}
rabbitClient, err := r.RabbitmqClientFactory(ctx, r.Client, binding.Spec.RabbitmqClusterReference, binding.Namespace)
if errors.Is(err, internal.NoSuchRabbitmqClusterError) && binding.ObjectMeta.DeletionTimestamp.IsZero() {
logger.Info("Could not generate rabbitClient for non existent cluster: " + err.Error())
return reconcile.Result{RequeueAfter: 10 * time.Second}, err
} else if err != nil && !errors.Is(err, internal.NoSuchRabbitmqClusterError) {
logger.Error(err, failedGenerateRabbitClient)
return reconcile.Result{}, err
}
if !binding.ObjectMeta.DeletionTimestamp.IsZero() {
logger.Info("Deleting")
return ctrl.Result{}, r.deleteBinding(ctx, rabbitClient, binding)
}
if err := r.addFinalizerIfNeeded(ctx, binding); err != nil {
return ctrl.Result{}, err
}
spec, err := json.Marshal(binding.Spec)
if err != nil {
logger.Error(err, failedMarshalSpec)
}
logger.Info("Start reconciling",
"spec", string(spec))
if err := r.declareBinding(ctx, rabbitClient, binding); err != nil {
// Set Condition 'Ready' to false with message
binding.Status.Conditions = []topology.Condition{topology.NotReady(err.Error())}
if writerErr := clientretry.RetryOnConflict(clientretry.DefaultRetry, func() error {
return r.Status().Update(ctx, binding)
}); writerErr != nil {
logger.Error(writerErr, failedStatusUpdate)
}
return ctrl.Result{}, err
}
binding.Status.Conditions = []topology.Condition{topology.Ready()}
binding.Status.ObservedGeneration = binding.GetGeneration()
if writerErr := clientretry.RetryOnConflict(clientretry.DefaultRetry, func() error {
return r.Status().Update(ctx, binding)
}); writerErr != nil {
logger.Error(writerErr, failedStatusUpdate)
}
logger.Info("Finished reconciling")
return ctrl.Result{}, nil
}
func (r *BindingReconciler) declareBinding(ctx context.Context, client internal.RabbitMQClient, binding *topology.Binding) error {
logger := ctrl.LoggerFrom(ctx)
info, err := internal.GenerateBindingInfo(binding)
if err != nil {
msg := "failed to generate binding info"
r.Recorder.Event(binding, corev1.EventTypeWarning, "FailedDeclare", msg)
logger.Error(err, msg)
return err
}
if err := validateResponse(client.DeclareBinding(binding.Spec.Vhost, *info)); err != nil {
msg := "failed to declare binding"
r.Recorder.Event(binding, corev1.EventTypeWarning, "FailedDeclare", msg)
logger.Error(err, msg)
return err
}
logger.Info("Successfully declared binding")
r.Recorder.Event(binding, corev1.EventTypeNormal, "SuccessfulDeclare", "Successfully declared binding")
return nil
}
// deletes binding from rabbitmq server; bindings have no name; server needs BindingInfo to delete them
// when server responds with '404' Not Found, it logs and does not requeue on error
// if no binding argument is set, generating properties key by using internal.GeneratePropertiesKey
// if binding arguments are set, list all bindings between source/destination to find the binding; if it failed to find corresponding binding, it assumes that the binding is already deleted and returns no error
func (r *BindingReconciler) deleteBinding(ctx context.Context, client internal.RabbitMQClient, binding *topology.Binding) error {
logger := ctrl.LoggerFrom(ctx)
var info *rabbithole.BindingInfo
var err error
if binding.Spec.Arguments != nil {
info, err = r.findBindingInfo(logger, binding, client)
if err != nil {
return err
}
if info == nil {
logger.Info("cannot find the corresponding binding info in rabbitmq server; binding already deleted")
return r.removeFinalizer(ctx, binding)
}
} else {
info, err = internal.GenerateBindingInfo(binding)
if err != nil {
msg := "failed to generate binding info"
r.Recorder.Event(binding, corev1.EventTypeWarning, "FailedDelete", msg)
logger.Error(err, msg)
return err
}
info.PropertiesKey = internal.GeneratePropertiesKey(binding)
}
err = validateResponseForDeletion(client.DeleteBinding(binding.Spec.Vhost, *info))
if errors.Is(err, NotFound) {
logger.Info("cannot find binding in rabbitmq server; already deleted")
} else if err != nil {
msg := "failed to delete binding"
r.Recorder.Event(binding, corev1.EventTypeWarning, "FailedDelete", msg)
logger.Error(err, msg)
return err
}
logger.Info("Successfully deleted binding")
return r.removeFinalizer(ctx, binding)
}
func (r *BindingReconciler) findBindingInfo(logger logr.Logger, binding *topology.Binding, client internal.RabbitMQClient) (*rabbithole.BindingInfo, error) {
logger.Info("binding arguments set; listing bindings from server to complete deletion")
arguments := make(map[string]interface{})
if binding.Spec.Arguments != nil {
if err := json.Unmarshal(binding.Spec.Arguments.Raw, &arguments); err != nil {
msg := "failed to unmarshall binding arguments"
r.Recorder.Event(binding, corev1.EventTypeWarning, "FailedDelete", msg)
logger.Error(err, msg)
return nil, err
}
}
var bindingInfos []rabbithole.BindingInfo
var err error
if binding.Spec.DestinationType == "queue" {
bindingInfos, err = client.ListQueueBindingsBetween(binding.Spec.Vhost, binding.Spec.Source, binding.Spec.Destination)
} else {
bindingInfos, err = client.ListExchangeBindingsBetween(binding.Spec.Vhost, binding.Spec.Source, binding.Spec.Destination)
}
if err != nil {
msg := "failed to list binding infos"
r.Recorder.Event(binding, corev1.EventTypeWarning, "FailedDelete", msg)
logger.Error(err, msg)
return nil, err
}
var info *rabbithole.BindingInfo
for _, b := range bindingInfos {
if binding.Spec.RoutingKey == b.RoutingKey && reflect.DeepEqual(b.Arguments, arguments) {
info = &b
}
}
return info, nil
}
func (r *BindingReconciler) removeFinalizer(ctx context.Context, binding *topology.Binding) error {
controllerutil.RemoveFinalizer(binding, bindingFinalizer)
if err := r.Client.Update(ctx, binding); err != nil {
return err
}
return nil
}
func (r *BindingReconciler) addFinalizerIfNeeded(ctx context.Context, binding *topology.Binding) error {
if binding.ObjectMeta.DeletionTimestamp.IsZero() && !controllerutil.ContainsFinalizer(binding, bindingFinalizer) {
controllerutil.AddFinalizer(binding, bindingFinalizer)
if err := r.Client.Update(ctx, binding); err != nil {
return err
}
}
return nil
}
func (r *BindingReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&topology.Binding{}).
Complete(r)
}