/
governor.go
529 lines (438 loc) · 12.6 KB
/
governor.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Copyright 2020-2022 The NATS 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.
//
// Copyright (c) 2022, R.I. Pienaar and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0
// Package governor controls the concurrency of a network wide process
//
// Using this one can, for example, create CRON jobs that can trigger
// 100s or 1000s concurrently but where most will wait for a set limit
// to complete. In effect limiting the overall concurrency of these
// execution.
//
// To do this a Stream is created that has a maximum message limit and
// that will reject new entries when full.
//
// Workers will try to place themselves in the Stream, they do their work
// if they succeed and remove themselves from the Stream once they are done.
//
// As a fail safe the stack will evict entries after a set time based on
// Stream max age.
//
// A manager is included to create, observe and edit these streams and the
// choria CLI has a new command build on this library: choria governor
package governor
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/choria-io/go-choria/backoff"
iu "github.com/choria-io/go-choria/internal/util"
"github.com/google/go-cmp/cmp"
"github.com/nats-io/jsm.go"
"github.com/nats-io/nats.go"
)
// DefaultInterval default sleep between tries, set with WithInterval()
const DefaultInterval = 250 * time.Millisecond
// Finisher signals that work is completed releasing the slot on the stack
type Finisher func() error
// Governor controls concurrency of distributed processes using a named governor stream
type Governor interface {
// Start attempts to get a spot in the Governor, gives up on context, call Finisher to signal end of work
Start(ctx context.Context, name string) (fin Finisher, seq uint64, err error)
// Connection is the NATS connection used to communicate
Connection() *nats.Conn
}
// Logger is a custom logger
type Logger interface {
Debugf(format string, a ...any)
Infof(format string, a ...any)
Warnf(format string, a ...any)
Errorf(format string, a ...any)
}
// Manager controls concurrent executions of work distributed throughout a nats network by using
// a stream as a capped stack where workers reserve a slot and later release the slot
type Manager interface {
// Limit is the configured maximum entries in the Governor
Limit() int64
// MaxAge is the time after which entries will be evicted
MaxAge() time.Duration
// Name is the Governor name
Name() string
// Replicas is how many data replicas are kept of the data
Replicas() int
// SetLimit configures the maximum entries in the Governor and takes immediate effect
SetLimit(uint64) error
// SetMaxAge configures the maximum age of entries, takes immediate effect
SetMaxAge(time.Duration) error
// SetSubject configures the underlying NATS subject the Governor listens on for entry campaigns
SetSubject(subj string) error
// Stream is the underlying JetStream stream
Stream() *jsm.Stream
// Subject is the subject the Governor listens on for entry campaigns
Subject() string
// Reset resets the governor removing all current entries from it
Reset() error
// Active is the number of active entries in the Governor
Active() (uint64, error)
// Evict removes an entry from the Governor given its unique id, returns the name that was on that entry
Evict(entry uint64) (name string, err error)
// LastActive returns the the since entry was added to the Governor, can be zero time when no entries were added
LastActive() (time.Time, error)
// Connection is the NATS connection used to communicate
Connection() *nats.Conn
}
var errRetry = errors.New("retryable error")
type jsGMgr struct {
name string
stream string
maxAge time.Duration
limit uint64
mgr *jsm.Manager
nc *nats.Conn
str *jsm.Stream
subj string
replicas int
running bool
noCreate bool
noLeave bool
logger Logger
cint time.Duration
bo *backoff.Policy
mu sync.Mutex
}
func NewManager(name string, limit uint64, maxAge time.Duration, replicas uint, nc *nats.Conn, update bool, opts ...Option) (Manager, error) {
mgr, err := jsm.New(nc)
if err != nil {
return nil, err
}
gov := &jsGMgr{
name: name,
maxAge: maxAge,
limit: limit,
mgr: mgr,
nc: nc,
replicas: int(replicas),
cint: DefaultInterval,
}
for _, opt := range opts {
opt(gov)
}
if limit == 0 {
gov.noCreate = true
}
gov.stream = gov.streamName()
gov.subj = gov.streamSubject()
err = gov.loadOrCreate(update)
if err != nil {
return nil, err
}
return gov, nil
}
type Option func(mgr *jsGMgr)
// WithLogger configures the logger to use, no logging when none is given
func WithLogger(log Logger) Option {
return func(mgr *jsGMgr) {
mgr.logger = log
}
}
// WithBackoff sets a backoff policy for gradually reducing try interval
func WithBackoff(p backoff.Policy) Option {
return func(mgr *jsGMgr) {
mgr.bo = &p
}
}
// WithInterval sets the interval between tries
func WithInterval(i time.Duration) Option {
return func(mgr *jsGMgr) {
mgr.cint = i
}
}
// WithSubject configures a specific subject for the governor to act on
func WithSubject(s string) Option {
return func(mgr *jsGMgr) {
mgr.subj = s
}
}
// WithoutLeavingOnCompletion prevents removal from the governor after execution
func WithoutLeavingOnCompletion() Option {
return func(mgr *jsGMgr) {
mgr.noLeave = true
}
}
func New(name string, nc *nats.Conn, opts ...Option) Governor {
mgr, err := jsm.New(nc)
if err != nil {
return nil
}
gov := &jsGMgr{
name: name,
mgr: mgr,
nc: nc,
cint: DefaultInterval,
}
for _, opt := range opts {
opt(gov)
}
gov.stream = gov.streamName()
gov.subj = gov.streamSubject()
return gov
}
func (g *jsGMgr) streamSubject() string {
if g.subj != "" {
return g.subj
}
return fmt.Sprintf("$GOVERNOR.campaign.%s", g.name)
}
func (g *jsGMgr) streamName() string {
if g.stream != "" {
return g.stream
}
return StreamName(g.name)
}
func StreamName(governor string) string {
return fmt.Sprintf("GOVERNOR_%s", governor)
}
func List(nc *nats.Conn, collective string) ([]string, error) {
mgr, err := jsm.New(nc)
if err != nil {
return nil, err
}
known, err := mgr.StreamNames(&jsm.StreamNamesFilter{
Subject: iu.GovernorSubject("*", collective),
})
if err != nil {
return nil, err
}
for i := 0; i < len(known); i++ {
known[i] = strings.TrimPrefix(known[i], "GOVERNOR_")
}
sort.Strings(known)
return known, nil
}
func (g *jsGMgr) Start(ctx context.Context, name string) (Finisher, uint64, error) {
g.mu.Lock()
defer g.mu.Unlock()
if g.running {
return nil, 0, fmt.Errorf("already running")
}
g.running = true
seq := uint64(0)
tries := 0
try := func() error {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
g.Debugf("Publishing to %s", g.subj)
m, err := g.nc.RequestWithContext(ctx, g.subj, []byte(name))
if err != nil {
g.Errorf("Publishing to governor %s via %s failed: %s", g.name, g.subj, err)
return err
}
res, err := jsm.ParsePubAck(m)
if err != nil {
// jetstream sent us a puback error, this is retryable in the case of governors
if jsm.IsNatsError(err, 10077) {
g.Debugf("Could not obtain a slot: %v", err)
return errRetry
}
g.Errorf("Invalid pub ack: %s", err)
return err
}
seq = res.Sequence
g.Infof("Got a slot on %s with sequence %d", g.name, seq)
return nil
}
closer := func() error {
if seq == 0 {
return nil
}
g.mu.Lock()
defer g.mu.Unlock()
if !g.running {
return nil
}
g.running = false
if g.noLeave {
g.Infof("Not evicting self from %s based on configuration directive", g.name)
return nil
}
g.Infof("Removing self from %s sequence %d", g.name, seq)
err := g.mgr.DeleteStreamMessage(g.stream, seq, true)
if err != nil {
g.Errorf("Could not remove self from %s: %s", g.name, err)
return fmt.Errorf("could not remove seq %d: %s", seq, err)
}
return nil
}
g.Debugf("Starting to campaign every %v for a slot on %s using %s", g.cint, g.name, g.subj)
// we try to enter the governor and if it fails in a way thats safe to retry
// we will do so else we exit.
//
// We need to handle thins like context timeout, bucket not found etc specifically
// as hard errors since, especially context timeout, it does not mean the message did
// not enter the governor, it just means something went wrong, perhaps in getting the
// ok reply. In the case where the message did reach the governor but the reply could
// not be processed we will retry again and again potentially filling the governor.
err := try()
if err == nil {
return closer, seq, nil
} else if err != errRetry {
return nil, 0, err
}
ticker := time.NewTicker(g.cint)
for {
select {
case <-ticker.C:
tries++
err = try()
if err == nil {
return closer, seq, nil
} else if err != errRetry {
return nil, 0, err
}
if g.bo != nil {
delay := g.bo.Duration(tries)
g.Debugf("Retrying after %v", delay)
ticker.Reset(delay)
}
case <-ctx.Done():
g.Infof("Stopping campaigns against %s due to context timeout after %d tries", g.name, tries)
ticker.Stop()
return nil, 0, ctx.Err()
}
}
}
func (g *jsGMgr) Reset() error {
return g.str.Purge()
}
func (g *jsGMgr) Stream() *jsm.Stream { return g.str }
func (g *jsGMgr) Limit() int64 { return g.str.MaxMsgs() }
func (g *jsGMgr) MaxAge() time.Duration { return g.str.MaxAge() }
func (g *jsGMgr) Subject() string { return g.str.Subjects()[0] }
func (g *jsGMgr) Replicas() int { return g.str.Replicas() }
func (g *jsGMgr) Connection() *nats.Conn { return g.nc }
func (g *jsGMgr) Name() string { return g.name }
func (g *jsGMgr) Evict(entry uint64) (string, error) {
msg, err := g.str.ReadMessage(entry)
if err != nil {
return "", err
}
return string(msg.Data), g.str.DeleteMessage(entry)
}
func (g *jsGMgr) Active() (uint64, error) {
nfo, err := g.str.Information()
if err != nil {
return 0, err
}
return nfo.State.Msgs, nil
}
func (g *jsGMgr) LastActive() (time.Time, error) {
nfo, err := g.str.Information()
if err != nil {
return time.Time{}, err
}
return nfo.State.LastTime, nil
}
func (g *jsGMgr) SetSubject(subj string) error {
g.mu.Lock()
g.subj = subj
g.mu.Unlock()
return g.updateConfig()
}
func (g *jsGMgr) SetLimit(limit uint64) error {
g.mu.Lock()
g.limit = limit
g.mu.Unlock()
return g.updateConfig()
}
func (g *jsGMgr) SetMaxAge(age time.Duration) error {
g.mu.Lock()
g.maxAge = age
g.mu.Unlock()
return g.updateConfig()
}
func (g *jsGMgr) updateConfig() error {
g.mu.Lock()
defer g.mu.Unlock()
if g.str.MaxAge() != g.maxAge || g.str.MaxMsgs() != int64(g.limit) || !cmp.Equal([]string{g.streamSubject()}, g.str.Subjects()) || g.str.Replicas() != g.replicas {
err := g.str.UpdateConfiguration(g.str.Configuration(), g.streamOpts()...)
if err != nil {
return fmt.Errorf("stream update failed: %s", err)
}
}
return nil
}
func (g *jsGMgr) streamOpts() []jsm.StreamOption {
opts := []jsm.StreamOption{
jsm.StreamDescription(fmt.Sprintf("Concurrency Governor %s", g.name)),
jsm.MaxAge(g.maxAge),
jsm.MaxMessages(int64(g.limit)),
jsm.Subjects(g.subj),
jsm.Replicas(g.replicas),
jsm.LimitsRetention(),
jsm.FileStorage(),
jsm.DiscardNew(),
jsm.DuplicateWindow(0),
}
if g.replicas > 0 {
opts = append(opts, jsm.Replicas(g.replicas))
}
return opts
}
func (g *jsGMgr) loadOrCreate(update bool) error {
opts := g.streamOpts()
if g.noCreate {
has, err := g.mgr.IsKnownStream(g.stream)
if err != nil {
return err
}
if !has {
return fmt.Errorf("unknown governor")
}
}
str, err := g.mgr.LoadOrNewStream(g.stream, opts...)
if err != nil {
return err
}
g.str = str
if update {
g.updateConfig()
}
return nil
}
func (g *jsGMgr) Debugf(format string, a ...any) {
if g.logger != nil {
g.logger.Debugf(format, a...)
}
}
func (g *jsGMgr) Infof(format string, a ...any) {
if g.logger != nil {
g.logger.Infof(format, a...)
}
}
func (g *jsGMgr) Warnf(format string, a ...any) {
if g.logger != nil {
g.logger.Warnf(format, a...)
}
}
func (g *jsGMgr) Errorf(format string, a ...any) {
if g.logger != nil {
g.logger.Errorf(format, a...)
}
}