forked from Azure/azure-event-hubs-go
/
eph.go
353 lines (294 loc) · 10 KB
/
eph.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Package eph provides functionality for balancing load of Event Hub receivers through scheduling receivers across
// processes and machines.
package eph
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"sync"
"time"
"github.com/Azure/azure-amqp-common-go/auth"
"github.com/Azure/azure-amqp-common-go/log"
"github.com/Azure/azure-amqp-common-go/persist"
"github.com/Azure/azure-amqp-common-go/uuid"
"github.com/Azure/azure-event-hubs-go"
"github.com/opentracing/opentracing-go"
tag "github.com/opentracing/opentracing-go/ext"
)
const (
banner = `
______ __ __ __ __
/ ____/ _____ ____ / /_/ / / /_ __/ /_ _____
/ __/ | | / / _ \/ __ \/ __/ /_/ / / / / __ \/ ___/
/ /___ | |/ / __/ / / / /_/ __ / /_/ / /_/ (__ )
/_____/ |___/\___/_/ /_/\__/_/ /_/\__,_/_.___/____/
`
exitPrompt = "=> processing events, ctrl+c to exit"
)
type (
// EventProcessorHost provides functionality for coordinating and balancing load across multiple Event Hub partitions
EventProcessorHost struct {
namespace string
hubName string
name string
tokenProvider auth.TokenProvider
client *eventhub.Hub
leaser Leaser
checkpointer Checkpointer
scheduler *scheduler
handlers map[string]eventhub.Handler
hostMu sync.Mutex
handlersMu sync.Mutex
partitionIDs []string
noBanner bool
}
// EventProcessorHostOption provides configuration options for an EventProcessorHost
EventProcessorHostOption func(host *EventProcessorHost) error
// Receiver provides the ability to handle Event Hub events
Receiver interface {
Receive(ctx context.Context, handler eventhub.Handler) (close func() error, err error)
}
checkpointPersister struct {
checkpointer Checkpointer
}
// HandlerID is a UUID in string format that identifies a registered handler
HandlerID string
)
// WithNoBanner will configure an EventProcessorHost to not output the banner upon start
func WithNoBanner() EventProcessorHostOption {
return func(host *EventProcessorHost) error {
host.noBanner = true
return nil
}
}
// New constructs a new instance of an EventHostProcessor
func New(ctx context.Context, namespace, hubName string, tokenProvider auth.TokenProvider, leaser Leaser, checkpointer Checkpointer, opts ...EventProcessorHostOption) (*EventProcessorHost, error) {
span, ctx := startConsumerSpanFromContext(ctx, "eph.New")
defer span.Finish()
persister := checkpointPersister{checkpointer: checkpointer}
client, err := eventhub.NewHub(namespace, hubName, tokenProvider, eventhub.HubWithOffsetPersistence(persister))
if err != nil {
return nil, err
}
runtimeInfo, err := client.GetRuntimeInformation(ctx)
if err != nil {
return nil, err
}
hostName, err := uuid.NewV4()
if err != nil {
return nil, err
}
host := &EventProcessorHost{
namespace: namespace,
name: hostName.String(),
hubName: hubName,
tokenProvider: tokenProvider,
client: client,
handlers: make(map[string]eventhub.Handler),
leaser: leaser,
checkpointer: checkpointer,
partitionIDs: runtimeInfo.PartitionIDs,
noBanner: false,
}
for _, opt := range opts {
err := opt(host)
if err != nil {
return nil, err
}
}
return host, nil
}
// RegisteredHandlerIDs will return the registered event handler IDs
func (h *EventProcessorHost) RegisteredHandlerIDs() []HandlerID {
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
ids := make([]HandlerID, len(h.handlers))
count := 0
for key := range h.handlers {
ids[count] = HandlerID(key)
count++
}
return ids
}
// RegisterHandler will register an event handler which will receive events after Start or StartNonBlocking is called
func (h *EventProcessorHost) RegisterHandler(ctx context.Context, handler eventhub.Handler) (HandlerID, error) {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.RegisterHandler")
defer span.Finish()
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
id, err := uuid.NewV4()
if err != nil {
return "", err
}
h.handlers[id.String()] = handler
return HandlerID(id.String()), nil
}
// UnregisterHandler will remove an event handler from receiving events, and will close the EventProcessorHost if it is
// the last handler registered.
func (h *EventProcessorHost) UnregisterHandler(ctx context.Context, id HandlerID) {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.UnregisterHandler")
defer span.Finish()
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
delete(h.handlers, string(id))
if len(h.handlers) == 0 {
h.Close(ctx)
}
}
// Start begins processing of messages for registered handlers on the EventHostProcessor. The call is blocking.
func (h *EventProcessorHost) Start(ctx context.Context) error {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.Start")
defer span.Finish()
if !h.noBanner {
fmt.Print(banner)
fmt.Println(exitPrompt)
}
if len(h.handlers) == 0 {
return errors.New("no handlers have been registered; call RegisterHandler to setup an event handler")
}
if err := h.setup(ctx); err != nil {
return err
}
go func() {
span := opentracing.SpanFromContext(ctx)
ctx := opentracing.ContextWithSpan(context.Background(), span)
h.scheduler.Run(ctx)
}()
// Wait for a signal to quit:
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, os.Kill)
<-signalChan
return h.Close(ctx)
}
// StartNonBlocking begins processing of messages for registered handlers
func (h *EventProcessorHost) StartNonBlocking(ctx context.Context) error {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.StartNonBlocking")
defer span.Finish()
if !h.noBanner {
fmt.Print(banner)
}
if err := h.setup(ctx); err != nil {
return err
}
go func() {
span := opentracing.SpanFromContext(ctx)
ctx := opentracing.ContextWithSpan(context.Background(), span)
h.scheduler.Run(ctx)
}()
return nil
}
// GetName returns the name of the EventProcessorHost
func (h *EventProcessorHost) GetName() string {
return h.name
}
// GetPartitionIDs fetches the partition IDs for the Event Hub
func (h *EventProcessorHost) GetPartitionIDs() []string {
return h.partitionIDs
}
// PartitionIDsBeingProcessed returns the partition IDs currently receiving messages
func (h *EventProcessorHost) PartitionIDsBeingProcessed() []string {
return h.scheduler.getPartitionIDsBeingProcessed()
}
// Close stops the EventHostProcessor from processing messages
func (h *EventProcessorHost) Close(ctx context.Context) error {
if !h.noBanner {
fmt.Println("shutting down...")
}
if h.scheduler != nil {
if err := h.scheduler.Stop(ctx); err != nil {
if h.client != nil {
_ = h.client.Close(ctx)
}
return err
}
}
if h.leaser != nil {
_ = h.leaser.Close()
}
if h.checkpointer != nil {
_ = h.checkpointer.Close()
}
return h.client.Close(ctx)
}
func (h *EventProcessorHost) setup(ctx context.Context) error {
h.hostMu.Lock()
defer h.hostMu.Unlock()
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.setup")
defer span.Finish()
if h.scheduler == nil {
h.leaser.SetEventHostProcessor(h)
h.checkpointer.SetEventHostProcessor(h)
if err := h.leaser.EnsureStore(ctx); err != nil {
return err
}
if err := h.checkpointer.EnsureStore(ctx); err != nil {
return err
}
scheduler := newScheduler(h)
for _, partitionID := range h.partitionIDs {
h.leaser.EnsureLease(ctx, partitionID)
h.checkpointer.EnsureCheckpoint(ctx, partitionID)
}
h.scheduler = scheduler
}
return nil
}
func (h *EventProcessorHost) compositeHandlers() eventhub.Handler {
return func(ctx context.Context, event *eventhub.Event) error {
span, ctx := startConsumerSpanFromContext(ctx, "eph.EventProcessorHost.compositeHandlers")
defer span.Finish()
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
var wg sync.WaitGroup
for _, handle := range h.handlers {
wg.Add(1)
go func(boundHandle eventhub.Handler) {
if err := boundHandle(ctx, event); err != nil {
log.For(ctx).Error(err)
}
wg.Done()
}(handle)
}
wg.Wait()
return nil
}
}
func (c checkpointPersister) Write(namespace, name, consumerGroup, partitionID string, checkpoint persist.Checkpoint) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return c.checkpointer.UpdateCheckpoint(ctx, partitionID, checkpoint)
}
func (c checkpointPersister) Read(namespace, name, consumerGroup, partitionID string) (persist.Checkpoint, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return c.checkpointer.EnsureCheckpoint(ctx, partitionID)
}
func startConsumerSpanFromContext(ctx context.Context, operationName string, opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context) {
span, ctx := opentracing.StartSpanFromContext(ctx, operationName, opts...)
eventhub.ApplyComponentInfo(span)
tag.SpanKindConsumer.Set(span)
return span, ctx
}