-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_test.go
More file actions
737 lines (644 loc) · 17 KB
/
example_test.go
File metadata and controls
737 lines (644 loc) · 17 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
package discovery_test
import (
"context"
"errors"
"fmt"
"io"
"log"
"sync"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/tests/v3/integration"
"github.com/tarantool/go-tarantool/v2"
"github.com/tarantool/go-tarantool/v2/test_helpers"
"github.com/tarantool/go-discovery"
"github.com/tarantool/go-discovery/dial"
"github.com/tarantool/go-discovery/discoverer"
"github.com/tarantool/go-discovery/filter"
"github.com/tarantool/go-discovery/observer"
"github.com/tarantool/go-discovery/pool"
"github.com/tarantool/go-discovery/scheduler"
"github.com/tarantool/go-discovery/subscriber"
)
func init() {
log.SetOutput(io.Discard)
}
func exampleStartTarantool(address string) (*test_helpers.TarantoolInstance, error) {
dialer := tarantool.NetDialer{
Address: address,
User: "testuser",
Password: "testpass",
}
startOpts := test_helpers.StartOpts{
Dialer: dialer,
InitScript: "testdata/init.lua",
Listen: address,
WaitStart: 100 * time.Millisecond,
ConnectRetry: 3,
RetryTimeout: 500 * time.Millisecond,
}
return test_helpers.StartTarantool(startOpts)
}
func exampleStopTarantool(instance *test_helpers.TarantoolInstance) {
test_helpers.StopTarantoolWithCleanup(instance)
}
// Example demonstrates how to create and use the simplest variant of the pool.
func Example() {
// Start test Tarantool instance.
ttInstance, err := exampleStartTarantool("127.0.0.1:3013")
if err != nil {
fmt.Println("Failed to start Tarantool:", err)
return
}
defer exampleStopTarantool(ttInstance)
// Start a test etcd cluster and connect with a client to it.
cluster := integration.NewLazyCluster()
defer cluster.Terminate()
etcd, err := clientv3.New(clientv3.Config{
Endpoints: cluster.EndpointsGRPC(),
})
if err != nil {
fmt.Println("Unable to start etcd client:", err)
return
}
defer func() { _ = etcd.Close() }()
// And publish a cluster configuration to it.
_, err = etcd.Put(context.Background(), "/prefix/config/all", `
groups:
foo:
replicasets:
bar:
instances:
instance1:
iproto:
listen:
- uri: 127.0.0.1:3011
- uri: 127.0.0.1:3013
roles: [crud]
labels:
tags: "any,bar,3"
instance2:
iproto:
listen:
- uri: 127.0.0.1:3014
instance3:
iproto:
advertise:
client: 127.0.0.1:3015
`)
if err != nil {
fmt.Println("Failed to publish cluster configuration error:", err)
return
}
// The pool will try to connect to instances without TLS. It will send
// requests in round-robin. But you could use pool.PriorityBalancer to
// send request into instances by a priority.
examplePool, err := pool.NewPool(
dial.NewNetDialerFactory("testuser", "testpass", tarantool.Opts{
Timeout: 5 * time.Second,
}),
pool.NewRoundRobinBalancer(),
)
if err != nil {
fmt.Println("Unable to create a pool:", err)
return
}
for {
// The scheduler will watch for updates from etcd.
sched := scheduler.NewEtcdWatch(etcd, "/prefix")
defer sched.Stop()
disc := discoverer.NewFilter(
// The base discoverer gets a list of instance configurations from
// etcd.
discoverer.NewEtcd(etcd, "/prefix"),
// The filter filters the list and leaves only instances with
// Group == "foo".
filter.GroupOneOf{Groups: []string{"foo"}},
// You can play with other filters here, see:
// https://github.com/tarantool/go-discovery/filter/
// subpackage.
)
// The Subscriber will send instance configurations into the pool
// on updates.
etcdSubscriber := subscriber.NewFilter(
// The base subscriber watches for updates from etcd and generates
// a list of update events from it.
subscriber.NewSchedule(sched, disc),
// The filter filters the list of updates and leaves only instances
// with Name == "instance1".
filter.NameOneOf{Names: []string{"instance1"}},
)
// Subscribe the pool for updates from the subscriber. Subscription
// only to single subscriber at a moment is supported.
err := etcdSubscriber.Subscribe(context.Background(), examplePool)
if err != nil {
fmt.Println("Failed to subscribe:", err)
return
}
for {
// Any request from go-tarantool could be used.
request := tarantool.NewEvalRequest("return box.cfg.listen")
// You could use discovery.ModeRW or discovery.ModeRO to send
// requests to only RW or RO instances.
result, err := examplePool.Do(request, discovery.ModeAny).Get()
if errors.Is(err, pool.ErrUnsubscribed) {
// Something happened with a scheduler (see log messages), we
// need to recreate scheduler and subscribe to it again.
time.Sleep(time.Second)
fmt.Println("Unsubscribed from a scheduler.")
etcdSubscriber.Unsubscribe(examplePool)
break
}
if errors.Is(err, pool.ErrNoConnectedInstances) {
// The pool is not connected to an instance yet. We could just
// repeat the request.
//
// fmt.Println("No instances.")
// time.Sleep(time.Second)
//
// Commented to make the example repeatable and fast.
continue
}
etcdSubscriber.Unsubscribe(examplePool)
fmt.Println("Result:", result)
fmt.Println("Error:", err)
fmt.Println("Done.")
return
}
}
// Output:
// Result: [127.0.0.1:3013]
// Error: <nil>
// Done.
}
type exampleObserver struct {
wgEvent sync.WaitGroup
}
func newExampleObserver() *exampleObserver {
obs := &exampleObserver{}
obs.wgEvent = sync.WaitGroup{}
return obs
}
func (o *exampleObserver) Observe(events []discovery.Event, err error) {
if len(events) > 0 || err == nil {
fmt.Println("An event found.")
for _, event := range events {
instance := event.New
if event.Type == discovery.EventTypeRemove {
instance = event.Old
}
fmt.Println("Type:", event.Type)
fmt.Println("Group:", instance.Group)
fmt.Println("Replicaset:", instance.Replicaset)
fmt.Println("Name:", instance.Name)
fmt.Println("Mode:", instance.Mode.String())
fmt.Println("URI:", instance.URI)
fmt.Println("Roles:", instance.Roles)
fmt.Println("Labels:", instance.Labels)
}
o.wgEvent.Done()
}
if err != nil {
fmt.Println("Error from the observer:", err)
}
}
func Example_subscriber_Schedule_Etcd() {
cluster := integration.NewLazyCluster()
defer cluster.Terminate()
etcd, err := clientv3.New(clientv3.Config{
Endpoints: cluster.EndpointsGRPC(),
})
if err != nil {
fmt.Println("Unable to start etcd client:", err)
return
}
defer func() { _ = etcd.Close() }()
schedule := subscriber.NewSchedule(scheduler.NewEtcdWatch(etcd, "foo"),
discoverer.NewEtcd(etcd, "foo"))
obs := newExampleObserver()
obs.wgEvent.Add(2)
err = schedule.Subscribe(context.Background(), obs)
if err != nil {
fmt.Println("Subscribe error:", err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, err = etcd.Put(ctx, "foo/config/key", `
database:
mode: ro
groups:
foo:
replicasets:
bar:
instances:
zoo:
iproto:
advertise:
client: localhost:3011
roles: [crud]
labels:
tags: "any,bar,3"
`)
cancel()
if err != nil {
fmt.Println("Put error:", err)
return
}
obs.wgEvent.Wait()
schedule.Unsubscribe(obs)
fmt.Println("Done.")
// Output:
// An event found.
// An event found.
// Type: add
// Group: foo
// Replicaset: bar
// Name: zoo
// Mode: ro
// URI: [localhost:3011]
// Roles: [crud]
// Labels: map[tags:any,bar,3]
// Error from the observer: unsubscribed
// Done.
}
func Example_subscriber_Schedule_Etcd_canceled() {
cluster := integration.NewLazyCluster()
defer cluster.Terminate()
etcd, err := clientv3.New(clientv3.Config{
Endpoints: cluster.EndpointsGRPC(),
})
if err != nil {
fmt.Println("Unable to start etcd client:", err)
return
}
defer func() { _ = etcd.Close() }()
schedule := subscriber.NewSchedule(scheduler.NewEtcdWatch(etcd, "foo"),
discoverer.NewEtcd(etcd, "foo"))
obs := newExampleObserver()
ctx, cancel := context.WithCancel(context.Background())
cancel()
err = schedule.Subscribe(ctx, obs)
if err != nil {
fmt.Println("Subscribe error:", err)
}
fmt.Println("Done.")
// Output:
// Subscribe error: context canceled
// Done.
}
func Example_subscriber_Filter() {
cluster := integration.NewLazyCluster()
defer cluster.Terminate()
etcd, err := clientv3.New(clientv3.Config{
Endpoints: cluster.EndpointsGRPC(),
})
if err != nil {
fmt.Println("Unable to start etcd client:", err)
return
}
defer func() { _ = etcd.Close() }()
schedule := subscriber.NewSchedule(scheduler.NewEtcdWatch(etcd, "foo"),
discoverer.NewEtcd(etcd, "foo"))
filters := []discovery.Filter{
discovery.FilterFunc(func(inst discovery.Instance) bool {
return inst.Name == "zoo"
}),
discovery.FilterFunc(func(inst discovery.Instance) bool {
return inst.Group == "foo"
}),
}
filter := subscriber.NewFilter(schedule, filters...)
obs := newExampleObserver()
obs.wgEvent.Add(2)
err = filter.Subscribe(context.Background(), obs)
if err != nil {
fmt.Println("Subscribe error:", err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, err = etcd.Put(ctx, "foo/config/key", `
database:
mode: ro
groups:
foo:
replicasets:
bar:
instances:
zoo:
iproto:
advertise:
client: localhost:3011
peer:
params:
transport: plain
roles: [crud]
labels:
tags: "any,bar,3"
foo2:
replicasets:
bar2:
instances:
zoo2:
iproto:
advertise:
client: localhost:3012
peer:
params:
transport: ssl
roles: [crud]
labels:
tags: "any,bar,3"
`)
cancel()
if err != nil {
fmt.Println("Put error:", err)
return
}
obs.wgEvent.Wait()
filter.Unsubscribe(obs)
fmt.Println("Done.")
// Output:
// An event found.
// An event found.
// Type: add
// Group: foo
// Replicaset: bar
// Name: zoo
// Mode: ro
// URI: [localhost:3011]
// Roles: [crud]
// Labels: map[tags:any,bar,3]
// Error from the observer: unsubscribed
// Done.
}
func Example_subscriber_Filter_Etcd_canceled() {
cluster := integration.NewLazyCluster()
defer cluster.Terminate()
etcd, err := clientv3.New(clientv3.Config{
Endpoints: cluster.EndpointsGRPC(),
})
if err != nil {
fmt.Println("Unable to start etcd client:", err)
return
}
defer func() { _ = etcd.Close() }()
schedule := subscriber.NewSchedule(scheduler.NewEtcdWatch(etcd, "foo"),
discoverer.NewEtcd(etcd, "foo"))
filters := []discovery.Filter{
discovery.FilterFunc(func(inst discovery.Instance) bool {
return inst.Name == "zoo"
}),
}
filter := subscriber.NewFilter(schedule, filters...)
obs := newExampleObserver()
ctx, cancel := context.WithCancel(context.Background())
cancel()
err = filter.Subscribe(ctx, obs)
if err != nil {
fmt.Println("Subscribe error:", err)
}
fmt.Println("Done.")
// Output:
// Subscribe error: context canceled
// Done.
}
func Example_discoverer_Connectable() {
// Start test Tarantool instance.
ttInstance, err := exampleStartTarantool("127.0.0.1:3013")
if err != nil {
fmt.Println("Failed to start Tarantool:", err)
return
}
defer exampleStopTarantool(ttInstance)
// Start a test etcd cluster and connect with a client to it.
cluster := integration.NewLazyCluster()
defer cluster.Terminate()
etcd, err := clientv3.New(clientv3.Config{
Endpoints: cluster.EndpointsGRPC(),
})
if err != nil {
fmt.Println("Unable to start etcd client:", err)
return
}
defer func() { _ = etcd.Close() }()
// And publish a cluster configuration to it.
_, err = etcd.Put(context.Background(), "/prefix/config/all", `
groups:
foo:
replicasets:
bar:
instances:
instance1:
iproto:
advertise:
client: 127.0.0.1:3013
roles: [crud]
labels:
tags: "any,bar,3"
instance2:
iproto:
advertise:
client: 127.0.0.1:3014
instance3:
iproto:
advertise:
client: 127.0.0.1:3015
`)
if err != nil {
fmt.Println("Failed to publish cluster configuration error:", err)
return
}
// Create a net dialer factory.
factory := dial.NewNetDialerFactory("testuser", "testpass",
tarantool.Opts{Timeout: 5 * time.Second})
// Create a Connectable discoverer based on the Etcd discoverer.
disc := discoverer.NewConnectable(factory,
discoverer.NewEtcd(etcd, "/prefix"))
// Get a list of connectable instances.
inst, err := disc.Discovery(context.Background())
if err != nil {
fmt.Println("Failed to discover connectable instances:", err)
return
}
for _, instance := range inst {
fmt.Println("Instance found")
fmt.Println("Name:", instance.Name)
fmt.Println("Mode:", instance.Mode)
fmt.Println("URI:", instance.URI)
fmt.Println("Roles:", instance.Roles)
fmt.Println("Labels:", instance.Labels)
fmt.Println("Group:", instance.Group)
fmt.Println("Replicaset:", instance.Replicaset)
}
fmt.Println("Done.")
// Output:
// Instance found
// Name: instance1
// Mode: rw
// URI: [127.0.0.1:3013]
// Roles: [crud]
// Labels: map[tags:any,bar,3]
// Group: foo
// Replicaset: bar
// Done.
}
func Example_observer_Accumulator() {
events := []discovery.Event{
{
Type: discovery.EventTypeAdd,
New: discovery.Instance{
Name: "Cpt. Jack Sparrow",
Group: "Black Pearl",
},
},
{
Type: discovery.EventTypeUpdate,
Old: discovery.Instance{
Name: "Cpt. Jack Sparrow",
Group: "Black Pearl",
},
New: discovery.Instance{
Name: "Cpt. Jack Sparrow",
},
},
{
Type: discovery.EventTypeAdd,
New: discovery.Instance{
Name: "Cpt. Barbossa",
Group: "Black Pearl",
},
},
{
Type: discovery.EventTypeUpdate,
Old: discovery.Instance{
Name: "Cpt. Barbossa",
Group: "Black Pearl",
},
New: discovery.Instance{
Name: "Cpt. Barbossa",
},
},
{
Type: discovery.EventTypeRemove,
Old: discovery.Instance{
Name: "Cpt. Barbossa",
},
},
{
Type: discovery.EventTypeUpdate,
Old: discovery.Instance{
Name: "Cpt. Jack Sparrow",
},
New: discovery.Instance{
Name: "Cpt. Jack Sparrow",
Group: "Black Pearl",
Replicaset: "Pirates",
},
},
}
obs := newExampleObserver()
obs.wgEvent.Add(1)
accumulator := observer.NewAccumulator(obs)
accumulator.Observe(events, nil)
accumulator.Observe(nil, fmt.Errorf("done"))
fmt.Println("Done.")
// Output:
// An event found.
// Type: add
// Group: Black Pearl
// Replicaset: Pirates
// Name: Cpt. Jack Sparrow
// Mode: any
// URI: []
// Roles: []
// Labels: map[]
// Error from the observer: done
// Done.
}
func Example_subscriber_Connectable() {
// Start test Tarantool instance.
ttInstance, err := exampleStartTarantool("127.0.0.1:3013")
if err != nil {
fmt.Println("Failed to start Tarantool:", err)
return
}
defer exampleStopTarantool(ttInstance)
cluster := integration.NewLazyCluster()
defer cluster.Terminate()
etcd, err := clientv3.New(clientv3.Config{
Endpoints: cluster.EndpointsGRPC(),
})
if err != nil {
fmt.Println("Unable to start etcd client:", err)
return
}
defer func() { _ = etcd.Close() }()
// Create a net dialer factory.
factory := dial.NewNetDialerFactory("testuser", "testpass",
tarantool.Opts{Timeout: 5 * time.Second})
// Create a Connectable subscriber based on the Etcd subscriber.
connectable := subscriber.NewConnectable(factory,
subscriber.NewSchedule(scheduler.NewEtcdWatch(etcd, "foo"),
discoverer.NewEtcd(etcd, "foo")))
obs := newExampleObserver()
obs.wgEvent.Add(1)
err = connectable.Subscribe(context.Background(), obs)
if err != nil {
fmt.Println("Subscribe error:", err)
return
}
defer connectable.Unsubscribe(obs)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = etcd.Put(ctx, "foo/config/key", `
groups:
foo:
replicasets:
bar:
instances:
instance1:
iproto:
listen:
- uri: 127.0.0.1:3013
roles: [crud]
labels:
tags: "any,bar,3"
instance2:
iproto:
advertise:
client: 127.0.0.1:3014
instance3:
iproto:
advertise:
client: 127.0.0.1:3015
`)
if err != nil {
fmt.Println("Failed to publish cluster configuration error:", err)
return
}
obs.wgEvent.Wait()
obs.wgEvent.Add(1)
connectable.Unsubscribe(obs)
fmt.Println("Done.")
// Output:
// An event found.
// Type: add
// Group: foo
// Replicaset: bar
// Name: instance1
// Mode: rw
// URI: [127.0.0.1:3013]
// Roles: [crud]
// Labels: map[tags:any,bar,3]
// An event found.
// Type: remove
// Group: foo
// Replicaset: bar
// Name: instance1
// Mode: rw
// URI: [127.0.0.1:3013]
// Roles: [crud]
// Labels: map[tags:any,bar,3]
// Error from the observer: unsubscribed
// Done.
}