forked from m3db/m3
/
session.go
4052 lines (3608 loc) · 122 KB
/
session.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 (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package client
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/m3db/m3/src/cluster/shard"
"github.com/m3db/m3/src/dbnode/clock"
"github.com/m3db/m3/src/dbnode/digest"
"github.com/m3db/m3/src/dbnode/encoding"
"github.com/m3db/m3/src/dbnode/generated/thrift/rpc"
"github.com/m3db/m3/src/dbnode/namespace"
"github.com/m3db/m3/src/dbnode/network/server/tchannelthrift/convert"
"github.com/m3db/m3/src/dbnode/runtime"
"github.com/m3db/m3/src/dbnode/storage/block"
"github.com/m3db/m3/src/dbnode/storage/bootstrap/result"
"github.com/m3db/m3/src/dbnode/storage/index"
idxconvert "github.com/m3db/m3/src/dbnode/storage/index/convert"
"github.com/m3db/m3/src/dbnode/topology"
"github.com/m3db/m3/src/dbnode/ts"
"github.com/m3db/m3/src/dbnode/x/xio"
"github.com/m3db/m3/src/dbnode/x/xpool"
"github.com/m3db/m3/src/x/checked"
xclose "github.com/m3db/m3/src/x/close"
"github.com/m3db/m3/src/x/context"
xerrors "github.com/m3db/m3/src/x/errors"
"github.com/m3db/m3/src/x/ident"
"github.com/m3db/m3/src/x/instrument"
"github.com/m3db/m3/src/x/pool"
xretry "github.com/m3db/m3/src/x/retry"
"github.com/m3db/m3/src/x/serialize"
xsync "github.com/m3db/m3/src/x/sync"
xtime "github.com/m3db/m3/src/x/time"
apachethrift "github.com/apache/thrift/lib/go/thrift"
"github.com/uber-go/tally"
"github.com/uber/tchannel-go/thrift"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
clusterConnectWaitInterval = 10 * time.Millisecond
blocksMetadataChannelInitialCapacity = 4096
gaugeReportInterval = 500 * time.Millisecond
blockMetadataChBufSize = 4096
shardResultCapacity = 4096
hostNotAvailableMinSleepInterval = 1 * time.Millisecond
hostNotAvailableMaxSleepInterval = 100 * time.Millisecond
)
type resultTypeEnum string
const (
resultTypeMetadata resultTypeEnum = "metadata"
resultTypeBootstrap = "bootstrap"
resultTypeRaw = "raw"
)
var (
errUnknownWriteAttemptType = errors.New(
"unknown write attempt type specified, internal error")
)
var (
// ErrClusterConnectTimeout is raised when connecting to the cluster and
// ensuring at least each partition has an up node with a connection to it
ErrClusterConnectTimeout = errors.New("timed out establishing min connections to cluster")
// errSessionStatusNotInitial is raised when trying to open a session and
// its not in the initial clean state
errSessionStatusNotInitial = errors.New("session not in initial state")
// errSessionStatusNotOpen is raised when operations are requested when the
// session is not in the open state
errSessionStatusNotOpen = errors.New("session not in open state")
// errSessionBadBlockResultFromPeer is raised when there is a bad block
// return from a peer when fetching blocks from peers
errSessionBadBlockResultFromPeer = errors.New("session fetched bad block result from peer")
// errSessionInvalidConnectClusterConnectConsistencyLevel is raised when
// the connect consistency level specified is not recognized
errSessionInvalidConnectClusterConnectConsistencyLevel = errors.New("session has invalid connect consistency level specified")
// errSessionHasNoHostQueueForHost is raised when host queue requested for a missing host
errSessionHasNoHostQueueForHost = newHostNotAvailableError(errors.New("session has no host queue for host"))
// errUnableToEncodeTags is raised when the server is unable to encode provided tags
// to be sent over the wire.
errUnableToEncodeTags = errors.New("unable to include tags")
// errEnqueueChIsClosed is returned when attempting to use a closed enqueuCh.
errEnqueueChIsClosed = errors.New("error enqueueCh is cosed")
)
// sessionState is volatile state that is protected by a
// read/write mutex
type sessionState struct {
sync.RWMutex
status status
writeLevel topology.ConsistencyLevel
readLevel topology.ReadConsistencyLevel
bootstrapLevel topology.ReadConsistencyLevel
queues []hostQueue
queuesByHostID map[string]hostQueue
topo topology.Topology
topoMap topology.Map
topoWatch topology.MapWatch
replicas int
majority int
}
type session struct {
state sessionState
opts Options
runtimeOptsListenerCloser xclose.Closer
scope tally.Scope
nowFn clock.NowFn
log *zap.Logger
newHostQueueFn newHostQueueFn
writeRetrier xretry.Retrier
fetchRetrier xretry.Retrier
streamBlocksRetrier xretry.Retrier
pools sessionPools
fetchBatchSize int
newPeerBlocksQueueFn newPeerBlocksQueueFn
reattemptStreamBlocksFromPeersFn reattemptStreamBlocksFromPeersFn
pickBestPeerFn pickBestPeerFn
origin topology.Host
streamBlocksMaxBlockRetries int
streamBlocksWorkers xsync.WorkerPool
streamBlocksBatchSize int
streamBlocksMetadataBatchTimeout time.Duration
streamBlocksBatchTimeout time.Duration
metrics sessionMetrics
}
type shardMetricsKey struct {
shardID uint32
resultType resultTypeEnum
}
type sessionMetrics struct {
sync.RWMutex
writeSuccess tally.Counter
writeErrors tally.Counter
writeLatencyHistogram tally.Histogram
writeNodesRespondingErrors []tally.Counter
writeNodesRespondingBadRequestErrors []tally.Counter
fetchSuccess tally.Counter
fetchErrors tally.Counter
fetchLatencyHistogram tally.Histogram
fetchNodesRespondingErrors []tally.Counter
fetchNodesRespondingBadRequestErrors []tally.Counter
topologyUpdatedSuccess tally.Counter
topologyUpdatedError tally.Counter
streamFromPeersMetrics map[shardMetricsKey]streamFromPeersMetrics
}
func newSessionMetrics(scope tally.Scope) sessionMetrics {
return sessionMetrics{
writeSuccess: scope.Counter("write.success"),
writeErrors: scope.Counter("write.errors"),
writeLatencyHistogram: histogramWithDurationBuckets(scope, "write.latency"),
fetchSuccess: scope.Counter("fetch.success"),
fetchErrors: scope.Counter("fetch.errors"),
fetchLatencyHistogram: histogramWithDurationBuckets(scope, "fetch.latency"),
topologyUpdatedSuccess: scope.Counter("topology.updated-success"),
topologyUpdatedError: scope.Counter("topology.updated-error"),
streamFromPeersMetrics: make(map[shardMetricsKey]streamFromPeersMetrics),
}
}
type streamFromPeersMetrics struct {
fetchBlocksFromPeers tally.Gauge
metadataFetches tally.Gauge
metadataFetchBatchCall tally.Counter
metadataFetchBatchSuccess tally.Counter
metadataFetchBatchError tally.Counter
metadataFetchBatchBlockErr tally.Counter
metadataReceived tally.Counter
metadataPeerRetry tally.Counter
fetchBlockSuccess tally.Counter
fetchBlockError tally.Counter
fetchBlockFullRetry tally.Counter
fetchBlockFinalError tally.Counter
fetchBlockRetriesReqError tally.Counter
fetchBlockRetriesRespError tally.Counter
fetchBlockRetriesConsistencyLevelNotAchievedError tally.Counter
blocksEnqueueChannel tally.Gauge
}
type hostQueueOpts struct {
writeBatchRawRequestPool writeBatchRawRequestPool
writeBatchRawV2RequestPool writeBatchRawV2RequestPool
writeBatchRawRequestElementArrayPool writeBatchRawRequestElementArrayPool
writeBatchRawV2RequestElementArrayPool writeBatchRawV2RequestElementArrayPool
writeTaggedBatchRawRequestPool writeTaggedBatchRawRequestPool
writeTaggedBatchRawV2RequestPool writeTaggedBatchRawV2RequestPool
writeTaggedBatchRawRequestElementArrayPool writeTaggedBatchRawRequestElementArrayPool
writeTaggedBatchRawV2RequestElementArrayPool writeTaggedBatchRawV2RequestElementArrayPool
fetchBatchRawV2RequestPool fetchBatchRawV2RequestPool
fetchBatchRawV2RequestElementArrayPool fetchBatchRawV2RequestElementArrayPool
opts Options
}
type newHostQueueFn func(
host topology.Host,
hostQueueOpts hostQueueOpts,
) (hostQueue, error)
func newSession(opts Options) (clientSession, error) {
topo, err := opts.TopologyInitializer().Init()
if err != nil {
return nil, err
}
scope := opts.InstrumentOptions().MetricsScope()
s := &session{
state: sessionState{
writeLevel: opts.WriteConsistencyLevel(),
readLevel: opts.ReadConsistencyLevel(),
queuesByHostID: make(map[string]hostQueue),
topo: topo,
},
opts: opts,
scope: scope,
nowFn: opts.ClockOptions().NowFn(),
log: opts.InstrumentOptions().Logger(),
newHostQueueFn: newHostQueue,
fetchBatchSize: opts.FetchBatchSize(),
newPeerBlocksQueueFn: newPeerBlocksQueue,
writeRetrier: opts.WriteRetrier(),
fetchRetrier: opts.FetchRetrier(),
pools: sessionPools{
context: opts.ContextPool(),
id: opts.IdentifierPool(),
},
metrics: newSessionMetrics(scope),
}
s.reattemptStreamBlocksFromPeersFn = s.streamBlocksReattemptFromPeers
s.pickBestPeerFn = s.streamBlocksPickBestPeer
writeAttemptPoolOpts := pool.NewObjectPoolOptions().
SetSize(opts.WriteOpPoolSize()).
SetInstrumentOptions(opts.InstrumentOptions().SetMetricsScope(
scope.SubScope("write-attempt-pool"),
))
s.pools.writeAttempt = newWriteAttemptPool(s, writeAttemptPoolOpts)
s.pools.writeAttempt.Init()
fetchAttemptPoolOpts := pool.NewObjectPoolOptions().
SetSize(opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(opts.InstrumentOptions().SetMetricsScope(
scope.SubScope("fetch-attempt-pool"),
))
s.pools.fetchAttempt = newFetchAttemptPool(s, fetchAttemptPoolOpts)
s.pools.fetchAttempt.Init()
fetchTaggedAttemptPoolImplOpts := pool.NewObjectPoolOptions().
SetSize(opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(opts.InstrumentOptions().SetMetricsScope(
scope.SubScope("fetch-tagged-attempt-pool"),
))
s.pools.fetchTaggedAttempt = newFetchTaggedAttemptPool(s, fetchTaggedAttemptPoolImplOpts)
s.pools.fetchTaggedAttempt.Init()
aggregateAttemptPoolImplOpts := pool.NewObjectPoolOptions().
SetSize(opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(opts.InstrumentOptions().SetMetricsScope(
scope.SubScope("aggregate-attempt-pool"),
))
s.pools.aggregateAttempt = newAggregateAttemptPool(s, aggregateAttemptPoolImplOpts)
s.pools.aggregateAttempt.Init()
tagEncoderPoolOpts := pool.NewObjectPoolOptions().
SetSize(opts.TagEncoderPoolSize()).
SetInstrumentOptions(opts.InstrumentOptions().SetMetricsScope(
scope.SubScope("tag-encoder-pool"),
))
s.pools.tagEncoder = serialize.NewTagEncoderPool(opts.TagEncoderOptions(), tagEncoderPoolOpts)
s.pools.tagEncoder.Init()
tagDecoderPoolOpts := pool.NewObjectPoolOptions().
SetSize(opts.TagDecoderPoolSize()).
SetInstrumentOptions(opts.InstrumentOptions().SetMetricsScope(
scope.SubScope("tag-decoder-pool"),
))
s.pools.tagDecoder = serialize.NewTagDecoderPool(opts.TagDecoderOptions(), tagDecoderPoolOpts)
s.pools.tagDecoder.Init()
wrapperPoolOpts := pool.NewObjectPoolOptions().
SetSize(opts.CheckedBytesWrapperPoolSize()).
SetInstrumentOptions(opts.InstrumentOptions().SetMetricsScope(
scope.SubScope("client-checked-bytes-wrapper-pool")))
s.pools.checkedBytesWrapper = xpool.NewCheckedBytesWrapperPool(wrapperPoolOpts)
s.pools.checkedBytesWrapper.Init()
if opts, ok := opts.(AdminOptions); ok {
s.state.bootstrapLevel = opts.BootstrapConsistencyLevel()
s.origin = opts.Origin()
s.streamBlocksMaxBlockRetries = opts.FetchSeriesBlocksMaxBlockRetries()
s.streamBlocksWorkers = xsync.NewWorkerPool(opts.FetchSeriesBlocksBatchConcurrency())
s.streamBlocksWorkers.Init()
s.streamBlocksBatchSize = opts.FetchSeriesBlocksBatchSize()
s.streamBlocksMetadataBatchTimeout = opts.FetchSeriesBlocksMetadataBatchTimeout()
s.streamBlocksBatchTimeout = opts.FetchSeriesBlocksBatchTimeout()
s.streamBlocksRetrier = opts.StreamBlocksRetrier()
}
if runtimeOptsMgr := opts.RuntimeOptionsManager(); runtimeOptsMgr != nil {
runtimeOptsMgr.RegisterListener(s)
}
return s, nil
}
func (s *session) SetRuntimeOptions(value runtime.Options) {
s.state.Lock()
s.state.bootstrapLevel = value.ClientBootstrapConsistencyLevel()
s.state.readLevel = value.ClientReadConsistencyLevel()
s.state.writeLevel = value.ClientWriteConsistencyLevel()
s.state.Unlock()
}
func (s *session) ShardID(id ident.ID) (uint32, error) {
s.state.RLock()
if s.state.status != statusOpen {
s.state.RUnlock()
return 0, errSessionStatusNotOpen
}
value := s.state.topoMap.ShardSet().Lookup(id)
s.state.RUnlock()
return value, nil
}
// newPeerMetadataStreamingProgressMetrics returns a struct with an embedded
// list of fields that can be used to emit metrics about the current state of
// the peer metadata streaming process
func (s *session) newPeerMetadataStreamingProgressMetrics(
shard uint32,
resultType resultTypeEnum,
) *streamFromPeersMetrics {
mKey := shardMetricsKey{shardID: shard, resultType: resultType}
s.metrics.RLock()
m, ok := s.metrics.streamFromPeersMetrics[mKey]
s.metrics.RUnlock()
if ok {
return &m
}
scope := s.opts.InstrumentOptions().MetricsScope()
s.metrics.Lock()
m, ok = s.metrics.streamFromPeersMetrics[mKey]
if ok {
s.metrics.Unlock()
return &m
}
scope = scope.SubScope("stream-from-peers").Tagged(map[string]string{
"shard": fmt.Sprintf("%d", shard),
"resultType": string(resultType),
})
m = streamFromPeersMetrics{
fetchBlocksFromPeers: scope.Gauge("fetch-blocks-inprogress"),
metadataFetches: scope.Gauge("fetch-metadata-peers-inprogress"),
metadataFetchBatchCall: scope.Counter("fetch-metadata-peers-batch-call"),
metadataFetchBatchSuccess: scope.Counter("fetch-metadata-peers-batch-success"),
metadataFetchBatchError: scope.Counter("fetch-metadata-peers-batch-error"),
metadataFetchBatchBlockErr: scope.Counter("fetch-metadata-peers-batch-block-err"),
metadataReceived: scope.Counter("fetch-metadata-peers-received"),
metadataPeerRetry: scope.Counter("fetch-metadata-peers-peer-retry"),
fetchBlockSuccess: scope.Counter("fetch-block-success"),
fetchBlockError: scope.Counter("fetch-block-error"),
fetchBlockFinalError: scope.Counter("fetch-block-final-error"),
fetchBlockFullRetry: scope.Counter("fetch-block-full-retry"),
fetchBlockRetriesReqError: scope.Tagged(map[string]string{
"reason": "request-error",
}).Counter("fetch-block-retries"),
fetchBlockRetriesRespError: scope.Tagged(map[string]string{
"reason": "response-error",
}).Counter("fetch-block-retries"),
fetchBlockRetriesConsistencyLevelNotAchievedError: scope.Tagged(map[string]string{
"reason": "consistency-level-not-achieved-error",
}).Counter("fetch-block-retries"),
blocksEnqueueChannel: scope.Gauge("fetch-blocks-enqueue-channel-length"),
}
s.metrics.streamFromPeersMetrics[mKey] = m
s.metrics.Unlock()
return &m
}
func (s *session) recordWriteMetrics(consistencyResultErr error, respErrs int32, start time.Time) {
if idx := s.nodesRespondingErrorsMetricIndex(respErrs); idx >= 0 {
if IsBadRequestError(consistencyResultErr) {
s.metrics.writeNodesRespondingBadRequestErrors[idx].Inc(1)
} else {
s.metrics.writeNodesRespondingErrors[idx].Inc(1)
}
}
if consistencyResultErr == nil {
s.metrics.writeSuccess.Inc(1)
} else {
s.metrics.writeErrors.Inc(1)
}
s.metrics.writeLatencyHistogram.RecordDuration(s.nowFn().Sub(start))
}
func (s *session) recordFetchMetrics(consistencyResultErr error, respErrs int32, start time.Time) {
if idx := s.nodesRespondingErrorsMetricIndex(respErrs); idx >= 0 {
if IsBadRequestError(consistencyResultErr) {
s.metrics.fetchNodesRespondingBadRequestErrors[idx].Inc(1)
} else {
s.metrics.fetchNodesRespondingErrors[idx].Inc(1)
}
}
if consistencyResultErr == nil {
s.metrics.fetchSuccess.Inc(1)
} else {
s.metrics.fetchErrors.Inc(1)
}
s.metrics.fetchLatencyHistogram.RecordDuration(s.nowFn().Sub(start))
}
func (s *session) nodesRespondingErrorsMetricIndex(respErrs int32) int32 {
idx := respErrs - 1
replicas := int32(s.Replicas())
if respErrs > replicas {
// Cap to the max replicas, we might get more errors
// when a node is initializing a shard causing replicas + 1
// nodes to respond to operations
idx = replicas - 1
}
return idx
}
func (s *session) Open() error {
s.state.Lock()
if s.state.status != statusNotOpen {
s.state.Unlock()
return errSessionStatusNotInitial
}
watch, err := s.state.topo.Watch()
if err != nil {
s.state.Unlock()
return err
}
// Wait for the topology to be available
<-watch.C()
topoMap := watch.Get()
queues, replicas, majority, err := s.hostQueues(topoMap, nil)
if err != nil {
s.state.Unlock()
return err
}
s.setTopologyWithLock(topoMap, queues, replicas, majority)
s.state.topoWatch = watch
// NB(r): Alloc pools that can take some time in Open, expectation
// is already that Open will take some time
writeOperationPoolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.WriteOpPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("write-op-pool"),
))
s.pools.writeOperation = newWriteOperationPool(writeOperationPoolOpts)
s.pools.writeOperation.Init()
writeTaggedOperationPoolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.WriteTaggedOpPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("write-op-tagged-pool"),
))
s.pools.writeTaggedOperation = newWriteTaggedOpPool(writeTaggedOperationPoolOpts)
s.pools.writeTaggedOperation.Init()
writeStatePoolSize := s.opts.WriteOpPoolSize()
if s.opts.WriteTaggedOpPoolSize() > writeStatePoolSize {
writeStatePoolSize = s.opts.WriteTaggedOpPoolSize()
}
writeStatePoolOpts := pool.NewObjectPoolOptions().
SetSize(writeStatePoolSize).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("write-state-pool"),
))
s.pools.writeState = newWriteStatePool(s.pools.tagEncoder, writeStatePoolOpts)
s.pools.writeState.Init()
fetchBatchOpPoolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("fetch-batch-op-pool"),
))
s.pools.fetchBatchOp = newFetchBatchOpPool(fetchBatchOpPoolOpts, s.fetchBatchSize)
s.pools.fetchBatchOp.Init()
fetchTaggedOpPoolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("fetch-tagged-op-pool"),
))
s.pools.fetchTaggedOp = newFetchTaggedOpPool(fetchTaggedOpPoolOpts)
s.pools.fetchTaggedOp.Init()
aggregateOpPoolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("aggregate-op-pool"),
))
s.pools.aggregateOp = newAggregateOpPool(aggregateOpPoolOpts)
s.pools.aggregateOp.Init()
fetchStatePoolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("fetch-tagged-state-pool"),
))
s.pools.fetchState = newFetchStatePool(fetchStatePoolOpts)
s.pools.fetchState.Init()
seriesIteratorPoolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.SeriesIteratorPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("series-iterator-pool"),
))
s.pools.seriesIterator = encoding.NewSeriesIteratorPool(seriesIteratorPoolOpts)
s.pools.seriesIterator.Init()
s.pools.seriesIterators = encoding.NewMutableSeriesIteratorsPool(s.opts.SeriesIteratorArrayPoolBuckets())
s.pools.seriesIterators.Init()
s.state.status = statusOpen
s.state.Unlock()
go func() {
for range watch.C() {
s.log.Info("received update for topology")
topoMap := watch.Get()
s.state.RLock()
existingQueues := s.state.queues
s.state.RUnlock()
queues, replicas, majority, err := s.hostQueues(topoMap, existingQueues)
if err != nil {
s.log.Error("could not update topology map", zap.Error(err))
s.metrics.topologyUpdatedError.Inc(1)
continue
}
s.state.Lock()
s.setTopologyWithLock(topoMap, queues, replicas, majority)
s.state.Unlock()
s.metrics.topologyUpdatedSuccess.Inc(1)
}
}()
return nil
}
func (s *session) BorrowConnection(hostID string, fn withConnectionFn) error {
s.state.RLock()
unlocked := false
queue, ok := s.state.queuesByHostID[hostID]
if !ok {
s.state.RUnlock()
return errSessionHasNoHostQueueForHost
}
err := queue.BorrowConnection(func(c rpc.TChanNode) {
// Unlock early on success
s.state.RUnlock()
unlocked = true
// Execute function with borrowed connection
fn(c)
})
if !unlocked {
s.state.RUnlock()
}
return err
}
func (s *session) hostQueues(
topoMap topology.Map,
existing []hostQueue,
) ([]hostQueue, int, int, error) {
// NB(r): we leave existing writes in the host queues to finish
// as they are already enroute to their destination. This is an edge case
// that might result in leaving nodes counting towards quorum, but fixing it
// would result in additional chatter.
start := s.nowFn()
existingByHostID := make(map[string]hostQueue, len(existing))
for _, queue := range existing {
existingByHostID[queue.Host().ID()] = queue
}
hosts := topoMap.Hosts()
queues := make([]hostQueue, 0, len(hosts))
newQueues := make([]hostQueue, 0, len(hosts))
for _, host := range hosts {
if existingQueue, ok := existingByHostID[host.ID()]; ok {
queues = append(queues, existingQueue)
continue
}
newQueue, err := s.newHostQueue(host, topoMap)
if err != nil {
return nil, 0, 0, err
}
queues = append(queues, newQueue)
newQueues = append(newQueues, newQueue)
}
shards := topoMap.ShardSet().AllIDs()
minConnectionCount := s.opts.MinConnectionCount()
replicas := topoMap.Replicas()
majority := topoMap.MajorityReplicas()
firstConnectConsistencyLevel := s.opts.ClusterConnectConsistencyLevel()
if firstConnectConsistencyLevel == topology.ConnectConsistencyLevelNone {
// Return immediately if no connect consistency required
return queues, replicas, majority, nil
}
connectConsistencyLevel := firstConnectConsistencyLevel
if connectConsistencyLevel == topology.ConnectConsistencyLevelAny {
// If level any specified, first attempt all then proceed lowering requirement
connectConsistencyLevel = topology.ConnectConsistencyLevelAll
}
// Abort if we do not connect
connected := false
defer func() {
if !connected {
for _, queue := range newQueues {
queue.Close()
}
}
}()
for {
if now := s.nowFn(); now.Sub(start) >= s.opts.ClusterConnectTimeout() {
switch firstConnectConsistencyLevel {
case topology.ConnectConsistencyLevelAny:
// If connecting with connect any strategy then keep
// trying but lower consistency requirement
start = now
connectConsistencyLevel--
if connectConsistencyLevel == topology.ConnectConsistencyLevelNone {
// Already tried to resolve all consistency requirements, just
// return successfully at this point
err := fmt.Errorf("timed out connecting, returning success")
s.log.Warn("cluster connect with consistency any", zap.Error(err))
connected = true
return queues, replicas, majority, nil
}
default:
// Timed out connecting to a specific consistency requirement
return nil, 0, 0, ErrClusterConnectTimeout
}
}
// Be optimistic
clusterAvailable := true
for _, shard := range shards {
shardReplicasAvailable := 0
routeErr := topoMap.RouteShardForEach(shard, func(idx int, _ topology.Host) {
if queues[idx].ConnectionCount() >= minConnectionCount {
shardReplicasAvailable++
}
})
if routeErr != nil {
return nil, 0, 0, routeErr
}
var clusterAvailableForShard bool
switch connectConsistencyLevel {
case topology.ConnectConsistencyLevelAll:
clusterAvailableForShard = shardReplicasAvailable == replicas
case topology.ConnectConsistencyLevelMajority:
clusterAvailableForShard = shardReplicasAvailable >= majority
case topology.ConnectConsistencyLevelOne:
clusterAvailableForShard = shardReplicasAvailable > 0
default:
return nil, 0, 0, errSessionInvalidConnectClusterConnectConsistencyLevel
}
if !clusterAvailableForShard {
clusterAvailable = false
break
}
}
if clusterAvailable { // All done
break
}
time.Sleep(clusterConnectWaitInterval)
}
connected = true
return queues, replicas, majority, nil
}
func (s *session) setTopologyWithLock(topoMap topology.Map, queues []hostQueue, replicas, majority int) {
prevQueues := s.state.queues
newQueuesByHostID := make(map[string]hostQueue, len(queues))
for _, queue := range queues {
newQueuesByHostID[queue.Host().ID()] = queue
}
s.state.queues = queues
s.state.queuesByHostID = newQueuesByHostID
s.state.topoMap = topoMap
s.state.replicas = replicas
s.state.majority = majority
// If the number of hostQueues has changed then we need to recreate the fetch
// batch op array pool as it must be the exact length of the queues as we index
// directly into the return array in fetch calls.
if len(queues) != len(prevQueues) {
poolOpts := pool.NewObjectPoolOptions().
SetSize(s.opts.FetchBatchOpPoolSize()).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("fetch-batch-op-array-array-pool"),
))
s.pools.fetchBatchOpArrayArray = newFetchBatchOpArrayArrayPool(
poolOpts,
len(queues),
s.opts.FetchBatchOpPoolSize()/len(queues))
s.pools.fetchBatchOpArrayArray.Init()
}
if s.pools.multiReaderIteratorArray == nil {
s.pools.multiReaderIteratorArray = encoding.NewMultiReaderIteratorArrayPool([]pool.Bucket{
pool.Bucket{
Capacity: replicas,
Count: s.opts.SeriesIteratorPoolSize(),
},
})
s.pools.multiReaderIteratorArray.Init()
}
if s.pools.readerSliceOfSlicesIterator == nil {
size := replicas * s.opts.SeriesIteratorPoolSize()
poolOpts := pool.NewObjectPoolOptions().
SetSize(size).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("reader-slice-of-slices-iterator-pool"),
))
s.pools.readerSliceOfSlicesIterator = newReaderSliceOfSlicesIteratorPool(poolOpts)
s.pools.readerSliceOfSlicesIterator.Init()
}
if s.pools.multiReaderIterator == nil {
size := replicas * s.opts.SeriesIteratorPoolSize()
poolOpts := pool.NewObjectPoolOptions().
SetSize(size).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("multi-reader-iterator-pool"),
))
s.pools.multiReaderIterator = encoding.NewMultiReaderIteratorPool(poolOpts)
s.pools.multiReaderIterator.Init(s.opts.ReaderIteratorAllocate())
}
if replicas > len(s.metrics.writeNodesRespondingErrors) {
curr := len(s.metrics.writeNodesRespondingErrors)
for i := curr; i < replicas; i++ {
tags := map[string]string{"nodes": fmt.Sprintf("%d", i+1)}
name := "write.nodes-responding-error"
serverErrsSubScope := s.scope.Tagged(tags).Tagged(map[string]string{
"error_type": "server_error",
})
badRequestErrsSubScope := s.scope.Tagged(tags).Tagged(map[string]string{
"error_type": "bad_request_error",
})
s.metrics.writeNodesRespondingErrors =
append(s.metrics.writeNodesRespondingErrors, serverErrsSubScope.Counter(name))
s.metrics.writeNodesRespondingBadRequestErrors =
append(s.metrics.writeNodesRespondingBadRequestErrors, badRequestErrsSubScope.Counter(name))
}
}
if replicas > len(s.metrics.fetchNodesRespondingErrors) {
curr := len(s.metrics.fetchNodesRespondingErrors)
for i := curr; i < replicas; i++ {
tags := map[string]string{"nodes": fmt.Sprintf("%d", i+1)}
name := "fetch.nodes-responding-error"
serverErrsSubScope := s.scope.Tagged(tags).Tagged(map[string]string{
"error_type": "server_error",
})
badRequestErrsSubScope := s.scope.Tagged(tags).Tagged(map[string]string{
"error_type": "bad_request_error",
})
s.metrics.fetchNodesRespondingErrors =
append(s.metrics.fetchNodesRespondingErrors, serverErrsSubScope.Counter(name))
s.metrics.fetchNodesRespondingBadRequestErrors =
append(s.metrics.fetchNodesRespondingBadRequestErrors, badRequestErrsSubScope.Counter(name))
}
}
// Asynchronously close the set of host queues no longer in use
go func() {
for _, queue := range prevQueues {
newQueue, ok := newQueuesByHostID[queue.Host().ID()]
if !ok || newQueue != queue {
queue.Close()
}
}
}()
s.log.Info("successfully updated topology", zap.Int("numHosts", topoMap.HostsLen()))
}
func (s *session) newHostQueue(host topology.Host, topoMap topology.Map) (hostQueue, error) {
// NB(r): Due to hosts being replicas we have:
// = replica * numWrites
// = total writes to all hosts
// We need to pool:
// = replica * (numWrites / writeBatchSize)
// = number of batch request structs to pool
// For purposes of simplifying the options for pooling the write op pool size
// represents the number of ops to pool not including replication, this is due
// to the fact that the ops are shared between the different host queue replicas.
writeOpPoolSize := s.opts.WriteOpPoolSize()
if s.opts.WriteTaggedOpPoolSize() > writeOpPoolSize {
writeOpPoolSize = s.opts.WriteTaggedOpPoolSize()
}
totalBatches := topoMap.Replicas() *
int(math.Ceil(float64(writeOpPoolSize)/float64(s.opts.WriteBatchSize())))
hostBatches := int(math.Ceil(float64(totalBatches) / float64(topoMap.HostsLen())))
writeBatchRequestPoolOpts := pool.NewObjectPoolOptions().
SetSize(hostBatches).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("write-batch-request-pool"),
))
writeBatchRequestPool := newWriteBatchRawRequestPool(writeBatchRequestPoolOpts)
writeBatchRequestPool.Init()
writeBatchV2RequestPool := newWriteBatchRawV2RequestPool(writeBatchRequestPoolOpts)
writeBatchV2RequestPool.Init()
writeTaggedBatchRequestPoolOpts := pool.NewObjectPoolOptions().
SetSize(hostBatches).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("write-tagged-batch-request-pool"),
))
writeTaggedBatchRequestPool := newWriteTaggedBatchRawRequestPool(writeTaggedBatchRequestPoolOpts)
writeTaggedBatchRequestPool.Init()
writeTaggedBatchV2RequestPool := newWriteTaggedBatchRawV2RequestPool(writeBatchRequestPoolOpts)
writeTaggedBatchV2RequestPool.Init()
writeBatchRawRequestElementArrayPoolOpts := pool.NewObjectPoolOptions().
SetSize(hostBatches).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("id-datapoint-array-pool"),
))
writeBatchRawRequestElementArrayPool := newWriteBatchRawRequestElementArrayPool(
writeBatchRawRequestElementArrayPoolOpts, s.opts.WriteBatchSize())
writeBatchRawRequestElementArrayPool.Init()
writeBatchRawV2RequestElementArrayPool := newWriteBatchRawV2RequestElementArrayPool(
writeBatchRawRequestElementArrayPoolOpts, s.opts.WriteBatchSize())
writeBatchRawV2RequestElementArrayPool.Init()
writeTaggedBatchRawRequestElementArrayPoolOpts := pool.NewObjectPoolOptions().
SetSize(hostBatches).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("id-tagged-datapoint-array-pool"),
))
writeTaggedBatchRawRequestElementArrayPool := newWriteTaggedBatchRawRequestElementArrayPool(
writeTaggedBatchRawRequestElementArrayPoolOpts, s.opts.WriteBatchSize())
writeTaggedBatchRawRequestElementArrayPool.Init()
writeTaggedBatchRawV2RequestElementArrayPool := newWriteTaggedBatchRawV2RequestElementArrayPool(
writeTaggedBatchRawRequestElementArrayPoolOpts, s.opts.WriteBatchSize())
writeTaggedBatchRawV2RequestElementArrayPool.Init()
fetchBatchRawV2RequestPoolOpts := pool.NewObjectPoolOptions().
SetSize(hostBatches).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("fetch-batch-request-pool"),
))
fetchBatchRawV2RequestPool := newFetchBatchRawV2RequestPool(fetchBatchRawV2RequestPoolOpts)
fetchBatchRawV2RequestPool.Init()
fetchBatchRawV2RequestElementArrayPoolOpts := pool.NewObjectPoolOptions().
SetSize(hostBatches).
SetInstrumentOptions(s.opts.InstrumentOptions().SetMetricsScope(
s.scope.SubScope("fetch-batch-request-array-pool"),
))
fetchBatchRawV2RequestElementArrayPool := newFetchBatchRawV2RequestElementArrayPool(fetchBatchRawV2RequestElementArrayPoolOpts, s.opts.FetchBatchSize())
fetchBatchRawV2RequestElementArrayPool.Init()
hostQueue, err := s.newHostQueueFn(host, hostQueueOpts{
writeBatchRawRequestPool: writeBatchRequestPool,
writeBatchRawV2RequestPool: writeBatchV2RequestPool,
writeBatchRawRequestElementArrayPool: writeBatchRawRequestElementArrayPool,
writeBatchRawV2RequestElementArrayPool: writeBatchRawV2RequestElementArrayPool,
writeTaggedBatchRawRequestPool: writeTaggedBatchRequestPool,
writeTaggedBatchRawV2RequestPool: writeTaggedBatchV2RequestPool,
writeTaggedBatchRawRequestElementArrayPool: writeTaggedBatchRawRequestElementArrayPool,
writeTaggedBatchRawV2RequestElementArrayPool: writeTaggedBatchRawV2RequestElementArrayPool,
fetchBatchRawV2RequestPool: fetchBatchRawV2RequestPool,
fetchBatchRawV2RequestElementArrayPool: fetchBatchRawV2RequestElementArrayPool,
opts: s.opts,
})
if err != nil {
return nil, err
}
hostQueue.Open()
return hostQueue, nil
}
func (s *session) Write(
nsID, id ident.ID,
t time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
) error {
w := s.pools.writeAttempt.Get()
w.args.attemptType = untaggedWriteAttemptType
w.args.namespace, w.args.id = nsID, id
w.args.tags = ident.EmptyTagIterator
w.args.t, w.args.value, w.args.unit, w.args.annotation =
t, value, unit, annotation
err := s.writeRetrier.Attempt(w.attemptFn)
s.pools.writeAttempt.Put(w)
return err
}
func (s *session) WriteTagged(
nsID, id ident.ID,
tags ident.TagIterator,
t time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
) error {
w := s.pools.writeAttempt.Get()
w.args.attemptType = taggedWriteAttemptType
w.args.namespace, w.args.id, w.args.tags = nsID, id, tags
w.args.t, w.args.value, w.args.unit, w.args.annotation =
t, value, unit, annotation
err := s.writeRetrier.Attempt(w.attemptFn)
s.pools.writeAttempt.Put(w)
return err
}
func (s *session) writeAttempt(
wType writeAttemptType,
nsID, id ident.ID,
inputTags ident.TagIterator,
t time.Time,
value float64,
unit xtime.Unit,
annotation []byte,
) error {
startWriteAttempt := s.nowFn()
timeType, timeTypeErr := convert.ToTimeType(unit)
if timeTypeErr != nil {
return timeTypeErr
}
timestamp, timestampErr := convert.ToValue(t, timeType)
if timestampErr != nil {
return timestampErr
}
s.state.RLock()
if s.state.status != statusOpen {
s.state.RUnlock()
return errSessionStatusNotOpen
}
state, majority, enqueued, err := s.writeAttemptWithRLock(
wType, nsID, id, inputTags, timestamp, value, timeType, annotation)
s.state.RUnlock()