forked from FeatureBaseDB/featurebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_directive.go
987 lines (860 loc) · 29.7 KB
/
api_directive.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
// Copyright 2021 Molecula Corp. All rights reserved.
package pilosa
import (
"context"
"io"
"log"
"sync"
"github.com/featurebasedb/featurebase/v3/dax"
"github.com/featurebasedb/featurebase/v3/dax/computer"
"github.com/featurebasedb/featurebase/v3/dax/storage"
"github.com/featurebasedb/featurebase/v3/disco"
"github.com/pkg/errors"
)
// ApplyDirective applies a Directive received, from the Controller, at the
// /directive endpoint.
func (api *API) ApplyDirective(ctx context.Context, d *dax.Directive) error {
// Get the current directive for comparison.
previousDirective := api.holder.Directive()
// Check that incoming version is newer.
// Note: 0 is an invalid Directive version. This decision was made because
// previousDirective is not a pointer to a directive, but a concrete
// Directive. Which means we can't check for nil, and by default it has a
// version of 0. So in order to ensure the version has increased, we need to
// require that incoming directive versions are greater than 0.
if d.Version == 0 {
return errors.Errorf("directive version cannot be 0")
} else if previousDirective.Version >= d.Version {
return errors.Errorf("directive version mismatch, got %d, but already have %d", d.Version, previousDirective.Version)
}
// Handle the operations based on the directive method.
switch d.Method {
case dax.DirectiveMethodDiff:
// In order to prevent adding too much code specific to handling a diff
// directive (e.g. adding something like an `enactDirectiveDiff()`
// method), we are instead going to build a full Directive based on the
// diff, and then proceed normally as if we had received a full
// Directive. We do that by copying the previous Directive and then
// applying the diffs to the copy.
newD := previousDirective.Copy()
// Apply the diffs from the incoming Directive to the new, copied
// Directive.
newD.ApplyDiff(d)
// Now proceed with the new diff as if we had received it as a full diff.
d = newD
case dax.DirectiveMethodFull:
// pass: normal operation
case dax.DirectiveMethodReset:
// Delete all tables.
if err := api.deleteAllIndexes(ctx); err != nil {
return errors.Wrap(err, "deleting all indexes")
}
// Set previousDirective to empty so the diff handles everything as new.
previousDirective = dax.Directive{}
case dax.DirectiveMethodSnapshot:
// TODO(tlt): this was the existing logic, but we should really diff the
// directive and ensure that overwriting the value in the cache doesn't
// have a negative effect.
api.holder.SetDirective(d)
return nil
default:
return errors.Errorf("invalid directive method: %s", d.Method)
}
// Cache this directive as the latest applied. There is functionality within
// the "enactDirective" stage of ApplyDirective which validates against this
// cached Directive, so it's important that it be set before calling
// enactDirective(). An example: when loading partition data from the
// Writelogger, there are validations to ensure that the partition being
// loaded is meant to be handled by this node; that validation is done
// against the cached Directive.
// TODO(tlt): despite what this comment says, this logic is not sound; we
// shouldn't be setting the directive until enactiveDirective() succeeds.
api.holder.SetDirective(d)
defer api.holder.SetDirectiveApplied(true)
return api.enactDirective(ctx, &previousDirective, d)
}
// deleteAllIndexes deletes all indexes handled by this node.
func (api *API) deleteAllIndexes(ctx context.Context) error {
indexes, err := api.Schema(ctx, false)
if err != nil {
return errors.Wrap(err, "getting schema")
}
for i := range indexes {
if err := api.DeleteIndex(ctx, indexes[i].Name); err != nil {
return errors.Wrapf(err, "deleting index: %s", indexes[i].Name)
}
}
return nil
}
// directiveJobType allows us to switch on jobType in the directiveWorker in
// order to use a single worker pool for all job types (as opposed to having a
// separate worker pool for each job type).
type directiveJobType interface {
// We have this method just to prevent *any* struct from implementing this
// interface automatically. But, interestingly enough, we don't actually
// have to have this method on the implementation because we embed the
// interface.
isJobType() bool
}
type directiveJobTableKeys struct {
directiveJobType
idx *Index
tkey dax.TableKey
partition dax.PartitionNum
}
type directiveJobFieldKeys struct {
directiveJobType
tkey dax.TableKey
field dax.FieldName
}
type directiveJobShards struct {
directiveJobType
tkey dax.TableKey
shard dax.ShardNum
}
// directiveWorker is a worker in a worker pool which handles portions of a
// directive. Multiple instances of directiveWorker run in goroutines in order
// to load data from snapshotter and writelogger concurrently. Note: unlike the
// api.ingestWorkerPool, of which one pool is always running, the
// directiveWorker pool is only running during the life of the
// api.ApplyDirective call. Technically, this means that multiple
// directiveWorker pools could be active at the same time, but we should never
// be running more than once instance of ApplyDirective concurrently.
func (api *API) directiveWorker(ctx context.Context, jobs <-chan directiveJobType, errs chan<- error) {
for j := range jobs {
switch job := j.(type) {
case directiveJobTableKeys:
if err := api.loadTableKeys(ctx, job.idx, job.tkey, job.partition); err != nil {
errs <- errors.Wrapf(err, "loading table keys: %s, %s", job.tkey, job.partition)
}
case directiveJobFieldKeys:
if err := api.loadFieldKeys(ctx, job.tkey, job.field); err != nil {
errs <- errors.Wrapf(err, "loading field keys: %s, %s", job.tkey, job.field)
}
case directiveJobShards:
if err := api.loadShard(ctx, job.tkey, job.shard); err != nil {
errs <- errors.Wrapf(err, "loading shard: %s, %s", job.tkey, job.shard)
}
default:
errs <- errors.Errorf("unsupported job type: %T %[1]v", job)
}
select {
case <-ctx.Done():
return
default:
// continue pulling jobs off the channel
}
}
}
func (api *API) enactDirective(ctx context.Context, fromD, toD *dax.Directive) error {
// enactTables is called before the jobs that run in the worker pool because
// it probably makes sense to apply the schema before trying to load data
// concurrently.
if err := api.enactTables(ctx, fromD, toD); err != nil {
return errors.Wrap(err, "enactTables")
}
// The following types use a shared pool of workers to run each
// directiveJobType.
var wg sync.WaitGroup
// open job channel
jobs := make(chan directiveJobType, api.directiveWorkerPoolSize)
errs := make(chan error)
done := make(chan struct{})
// Spin up n workers in goroutines that pull jobs from the jobs channel.
for i := 0; i < api.directiveWorkerPoolSize; i++ {
wg.Add(1)
go func() {
api.directiveWorker(ctx, jobs, errs)
defer wg.Done()
}()
}
// Wait for the WaitGroup counter to reach 0. When it has, indicate that
// we're done processing all jobs by closing the done channel.
go func() {
wg.Wait()
close(done)
}()
// Run through all the "enact" methods. These push jobs onto the jobs
// channel. Once all the jobs have been queued to the channel, we close the
// jobs channel. This allows the directiveWorkers to exit out of the
// function, which will then decrement the WaitGroup counter.
go func() {
api.pushJobsTableKeys(ctx, jobs, fromD, toD)
api.pushJobsFieldKeys(ctx, jobs, fromD, toD)
api.pushJobsShards(ctx, jobs, fromD, toD)
close(jobs)
}()
// Keep running until we get an error or until the done channel is closed.
// Note: the code is written such that only non-nil errors are pushed to the
// errs channel.
for {
select {
case err := <-errs:
return err
case <-done:
return nil
}
}
}
func (api *API) enactTables(ctx context.Context, fromD, toD *dax.Directive) error {
currentIndexes := api.holder.Indexes()
// Make a list of indexes that currently exist (from).
from := make(dax.TableKeys, 0, len(currentIndexes))
for _, idx := range currentIndexes {
qtid, err := dax.QualifiedTableIDFromKey(idx.Name())
if err != nil {
return errors.Wrap(err, "converting index name to qualified table id")
}
from = append(from, qtid.Key())
}
// TODO sanity check holder against fromD. We're getting existing
// indexes from holder, but in theory fromD should be
// identical. If we have an error in our directive-caching logic
// (it has happened before (just now, in fact!) and we'd be
// foolish to think it won't happen again), or we have schema
// mutations that are not going through the directive path, we
// could potentially catch them here.
// Make a list of tables that are in the directive (to) along with a map of
// tableKey to table (m).
m := make(map[dax.TableKey]*dax.QualifiedTable, len(toD.Tables))
to := make(dax.TableKeys, 0, len(toD.Tables))
for _, t := range toD.Tables {
m[t.Key()] = t
to = append(to, t.Key())
}
sc := newSliceComparer(from, to)
// Remove all indexes that are no longer part of the directive.
for _, tkey := range sc.removed() {
idx := string(tkey)
if err := api.DeleteIndex(ctx, idx); err != nil {
return errors.Wrapf(err, "deleting index: %s", tkey)
}
}
// Put partitions into a map by table.
partitionMap := toD.TranslatePartitionsMap()
// Add all indexes that weren't previously (but now are) a part of the
// directive.
for _, tkey := range sc.added() {
if qtbl, found := m[tkey]; !found {
return errors.Errorf("table '%s' was not in map", tkey)
} else if err := api.createTableAndFields(qtbl, partitionMap[tkey]); err != nil {
return err
}
}
// Check fields on all indexes present in both from and to.
for _, tkey := range sc.same() {
if err := api.enactFieldsForTable(ctx, tkey, fromD, toD); err != nil {
return errors.Wrapf(err, "enacting fields for table: '%s'", tkey)
}
}
return nil
}
func (api *API) enactFieldsForTable(ctx context.Context, tkey dax.TableKey, fromD, toD *dax.Directive) error {
qtid := tkey.QualifiedTableID()
fromT, err := fromD.Table(qtid)
if err != nil {
return errors.Wrap(err, "getting from table")
}
toT, err := toD.Table(qtid)
if err != nil {
return errors.Wrap(err, "getting to table")
}
// Get the index for tkey.
idx := api.holder.Index(string(tkey))
if idx == nil {
return errors.Errorf("index not found: %s", tkey)
}
sc := newSliceComparer(fromT.FieldNames(), toT.FieldNames())
// Add fields new to toT.
for _, fldName := range sc.added() {
if field, found := toT.Field(fldName); !found {
return dax.NewErrFieldDoesNotExist(fldName)
} else if err := createField(idx, field); err != nil {
return errors.Wrapf(err, "creating field: %s/%s", tkey, fldName)
}
}
// Remove fields which don't exist in toT.
for _, fldName := range sc.removed() {
if err := api.DeleteField(ctx, string(tkey), string(fldName)); err != nil {
return errors.Wrapf(err, "deleting field: %s/%s", tkey, fldName)
}
}
// // Update any field options which have changed for existing fields.
// for _, fldName := range sc.same() {
// // handle changed field options??
// }
return nil
}
func (api *API) pushJobsTableKeys(ctx context.Context, jobs chan<- directiveJobType, fromD, toD *dax.Directive) {
toPartitionsMap := toD.TranslatePartitionsMap()
// Get the diff between from/to directive.partitions.
partComp := newPartitionsComparer(fromD.TranslatePartitionsMap(), toPartitionsMap)
// Remove any partitions which are no longer assigned to this worker.
// TODO(tlt): currently, this is just removing the file lock on the
// resource; it's not actually removing the resource from the local
// computer. We should do that.
for tkey, partitions := range partComp.removed() {
qtid := tkey.QualifiedTableID()
for _, partition := range partitions {
api.serverlessStorage.RemoveTableKeyResource(qtid, partition)
}
}
// Loop over the partition map and load from Writelogger.
for tkey, partitions := range partComp.added() {
// Get index in order to find the translate stores (by partition) for
// the table.
idx := api.holder.Index(string(tkey))
if idx == nil {
log.Printf("index not found in holder: %s", tkey)
continue
}
// Update the cached version of translate partitions that we keep on the
// Index.
idx.SetTranslatePartitions(toPartitionsMap[tkey])
for _, partition := range partitions {
jobs <- directiveJobTableKeys{
idx: idx,
tkey: tkey,
partition: partition,
}
}
}
}
func (api *API) loadTableKeys(ctx context.Context, idx *Index, tkey dax.TableKey, partition dax.PartitionNum) error {
qtid := tkey.QualifiedTableID()
resource := api.serverlessStorage.GetTableKeyResource(qtid, partition)
if resource.IsLocked() {
api.logger().Warnf("skipping loadTableKeys (already held) %s %d", tkey, partition)
return nil
}
// load latest snapshot
if rc, err := resource.LoadLatestSnapshot(); err != nil {
return errors.Wrap(err, "loading table key snapshot")
} else if rc != nil {
defer rc.Close()
if err := api.TranslateIndexDB(ctx, string(tkey), int(partition), rc); err != nil {
return errors.Wrap(err, "restoring table keys")
}
}
// define write log loading in a function since we have to do it
// before and after locking
loadWriteLog := func() error {
writelog, err := resource.LoadWriteLog()
if err != nil {
return errors.Wrap(err, "getting write log reader for table keys")
}
if writelog == nil {
return nil
}
reader := storage.NewTableKeyReader(qtid, partition, writelog)
defer reader.Close()
store := idx.TranslateStore(int(partition))
for msg, err := reader.Read(); err != io.EOF; msg, err = reader.Read() {
if err != nil {
return errors.Wrap(err, "reading from log reader")
}
for key, id := range msg.StringToID {
if err := store.ForceSet(id, key); err != nil {
return errors.Wrapf(err, "forcing set id, key: %d, %s", id, key)
}
}
}
return nil
}
// 1st write log load
if err := loadWriteLog(); err != nil {
return err
}
// acquire lock on this partition's keys
if err := resource.Lock(); err != nil {
return errors.Wrap(err, "locking table key partition")
}
// reload writelog in case of changes between last load and
// lock. The resource object takes care of only loading new data.
return loadWriteLog()
}
func (api *API) pushJobsFieldKeys(ctx context.Context, jobs chan<- directiveJobType, fromD, toD *dax.Directive) {
// Get the diff between from/to directive.fields.
fieldComp := newFieldsComparer(fromD.TranslateFieldsMap(), toD.TranslateFieldsMap())
// Remove any field keys which are no longer assigned to this worker.
// TODO(tlt): currently, this is just removing the file lock on the
// resource; it's not actually removing the resource from the local
// computer. We should do that.
for tkey, fields := range fieldComp.removed() {
qtid := tkey.QualifiedTableID()
for _, field := range fields {
api.serverlessStorage.RemoveFieldKeyResource(qtid, field)
}
}
// Loop over the field map and load from Writelogger.
for tkey, fields := range fieldComp.added() {
for _, field := range fields {
jobs <- directiveJobFieldKeys{
tkey: tkey,
field: field,
}
}
}
}
func (api *API) loadFieldKeys(ctx context.Context, tkey dax.TableKey, field dax.FieldName) error {
qtid := tkey.QualifiedTableID()
resource := api.serverlessStorage.GetFieldKeyResource(qtid, field)
if resource.IsLocked() {
api.logger().Warnf("skipping loadFieldKeys (already held) %s %s", tkey, field)
return nil
}
// load latest snapshot
if rc, err := resource.LoadLatestSnapshot(); err != nil {
return errors.Wrap(err, "loading field key snapshot")
} else if rc != nil {
defer rc.Close()
if err := api.TranslateFieldDB(ctx, string(tkey), string(field), rc); err != nil {
return errors.Wrap(err, "restoring field keys")
}
}
// define write log loading in a function since we have to do it
// before and after locking
loadWriteLog := func() error {
writelog, err := resource.LoadWriteLog()
if err != nil {
return errors.Wrap(err, "getting write log reader for field keys")
}
if writelog == nil {
return nil
}
reader := storage.NewFieldKeyReader(qtid, field, writelog)
defer reader.Close()
// Get field in order to find the translate store.
fld := api.holder.Field(string(tkey), string(field))
if fld == nil {
log.Printf("field not found in holder: %s", field)
return nil
}
store := fld.TranslateStore()
for msg, err := reader.Read(); err != io.EOF; msg, err = reader.Read() {
if err != nil {
return errors.Wrap(err, "reading from log reader")
}
for key, id := range msg.StringToID {
if err := store.ForceSet(id, key); err != nil {
return errors.Wrapf(err, "forcing set id, key: %d, %s", id, key)
}
}
}
return nil
}
// 1st write log load
if err := loadWriteLog(); err != nil {
return err
}
// acquire lock on this partition's keys
if err := resource.Lock(); err != nil {
return errors.Wrap(err, "locking field key partition")
}
// reload writelog in case of changes between last load and
// lock. The resource object takes care of only loading new data.
return loadWriteLog()
}
func (api *API) pushJobsShards(ctx context.Context, jobs chan<- directiveJobType, fromD, toD *dax.Directive) {
// Put shards into a map by table.
shardMap := toD.ComputeShardsMap()
// Get the diff between from/to directive shards.
shardComp := newShardsComparer(fromD.ComputeShardsMap(), shardMap)
// Remove any shards which are no longer assigned to this worker.
// TODO(tlt): currently, this is just removing the file lock on the
// resource; it's not actually removing the resource from the local
// computer. We should do that.
for tkey, shards := range shardComp.removed() {
qtid := tkey.QualifiedTableID()
for _, shard := range shards {
partition := dax.PartitionNum(disco.ShardToShardPartition(string(tkey), uint64(shard), disco.DefaultPartitionN))
api.serverlessStorage.RemoveShardResource(qtid, partition, shard)
}
}
// Loop over the shard map and load from Writelogger.
for tkey, shards := range shardComp.added() {
for _, shard := range shards {
jobs <- directiveJobShards{
tkey: tkey,
shard: shard,
}
}
}
}
func (api *API) loadShard(ctx context.Context, tkey dax.TableKey, shard dax.ShardNum) error {
qtid := tkey.QualifiedTableID()
partition := dax.PartitionNum(disco.ShardToShardPartition(string(tkey), uint64(shard), disco.DefaultPartitionN))
resource := api.serverlessStorage.GetShardResource(qtid, partition, shard)
if resource.IsLocked() {
api.logger().Warnf("skipping loadShard (already held) %s %d", tkey, shard)
return nil
}
if rc, err := resource.LoadLatestSnapshot(); err != nil {
return errors.Wrap(err, "reading latest snapshot for shard")
} else if rc != nil {
defer rc.Close()
if err := api.RestoreShard(ctx, string(tkey), uint64(shard), rc); err != nil {
return errors.Wrap(err, "restoring shard data")
}
}
// define write log loading in a func because we do it twice.
loadWriteLog := func() error {
writelog, err := resource.LoadWriteLog()
if err != nil {
return errors.Wrap(err, "")
}
if writelog == nil {
return nil
}
reader := storage.NewShardReader(qtid, partition, shard, writelog)
defer reader.Close()
for logMsg, err := reader.Read(); err != io.EOF; logMsg, err = reader.Read() {
if err != nil {
return errors.Wrap(err, "reading from log reader")
}
switch msg := logMsg.(type) {
case *computer.ImportRoaringMessage:
req := &ImportRoaringRequest{
Clear: msg.Clear,
Action: msg.Action,
Block: msg.Block,
Views: msg.Views,
UpdateExistence: msg.UpdateExistence,
SuppressLog: true,
}
if err := api.ImportRoaring(ctx, msg.Table, msg.Field, msg.Shard, true, req); err != nil {
return errors.Wrapf(err, "import roaring, table: %s, field: %s, shard: %d", msg.Table, msg.Field, msg.Shard)
}
case *computer.ImportMessage:
req := &ImportRequest{
Index: msg.Table,
Field: msg.Field,
Shard: msg.Shard,
RowIDs: msg.RowIDs,
ColumnIDs: msg.ColumnIDs,
RowKeys: msg.RowKeys,
ColumnKeys: msg.ColumnKeys,
Timestamps: msg.Timestamps,
Clear: msg.Clear,
}
qcx := api.Txf().NewQcx()
defer qcx.Abort()
opts := []ImportOption{
OptImportOptionsClear(msg.Clear),
OptImportOptionsIgnoreKeyCheck(msg.IgnoreKeyCheck),
OptImportOptionsPresorted(msg.Presorted),
OptImportOptionsSuppressLog(true),
}
if err := api.Import(ctx, qcx, req, opts...); err != nil {
return errors.Wrapf(err, "import, table: %s, field: %s, shard: %d", msg.Table, msg.Field, msg.Shard)
}
case *computer.ImportValueMessage:
req := &ImportValueRequest{
Index: msg.Table,
Field: msg.Field,
Shard: msg.Shard,
ColumnIDs: msg.ColumnIDs,
ColumnKeys: msg.ColumnKeys,
Values: msg.Values,
FloatValues: msg.FloatValues,
TimestampValues: msg.TimestampValues,
StringValues: msg.StringValues,
Clear: msg.Clear,
}
qcx := api.Txf().NewQcx()
defer qcx.Abort()
opts := []ImportOption{
OptImportOptionsClear(msg.Clear),
OptImportOptionsIgnoreKeyCheck(msg.IgnoreKeyCheck),
OptImportOptionsPresorted(msg.Presorted),
OptImportOptionsSuppressLog(true),
}
if err := api.ImportValue(ctx, qcx, req, opts...); err != nil {
return errors.Wrapf(err, "import value, table: %s, field: %s, shard: %d", msg.Table, msg.Field, msg.Shard)
}
case *computer.ImportRoaringShardMessage:
req := &ImportRoaringShardRequest{
Remote: true,
Views: make([]RoaringUpdate, len(msg.Views)),
SuppressLog: true,
}
for i, view := range msg.Views {
req.Views[i] = RoaringUpdate{
Field: view.Field,
View: view.View,
Clear: view.Clear,
Set: view.Set,
ClearRecords: view.ClearRecords,
}
}
if err := api.ImportRoaringShard(ctx, msg.Table, msg.Shard, req); err != nil {
return errors.Wrapf(err, "import roaring shard table: %s, shard: %d", msg.Table, msg.Shard)
}
}
}
return nil
}
// 1st write log load
if err := loadWriteLog(); err != nil {
return err
}
// acquire lock on this partition's keys
if err := resource.Lock(); err != nil {
return errors.Wrap(err, "locking field key partition")
}
// reload writelog in case of changes between last load and
// lock. The resource object takes care of only loading new data.
return loadWriteLog()
}
//////////////////////////////////////////////////////////////
// sliceComparer is used to compare the differences between two slices of comparables.
type sliceComparer[K comparable] struct {
from []K
to []K
}
func newSliceComparer[K comparable](from []K, to []K) *sliceComparer[K] {
return &sliceComparer[K]{
from: from,
to: to,
}
}
// added returns the items which are present in `to` but not in `from`.
func (s *sliceComparer[K]) added() []K {
return thingsAdded(s.from, s.to)
}
// removed returns the items which are present in `from` but not in `to`.
func (s *sliceComparer[K]) removed() []K {
return thingsAdded(s.to, s.from)
}
// same returns the items which are in both `to` and `from`.
func (s *sliceComparer[K]) same() []K {
var same []K
for _, fromThing := range s.from {
for _, toThing := range s.to {
if fromThing == toThing {
same = append(same, fromThing)
break
}
}
}
return same
}
// thingsAdded returns the comparable things which are present in `to` but not
// in `from`.
func thingsAdded[K comparable](from []K, to []K) []K {
var added []K
for i := range to {
var found bool
for j := range from {
if from[j] == to[i] {
found = true
break
}
}
if !found {
added = append(added, to[i])
}
}
return added
}
// partitionsComparer is used to compare the differences between two maps of
// table:[]partition.
type partitionsComparer struct {
from map[dax.TableKey]dax.PartitionNums
to map[dax.TableKey]dax.PartitionNums
}
func newPartitionsComparer(from map[dax.TableKey]dax.PartitionNums, to map[dax.TableKey]dax.PartitionNums) *partitionsComparer {
return &partitionsComparer{
from: from,
to: to,
}
}
// added returns the partitions which are present in `to` but not in `from`. The
// results remain in the format of a map of table:[]partition.
func (p *partitionsComparer) added() map[dax.TableKey]dax.PartitionNums {
return partitionsAdded(p.from, p.to)
}
// removed returns the partitions which are present in `from` but not in `to`.
// The results remain in the format of a map of table:[]partition.
func (p *partitionsComparer) removed() map[dax.TableKey]dax.PartitionNums {
return partitionsAdded(p.to, p.from)
}
// partitionsAdded returns the partitions which are present in `to` but not in `from`.
func partitionsAdded(from map[dax.TableKey]dax.PartitionNums, to map[dax.TableKey]dax.PartitionNums) map[dax.TableKey]dax.PartitionNums {
if from == nil {
return to
}
added := make(map[dax.TableKey]dax.PartitionNums)
for tt, tps := range to {
fps, found := from[tt]
if !found {
added[tt] = tps
continue
}
addedPartitions := dax.PartitionNums{}
for i := range tps {
var found bool
for j := range fps {
if fps[j] == tps[i] {
found = true
break
}
}
if !found {
addedPartitions = append(addedPartitions, tps[i])
}
}
if len(addedPartitions) > 0 {
added[tt] = addedPartitions
}
}
return added
}
// fieldsComparer is used to compare the differences between two maps of
// table:[]fieldVersion.
type fieldsComparer struct {
from map[dax.TableKey][]dax.FieldName
to map[dax.TableKey][]dax.FieldName
}
func newFieldsComparer(from map[dax.TableKey][]dax.FieldName, to map[dax.TableKey][]dax.FieldName) *fieldsComparer {
return &fieldsComparer{
from: from,
to: to,
}
}
// added returns the fields which are present in `to` but not in `from`. The
// results remain in the format of a map of table:[]field.
func (f *fieldsComparer) added() map[dax.TableKey][]dax.FieldName {
return fieldsAdded(f.from, f.to)
}
// removed returns the fields which are present in `from` but not in `to`.
// The results remain in the format of a map of table:[]field.
func (f *fieldsComparer) removed() map[dax.TableKey][]dax.FieldName {
return fieldsAdded(f.to, f.from)
}
// fieldsAdded returns the fields which are present in `to` but not in `from`.
func fieldsAdded(from map[dax.TableKey][]dax.FieldName, to map[dax.TableKey][]dax.FieldName) map[dax.TableKey][]dax.FieldName {
if from == nil {
return to
}
added := make(map[dax.TableKey][]dax.FieldName)
for tt, tps := range to {
fps, found := from[tt]
if !found {
added[tt] = tps
continue
}
addedFieldVersions := []dax.FieldName{}
for i := range tps {
var found bool
for j := range fps {
if fps[j] == tps[i] {
found = true
break
}
}
if !found {
addedFieldVersions = append(addedFieldVersions, tps[i])
}
}
if len(addedFieldVersions) > 0 {
added[tt] = addedFieldVersions
}
}
return added
}
// shardsComparer is used to compare the differences between two maps of
// table:[]shardV.
type shardsComparer struct {
from map[dax.TableKey]dax.ShardNums
to map[dax.TableKey]dax.ShardNums
}
func newShardsComparer(from map[dax.TableKey]dax.ShardNums, to map[dax.TableKey]dax.ShardNums) *shardsComparer {
return &shardsComparer{
from: from,
to: to,
}
}
// added returns the shards which are present in `to` but not in `from`. The
// results remain in the format of a map of table:[]shard.
func (s *shardsComparer) added() map[dax.TableKey]dax.ShardNums {
return shardsAdded(s.from, s.to)
}
// removed returns the shards which are present in `from` but not in `to`. The
// results remain in the format of a map of table:[]shard.
func (s *shardsComparer) removed() map[dax.TableKey]dax.ShardNums {
return shardsAdded(s.to, s.from)
}
// shardsAdded returns the shards which are present in `to` but not in `from`.
func shardsAdded(from map[dax.TableKey]dax.ShardNums, to map[dax.TableKey]dax.ShardNums) map[dax.TableKey]dax.ShardNums {
if from == nil {
return to
}
added := make(map[dax.TableKey]dax.ShardNums)
for tt, tss := range to {
fss, found := from[tt]
if !found {
added[tt] = tss
continue
}
addedShards := dax.ShardNums{}
for i := range tss {
var found bool
for j := range fss {
if fss[j] == tss[i] {
found = true
break
}
}
if !found {
addedShards = append(addedShards, tss[i])
}
}
if len(addedShards) > 0 {
added[tt] = addedShards
}
}
return added
}
// createTableAndFields creates the FeatureBase Tables and Fields provided in
// the dax.Directive format.
func (api *API) createTableAndFields(tbl *dax.QualifiedTable, partitions dax.PartitionNums) error {
cim := &CreateIndexMessage{
Index: string(tbl.Key()),
CreatedAt: 0,
Meta: IndexOptions{
Keys: tbl.StringKeys(),
TrackExistence: true,
},
}
// Create the index in etcd as the system of record.
if err := api.holder.persistIndex(context.Background(), cim); err != nil {
return errors.Wrap(err, "persisting index")
}
idx, err := api.holder.createIndexWithPartitions(cim, partitions)
if err != nil {
return errors.Wrapf(err, "adding index: %s", tbl.Name)
}
// Add the fields
for _, fld := range tbl.Fields {
if fld.IsPrimaryKey() {
continue
}
if err := createField(idx, fld); err != nil {
return errors.Wrapf(err, "creating field: %s", fld.Name)
}
}
return nil
}
// createField creates a FeatureBase Field in the provided FeatureBase Index
// based on the provided field's type.
func createField(idx *Index, fld *dax.Field) error {
opts, err := FieldOptionsFromField(fld)
if err != nil {
return errors.Wrapf(err, "creating field options from field: %s", fld.Name)
}
if _, err := idx.createNullableField(string(fld.Name), "", opts...); err != nil {
return errors.Wrapf(err, "creating field on index: %s", fld.Name)
}
return nil
}