-
Notifications
You must be signed in to change notification settings - Fork 12
/
feed_dcp_gocbcore.go
1457 lines (1238 loc) · 41.1 KB
/
feed_dcp_gocbcore.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 2018-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package cbgt
import (
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
log "github.com/couchbase/clog"
"github.com/couchbase/gocbcore/v10"
"github.com/couchbase/gocbcore/v10/memd"
)
const SOURCE_GOCBCORE = "gocbcore"
var maxEndSeqno = gocbcore.SeqNo(0xffffffffffffffff)
var errBucketUUIDMismatched = fmt.Errorf("mismatched bucketUUID")
// ----------------------------------------------------------------
var streamID uint64
func newStreamID() uint16 {
// OpenStreamOptions needs streamID to be of type uint16.
// Also, KV requires streamID to fall within a range of: 1 to 65535.
// Here we do a mod operation, to circle around in case of an overflow.
for {
ret := uint16(atomic.AddUint64(&streamID, 1) % (math.MaxUint16 + 1))
if ret != 0 {
return ret
}
}
}
// ----------------------------------------------------------------
// Function overrride to set up a gocbcore.DCPAgent
// servers: single URL or multiple URLs delimited by ';'
var FetchDCPAgent func(bucketName, bucketUUID, paramsStr, servers string,
options map[string]string) (*gocbcore.DCPAgent, error)
// Function overrride to close a gocbcore.DCPAgent
var CloseDCPAgent func(bucketName, bucketUUID string, agent *gocbcore.DCPAgent) error
// ----------------------------------------------------------------
type streamDetails struct {
Partition string `json:"pindex"`
NumVBuckets uint64 `json:"num_vbuckets"`
}
type dcpAgentDetails struct {
dcpConnName string
Refs int `json:"refs"`
NumStreamReqs uint64 `json:"num_stream_reqs"`
// streamID:streamDetails
Streams map[string]*streamDetails `json:"streams"`
// extended attributes flag
xattrs bool
}
// Map to hold a pool of gocbcore.DCPAgents for every bucket, each
// gocbcore.DCPAgent will be allowed a maximum reference count controlled
// by maxFeedsPerDCPAgent.
type gocbcoreDCPAgentMap struct {
// mutex to serialize access to entries/refCount
m sync.RWMutex
// map of gocbcore.DCPAgents with ref counts for bucket <name>:<uuid>
entries map[string]map[*gocbcore.DCPAgent]*dcpAgentDetails
// stat to track number of live DCP agents (connections)
numDCPAgents uint64
}
// Max references for a gocbcore.DCPAgent
// NOTE: Increasing this value to > 1 will cause agents to be reused for
// multiple feeds, provided they're up against the same source.
const defaultMaxFeedsPerDCPAgent = int(1)
var dcpAgentMap *gocbcoreDCPAgentMap
func init() {
dcpAgentMap = &gocbcoreDCPAgentMap{
entries: make(map[string]map[*gocbcore.DCPAgent]*dcpAgentDetails),
}
FetchDCPAgent = dcpAgentMap.fetchAgent
CloseDCPAgent = dcpAgentMap.releaseAgent
}
func NumDCPAgents() uint64 {
if dcpAgentMap != nil {
return atomic.LoadUint64(&dcpAgentMap.numDCPAgents)
}
return 0
}
func updateDCPAgentsDetails(bucketName, bucketUUID, feedName string,
agent *gocbcore.DCPAgent, streamID int16, openStream bool) {
dcpAgentMap.m.Lock()
defer dcpAgentMap.m.Unlock()
entry, exists := dcpAgentMap.entries[bucketName+":"+bucketUUID]
if !exists {
return
}
dcpAgentDetails, _ := entry[agent]
if dcpAgentDetails == nil {
return
}
sID := fmt.Sprintf("%v", streamID)
if openStream {
dcpAgentDetails.NumStreamReqs += 1
if v, ok := dcpAgentDetails.Streams[sID]; !ok {
dcpAgentDetails.Streams[sID] = &streamDetails{
NumVBuckets: 1,
Partition: feedName,
}
} else {
v.NumVBuckets++
}
return
}
// decrement counts appropriately for close stream reqs
if _, exists := dcpAgentDetails.Streams[sID]; exists {
dcpAgentDetails.NumStreamReqs -= 1
dcpAgentDetails.Streams[sID].NumVBuckets -= 1
if dcpAgentDetails.Streams[sID].NumVBuckets == 0 {
delete(dcpAgentDetails.Streams, sID)
}
}
return
}
func DCPAgentsStatsMap() map[string]interface{} {
rv := make(map[string]interface{})
if dcpAgentMap != nil {
rv["total_gocbcore_dcp_agents"] = atomic.LoadUint64(&dcpAgentMap.numDCPAgents)
dcpAgentMap.m.RLock()
for keySpace, agents := range dcpAgentMap.entries {
keySpace := strings.Split(keySpace, ":")
if len(keySpace) == 2 {
agentsMap := make(map[string]interface{})
for _, v := range agents {
agentsMap[v.dcpConnName] = v
}
rv[keySpace[0]] = struct {
NumDCPAgents int `json:"num_dcp_agents"`
DcpAgentDetails map[string]interface{} `json:"dcp_agents_details"`
}{
NumDCPAgents: len(agents),
DcpAgentDetails: agentsMap,
}
}
}
dcpAgentMap.m.RUnlock()
}
return rv
}
// Fetches a gocbcore.DCPAgent instance for the bucket (name:uuid),
// after increasing it's reference count.
// If no instance is available or reference count for existing instances
// is at limit, creates a new instance and stashes it with reference
// count of 1, before returning it.
func (dm *gocbcoreDCPAgentMap) fetchAgent(bucketName, bucketUUID, paramsStr,
servers string, options map[string]string) (*gocbcore.DCPAgent, error) {
var maxFeedsPerDCPAgent int
params := NewDCPFeedParams()
err := UnmarshalJSON([]byte(paramsStr), params)
if err != nil {
return nil, fmt.Errorf("feed_dcp_gocbcore: fetchAgent, params err: %v", err)
}
if v, exists := options["maxFeedsPerDCPAgent"]; exists {
if i, err := strconv.Atoi(v); err == nil {
maxFeedsPerDCPAgent = i
}
}
if maxFeedsPerDCPAgent <= 0 {
maxFeedsPerDCPAgent = defaultMaxFeedsPerDCPAgent
}
dm.m.Lock()
defer dm.m.Unlock()
key := bucketName + ":" + bucketUUID
if _, exists := dm.entries[key]; exists {
for agent, agentInfo := range dm.entries[key] {
if agentInfo.Refs < maxFeedsPerDCPAgent &&
agentInfo.xattrs == params.IncludeXAttrs {
dm.entries[key][agent].Refs++
log.Printf("feed_dcp_gocbcore: fetchAgent, re-using existing DCP agent"+
" (key: %v, agent: %s, ref count: %v, number of agents for key: %v)",
key, dm.entries[key][agent].dcpConnName, dm.entries[key][agent].Refs,
len(dm.entries[key]))
return agent, nil
}
}
} else {
dm.entries[key] = map[*gocbcore.DCPAgent]*dcpAgentDetails{}
}
auth, err := gocbAuth(paramsStr, options["authType"])
if err != nil {
return nil, fmt.Errorf("feed_dcp_gocbcore: fetchAgent, gocbAuth,"+
" bucketName: %s, err: %v", bucketName, err)
}
dcpConnName := fmt.Sprintf("%s%s-%x", DCPFeedPrefix, key, rand.Int31())
config := setupDCPAgentConfig(dcpConnName, bucketName, auth,
gocbcore.DcpAgentPriorityMed, options)
svrs := strings.Split(servers, ";")
if len(svrs) == 0 {
return nil, fmt.Errorf("feed_dcp_gocbcore: fetchAgent, no servers provided")
}
connStr, useTLS, caProvider := setupConfigParams(bucketName, bucketUUID, svrs[0], options)
err = config.FromConnStr(connStr)
if err != nil {
return nil, fmt.Errorf("feed_dcp_gocbcore: fetchAgent,"+
" unable to build config from connStr: %s, err: %v", connStr, err)
}
config.SecurityConfig.UseTLS = useTLS
config.SecurityConfig.TLSRootCAProvider = caProvider
flags := memd.DcpOpenFlagProducer
if params.IncludeXAttrs {
flags |= memd.DcpOpenFlagIncludeXattrs
}
if params.NoValue {
flags |= memd.DcpOpenFlagNoValue
}
agent, err := setupGocbcoreDCPAgent(config, dcpConnName, flags)
if err != nil {
return nil, fmt.Errorf("feed_dcp_gocbcore: fetchAgent, setup err: %w", err)
}
dm.entries[key][agent] = &dcpAgentDetails{
dcpConnName: dcpConnName,
Refs: 1,
Streams: make(map[string]*streamDetails),
xattrs: params.IncludeXAttrs,
}
log.Printf("feed_dcp_gocbcore: fetchAgent, set up new DCP agent "+
" (key: %v, agent: %s, number of agents for key: %v)",
key, dcpConnName, len(dm.entries[key]))
atomic.AddUint64(&dm.numDCPAgents, 1)
return agent, nil
}
// Releases reference for the gocbcore.DCPAgent instance key'ed by name:uuid.
// Also, closes and removes the gocbcore DCPAgent if reference count is down
// to zero.
func (dm *gocbcoreDCPAgentMap) releaseAgent(bucketName, bucketUUID string,
agent *gocbcore.DCPAgent) error {
key := bucketName + ":" + bucketUUID
dm.m.Lock()
defer dm.m.Unlock()
if _, exists := dm.entries[key]; !exists {
log.Warnf("feed_dcp_gocbcore: releaseAgent, no entry for key %v", key)
return nil
}
if _, exists := dm.entries[key][agent]; !exists {
log.Warnf("feed_dcp_gocbcore: releaseAgent, DCPAgent doesn't exist"+
" (key: %v)", key)
} else {
dm.entries[key][agent].Refs--
if dm.entries[key][agent].Refs > 0 {
log.Printf("feed_dcp_gocbcore: releaseAgent, ref count decremented for"+
" DCPagent (key: %v, agent: %s, ref count: %v, number of agents"+
" for key: %v)",
key, dm.entries[key][agent].dcpConnName, dm.entries[key][agent].Refs, len(dm.entries[key]))
return nil
}
connName := dm.entries[key][agent].dcpConnName
// ref count of agent down to 0
delete(dm.entries[key], agent)
atomic.AddUint64(&dm.numDCPAgents, ^uint64(0)) // decrement by 1
log.Printf("feed_dcp_gocbcore: releaseAgent, closing DCPAgent"+
" (key: %v, agent: %s, number of agents for key: %v)",
key, connName, len(dm.entries[key]))
// close the agent only once
go agent.Close()
}
if len(dm.entries[key]) == 0 {
// no agents listed for bucket
delete(dm.entries, key)
}
return nil
}
// Gocbcore supports ReconfigureSecurity _only_ when the ns_server scheme is used ;
// where the seed poller is in use. This method is ONLY called in cbauth node.
// See: https://github.com/couchbase/gocbcore/blob/v10.2.10/agent.go#L591-L615
func (dm *gocbcoreDCPAgentMap) reconfigureSecurityForAgents(
useTLS bool, caProvider certProvider) {
reconfigureSecurityOptions := gocbcore.ReconfigureSecurityOptions{
UseTLS: useTLS,
TLSRootCAProvider: caProvider,
}
dm.m.Lock()
for _, agents := range dm.entries {
for agent := range agents {
go agent.ReconfigureSecurity(reconfigureSecurityOptions)
}
}
dm.m.Unlock()
}
// ----------------------------------------------------------------
func waitForResponse(signal <-chan error, closeCh <-chan struct{},
op gocbcore.PendingOp, timeout time.Duration) error {
timeoutTmr := gocbcore.AcquireTimer(timeout)
select {
case err := <-signal:
gocbcore.ReleaseTimer(timeoutTmr, false)
return err
case <-closeCh:
gocbcore.ReleaseTimer(timeoutTmr, false)
return gocbcore.ErrDCPStreamDisconnected
case <-timeoutTmr.C:
gocbcore.ReleaseTimer(timeoutTmr, true)
log.Warnf("feed_dcp_gocbcore: Request has timed out, canceling op")
if op != nil {
op.Cancel()
// wait for confirmation after canceling the PendingOp
<-signal
}
return gocbcore.ErrTimeout
}
}
// ----------------------------------------------------------------
func init() {
RegisterFeedType(SOURCE_GOCBCORE, &FeedType{
Start: StartGocbcoreDCPFeed,
Partitions: CBPartitions,
PartitionSeqs: CBPartitionSeqs,
Stats: CBStats,
PartitionLookUp: CBVBucketLookUp,
SourceUUIDLookUp: CBSourceUUIDLookUp,
Public: true,
Description: "general/" + SOURCE_GOCBCORE +
" - a Couchbase Server bucket will be the data source",
StartSample: NewDCPFeedParams(),
})
}
func StartGocbcoreDCPFeed(mgr *Manager, feedName, indexName, indexUUID,
sourceType, sourceName, bucketUUID, params string,
dests map[string]Dest) error {
if mgr == nil {
return fmt.Errorf("feed_dcp_gocbcore: StartGocbcoreDCPFeed," +
" mgr is nil")
}
servers, _, bucketName :=
CouchbaseParseSourceName(mgr.server, "default", sourceName)
feed, err := newGocbcoreDCPFeed(feedName, indexName, indexUUID,
servers, bucketName, bucketUUID, params, BasicPartitionFunc,
dests, mgr.tagsMap != nil && !mgr.tagsMap["feed"], mgr)
if err != nil {
if errors.Is(err, errAgentSetupFailed) {
// In the event of a connection error (agent setup error,
// likely because KV wasn't ready), notify the manager
// (asynchronously) that the feed setup has failed, so
// the janitor can reattempt this operation.
//
// This needs to be asynchronous, as "kick"ing the Janitor
// from within the JanitorLoop (this API is invoked from
// within JanitorOnce) is prohibited - deadlock!
go mgr.Kick(fmt.Sprintf("gocbcore-feed-start, feed: %v", feedName))
} else if errors.Is(err, errBucketUUIDMismatched) {
// In the event the bucket UUID changed between index
// creation and feed setup - and if the request was for
// the older bucket UUID, then due to the feed error drop
// the index (asynchronously).
log.Warnf("feed_dcp_gocbcore: DeleteIndex, indexName: %s,"+
" indexUUID: %s, err: %v", indexName, indexUUID, err)
go mgr.DeleteIndexEx(indexName, indexUUID)
}
return fmt.Errorf("feed_dcp_gocbcore: StartGocbcoreDCPFeed,"+
" could not prepare DCP feed, name: %s, server: %s,"+
" bucketName: %s, indexName: %s, err: %v",
feedName, mgr.server, bucketName, indexName, err)
}
err = mgr.registerFeed(feed)
if err != nil {
// A feed for this pindex already exists, no need to notify
// manager on this closure
return feed.onError(false, err)
}
// register the bucket with the pools tracker.
// optionally create a routine if needed.
trackBucket(mgr, bucketName)
err = feed.Start()
if err != nil {
untrackBucket(mgr, bucketName)
return feed.onError(true,
fmt.Errorf("feed_dcp_gocbcore: StartGocbcoreDCPFeed,"+
" could not start feed: %s, server: %s, err: %v",
feed.Name(), mgr.server, err))
}
return nil
}
type vbucketState struct {
snapStart uint64
snapEnd uint64
failoverLog [][]uint64
snapSaved bool // True when snapStart/snapEnd have been persisted
}
// A GocbcoreDCPFeed implements both Feed and gocb.StreamObserver
// interfaces, and forwards any incoming gocb.StreamObserver
// callbacks to the relevant, hooked-up Dest instances.
//
// servers: single URL or multiple URLs delimited by ';'
type GocbcoreDCPFeed struct {
name string
indexName string
indexUUID string
servers string
bucketName string
bucketUUID string
params *DCPFeedParams
pf DestPartitionFunc
dests map[string]Dest
disable bool
stopAfter map[string]UUIDSeq
mgr *Manager
agent *gocbcore.DCPAgent
scope string
collections []string
manifestUID uint64
scopeID uint32
collectionIDs []uint32
streamOptions gocbcore.OpenStreamOptions
vbucketIds []uint16
lastReceivedSeqno []uint64
currVBs []*vbucketState
dcpStats *gocbcoreDCPFeedStats
m sync.Mutex
remaining sync.WaitGroup
closed bool
shutdownInitiated bool
active map[uint16]bool
stats *DestStats
stopAfterReached map[string]bool // May be nil.
closeCh chan struct{}
}
type gocbcoreDCPFeedStats struct {
// TODO: Add more stats
TotDCPStreamReqs uint64
TotDCPStreamEnds uint64
TotDCPRollbacks uint64
TotDCPSnapshotMarkers uint64
TotDCPMutations uint64
TotDCPDeletions uint64
TotDCPSeqNoAdvanceds uint64
TotDCPCreateCollections uint64
}
// atomicCopyTo copies metrics from s to r (or, from source to
// result), and also applies an optional fn function. The fn is
// invoked with metrics from s and r, and can be used to compute
// additions, subtractions, negatoions, etc. When fn is nil,
// atomicCopyTo behaves as a straight copier.
func (s *gocbcoreDCPFeedStats) atomicCopyTo(r *gocbcoreDCPFeedStats,
fn func(sv uint64, rv uint64) uint64) {
// Using reflection rather than a whole slew of explicit
// invocations of atomic.LoadUint64()/StoreUint64()'s.
if fn == nil {
fn = func(sv uint64, rv uint64) uint64 { return sv }
}
rve := reflect.ValueOf(r).Elem()
sve := reflect.ValueOf(s).Elem()
svet := sve.Type()
for i := 0; i < svet.NumField(); i++ {
rvef := rve.Field(i)
svef := sve.Field(i)
if rvef.CanAddr() && svef.CanAddr() {
rvefp := rvef.Addr().Interface()
svefp := svef.Addr().Interface()
rv := atomic.LoadUint64(rvefp.(*uint64))
sv := atomic.LoadUint64(svefp.(*uint64))
atomic.StoreUint64(rvefp.(*uint64), fn(sv, rv))
}
}
}
func newGocbcoreDCPFeed(name, indexName, indexUUID, servers,
bucketName, bucketUUID, paramsStr string,
pf DestPartitionFunc, dests map[string]Dest,
disable bool, mgr *Manager) (*GocbcoreDCPFeed, error) {
var stopAfter map[string]UUIDSeq
params := NewDCPFeedParams()
if paramsStr != "" {
err := UnmarshalJSON([]byte(paramsStr), params)
if err != nil {
return nil, fmt.Errorf("newGocbcoreDCPFeed params, err: %v", err)
}
stopAfterSourceParams := StopAfterSourceParams{}
err = UnmarshalJSON([]byte(paramsStr), &stopAfterSourceParams)
if err != nil {
return nil, fmt.Errorf("newGocbcoreDCPFeed stopAfterSourceParams,"+
" err: %v", err)
}
if stopAfterSourceParams.StopAfter == "markReached" {
stopAfter = stopAfterSourceParams.MarkPartitionSeqs
}
}
// TODO: Using default settings for flow control; includes parameters:
// buffer size, buffer ack threshold, noop time interval;
// Maybe make these configurable?
vbucketIds, err := ParsePartitionsToVBucketIds(dests)
if err != nil {
return nil, fmt.Errorf("newGocbcoreDCPFeed, err: %v", err)
}
if len(vbucketIds) == 0 {
return nil, fmt.Errorf("newGocbcoreDCPFeed:" +
" no vbucketids for this feed")
}
feed := &GocbcoreDCPFeed{
name: name,
indexName: indexName,
indexUUID: indexUUID,
servers: servers,
bucketName: bucketName,
bucketUUID: bucketUUID,
params: params,
pf: pf,
dests: dests,
disable: disable,
stopAfter: stopAfter,
mgr: mgr,
vbucketIds: vbucketIds,
dcpStats: &gocbcoreDCPFeedStats{},
stats: NewDestStats(),
active: make(map[uint16]bool),
closeCh: make(chan struct{}),
}
for partition, dest := range dests {
if destColl, ok := dest.(DestCollection); ok {
err := destColl.PrepareFeedParams(partition, params)
if err != nil {
return nil, feed.onSetupError(err)
}
}
}
if len(params.Scope) == 0 && len(params.Collections) == 0 {
feed.scope = "_default"
feed.collections = []string{"_default"}
} else {
feed.scope = params.Scope
feed.collections = params.Collections
}
// sort the vbucketIds list to determine the largest vbucketId
sort.Slice(vbucketIds, func(i, j int) bool { return vbucketIds[i] < vbucketIds[j] })
largestVBId := vbucketIds[len(vbucketIds)-1]
feed.lastReceivedSeqno = make([]uint64, largestVBId+1)
feed.currVBs = make([]*vbucketState, largestVBId+1)
for _, vbid := range vbucketIds {
feed.currVBs[vbid] = &vbucketState{}
}
if err = feed.setupStreamOptions(paramsStr, mgr.Options()); err != nil {
return nil, feed.onSetupError(fmt.Errorf("newGocbcoreDCPFeed:"+
" error in setting up feed's stream options, err: %w", err))
}
feed.agent, err = FetchDCPAgent(feed.bucketName, feed.bucketUUID,
paramsStr, servers, mgr.Options())
if err != nil {
return nil, feed.onSetupError(
fmt.Errorf("newGocbcoreDCPFeed DCPAgent, err: %w", err))
}
log.Printf("feed_dcp_gocbcore: newGocbcoreDCPFeed, name: %s, indexName: %s,"+
" server: %v, bucketName: %s, bucketUUID: %s",
name, indexName, feed.servers, feed.bucketName, feed.bucketUUID)
return feed, nil
}
func (f *GocbcoreDCPFeed) setupStreamOptions(paramsStr string,
options map[string]string) error {
svrs := strings.Split(f.servers, ";")
if len(svrs) == 0 {
return fmt.Errorf("no servers provided")
}
agent, _, err := statsAgentsMap.obtainAgents(f.bucketName, f.bucketUUID,
paramsStr, svrs[0], options)
if err != nil {
return fmt.Errorf("%w, err: %v", errAgentSetupFailed, err)
}
// the sourceUUID setting in the index definition is optional,
// so make sure the feed's bucketUUID is set in case it wasn't
// provided, and validated otherwise
snapshot, err := agent.ConfigSnapshot()
if err != nil {
return err
}
bucketUUID := snapshot.BucketUUID()
if len(f.bucketUUID) == 0 {
f.bucketUUID = bucketUUID
} else if f.bucketUUID != bucketUUID {
return fmt.Errorf("%w, bucket: [%s, %s], request: %s",
errBucketUUIDMismatched, f.bucketName, bucketUUID, f.bucketUUID)
}
f.streamOptions = gocbcore.OpenStreamOptions{}
if !agent.HasCollectionsSupport() {
// No support for collections
return nil
}
signal := make(chan error, 1)
var manifest gocbcore.Manifest
op, err := agent.GetCollectionManifest(
gocbcore.GetCollectionManifestOptions{},
func(res *gocbcore.GetCollectionManifestResult, er error) {
if er == nil && res == nil {
er = fmt.Errorf("manifest not retrieved")
}
if er == nil {
er = manifest.UnmarshalJSON(res.Manifest)
}
signal <- er
})
if err != nil {
return fmt.Errorf("GetCollectionManifest, err: %v", err)
}
err = waitForResponse(signal, f.closeCh, op, GocbcoreStatsTimeout)
if err != nil {
return fmt.Errorf("failed to get manifest, err: %v", err)
}
f.manifestUID = manifest.UID
var scopeIDFound bool
for _, manifestScope := range manifest.Scopes {
if manifestScope.Name == f.scope {
f.scopeID = manifestScope.UID
scopeIDFound = true
break
}
}
if !scopeIDFound {
return fmt.Errorf("scope not found: %v", f.scope)
}
f.streamOptions.StreamOptions = &gocbcore.OpenStreamStreamOptions{
StreamID: newStreamID(),
}
if len(f.collections) == 0 {
// if no collections were specified, set up stream requests for
// the entire scope.
f.streamOptions.FilterOptions = &gocbcore.OpenStreamFilterOptions{
ScopeID: f.scopeID,
}
} else {
for _, coll := range f.collections {
op, err = agent.GetCollectionID(f.scope, coll,
gocbcore.GetCollectionIDOptions{},
func(res *gocbcore.GetCollectionIDResult, er error) {
if er == nil && res == nil {
er = fmt.Errorf("collection ID not retrieved")
}
if er == nil {
if res.ManifestID != f.manifestUID {
er = fmt.Errorf("manifestID mismatch, %v != %v",
res.ManifestID, f.manifestUID)
} else {
f.collectionIDs =
append(f.collectionIDs, res.CollectionID)
}
}
signal <- er
})
if err != nil {
return fmt.Errorf("GetCollectionID, collection: %v, err: %v",
coll, err)
}
err = waitForResponse(signal, f.closeCh, op, GocbcoreStatsTimeout)
if err != nil {
return fmt.Errorf("failed to get collection ID, err : %v", err)
}
}
f.streamOptions.FilterOptions = &gocbcore.OpenStreamFilterOptions{
CollectionIDs: f.collectionIDs,
}
}
return nil
}
// ----------------------------------------------------------------
func (f *GocbcoreDCPFeed) Name() string {
return f.name
}
func (f *GocbcoreDCPFeed) IndexName() string {
return f.indexName
}
func (f *GocbcoreDCPFeed) Start() error {
if f.disable {
log.Printf("feed_dcp_gocbcore: Start, DISABLED, name: %s", f.Name())
return nil
}
log.Printf("feed_dcp_gocbcore: Start, name: %s, num streams: %d,"+
" manifestUID: %v, streamOptions: {FilterOptions: %+v, StreamOptions: %+v},"+
" vbuckets: %v", f.Name(), len(f.vbucketIds), f.manifestUID,
f.streamOptions.FilterOptions, f.streamOptions.StreamOptions, f.vbucketIds)
for _, vbid := range f.vbucketIds {
err := f.initiateStream(uint16(vbid))
if err != nil {
return fmt.Errorf("Start, name: %s, vbid: %v, err: %v",
f.Name(), vbid, err)
}
}
return nil
}
func (f *GocbcoreDCPFeed) Close() error {
if f.close() {
log.Printf("feed_dcp_gocbcore: Close, name: %s", f.Name())
}
return nil
}
func (f *GocbcoreDCPFeed) NotifyMgrOnClose() {
if f.close() {
log.Printf("feed_dcp_gocbcore: Close, name: %s, notify manager",
f.Name())
go f.mgr.Kick(fmt.Sprintf("gocbcore-feed, feed: %v", f.Name()))
}
}
func (f *GocbcoreDCPFeed) close() bool {
f.m.Lock()
if f.closed {
f.m.Unlock()
return false
}
f.closed = true
f.closeAllStreamsLOCKED()
CloseDCPAgent(f.bucketName, f.bucketUUID, f.agent)
f.m.Unlock()
f.mgr.unregisterFeed(f.Name())
close(f.closeCh)
f.wait()
untrackBucket(f.mgr, f.bucketName)
return true
}
func (f *GocbcoreDCPFeed) getCloseStreamOptions() gocbcore.CloseStreamOptions {
rv := gocbcore.CloseStreamOptions{}
if f.agent.HasCollectionsSupport() {
rv.StreamOptions = &gocbcore.CloseStreamStreamOptions{}
if f.streamOptions.StreamOptions != nil {
rv.StreamOptions.StreamID = f.streamOptions.StreamOptions.StreamID
}
}
return rv
}
// This will call close on all streams on feed closure. Note that
// streams would then see an END message with the reason: "closed by
// consumer".
func (f *GocbcoreDCPFeed) closeAllStreamsLOCKED() {
closeStreamOptions := f.getCloseStreamOptions()
log.Printf("feed_dcp_gocbcore: name: %s, streamOptions: %+v,"+
" close any open streams over vbuckets: %v",
f.Name(), closeStreamOptions.StreamOptions, f.vbucketIds)
for _, vbId := range f.vbucketIds {
if f.active[vbId] {
f.agent.CloseStream(vbId, closeStreamOptions, func(err error) {})
var sid int16
if f.streamOptions.StreamOptions != nil {
sid = int16(f.streamOptions.StreamOptions.StreamID)
}
updateDCPAgentsDetails(f.bucketName, f.bucketUUID, f.name, f.agent, sid, false)
f.active[vbId] = false
f.remaining.Done()
}
}
}
func (f *GocbcoreDCPFeed) Dests() map[string]Dest {
return f.dests
}
var prefixAgentDCPStats = []byte(`{"agentDCPStats":`)
func (f *GocbcoreDCPFeed) Stats(w io.Writer) error {
dcpStats := &gocbcoreDCPFeedStats{}
f.dcpStats.atomicCopyTo(dcpStats, nil)
_, err := w.Write(prefixAgentDCPStats)
if err != nil {
return err
}
err = json.NewEncoder(w).Encode(dcpStats)
if err != nil {
return err
}
_, err = w.Write(prefixDestStats)
if err != nil {
return err
}
f.stats.WriteJSON(w)
_, err = w.Write(JsonCloseBrace)
return err
}
// ----------------------------------------------------------------
func (f *GocbcoreDCPFeed) lastVbUUIDSeqFromFailOverLog(vbId uint16) (
uint64, uint64, error) {
vbMetaData, lastSeq, err := f.getMetaData(vbId)
if err != nil {
return 0, 0, err
}
var vbuuid uint64
if len(vbMetaData.FailOverLog) > 0 {
vbuuid = vbMetaData.FailOverLog[0][0]
}
return vbuuid, lastSeq, nil
}
func (f *GocbcoreDCPFeed) initiateStream(vbId uint16) error {
vbuuid, lastSeq, err := f.lastVbUUIDSeqFromFailOverLog(vbId)
if err != nil {
return err
}
go f.initiateStreamEx(vbId, true, gocbcore.VbUUID(vbuuid),
gocbcore.SeqNo(lastSeq), maxEndSeqno)
return nil
}
func (f *GocbcoreDCPFeed) initiateStreamEx(vbId uint16, isNewStream bool,
vbuuid gocbcore.VbUUID, seqStart, seqEnd gocbcore.SeqNo) {
f.m.Lock()
if f.closed {
f.m.Unlock()
return
}
if isNewStream {
if !f.active[vbId] {
f.remaining.Add(1)
f.active[vbId] = true
}
}
f.m.Unlock()
dcpStreamAddFlags := memd.DcpStreamAddFlagActiveOnly |
memd.DcpStreamAddFlagStrictVBUUID
snapStart := seqStart
signal := make(chan error, 1)
log.Debugf("feed_dcp_gocbcore: [%s] Initiating DCP stream request for vb: %v,"+
" vbUUID: %v, seqStart: %v, seqEnd: %v, manifestUID: %v,"+
" streamOptions: {%+v, %+v}", f.Name(), vbId, vbuuid, seqStart, seqEnd,
f.manifestUID, f.streamOptions.FilterOptions, f.streamOptions.StreamOptions)
op, err := f.agent.OpenStream(vbId, dcpStreamAddFlags,
vbuuid, seqStart, seqEnd, snapStart, snapStart, f, f.streamOptions,
func(entries []gocbcore.FailoverEntry, er error) {
if errors.Is(er, gocbcore.ErrShutdown) ||
errors.Is(er, gocbcore.ErrSocketClosed) ||
errors.Is(er, gocbcore.ErrScopeNotFound) ||
errors.Is(er, gocbcore.ErrCollectionNotFound) {
f.initiateShutdown(fmt.Errorf("feed_dcp_gocbcore: [%s] OpenStream,"+
" vb: %v, streamOptions: %+v, err: %v", f.Name(),
vbId, f.streamOptions.StreamOptions, er))
er = nil
} else if errors.Is(er, gocbcore.ErrMemdRollback) {
log.Printf("feed_dcp_gocbcore: [%s] OpenStream received rollback,"+
" for vb: %v, streamOptions: %+v, seqno requested: %v", f.Name(),
vbId, f.streamOptions.StreamOptions, seqStart)
f.complete(vbId)
var dcpRollbackErr gocbcore.DCPRollbackError
if errors.As(er, &dcpRollbackErr) {
go f.rollback(vbId, uint64(dcpRollbackErr.SeqNo))
} else {
go f.rollback(vbId, 0)
}
// rollback will handle this feed closure and setting up of a new feed
er = nil
} else if errors.Is(er, gocbcore.ErrRequestCanceled) {
// request was canceled by FTS, catch error and re-initiate stream request
log.Warnf("feed_dcp_gocbcore: [%s] OpenStream for vb: %v, streamOptions: %+v"+
" was canceled, (timeout) will re-initiate the stream request",
f.Name(), vbId, f.streamOptions.StreamOptions)
} else if errors.Is(er, gocbcore.ErrForcedReconnect) {
// request was canceled by GOCBCORE, catch error and re-initate stream request
log.Warnf("feed_dcp_gocbcore: [%s] OpenStream for vb: %v, streamOptions: %+v"+
"failed with err: %v, reconnecting ...", f.Name(),
vbId, f.streamOptions.StreamOptions, er)
} else if er != nil {
// unidentified error
log.Errorf("feed_dcp_gocbcore: [%s] OpenStream received error for vb: %v, "+
" streamOptions: %+v, err: %v", f.Name(), vbId,
f.streamOptions.StreamOptions, er)