forked from FeatureBaseDB/featurebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
1490 lines (1306 loc) · 41 KB
/
server.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
// Copyright 2022 Molecula Corp. (DBA FeatureBase).
// SPDX-License-Identifier: Apache-2.0
package pilosa
import (
"context"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
uuid "github.com/satori/go.uuid"
daxstorage "github.com/featurebasedb/featurebase/v3/dax/storage"
"github.com/featurebasedb/featurebase/v3/disco"
"github.com/featurebasedb/featurebase/v3/logger"
pnet "github.com/featurebasedb/featurebase/v3/net"
rbfcfg "github.com/featurebasedb/featurebase/v3/rbf/cfg"
"github.com/featurebasedb/featurebase/v3/roaring"
"github.com/featurebasedb/featurebase/v3/sql3"
"github.com/featurebasedb/featurebase/v3/sql3/parser"
planner_types "github.com/featurebasedb/featurebase/v3/sql3/planner/types"
"github.com/featurebasedb/featurebase/v3/storage"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
_ "github.com/lib/pq"
)
// Default server settings.
const (
defaultDiagnosticServer = "https://diagnostics.pilosa.com/v0/diagnostics"
)
// Ensure Server implements interfaces.
var _ broadcaster = &Server{}
// Server represents a holder wrapped by a running HTTP server.
type Server struct { // nolint: maligned
// Close management.
wg sync.WaitGroup
muWG sync.Mutex
closing chan struct{}
// Internal
holder *Holder
cluster *cluster
diagnostics *diagnosticsCollector
executor *executor
executorPoolSize int
serializer Serializer
SystemLayer SystemLayerAPI
// Distributed Consensus
disCo disco.DisCo
noder disco.Noder
sharder disco.Sharder
// External
systemInfo SystemInfo
gcNotifier GCNotifier
logger logger.Logger
queryLogger logger.Logger
nodeID string
uri pnet.URI
grpcURI pnet.URI
metricInterval time.Duration
diagnosticInterval time.Duration
viewsRemovalInterval time.Duration
maxWritesPerRequest int
confirmDownSleep time.Duration
confirmDownRetries int
syncer holderSyncer
maxQueryMemory int64
translationSyncer TranslationSyncer
resetTranslationSyncCh chan struct{}
// HolderConfig stashes server options that are really Holder options.
holderConfig *HolderConfig
defaultClient *InternalClient
dataDir string
verChkAddress string
uuidFile string
// Threshold for logging long-running queries
longQueryTime time.Duration
queryHistoryLength int
executionPlannerFn ExecutionPlannerFn
serverlessStorage *daxstorage.ResourceManager
dataframeEnabled bool
dataframeUseParquet bool
}
type ExecutionPlannerFn func(executor Executor, api *API, sql string) sql3.CompilePlanner
// Holder returns the holder for server.
func (s *Server) Holder() *Holder {
return s.holder
}
// addToWaitGroup adds to the server WaitGroup but makes sure the server isn't
// closing, and that the WaitGroup is not already waiting before it adds
func (s *Server) addToWaitGroup(delta int) bool {
select {
case <-s.closing:
return false
default:
s.muWG.Lock()
defer s.muWG.Unlock()
select {
case <-s.closing:
// if we're closing after having gotten the lock, stop!!
return false
default:
s.wg.Add(delta)
return true
}
}
}
// ServerOption is a functional option type for pilosa.Server
type ServerOption func(s *Server) error
// OptServerLogger is a functional option on Server
// used to set the logger.
func OptServerLogger(l logger.Logger) ServerOption {
return func(s *Server) error {
s.logger = l
s.holderConfig.Logger = l
return nil
}
}
func OptServerQueryLogger(l logger.Logger) ServerOption {
return func(s *Server) error {
s.queryLogger = l
return nil
}
}
// OptServerReplicaN is a functional option on Server
// used to set the number of replicas.
func OptServerReplicaN(n int) ServerOption {
return func(s *Server) error {
s.cluster.ReplicaN = n
return nil
}
}
// OptServerDataDir is a functional option on Server
// used to set the data directory.
func OptServerDataDir(dir string) ServerOption {
return func(s *Server) error {
s.dataDir = dir
return nil
}
}
// OptServerVerChkAddress is a functional option on Server
// used to set the address to check for the current version.
func OptServerVerChkAddress(addr string) ServerOption {
return func(s *Server) error {
s.verChkAddress = addr
return nil
}
}
// OptServerUUIDFile is a functional option on Server
// used to set the file name for storing the checkin UUID.
func OptServerUUIDFile(uf string) ServerOption {
return func(s *Server) error {
s.uuidFile = uf
return nil
}
}
// OptServerViewsRemovalInterval is a functional option on Server
// used to set the ttl removal interval.
func OptServerViewsRemovalInterval(interval time.Duration) ServerOption {
return func(s *Server) error {
s.viewsRemovalInterval = interval
return nil
}
}
// OptServerLongQueryTime is a functional option on Server
// used to set long query duration.
func OptServerLongQueryTime(dur time.Duration) ServerOption {
return func(s *Server) error {
s.longQueryTime = dur
return nil
}
}
// OptServerMaxWritesPerRequest is a functional option on Server
// used to set the maximum number of writes allowed per request.
func OptServerMaxWritesPerRequest(n int) ServerOption {
return func(s *Server) error {
s.maxWritesPerRequest = n
return nil
}
}
// OptServerMetricInterval is a functional option on Server
// used to set the interval between metric samples.
func OptServerMetricInterval(dur time.Duration) ServerOption {
return func(s *Server) error {
s.metricInterval = dur
return nil
}
}
// OptServerSystemInfo is a functional option on Server
// used to set the system information source.
func OptServerSystemInfo(si SystemInfo) ServerOption {
return func(s *Server) error {
s.systemInfo = si
return nil
}
}
// OptServerGCNotifier is a functional option on Server
// used to set the garbage collection notification source.
func OptServerGCNotifier(gcn GCNotifier) ServerOption {
return func(s *Server) error {
s.gcNotifier = gcn
return nil
}
}
// OptServerInternalClient is a functional option on Server
// used to set the implementation of InternalClient.
func OptServerInternalClient(c *InternalClient) ServerOption {
return func(s *Server) error {
s.defaultClient = c
s.cluster.InternalClient = c
return nil
}
}
func OptServerExecutorPoolSize(size int) ServerOption {
return func(s *Server) error {
s.executorPoolSize = size
return nil
}
}
// OptServerPrimaryTranslateStore has been deprecated.
func OptServerPrimaryTranslateStore(store TranslateStore) ServerOption {
return func(s *Server) error {
s.logger.Infof("DEPRECATED: OptServerPrimaryTranslateStore")
return nil
}
}
// OptServerDiagnosticsInterval is a functional option on Server
// used to specify the duration between diagnostic checks.
func OptServerDiagnosticsInterval(dur time.Duration) ServerOption {
return func(s *Server) error {
s.diagnosticInterval = dur
return nil
}
}
// OptServerNodeDownRetries is a functional option on Server
// used to specify the retries and sleep duration for node down
// checks.
func OptServerNodeDownRetries(retries int, sleep time.Duration) ServerOption {
return func(s *Server) error {
s.confirmDownRetries = retries
s.confirmDownSleep = sleep
return nil
}
}
// OptServerURI is a functional option on Server
// used to set the server URI.
func OptServerURI(uri *pnet.URI) ServerOption {
return func(s *Server) error {
s.uri = *uri
return nil
}
}
// OptServerGRPCURI is a functional option on Server
// used to set the server gRPC URI.
func OptServerGRPCURI(uri *pnet.URI) ServerOption {
return func(s *Server) error {
s.grpcURI = *uri
return nil
}
}
// OptServerClusterName sets the human-readable cluster name.
func OptServerClusterName(name string) ServerOption {
return func(s *Server) error {
s.cluster.Name = name
return nil
}
}
// OptServerSerializer is a functional option on Server
// used to set the serializer.
func OptServerSerializer(ser Serializer) ServerOption {
return func(s *Server) error {
s.serializer = ser
return nil
}
}
// OptServerNodeID is a functional option on Server
// used to set the server node ID.
func OptServerNodeID(nodeID string) ServerOption {
return func(s *Server) error {
s.nodeID = nodeID
return nil
}
}
// OptServerClusterHasher is a functional option on Server
// used to specify the consistent hash algorithm for data
// location within the cluster.
func OptServerClusterHasher(h disco.Hasher) ServerOption {
return func(s *Server) error {
s.cluster.Hasher = h
return nil
}
}
// OptServerOpenTranslateStore is a functional option on Server
// used to specify the translation data store type.
func OptServerOpenTranslateStore(fn OpenTranslateStoreFunc) ServerOption {
return func(s *Server) error {
s.holderConfig.OpenTranslateStore = fn
return nil
}
}
// OptServerOpenIDAllocator is a functional option on Server
// used to specify the ID allocator data store type.
// Except not really (because there's only one at this time).
func OptServerOpenIDAllocator(fn OpenIDAllocatorFunc) ServerOption {
return func(s *Server) error {
s.holderConfig.OpenIDAllocator = fn
return nil
}
}
// OptServerOpenTranslateReader is a functional option on Server
// used to specify the remote translation data reader.
func OptServerOpenTranslateReader(fn OpenTranslateReaderFunc) ServerOption {
return func(s *Server) error {
s.holderConfig.OpenTranslateReader = fn
return nil
}
}
// OptServerStorageConfig is a functional option on Server used to specify the
// transactional-storage backend to use, resulting in RoaringTx or RbfTx
// being used for all Tx interface calls.
func OptServerStorageConfig(cfg *storage.Config) ServerOption {
return func(s *Server) error {
s.holderConfig.StorageConfig = cfg
// For historical reasons, RBF's config can ignore the storage config
// in some cases.
s.holderConfig.RBFConfig.FsyncEnabled = s.holderConfig.StorageConfig.FsyncEnabled
return nil
}
}
// OptServerRBFConfig conveys the RBF flags to the Holder.
func OptServerRBFConfig(cfg *rbfcfg.Config) ServerOption {
return func(s *Server) error {
s.holderConfig.RBFConfig = cfg
return nil
}
}
// OptServerQueryHistoryLength is a functional option on Server
// used to specify the length of the query history buffer that maintains
// the information returned at /query-history.
func OptServerQueryHistoryLength(length int) ServerOption {
return func(s *Server) error {
s.queryHistoryLength = length
return nil
}
}
// OptServerMaxQueryMemory sets the memory used per Extract() and SELECT query.
func OptServerMaxQueryMemory(v int64) ServerOption {
return func(s *Server) error {
s.maxQueryMemory = v
return nil
}
}
// OptServerDisCo is a functional option on Server
// used to set the Distributed Consensus implementation.
func OptServerDisCo(disCo disco.DisCo,
noder disco.Noder,
sharder disco.Sharder,
schemator disco.Schemator,
) ServerOption {
return func(s *Server) error {
s.disCo = disCo
s.noder = noder
s.sharder = sharder
s.holderConfig.Schemator = schemator
return nil
}
}
// OptServerLookupDB configures a connection to an external postgres database for ExternalLookup queries.
func OptServerLookupDB(dsn string) ServerOption {
return func(s *Server) error {
s.holderConfig.LookupDBDSN = dsn
return nil
}
}
func OptServerPartitionAssigner(p string) ServerOption {
return func(s *Server) error {
s.cluster.partitionAssigner = p
return nil
}
}
func OptServerExecutionPlannerFn(fn ExecutionPlannerFn) ServerOption {
return func(s *Server) error {
s.executionPlannerFn = fn
return nil
}
}
func OptServerServerlessStorage(mm *daxstorage.ResourceManager) ServerOption {
return func(s *Server) error {
s.serverlessStorage = mm
return nil
}
}
// OptServerIsComputeNode specifies that this node is running as a DAX compute node.
func OptServerIsComputeNode(is bool) ServerOption {
return func(s *Server) error {
s.cluster.isComputeNode = is
return nil
}
}
// OptServerIsDataframeEnabled specifies if experimental dataframe support available
func OptServerIsDataframeEnabled(is bool) ServerOption {
return func(s *Server) error {
s.dataframeEnabled = is
return nil
}
}
func OptServerDataframeUseParquet(is bool) ServerOption {
return func(s *Server) error {
s.dataframeUseParquet = is
return nil
}
}
// NewServer returns a new instance of Server.
func NewServer(opts ...ServerOption) (*Server, error) {
cluster := newCluster()
s := &Server{
closing: make(chan struct{}),
cluster: cluster,
diagnostics: newDiagnosticsCollector(defaultDiagnosticServer),
systemInfo: newNopSystemInfo(),
defaultClient: &InternalClient{}, // TODO may need to make this a valid thing
gcNotifier: NopGCNotifier,
metricInterval: 0,
diagnosticInterval: 0,
viewsRemovalInterval: time.Hour,
disCo: disco.NopDisCo,
noder: disco.NewEmptyLocalNoder(),
sharder: disco.NopSharder,
serializer: NopSerializer,
confirmDownRetries: defaultConfirmDownRetries,
confirmDownSleep: defaultConfirmDownSleep,
resetTranslationSyncCh: make(chan struct{}, 1),
logger: logger.NopLogger,
executionPlannerFn: func(e Executor, a *API, s string) sql3.CompilePlanner {
return sql3.NewNopCompilePlanner()
},
}
s.cluster.InternalClient = s.defaultClient
s.translationSyncer = newActiveTranslationSyncer(s.resetTranslationSyncCh)
s.cluster.translationSyncer = s.translationSyncer
s.diagnostics.server = s
s.holderConfig = DefaultHolderConfig()
s.holderConfig.TranslationSyncer = s.translationSyncer
s.holderConfig.Logger = s.logger
for _, opt := range opts {
err := opt(s)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
}
memTotal, err := s.systemInfo.MemTotal()
if err != nil {
return nil, errors.Wrap(err, "mem total")
}
// Default memory to 20% of total.
maxQueryMemory := s.maxQueryMemory
if maxQueryMemory == 0 {
maxQueryMemory = int64(float64(memTotal) * .20)
}
// set up executor after server opts have been processed
executorOpts := []executorOption{
optExecutorInternalQueryClient(s.defaultClient),
optExecutorMaxMemory(maxQueryMemory),
}
if s.executorPoolSize > 0 {
executorOpts = append(executorOpts, optExecutorWorkerPoolSize(s.executorPoolSize))
}
s.executor = newExecutor(executorOpts...)
s.executor.dataframeEnabled = s.dataframeEnabled
s.executor.datafameUseParquet = s.dataframeUseParquet
path, err := expandDirName(s.dataDir)
if err != nil {
return nil, err
}
s.holder = NewHolder(path, s.holderConfig)
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
s.holder.Logger.Infof("cwd: %v", cwd)
s.holder.Logger.Infof("cmd line: %v", strings.Join(os.Args, " "))
s.cluster.Path = path
s.cluster.logger = s.logger
s.cluster.holder = s.holder
s.cluster.disCo = s.disCo
s.cluster.noder = s.noder
s.cluster.sharder = s.sharder
s.cluster.serverlessStorage = s.serverlessStorage
s.executor.Holder = s.holder
s.holder.executor = s.executor
s.executor.Cluster = s.cluster
s.executor.MaxWritesPerRequest = s.maxWritesPerRequest
s.cluster.broadcaster = s
s.cluster.maxWritesPerRequest = s.maxWritesPerRequest
s.cluster.confirmDownRetries = s.confirmDownRetries
s.cluster.confirmDownSleep = s.confirmDownSleep
s.holder.broadcaster = s
s.holder.sharder = s.sharder
s.holder.serializer = s.serializer
// Initial stats must be invoked after the executor obtains reference to the holder.
s.executor.InitStats()
return s, nil
}
func (s *Server) InternalClient() *InternalClient {
return s.defaultClient
}
func (s *Server) GRPCURI() pnet.URI {
return s.grpcURI
}
func (s *Server) SetAPI(api *API) {
s.defaultClient.SetInternalAPI(api)
}
// UpAndDown brings the server up minimally and shuts it down
// again; basically, it exists for testing holder open and close.
func (s *Server) UpAndDown() error {
// Log startup
err := s.holder.logStartup()
if err != nil {
log.Println(errors.Wrap(err, "logging startup"))
}
s.logger.Infof("open server. PID %v", os.Getpid())
if err = s.Open(); err != nil {
return errors.Wrap(err, "starting server")
}
err = s.Close()
return errors.Wrap(err, "shutting down server")
}
// Open opens and initializes the server.
func (s *Server) Open() error {
s.logger.Infof("open server. PID %v", os.Getpid())
// Log startup
err := s.holder.logStartup()
if err != nil {
log.Println(errors.Wrap(err, "logging startup"))
}
// Do version check in. This is in a goroutine so that we don't block server
// startup if the server endpoint is down/having issues.
go func() {
s.logger.Printf("Beginning featurebase version check-in")
vc := newVersionChecker(s.cluster.Path, s.verChkAddress, s.uuidFile)
resp, err := vc.checkIn()
if err != nil {
s.logger.Errorf("doing version checkin. Error was %s", err)
return
}
if resp.Error != "" {
s.logger.Printf("Version check-in failed, endpoint response was %s", resp.Error)
} else {
s.logger.Printf("Version check-in complete. Latest version is %s", resp.Version)
}
}()
// Start DisCo.
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
initState, err := s.disCo.Start(ctx)
if err != nil {
return errors.Wrap(err, "starting DisCo")
}
// I'm pretty sure this can't happen, because the path that would have led to it
// happening now generates an error already, but let's be careful.
if initState == disco.InitialClusterStateExisting {
return errors.New("disco reports existing cluster, but this is not supported")
}
// Set node ID.
s.nodeID = s.disCo.ID()
nodeState := disco.NodeStateUnknown
if s.cluster.isComputeNode {
nodeState = disco.NodeStateStarted
}
node := &disco.Node{
ID: s.nodeID,
URI: s.uri,
GRPCURI: s.grpcURI,
State: nodeState,
IsPrimary: s.IsPrimary(),
}
if err := s.noder.SetMetadata(context.Background(), node); err != nil {
return errors.Wrap(err, "setting metadata")
}
s.cluster.Node = node
s.executor.Node = node
// Set up the holderSyncer.
s.syncer.Holder = s.holder
s.syncer.Node = node
s.syncer.Cluster = s.cluster
s.syncer.Closing = s.closing
// Start background process listening for translation
// sync resets.
if ok := s.addToWaitGroup(1); !ok {
return fmt.Errorf("closing server while opening server is NOT allowed")
}
go func() { defer s.wg.Done(); s.monitorResetTranslationSync() }()
go func() { _ = s.translationSyncer.Reset() }()
// Open holder.
func() {
s.holder.startMsgsMu.Lock()
defer s.holder.startMsgsMu.Unlock()
s.holder.startMsgs = []Message{}
}()
if err := s.holder.Open(); err != nil {
return errors.Wrap(err, "opening Holder")
}
// bring up the background tasks for the holder.
s.holder.Activate()
if err := s.noder.SetState(context.Background(), disco.NodeStateStarted); err != nil {
return errors.Wrap(err, "setting nodeState")
}
if ok := s.addToWaitGroup(3); !ok {
return fmt.Errorf("closing server while opening server is NOT allowed")
}
go func() { defer s.wg.Done(); s.monitorRuntime() }()
go func() { defer s.wg.Done(); s.monitorDiagnostics() }()
go func() { defer s.wg.Done(); s.monitorViewsRemoval() }()
toSend := func() []Message {
s.holder.startMsgsMu.Lock()
defer s.holder.startMsgsMu.Unlock()
toSend := s.holder.startMsgs
s.holder.startMsgs = nil
return toSend
}()
if ok := s.addToWaitGroup(1); !ok {
return fmt.Errorf("closing server while opening server is NOT allowed")
}
go func() {
defer s.wg.Done()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if ok := s.addToWaitGroup(1); !ok {
// the server is closing, stop!!
return
}
go func() {
defer s.wg.Done()
defer cancel()
select {
case <-s.closing:
case <-ctx.Done():
}
}()
timer := time.NewTimer(0)
defer timer.Stop()
if !timer.Stop() {
<-timer.C
}
// wait for cluster to achieve Normal state
//
// This used to loop as long as the cluster was Starting, Down,
// or Unknown. It would come up in a Degraded state, except
// that during startup, as long as at least one node was Starting,
// we'd stay in Starting rather than Degraded. We've dropped the
// special case of Starting state, so now we just want to wait
// for Normal.
for {
state, err := s.noder.ClusterState(ctx)
if err != nil {
s.logger.Printf("failed to check cluster state: %v", err)
}
if state == disco.ClusterStateNormal {
break
}
timer.Reset(time.Second)
select {
case <-s.closing:
return
case <-timer.C:
continue
}
}
start := time.Now()
prevMsg := start
numMsgs := uint(len(toSend))
s.logger.Printf("start initial cluster state sync")
for i := range toSend {
for {
err := s.holder.broadcaster.SendSync(toSend[i])
if err != nil {
s.logger.Printf("failed to broadcast startup cluster message (trying again in a bit): %v", err)
timer.Reset(time.Second)
select {
case <-s.closing:
return
case <-timer.C:
continue
}
}
break
}
if now := time.Now(); now.Sub(prevMsg) > time.Second {
estimate, pctDone := GetLoopProgress(start, now, uint(i), numMsgs)
s.logger.Printf("synced %d/%d messages (%.2f%% complete; %s remaining)", i+1, numMsgs, pctDone, estimate)
prevMsg = now
}
}
s.logger.Printf("completed initial cluster state sync in %s", time.Since(start).String())
}()
return nil
}
// Close closes the server and waits for it to shutdown.
func (s *Server) Close() error {
select {
case <-s.closing:
return nil
default:
// get the muWG lock so that noone adds to the WaitGroup while it Waits
s.muWG.Lock()
defer s.muWG.Unlock()
// Notify goroutines to stop.
close(s.closing)
s.wg.Wait()
errE := s.executor.Close()
var errh, errd error
var errhs error
var errc error
var errSS error
if s.cluster != nil {
errc = s.cluster.close()
}
errhs = s.syncer.stopTranslationSync()
if s.disCo != nil {
errd = s.disCo.Close()
}
if s.holder != nil {
errh = s.holder.Close()
}
if s.serverlessStorage != nil {
errSS = s.serverlessStorage.RemoveAll()
}
// prefer to return holder error over cluster
// error. This order is somewhat arbitrary. It would be better if we had
// some way to combine all the errors, but probably not important enough to
// warrant the extra complexity.
if errh != nil {
return errors.Wrap(errh, "closing holder")
}
if errhs != nil {
return errors.Wrap(errhs, "terminating holder translation sync")
}
if errc != nil {
return errors.Wrap(errc, "closing cluster")
}
if errd != nil {
return errors.Wrap(errd, "closing disco")
}
if errE != nil {
return errors.Wrap(errE, "closing executor")
}
return errors.Wrap(errSS, "unlocking all serverless storage")
}
}
// NodeID returns the server's node id.
func (s *Server) NodeID() string { return s.nodeID }
// monitorResetTranslationSync is a background process which
// listens for events indicating the need to reset the translation
// sync processes.
func (s *Server) monitorResetTranslationSync() {
s.logger.Infof("holder translation sync monitor initializing")
for {
// Wait for a reset or a close.
select {
case <-s.closing:
return
case <-s.resetTranslationSyncCh:
if ok := s.addToWaitGroup(1); !ok {
// the server is closing!!! stop!!
return
}
s.logger.Infof("holder translation sync beginning")
go func() {
// Obtaining this lock ensures that there is only
// one instance of resetTranslationSync() running
// at once.
s.syncer.mu.Lock()
defer s.syncer.mu.Unlock()
defer s.wg.Done()
if err := s.syncer.resetTranslationSync(); err != nil {
s.logger.Errorf("holder translation sync error: err=%s", err)
}
}()
}
}
}
func (s *Server) monitorViewsRemoval() {
ctx := context.Background()
// Run ViewsRemoval on server start
s.ViewsRemoval(ctx)
ticker := time.NewTicker(s.viewsRemovalInterval)
for {
select {
case <-s.closing:
return
case <-ticker.C:
s.ViewsRemoval(ctx)
}
}
}
// Remove views based on these criterias:
// 1. views that are older than specified TTL
// 2. "standard" view of a field if its "noStandardView" option is set to true
func (s *Server) ViewsRemoval(ctx context.Context) {
for _, index := range s.holder.Indexes() {
for _, field := range index.Fields() {
if field.Options().Type == "time" {
if field.Options().TTL > 0 {
for _, view := range field.views() {
// view names follow the format of "standard_(time_quantum)"
// to get view time, we split the view.name by "_"
// then grab the second value (the time quantum)
viewName := strings.Split(view.name, "_")
if len(viewName) == 2 {
// when getting the view time, we want to grab the end date
// because start date will aways be older
viewTime, err := timeOfView(view.name, true)
if err != nil {
s.logger.Printf("view: %s; err: %s", viewName, err)
continue
}
timeSince := time.Since(viewTime)
if timeSince >= field.Options().TTL {
for _, shard := range field.AvailableShards(true).Slice() {
err := s.holder.txf.DeleteFragmentFromStore(index.Name(), field.Name(), view.name, shard, nil)
if err != nil {
s.logger.Errorf("view: %s, shard: %d, ttl delete fragment: %s", shard, viewName, err)
}
}
err := s.defaultClient.api.DeleteView(ctx, index.Name(), field.Name(), view.name)
if err != nil {
s.logger.Errorf("view: %s, ttl delete view: %s", viewName, err)
}
s.logger.Infof("ttl deleted - index: %s, field: %s, view: %s ", index.name, field.name, view.name)
}
}
}
}
if field.Options().NoStandardView {
if field.view(viewStandard) != nil {
// delete view "standard" if NoStandardView is true and view "standard" exists
for _, shard := range field.AvailableShards(true).Slice() {
err := s.holder.txf.DeleteFragmentFromStore(index.Name(), field.Name(), viewStandard, shard, nil)
if err != nil {
s.logger.Errorf("delete view %s from shard %d: %s", viewStandard, shard, err)
}
}
err := s.defaultClient.api.DeleteView(ctx, index.Name(), field.Name(), viewStandard)
if err != nil {
s.logger.Errorf("view: %s, delete view: %s", viewStandard, err)
}
s.logger.Infof("view %s deleted - index: %s, field: %s ", viewStandard, index.name, field.name)
}
if field.view(viewExistence) != nil {
// delete view "existence" if NoStandardView is true and view "existence" exists
for _, shard := range field.AvailableShards(true).Slice() {
err := s.holder.txf.DeleteFragmentFromStore(index.Name(), field.Name(), viewExistence, shard, nil)
if err != nil {
s.logger.Errorf("delete view %s from shard %d: %s", viewExistence, shard, err)
}
}
err := s.defaultClient.api.DeleteView(ctx, index.Name(), field.Name(), viewExistence)
if err != nil {
s.logger.Errorf("view: %s, delete view: %s", viewExistence, err)
}
s.logger.Infof("view %s deleted - index: %s, field: %s ", viewExistence, index.name, field.name)
}
}
}
}
}
}
// receiveMessage represents an implementation of BroadcastHandler.
func (s *Server) receiveMessage(m Message) error {
switch obj := m.(type) {
case *CreateShardMessage:
f := s.holder.Field(obj.Index, obj.Field)
if f == nil {
return fmt.Errorf("local field not found: %s/%s", obj.Index, obj.Field)