This repository was archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathcontroller.go
2227 lines (1840 loc) · 69 KB
/
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
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package controller provides the core Controller struct.
package controller
import (
"context"
"fmt"
"sort"
"time"
"github.com/featurebasedb/featurebase/v3/dax"
"github.com/featurebasedb/featurebase/v3/dax/computer"
"github.com/featurebasedb/featurebase/v3/dax/controller/poller"
"github.com/featurebasedb/featurebase/v3/dax/controller/schemar"
"github.com/featurebasedb/featurebase/v3/dax/snapshotter"
"github.com/featurebasedb/featurebase/v3/dax/writelogger"
"github.com/featurebasedb/featurebase/v3/errors"
"github.com/featurebasedb/featurebase/v3/logger"
"golang.org/x/sync/errgroup"
)
const (
txRetry = 5
)
// Ensure type implements interface.
var _ computer.Registrar = (*Controller)(nil)
var _ dax.Schemar = (*Controller)(nil)
var _ dax.WorkerRegistry = (*Controller)(nil)
type Controller struct {
// Schemar is used by the controller to get table, and other schema,
// information.
Schemar schemar.Schemar
Balancer Balancer
Transactor dax.Transactor
Snapshotter *snapshotter.Snapshotter
Writelogger *writelogger.Writelogger
// Director is used to send directives to computer workers.
Director Director
DirectiveVersion dax.DirectiveVersion
poller *poller.Poller
registrationBatchTimeout time.Duration
nodeChan chan *dax.Node
snappingTurtleTimeout time.Duration
snapControl chan struct{}
stopping chan struct{}
backgroundGroup errgroup.Group
logger logger.Logger
}
var supportedRoleTypes []dax.RoleType = []dax.RoleType{
dax.RoleTypeCompute,
dax.RoleTypeTranslate,
}
// New returns a new instance of Controller with default values.
func New(cfg Config) *Controller {
// Set up logger.
var logr logger.Logger = logger.StderrLogger
if cfg.Logger != nil {
logr = cfg.Logger
}
c := &Controller{
Schemar: schemar.NewNopSchemar(),
Balancer: NewNopBalancer(),
Director: NewNopDirector(),
registrationBatchTimeout: cfg.RegistrationBatchTimeout,
nodeChan: make(chan *dax.Node, 10),
snappingTurtleTimeout: cfg.SnappingTurtleTimeout,
snapControl: make(chan struct{}),
logger: logr,
}
// Poller.
pollerCfg := poller.Config{
AddressManager: c,
WorkerRegistry: c,
NodePoller: poller.NewHTTPNodePoller(logr),
PollInterval: cfg.PollInterval,
Logger: logr,
}
c.poller = poller.New(pollerCfg)
// Snapshotter.
c.Snapshotter = snapshotter.New(cfg.SnapshotterDir, c.logger)
// Writelogger.
c.Writelogger = writelogger.New(cfg.WriteloggerDir, c.logger)
return c
}
// Start starts long running subroutines.
func (c *Controller) Start() error {
// Set up the stopping channel here in case the controller restarts.
c.stopping = make(chan struct{})
if err := c.Transactor.Start(); err != nil {
return errors.Wrap(err, "starting transactor")
}
c.backgroundGroup.Go(c.poller.Run) // TODO: this could just use c.stopping as well?
c.backgroundGroup.Go(func() error {
return c.nodeRegistrationRoutine(c.nodeChan, c.registrationBatchTimeout)
})
c.backgroundGroup.Go(func() error {
return c.snappingTurtleRoutine(c.snappingTurtleTimeout, c.snapControl, c.logger.WithPrefix("Snapping Turtle: "))
})
return nil
}
// Stop stops the node registration routine.
func (c *Controller) Stop() error {
c.poller.Stop()
close(c.stopping)
err := c.backgroundGroup.Wait()
err2 := c.Transactor.Close()
if err != nil {
return errors.Wrap(err, "waiting on background routines")
}
return errors.Wrap(err2, "closing transactor")
}
// RegisterNodes adds nodes to the controller's list of registered
// nodes.
func (c *Controller) RegisterNodes(ctx context.Context, nodes ...*dax.Node) error {
c.logger.Printf("c.RegisterNodes(): %s", dax.Nodes(nodes))
// Validate input.
for _, n := range nodes {
if n.Address == "" {
return NewErrNodeKeyInvalid(n.Address)
}
if len(n.RoleTypes) == 0 {
return NewErrRoleTypeInvalid(dax.RoleType(""))
}
for _, v := range n.RoleTypes {
if !dax.RoleTypes(supportedRoleTypes).Contains(v) {
return NewErrRoleTypeInvalid(v)
}
}
}
var directives []*dax.Directive
fn := func(tx dax.Transaction, writable bool) error {
// workerSet maintains the set of workers which have a job assignment change
// and therefore need to be sent an updated Directive.
workerSet := NewAddressSet()
// diffByAddr keeps track of the diffs that have been applied to each
// specific address.
// TODO(tlt): I don't understand why we're keeping track of the
// dax.WorkerDiff here (as opposed to just the unique Address) because it
// doesn't ever seem to be used.
diffByAddr := make(map[dax.Address]dax.WorkerDiff)
// Create node if we don't already have it
for _, n := range nodes {
// If the node already exists, skip it.
if node, _ := c.Balancer.ReadNode(tx, n.Address); node != nil {
// If the node already exists, but it has indicated that it doesn't
// have a directive, then send it one.
if !n.HasDirective {
workerSet.Add(n.Address)
}
continue
}
// Add the node to the workerSet so that it receives a directive.
// Even if there is currently no data for this worker (i.e. it
// doesn't result in a diffByAddr entry below), we still want to
// send it a "reset" directive so that in the off chance it has some
// local data, that data gets removed.
workerSet.Add(n.Address)
adiffs, err := c.Balancer.AddWorker(tx, n)
if err != nil {
return errors.Wrap(err, "adding worker")
}
for _, diff := range adiffs {
existingDiff, ok := diffByAddr[dax.Address(diff.Address)]
if !ok {
existingDiff.Address = diff.Address
}
existingDiff.Add(diff)
diffByAddr[dax.Address(diff.Address)] = existingDiff
}
}
// Add any worker which has a diff to the workerSet so that it receives a
// directive.
for addr := range diffByAddr {
workerSet.Add(addr)
}
// No need to send directives if the workerSet is empty.
if len(workerSet) == 0 {
return nil
}
// Convert the slice of addresses into a slice of addressMethod containing
// the appropriate method.
addrMethods := applyAddressMethod(workerSet.SortedSlice(), dax.DirectiveMethodFull)
// For the addresses which are being added, set their method to "reset".
for i := range addrMethods {
for j := range nodes {
if addrMethods[i].address == nodes[j].Address {
addrMethods[i].method = dax.DirectiveMethodReset
}
}
}
var err error
directives, err = c.buildDirectives(ctx, tx, addrMethods)
if err != nil {
return errors.Wrap(err, "building directives")
}
return nil
}
if err := dax.RetryWithTx(ctx, c.Transactor, fn, true, txRetry); err != nil {
return errors.Wrap(err, "retry with tx: write")
}
if err := c.sendDirectives(ctx, directives); err != nil {
return NewErrDirectiveSendFailure(err.Error())
}
return nil
}
// RegisterNode adds a node to the controller's list of registered
// nodes. It makes no guarantees about when the node will actually be
// used for anything or assigned any jobs.
func (c *Controller) RegisterNode(ctx context.Context, n *dax.Node) error {
// Validate input.
if n.Address == "" {
return NewErrNodeKeyInvalid(n.Address)
}
if len(n.RoleTypes) == 0 {
return NewErrRoleTypeInvalid(dax.RoleType(""))
}
for _, v := range n.RoleTypes {
if !dax.RoleTypes(supportedRoleTypes).Contains(v) {
return NewErrRoleTypeInvalid(v)
}
}
tx, err := c.Transactor.BeginTx(ctx, false)
if err != nil {
return errors.Wrap(err, "beginning tx")
}
defer tx.Rollback()
// If the node is telling us that it doesn't have a directive, let it
// continue because we need to send it one even though we already think we
// know about it.
if node, _ := c.Balancer.ReadNode(tx, n.Address); node != nil && n.HasDirective {
return nil
}
c.nodeChan <- n
return nil
}
// CheckInNode handles a "check-in" from a compute node. These come
// periodically, and if the controller already knows about the compute node, it
// can simply no-op. If, however, the controller is not aware of the node
// checking in, then that probably means that the poller has removed that node
// from its list (perhaps due to a network fault) and therefore the node needs
// to be re-registered.
func (c *Controller) CheckInNode(ctx context.Context, n *dax.Node) error {
if n == nil || n.Address == "" {
return NewErrNodeKeyInvalid("")
}
tx, err := c.Transactor.BeginTx(ctx, false)
if err != nil {
return errors.Wrap(err, "beginning tx")
}
defer tx.Rollback()
// If we already know about this node, just no-op. In the future, we may
// want this check-in payload to include things like the compute node's
// Directive; then we could check that the compute node is actually doing
// what we expect it to be doing. But for now, we're just checking that we
// know about the compute node at all.
//
// However, if the node is telling us that it doesn't have a directive, let
// it continue because we need to send it one even though we already think
// we know about it.
if node, _ := c.Balancer.ReadNode(tx, n.Address); node != nil && n.HasDirective {
return nil
}
c.nodeChan <- n
return nil
}
// DeregisterNodes removes nodes from the controller's list of registered nodes.
// It sends directives to the removed nodes, but ignores errors.
func (c *Controller) DeregisterNodes(ctx context.Context, addresses ...dax.Address) error {
var directives []*dax.Directive
fn := func(tx dax.Transaction, writable bool) error {
// workerSet maintains the set of workers which have a job assignment change
// and therefore need to be sent an updated Directive.
workerSet := NewAddressSet()
// diffByAddr keeps track of the diffs that have been applied to each
// specific address.
diffByAddr := make(map[dax.Address]dax.WorkerDiff)
for _, address := range addresses {
// Add the removed node to the workerSet so that it receives a
// directive. Even if there is currently no data for the worker (i.e. it
// doesn't result in a diffByAddr entry below), we still want to send it
// a "reset" directive so that in the off chance it has some local data,
// that data gets removed.
// TODO(tlt): see below where we actually REMOVE this. We need to
// address this confusion.
// workerSet.Add(address)
rdiffs, err := c.Balancer.RemoveWorker(tx, address)
if err != nil {
return errors.Wrapf(err, "removing worker: %s", address)
}
// we assume that the job names are different between the
// different role types so we don't have to track each
// role separately which would be annoying.
for _, diff := range rdiffs {
existingDiff, ok := diffByAddr[dax.Address(diff.Address)]
if !ok {
existingDiff.Address = diff.Address
}
existingDiff.Add(diff)
diffByAddr[dax.Address(diff.Address)] = existingDiff
}
}
for addr := range diffByAddr {
workerSet.Add(addr)
}
// Don't send a Directive to the removed nodes after all.
// TODO(tlt): we have to do this because otherwise the send request hangs
// while holding a mu.Lock on Controller.
for _, addr := range addresses {
workerSet.Remove(addr)
}
// No need to send Directives if nothing has ultimately changed.
if len(workerSet) == 0 {
return nil
}
// Convert the slice of addresses into a slice of addressMethod containing
// the appropriate method.
addrMethods := applyAddressMethod(workerSet.SortedSlice(), dax.DirectiveMethodFull)
// For the addresses which are being removed, set their method to "reset".
for i := range addrMethods {
for j := range addresses {
if addrMethods[i].address == addresses[j] {
addrMethods[i].method = dax.DirectiveMethodReset
}
}
}
var err error
directives, err = c.buildDirectives(ctx, tx, addrMethods)
if err != nil {
return errors.Wrap(err, "building directives")
}
return nil
}
if err := dax.RetryWithTx(ctx, c.Transactor, fn, true, txRetry); err != nil {
return errors.Wrap(err, "retry with tx: write")
}
if err := c.sendDirectives(ctx, directives); err != nil {
return NewErrDirectiveSendFailure(err.Error())
}
return nil
}
// nodesTranslateReadOrWrite contains the logic for the c.nodesTranslate()
// method, but it supports being called with either a read or write lock.
func (c *Controller) nodesTranslateReadOrWrite(ctx context.Context, tx dax.Transaction, role *dax.TranslateRole, qdbid dax.QualifiedDatabaseID, createMissing bool, asWrite bool) ([]dax.AssignedNode, bool, []*dax.Directive, error) {
qtid := role.TableKey.QualifiedTableID()
roleType := dax.RoleTypeTranslate
inJobs := dax.NewSet[dax.Job]()
for _, p := range role.Partitions {
partitionString := partition(role.TableKey, p).String()
inJobs.Add(dax.Job(partitionString))
}
workers, err := c.Balancer.WorkersForJobs(tx, roleType, qdbid, inJobs.Sorted()...)
if err != nil {
return nil, false, nil, errors.Wrap(err, "getting workers for jobs")
}
// figure out if any jobs in the role have no workers assigned
outJobs := dax.NewSet[dax.Job]()
for _, worker := range workers {
for _, job := range worker.Jobs {
outJobs.Add(job)
}
}
missed := inJobs.Minus(outJobs).Sorted()
if !createMissing && len(missed) > 0 {
return nil, false, nil, NewErrUnassignedJobs(missed)
}
var directives []*dax.Directive
// If any provided jobs were not returned in the WorkersForJobs request,
// then create those.
if createMissing && len(missed) > 0 {
// If we are currently under a read lock, and we get to this point, it
// means that we have partitions which need to be assigned (and
// directives sent) to workers. In that case, we need to abort this
// method run and notify the caller to rety as a write.
if !asWrite {
return nil, true, nil, nil
}
sort.Slice(missed, func(i, j int) bool { return missed[i] < missed[j] })
workerDiffs := dax.WorkerDiffs{}
for _, job := range missed {
j, err := decodePartition(job)
if err != nil {
return nil, false, nil, NewErrInternal(err.Error())
}
diffs, err := c.Balancer.AddJobs(tx, roleType, qtid, j.Job())
if err != nil {
return nil, false, nil, errors.Wrap(err, "adding job")
}
workerDiffs = workerDiffs.Apply(diffs)
}
directives, err = c.buildDirectivesAsDiffs(ctx, tx, roleType, workerDiffs)
if err != nil {
return nil, false, nil, errors.Wrap(err, "building directives as diffs")
}
// Re-run WorkersForJobs.
workers, err = c.Balancer.WorkersForJobs(tx, roleType, qdbid, inJobs.Sorted()...)
if err != nil {
return nil, false, nil, errors.Wrap(err, "getting workers for jobs")
}
}
nodes, err := c.translateWorkersToAssignedNodes(tx, workers)
return nodes, false, directives, errors.Wrap(err, "converting to assigned nodes")
}
// nodesComputeReadOrWrite contains the logic for the c.nodesCompute() method,
// but it supports being called with either a read or write lock.
func (c *Controller) nodesComputeReadOrWrite(ctx context.Context, tx dax.Transaction, role *dax.ComputeRole, qdbid dax.QualifiedDatabaseID, createMissing bool, asWrite bool) ([]dax.AssignedNode, bool, []*dax.Directive, error) {
qtid := role.TableKey.QualifiedTableID()
roleType := dax.RoleTypeCompute
inJobs := dax.NewSet[dax.Job]()
for _, s := range role.Shards {
shardString := shard(role.TableKey, s).String()
inJobs.Add(dax.Job(shardString))
}
workers, err := c.Balancer.WorkersForJobs(tx, roleType, qdbid, inJobs.Sorted()...)
if err != nil {
return nil, false, nil, errors.Wrap(err, "getting workers for jobs")
}
// figure out if any jobs in the role have no workers assigned
outJobs := dax.NewSet[dax.Job]()
for _, worker := range workers {
for _, job := range worker.Jobs {
outJobs.Add(job)
}
}
missed := inJobs.Minus(outJobs).Sorted()
if !createMissing && len(missed) > 0 {
return nil, false, nil, NewErrUnassignedJobs(missed)
}
var directives []*dax.Directive
// If any provided jobs were not returned in the WorkersForJobs request,
// then create those.
if createMissing && len(missed) > 0 {
// If we are currently under a read lock, and we get to this point, it
// means that we have shards which need to be assigned (and directives
// sent) to workers. In that case, we need to abort this method run and
// notify the caller to rety as a write.
if !asWrite {
return nil, true, nil, nil
}
sort.Slice(missed, func(i, j int) bool { return missed[i] < missed[j] })
workerDiffs := dax.WorkerDiffs{}
for _, job := range missed {
j, err := decodeShard(job)
if err != nil {
return nil, false, nil, NewErrInternal(err.Error())
}
diffs, err := c.Balancer.AddJobs(tx, roleType, qtid, j.Job())
if err != nil {
return nil, false, nil, errors.Wrap(err, "adding job")
}
workerDiffs = workerDiffs.Apply(diffs)
}
directives, err = c.buildDirectivesAsDiffs(ctx, tx, roleType, workerDiffs)
if err != nil {
return nil, false, nil, errors.Wrap(err, "building directives as diffs")
}
// Re-run WorkersForJobs.
workers, err = c.Balancer.WorkersForJobs(tx, roleType, qdbid, inJobs.Sorted()...)
if err != nil {
return nil, false, nil, errors.Wrap(err, "getting workers for jobs")
}
}
nodes, err := c.computeWorkersToAssignedNodes(tx, workers)
return nodes, false, directives, errors.Wrap(err, "converting to assigned nodes")
}
func (c *Controller) computeWorkersToAssignedNodes(tx dax.Transaction, workers []dax.WorkerInfo) ([]dax.AssignedNode, error) {
nodes := []dax.AssignedNode{}
for _, worker := range workers {
// convert worker.Jobs []string to map[TableName][]Shard
computeMap := make(map[dax.TableKey]dax.ShardNums)
for _, job := range worker.Jobs {
j, err := decodeShard(job)
if err != nil {
return nil, NewErrInternal(err.Error())
}
computeMap[j.table()] = append(computeMap[j.table()], j.shardNum())
}
for table, shards := range computeMap {
// Sort the shards uint64 slice before returning it.
sort.Sort(shards)
nodes = append(nodes, dax.AssignedNode{
Address: dax.Address(worker.Address),
Role: &dax.ComputeRole{
TableKey: table,
Shards: shards,
},
})
}
}
return nodes, nil
}
func (c *Controller) translateWorkersToAssignedNodes(tx dax.Transaction, workers []dax.WorkerInfo) ([]dax.AssignedNode, error) {
nodes := []dax.AssignedNode{}
for _, worker := range workers {
// covert worker.Jobs []string to map[string][]Partition
translateMap := make(map[dax.TableKey]dax.PartitionNums)
for _, job := range worker.Jobs {
j, err := decodePartition(job)
if err != nil {
return nil, NewErrInternal(err.Error())
}
translateMap[j.table()] = append(translateMap[j.table()], j.partitionNum())
}
for table, partitions := range translateMap {
// Sort the partitions int slice before returning it.
sort.Sort(partitions)
nodes = append(nodes, dax.AssignedNode{
Address: dax.Address(worker.Address),
Role: &dax.TranslateRole{
TableKey: table,
Partitions: partitions,
},
})
}
}
return nodes, nil
}
// CreateDatabase adds a database to the schemar.
func (c *Controller) CreateDatabase(ctx context.Context, qdb *dax.QualifiedDatabase) error {
// Create Database ID.
if _, err := qdb.CreateID(); err != nil {
return errors.Wrap(err, "creating database ID")
}
fn := func(tx dax.Transaction, writable bool) error {
if err := c.Schemar.CreateDatabase(tx, qdb); err != nil {
return errors.Wrap(err, "creating database in schemar")
}
return nil
}
return dax.RetryWithTx(ctx, c.Transactor, fn, true, txRetry)
}
func (c *Controller) DropDatabase(ctx context.Context, qdbid dax.QualifiedDatabaseID) error {
var directives []*dax.Directive
fn := func(tx dax.Transaction, writable bool) error {
// Get all the tables for the database and call dropTable on each one.
qtbls, err := c.Schemar.Tables(tx, qdbid)
if err != nil {
return errors.Wrapf(err, "getting tables for database: %s", qdbid)
}
// workerSet maintains the set of workers which have a job assignment change
// and therefore need to be sent an updated Directive.
workerSet := NewAddressSet()
for _, qtbl := range qtbls {
qtid := qtbl.QualifiedID()
addrs, err := c.dropTable(tx, qtid)
if err != nil {
return errors.Wrapf(err, "dropping table: %s", qtid)
}
workerSet.Merge(addrs)
}
addrs := make([]dax.Address, 0, len(workerSet))
for worker := range workerSet {
addrs = append(addrs, worker)
}
if err := c.Balancer.ReleaseWorkers(tx, addrs...); err != nil {
return errors.Wrap(err, "freeing workers")
}
// Drop the database record from the schema.
if err := c.Schemar.DropDatabase(tx, qdbid); err != nil {
return errors.Wrap(err, "dropping database from schemar")
}
// Convert the slice of addresses into a slice of addressMethod containing
// the appropriate method.
addrMethods := applyAddressMethod(workerSet.SortedSlice(), dax.DirectiveMethodFull)
directives, err = c.buildDirectives(ctx, tx, addrMethods)
if err != nil {
return errors.Wrap(err, "building directives")
}
return nil
}
if err := dax.RetryWithTx(ctx, c.Transactor, fn, true, txRetry); err != nil {
return errors.Wrap(err, "retry with tx: write")
}
if err := c.sendDirectives(ctx, directives); err != nil {
return NewErrDirectiveSendFailure(err.Error())
}
return nil
}
// DatabaseByName returns the database for the given name.
func (c *Controller) DatabaseByName(ctx context.Context, orgID dax.OrganizationID, dbname dax.DatabaseName) (*dax.QualifiedDatabase, error) {
tx, err := c.Transactor.BeginTx(ctx, false)
if err != nil {
return nil, errors.Wrap(err, "beginning tx")
}
defer tx.Rollback()
qdb, err := c.Schemar.DatabaseByName(tx, orgID, dbname)
if err != nil {
return nil, errors.Wrap(err, "getting database by name from schemar")
}
return qdb, nil
}
// DatabaseByID returns the database for the given id.
func (c *Controller) DatabaseByID(ctx context.Context, qdbid dax.QualifiedDatabaseID) (*dax.QualifiedDatabase, error) {
tx, err := c.Transactor.BeginTx(ctx, false)
if err != nil {
return nil, errors.Wrap(err, "beginning tx")
}
defer tx.Rollback()
qdb, err := c.Schemar.DatabaseByID(tx, qdbid)
if err != nil {
return nil, errors.Wrap(err, "getting database by id from schemar")
}
return qdb, nil
}
// SetDatabaseOption sets the option on the given database.
func (c *Controller) SetDatabaseOption(ctx context.Context, qdbid dax.QualifiedDatabaseID, option string, value string) error {
var directives []*dax.Directive
fn := func(tx dax.Transaction, writable bool) error {
if err := c.Schemar.SetDatabaseOption(tx, qdbid, option, value); err != nil {
return errors.Wrapf(err, "setting database option: %s", option)
}
diffs, err := c.Balancer.BalanceDatabase(tx, qdbid)
if err != nil {
return errors.Wrapf(err, "balancing database: %s", qdbid)
}
workerSet := NewAddressSet()
for _, diff := range diffs {
workerSet.Add(dax.Address(diff.Address))
}
// Convert the slice of addresses into a slice of addressMethod containing
// the appropriate method.
addrMethods := applyAddressMethod(workerSet.SortedSlice(), dax.DirectiveMethodFull)
directives, err = c.buildDirectives(ctx, tx, addrMethods)
if err != nil {
return errors.Wrap(err, "building directives")
}
return nil
}
if err := dax.RetryWithTx(ctx, c.Transactor, fn, true, txRetry); err != nil {
return errors.Wrap(err, "retry with tx: write")
}
if err := c.sendDirectives(ctx, directives); err != nil {
return NewErrDirectiveSendFailure(err.Error())
}
return nil
}
func (c *Controller) Databases(ctx context.Context, orgID dax.OrganizationID, ids ...dax.DatabaseID) ([]*dax.QualifiedDatabase, error) {
if orgID == "" {
return nil, dax.NewErrOrganizationIDDoesNotExist(orgID)
}
tx, err := c.Transactor.BeginTx(ctx, false)
if err != nil {
return nil, errors.Wrap(err, "beginning tx")
}
defer tx.Rollback()
// Get the tables from the schemar.
return c.Schemar.Databases(tx, orgID, ids...)
}
// CreateTable adds a table to the schemar, and then sends directives to all
// affected nodes based on the change.
func (c *Controller) CreateTable(ctx context.Context, qtbl *dax.QualifiedTable) error {
c.logger.Debugf("CreateTable %+v", qtbl)
// Create Table ID.
if _, err := qtbl.CreateID(); err != nil {
return errors.Wrap(err, "creating table ID")
}
var directives []*dax.Directive
fn := func(tx dax.Transaction, writable bool) error {
// Create the table in schemar.
if err := c.Schemar.CreateTable(tx, qtbl); err != nil {
return errors.Wrapf(err, "creating table: %s", qtbl)
}
var addrMethods []addressMethod
// If the table is keyed, add partitions to the balancer.
if qtbl.StringKeys() {
// workerSet maintains the set of workers which have a job assignment change
// and therefore need to be sent an updated Directive.
workerSet := NewAddressSet()
// Generate the list of partitionsToAdd to be added.
partitionsToAdd := make(dax.PartitionNums, qtbl.PartitionN)
for partitionNum := 0; partitionNum < qtbl.PartitionN; partitionNum++ {
partitionsToAdd[partitionNum] = dax.PartitionNum(partitionNum)
}
jobs := make([]dax.Job, 0, len(partitionsToAdd))
for _, p := range partitionsToAdd {
jobs = append(jobs, partition(qtbl.Key(), p).Job())
}
diffs, err := c.Balancer.AddJobs(tx, dax.RoleTypeTranslate, qtbl.QualifiedID(), jobs...)
if err != nil {
return errors.Wrap(err, "adding job")
}
for _, diff := range diffs {
workerSet.Add(dax.Address(diff.Address))
}
// Convert the slice of addresses into a slice of addressMethod containing
// the appropriate method.
addrMethods = applyAddressMethod(workerSet.SortedSlice(), dax.DirectiveMethodFull)
}
// This is more FieldVersion hackery. Even if the table is not keyed, we
// still want to manage partition 0 for the table in case any of the table's
// fields contain string keys (we use partition 0 for field string keys for
// now; in the future we should distribute/balance the field key translation
// like we do shards and partitions).
if !qtbl.StringKeys() {
// workerSet maintains the set of workers which have a job assignment change
// and therefore need to be sent an updated Directive.
workerSet := NewAddressSet()
p := dax.PartitionNum(0)
// We don't currently use the returned diff, other than to determine
// which worker was affected, because we send the full Directive
// every time.
diffs, err := c.Balancer.AddJobs(tx, dax.RoleTypeTranslate, qtbl.QualifiedID(), partition(qtbl.Key(), p).Job())
if err != nil {
return errors.Wrap(err, "adding job")
}
for _, diff := range diffs {
workerSet.Add(dax.Address(diff.Address))
}
// Convert the slice of addresses into a slice of addressMethod containing
// the appropriate method.
addrMethods = applyAddressMethod(workerSet.SortedSlice(), dax.DirectiveMethodFull)
}
var err error
directives, err = c.buildDirectives(ctx, tx, addrMethods)
if err != nil {
return errors.Wrap(err, "building directives")
}
return nil
}
if err := dax.RetryWithTx(ctx, c.Transactor, fn, true, txRetry); err != nil {
return errors.Wrap(err, "retry with tx: write")
}
if err := c.sendDirectives(ctx, directives); err != nil {
return NewErrDirectiveSendFailure(err.Error())
}
return nil
}
// DropTable removes a table from the schema and sends directives to all affected
// nodes based on the change.
func (c *Controller) DropTable(ctx context.Context, qtid dax.QualifiedTableID) error {
var directives []*dax.Directive
fn := func(tx dax.Transaction, writable bool) error {
addrs, err := c.dropTable(tx, qtid)
if err != nil {
return errors.Wrapf(err, "dropping table: %s", qtid)
}
// Convert the slice of addresses into a slice of addressMethod containing
// the appropriate method.
addrMethods := applyAddressMethod(addrs.SortedSlice(), dax.DirectiveMethodFull)
directives, err = c.buildDirectives(ctx, tx, addrMethods)
if err != nil {
return errors.Wrap(err, "building directives")
}
return nil
}
if err := dax.RetryWithTx(ctx, c.Transactor, fn, true, txRetry); err != nil {
return errors.Wrap(err, "retry with tx: write")
}
if err := c.sendDirectives(ctx, directives); err != nil {
return NewErrDirectiveSendFailure(err.Error())
}
return nil
}
// dropTable removes a table from the schema and sends directives to all affected
// nodes based on the change.
func (c *Controller) dropTable(tx dax.Transaction, qtid dax.QualifiedTableID) (AddressSet, error) {
// Get the table from the schemar.
if _, err := c.Schemar.Table(tx, qtid); err != nil {
return nil, errors.Wrapf(err, "table not in schemar: %s", qtid)
}
// workerSet maintains the set of workers which have a job assignment change
// and therefore need to be sent an updated Directive.
workerSet := NewAddressSet()
diffs, err := c.Balancer.RemoveJobs(tx, dax.RoleTypeCompute, qtid)
if err != nil {
return nil, errors.Wrapf(err, "removing compute jobs for table: %s", qtid)
}
for _, diff := range diffs {
workerSet.Add(dax.Address(diff.Address))
}
diffs, err = c.Balancer.RemoveJobs(tx, dax.RoleTypeTranslate, qtid)
if err != nil {
return nil, errors.Wrapf(err, "removing translate jobs for table: %s", qtid)
}
for _, diff := range diffs {
workerSet.Add(dax.Address(diff.Address))
}
// Remove table from schemar.
if err := c.Schemar.DropTable(tx, qtid); err != nil {
return nil, errors.Wrapf(err, "dropping table from schemar: %s", qtid)
}
// Delete relevant table files from snapshotter and writelogger.
if err := c.Snapshotter.DeleteTable(qtid); err != nil {
return nil, errors.Wrap(err, "deleting from snapshotter")
}
if err := c.Writelogger.DeleteTable(qtid); err != nil {
return nil, errors.Wrap(err, "deleting from writelogger")
}
return workerSet, nil
}
// TableByID returns a table by quaified table id.
func (c *Controller) TableByID(ctx context.Context, qtid dax.QualifiedTableID) (*dax.QualifiedTable, error) {
tx, err := c.Transactor.BeginTx(ctx, false)
if err != nil {
return nil, errors.Wrap(err, "beginning tx")
}
defer tx.Rollback()
// Get the table from the schemar.
return c.Schemar.Table(tx, qtid)
}
// Tables returns a list of tables by name.
func (c *Controller) Tables(ctx context.Context, qdbid dax.QualifiedDatabaseID, ids ...dax.TableID) ([]*dax.QualifiedTable, error) {
tx, err := c.Transactor.BeginTx(ctx, false)
if err != nil {
return nil, errors.Wrap(err, "beginning tx")
}
defer tx.Rollback()
// Get the tables from the schemar.
return c.Schemar.Tables(tx, qdbid, ids...)
}
// RemoveShards deregisters the table/shard combinations with the controller and
// sends the necessary directives.
func (c *Controller) RemoveShards(ctx context.Context, qtid dax.QualifiedTableID, shards ...dax.ShardNum) error {
var directives []*dax.Directive
fn := func(tx dax.Transaction, writable bool) error {
// workerSet maintains the set of workers which have a job assignment change
// and therefore need to be sent an updated Directive.
workerSet := NewAddressSet()
for _, s := range shards {
// We don't currently use the returned diff, other than to determine
// which worker was affected, because we send the full Directive every
// time.
diffs, err := c.Balancer.RemoveJobs(tx, dax.RoleTypeCompute, qtid, shard(qtid.Key(), s).Job())