-
Notifications
You must be signed in to change notification settings - Fork 69
/
event_subs.go
269 lines (217 loc) · 9.86 KB
/
event_subs.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
/*
Copyright 2022 TriggerMesh Inc.
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 azureeventgridsource
import (
"context"
"fmt"
"hash/crc32"
"strconv"
"time"
corev1 "k8s.io/api/core/v1"
"knative.dev/pkg/controller"
"knative.dev/pkg/reconciler"
azureeventgrid "github.com/Azure/azure-sdk-for-go/profiles/latest/eventgrid/mgmt/eventgrid"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
commonv1alpha1 "github.com/triggermesh/triggermesh/pkg/apis/common/v1alpha1"
"github.com/triggermesh/triggermesh/pkg/apis/sources/v1alpha1"
"github.com/triggermesh/triggermesh/pkg/reconciler/event"
"github.com/triggermesh/triggermesh/pkg/reconciler/skip"
"github.com/triggermesh/triggermesh/pkg/sources/client/azure/eventgrid"
)
const crudTimeout = time.Second * 15
const (
defaultMaxDeliveryAttempts = 30
defaultEventTTL = 1440
)
// EnsureEventSubscription ensures an event subscription exists with the expected configuration.
// Required permissions:
// - Microsoft.EventGrid/systemTopics/eventSubscriptions/read
// - Microsoft.EventGrid/systemTopics/eventSubscriptions/write
// - Microsoft.EventHub/namespaces/eventhubs/write
func EnsureEventSubscription(ctx context.Context, cli eventgrid.EventSubscriptionsClient,
sysTopicResID *v1alpha1.AzureResourceID, eventHubResID string) error {
if skip.Skip(ctx) {
return nil
}
src := commonv1alpha1.ReconcilableFromContext(ctx)
typedSrc := src.(*v1alpha1.AzureEventGridSource)
status := &typedSrc.Status
// read current event subscription
rgName := sysTopicResID.ResourceGroup
sysTopicName := sysTopicResID.ResourceName
sysTopicResIDStr := sysTopicResID.String()
subsName := eventSubscriptionResourceName(typedSrc)
restCtx, cancel := context.WithTimeout(ctx, crudTimeout)
defer cancel()
currentEventSubs, err := cli.Get(restCtx, rgName, sysTopicName, subsName)
switch {
case isNotFound(err):
// no-op
case isDenied(err):
status.MarkNotSubscribed(v1alpha1.AzureReasonAPIError, "Access denied to event subscription API: "+toErrMsg(err))
return controller.NewPermanentError(failGetEventSubscriptionEvent(sysTopicResIDStr, err))
case err != nil:
status.MarkNotSubscribed(v1alpha1.AzureReasonAPIError, "Cannot look up event subscription: "+toErrMsg(err))
// wrap any other error to fail the reconciliation
return fmt.Errorf("%w", failGetEventSubscriptionEvent(sysTopicResIDStr, err))
}
subsExists := currentEventSubs.ID != nil
// compare and create/update event subscription
desiredEventSubs := newEventSubscription(eventHubResID, typedSrc.GetEventTypes())
if equalEventSubscription(ctx, desiredEventSubs, currentEventSubs) {
eventSubscriptionResID, err := parseResourceID(*currentEventSubs.ID)
if err != nil {
return fmt.Errorf("converting resource ID string to structured resource ID: %w", err)
}
status.EventSubscriptionID = eventSubscriptionResID
status.MarkSubscribed()
return nil
}
restCtx, cancel = context.WithTimeout(ctx, crudTimeout)
defer cancel()
resultFuture, err := cli.CreateOrUpdate(restCtx, rgName, sysTopicName, subsName, desiredEventSubs)
switch {
case isDenied(err):
status.MarkNotSubscribed(v1alpha1.AzureReasonAPIError, "Access denied to event subscription API: "+toErrMsg(err))
return controller.NewPermanentError(failSubscribeEvent(sysTopicResIDStr, subsExists, err))
case err != nil:
status.MarkNotSubscribed(v1alpha1.AzureReasonAPIError, "Cannot subscribe to events: "+toErrMsg(err))
return fmt.Errorf("%w", failSubscribeEvent(sysTopicResIDStr, subsExists, err))
}
if err := resultFuture.WaitForCompletionRef(ctx, cli.BaseClient()); err != nil {
return fmt.Errorf("waiting for creation of event subscription %q: %w", subsName, err)
}
subsResult, err := resultFuture.Result(cli.ConcreteClient())
if err != nil {
return fmt.Errorf("reading created/updated event subscription %q: %w", subsName, err)
}
recordSubscribedEvent(ctx, *subsResult.ID, subsExists)
eventSubscriptionResID, err := parseResourceID(*subsResult.ID)
if err != nil {
return fmt.Errorf("converting resource ID string to structured resource ID: %w", err)
}
status.EventSubscriptionID = eventSubscriptionResID
status.MarkSubscribed()
return nil
}
// newEventSubscription returns the desired state of the event subscription.
func newEventSubscription(eventHubResID string, eventTypes []string) azureeventgrid.EventSubscription {
// Fields marked with a '*' below are attributes which would be
// defaulted on creation by Azure if not explicitly set, but which we
// set manually nevertheless in order to ease the comparison with the
// current state in the main synchronization logic.
return azureeventgrid.EventSubscription{
EventSubscriptionProperties: &azureeventgrid.EventSubscriptionProperties{
Destination: azureeventgrid.EventHubEventSubscriptionDestination{
EndpointType: azureeventgrid.EndpointTypeEventHub,
EventHubEventSubscriptionDestinationProperties: &azureeventgrid.EventHubEventSubscriptionDestinationProperties{
ResourceID: to.Ptr(eventHubResID),
},
},
Filter: &azureeventgrid.EventSubscriptionFilter{
IncludedEventTypes: to.Ptr(eventTypes),
SubjectBeginsWith: to.Ptr(""), // *
SubjectEndsWith: to.Ptr(""), // *
},
RetryPolicy: &azureeventgrid.RetryPolicy{
MaxDeliveryAttempts: to.Ptr[int32](defaultMaxDeliveryAttempts), // *
EventTimeToLiveInMinutes: to.Ptr[int32](defaultEventTTL), // *
},
EventDeliverySchema: azureeventgrid.EventDeliverySchemaCloudEventSchemaV10,
},
}
}
// EnsureNoEventSubscription ensures the event subscription is removed.
// Required permissions:
// - Microsoft.EventGrid/systemTopics/eventSubscriptions/delete
func EnsureNoEventSubscription(ctx context.Context, cli eventgrid.EventSubscriptionsClient,
sysTopic *azureeventgrid.SystemTopic) reconciler.Event {
if skip.Skip(ctx) {
return nil
}
if sysTopic == nil {
event.Warn(ctx, ReasonUnsubscribed, "System topic not found, skipping finalization of event subscription")
return nil
}
sysTopicResID, err := parseResourceID(*sysTopic.ID)
if err != nil {
return fmt.Errorf("converting resource ID string to structured resource ID: %w", err)
}
src := commonv1alpha1.ReconcilableFromContext(ctx)
typedSrc := src.(*v1alpha1.AzureEventGridSource)
rgName := sysTopicResID.ResourceGroup
sysTopicName := sysTopicResID.ResourceName
subsName := eventSubscriptionResourceName(typedSrc)
restCtx, cancel := context.WithTimeout(ctx, crudTimeout)
defer cancel()
resultFuture, err := cli.Delete(restCtx, rgName, sysTopicName, subsName)
switch {
case isNotFound(err):
event.Warn(ctx, ReasonUnsubscribed, "Event subscription %q not found, skipping deletion", subsName)
return nil
case isDenied(err):
// it is unlikely that we recover from auth errors in the
// finalizer, so we simply record a warning event and return
event.Warn(ctx, ReasonFailedUnsubscribe,
"Access denied to event subscription API. Ignoring: %s", toErrMsg(err))
return nil
case err != nil:
return failUnsubscribeEvent(subsName, *sysTopic.ID, err)
}
if err := resultFuture.WaitForCompletionRef(ctx, cli.BaseClient()); err != nil {
return fmt.Errorf("waiting for deletion of event subscription %q: %w", subsName, err)
}
event.Normal(ctx, ReasonUnsubscribed, "Deleted event subscription %q from system topic %q", subsName, *sysTopic.ID)
return nil
}
// eventSubscriptionResourceName returns a deterministic name for an Event Grid
// event subscription associated with the given source instance.
// The Event Subscription name must be 3-64 characters in length and can only
// contain a-z, A-Z, 0-9, and "-".
func eventSubscriptionResourceName(src *v1alpha1.AzureEventGridSource) string {
nsNameChecksum := crc32.ChecksumIEEE([]byte(src.Namespace + "/" + src.Name))
return "io-triggermesh-azureeventgridsources-" + strconv.FormatUint(uint64(nsNameChecksum), 10)
}
// recordSubscribedEvent records a Kubernetes API event which indicates that an
// event subscription was either created or updated.
func recordSubscribedEvent(ctx context.Context, subsID string, isUpdate bool) {
verb := "Created"
if isUpdate {
verb = "Updated"
}
event.Normal(ctx, ReasonSubscribed, "%s event subscription %q", verb, subsID)
}
// failGetEventSubscriptionEvent returns a reconciler event which indicates
// that an event subscription for the given system topic could not be retrieved
// from the Azure API.
func failGetEventSubscriptionEvent(sysTopic string, origErr error) reconciler.Event {
return reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,
"Error getting event subscription from system topic %q: %s", sysTopic, toErrMsg(origErr))
}
// failSubscribeEvent returns a reconciler event which indicates that an event
// subscription for the given system topic could not be created or updated via
// the Azure API.
func failSubscribeEvent(sysTopic string, isUpdate bool, origErr error) reconciler.Event {
verb := "creating"
if isUpdate {
verb = "updating"
}
return reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,
"Error %s event subscription in system topic %q: %s", verb, sysTopic, toErrMsg(origErr))
}
// failUnsubscribeEvent returns a reconciler event which indicates that an
// event subscription could not be deleted via the Azure API.
func failUnsubscribeEvent(subs, sysTopic string, origErr error) reconciler.Event {
return reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,
"Error deleting event subscription %q from system topic %q: %s", subs, sysTopic, toErrMsg(origErr))
}