-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathbucket_gocb.go
2034 lines (1615 loc) · 58.3 KB
/
bucket_gocb.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 2013-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 base
import (
"bytes"
"errors"
"expvar"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/couchbase/gocbcore/v10/memd"
sgbucket "github.com/couchbase/sg-bucket"
pkgerrors "github.com/pkg/errors"
"gopkg.in/couchbase/gocb.v1"
"gopkg.in/couchbase/gocbcore.v7"
)
const (
MaxConcurrentSingleOps = 1000 // Max 1000 concurrent single bucket ops
MaxConcurrentBulkOps = 35 // Max 35 concurrent bulk ops
MaxConcurrentQueryOps = 1000 // Max concurrent query ops
MaxBulkBatchSize = 100 // Maximum number of ops per bulk call
// Causes the write op to block until the change has been replicated to numNodesReplicateTo many nodes.
// In our case, we only want to block until it's durable on the node we're writing to, so this is set to 0.
numNodesReplicateTo = uint(0)
// Causes the write op to block until the change has been persisted (made durable -- written to disk) on
// numNodesPersistTo. In our case, we only want to block until it's durable on the node we're writing to,
// so this is set to 1
numNodesPersistTo = uint(1)
// CRC-32 checksum represents the body hash of "Deleted" document.
DeleteCrc32c = "0x00000000"
// Can be removed and usages swapped out once this is present in gocb
SubdocDocFlagCreateAsDeleted = gocb.SubdocDocFlag(gocbcore.SubdocDocFlag(0x08))
)
var recoverableGocbV1Errors = map[string]struct{}{
gocbcore.ErrOverload.Error(): {},
gocbcore.ErrBusy.Error(): {},
gocbcore.ErrTmpFail.Error(): {},
}
// Implementation of sgbucket.Bucket that talks to a Couchbase server and uses gocb v1
type CouchbaseBucketGoCB struct {
*gocb.Bucket // the underlying gocb bucket
Spec BucketSpec // keep a copy of the BucketSpec for DCP usage
singleOps chan struct{} // Manages max concurrent single ops (per kv node)
bulkOps chan struct{} // Manages max concurrent bulk ops (per kv node)
queryOps chan struct{} // Manages max concurrent view / query ops (per kv node)
clusterCompatMajorVersion, clusterCompatMinorVersion uint64 // E.g: 6 and 0 for 6.0.3
}
var _ sgbucket.KVStore = &CouchbaseBucketGoCB{}
var _ CouchbaseStore = &CouchbaseBucketGoCB{}
// Creates a Bucket that talks to a real live Couchbase server.
func GetCouchbaseBucketGoCB(spec BucketSpec) (bucket *CouchbaseBucketGoCB, err error) {
connString, err := spec.GetGoCBConnString()
if err != nil {
Warnf("Unable to parse server value: %s error: %v", SD(spec.Server), err)
return nil, err
}
cluster, err := gocb.Connect(connString)
if err != nil {
Infof(KeyAuth, "gocb connect returned error: %v", err)
return nil, err
}
bucketPassword := ""
// Check for client cert (x.509) authentication
if spec.Certpath != "" {
Infof(KeyAuth, "Attempting cert authentication against bucket %s on %s", MD(spec.BucketName), MD(spec.Server))
certAuthErr := cluster.Authenticate(gocb.CertAuthenticator{})
if certAuthErr != nil {
Infof(KeyAuth, "Error Attempting certificate authentication %s", certAuthErr)
return nil, pkgerrors.WithStack(certAuthErr)
}
} else if spec.Auth != nil {
Infof(KeyAuth, "Attempting credential authentication against bucket %s on %s", MD(spec.BucketName), MD(spec.Server))
user, pass, _ := spec.Auth.GetCredentials()
authErr := cluster.Authenticate(gocb.PasswordAuthenticator{
Username: user,
Password: pass,
})
// If RBAC authentication fails, revert to non-RBAC authentication by including the password to OpenBucket
if authErr != nil {
Warnf("RBAC authentication against bucket %s as user %s failed - will re-attempt w/ bucketname, password", MD(spec.BucketName), UD(user))
bucketPassword = pass
}
}
return GetCouchbaseBucketGoCBFromAuthenticatedCluster(cluster, spec, bucketPassword)
}
func GetCouchbaseBucketGoCBFromAuthenticatedCluster(cluster *gocb.Cluster, spec BucketSpec, bucketPassword string) (bucket *CouchbaseBucketGoCB, err error) {
goCBBucket, err := cluster.OpenBucket(spec.BucketName, bucketPassword)
if err != nil {
Infof(KeyAll, "Error opening bucket %s: %v", spec.BucketName, err)
if pkgerrors.Cause(err) == gocb.ErrAuthError {
return nil, ErrAuthError
}
return nil, pkgerrors.WithStack(err)
}
Infof(KeyAll, "Successfully opened bucket %s", spec.BucketName)
// Query node meta to find cluster compat version
user, pass, _ := spec.Auth.GetCredentials()
nodesMetadata, err := cluster.Manager(user, pass).Internal().GetNodesMetadata()
if err != nil || len(nodesMetadata) == 0 {
_ = goCBBucket.Close()
return nil, fmt.Errorf("Unable to get server cluster compatibility for %d nodes: %w", len(nodesMetadata), err)
}
// Safe to get first node as there will always be at least one node in the list and cluster compat is uniform across all nodes.
clusterCompatMajor, clusterCompatMinor := decodeClusterVersion(nodesMetadata[0].ClusterCompatibility)
// Set the GoCB opTimeout which controls how long blocking GoCB ops remain blocked before
// returning an "operation timed out" error. Defaults to 2.5 seconds. (SG #3508)
if spec.BucketOpTimeout != nil {
goCBBucket.SetOperationTimeout(*spec.BucketOpTimeout)
// Update the bulk op timeout to preserve the 1:4 ratio between op timeouts and bulk op timeouts.
goCBBucket.SetBulkOperationTimeout(*spec.BucketOpTimeout * 4)
}
if spec.CouchbaseDriver == GoCBCustomSGTranscoder {
// Set transcoder to SGTranscoder to avoid cases where it tries to write docs as []byte without setting
// the proper doctype flag and then later read them as JSON, which fails because it gets back a []byte
// initially this was using SGTranscoder for all GoCB buckets, but due to
// https://github.com/couchbase/sync_gateway/pull/2416#issuecomment-288882896
// it's only being set for data buckets
goCBBucket.SetTranscoder(SGTranscoder{})
}
spec.MaxNumRetries = 10
spec.InitialRetrySleepTimeMS = 5
// Identify number of nodes to use as a multiplier for MaxConcurrentOps, since gocb maintains one pipeline per data node.
// TODO: We don't currently have a process to monitor cluster changes behind a gocb bucket. When that's available, should
// consider the ability to modify this as the cluster changes.
nodeCount := 1
mgmtEps := goCBBucket.IoRouter().MgmtEps()
if mgmtEps != nil && len(mgmtEps) > 0 {
nodeCount = len(mgmtEps)
}
// Scale gocb pipeline size with KV pool size
numPools := 1
if spec.KvPoolSize > 0 {
numPools = spec.KvPoolSize
}
// Define channels to limit the number of concurrent single and bulk operations,
// to avoid gocb queue overflow issues
singleOpsQueue := make(chan struct{}, MaxConcurrentSingleOps*nodeCount*numPools)
bucketOpsQueue := make(chan struct{}, MaxConcurrentBulkOps*nodeCount*numPools)
maxConcurrentQueryOps := MaxConcurrentQueryOps
if spec.MaxConcurrentQueryOps != nil {
maxConcurrentQueryOps = *spec.MaxConcurrentQueryOps
}
queryNodeCount := len(goCBBucket.IoRouter().N1qlEps())
if queryNodeCount == 0 {
queryNodeCount = 1
}
if maxConcurrentQueryOps > DefaultHttpMaxIdleConnsPerHost*queryNodeCount {
maxConcurrentQueryOps = DefaultHttpMaxIdleConnsPerHost * queryNodeCount
Infof(KeyAll, "Setting max_concurrent_query_ops to %d based on query node count (%d)", maxConcurrentQueryOps, queryNodeCount)
}
viewOpsQueue := make(chan struct{}, maxConcurrentQueryOps)
bucket = &CouchbaseBucketGoCB{
Bucket: goCBBucket,
Spec: spec,
singleOps: singleOpsQueue,
bulkOps: bucketOpsQueue,
queryOps: viewOpsQueue,
clusterCompatMajorVersion: uint64(clusterCompatMajor),
clusterCompatMinorVersion: uint64(clusterCompatMinor),
}
bucket.Bucket.SetViewTimeout(bucket.Spec.GetViewQueryTimeout())
bucket.Bucket.SetN1qlTimeout(bucket.Spec.GetViewQueryTimeout())
Infof(KeyAll, "Set query timeouts for bucket %s to cluster:%v, bucket:%v", spec.BucketName, cluster.N1qlTimeout(), bucket.N1qlTimeout())
return bucket, err
}
func (bucket *CouchbaseBucketGoCB) GetBucketCredentials() (username, password string) {
if bucket.Spec.Auth != nil {
username, password, _ = bucket.Spec.Auth.GetCredentials()
}
return username, password
}
// Gets the metadata purge interval for the bucket. First checks for a bucket-specific value. If not
// found, retrieves the cluster-wide value.
func (bucket *CouchbaseBucketGoCB) MetadataPurgeInterval() (time.Duration, error) {
return getMetadataPurgeInterval(bucket)
}
// Get the Server UUID of the bucket, this is also known as the Cluster UUID
func (bucket *CouchbaseBucketGoCB) ServerUUID() (uuid string, err error) {
return getServerUUID(bucket)
}
// Gets the bucket max TTL, or 0 if no TTL was set. Sync gateway should fail to bring the DB online if this is non-zero,
// since it's not meant to operate against buckets that auto-delete data.
func (bucket *CouchbaseBucketGoCB) MaxTTL() (int, error) {
return getMaxTTL(bucket)
}
// mgmtRequest is a re-implementation of gocb's mgmtRequest
// TODO: Request gocb to either:
// - Make a public version of mgmtRequest for us to use
// - Or add all of the neccesary APIs we need to use
func (bucket *CouchbaseBucketGoCB) mgmtRequest(method, uri, contentType string, body io.Reader) (*http.Response, error) {
if contentType == "" && body != nil {
panic("Content-type must be specified for non-null body.")
}
mgmtEp, err := GoCBBucketMgmtEndpoint(bucket)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, mgmtEp+uri, body)
if err != nil {
return nil, err
}
if contentType != "" {
req.Header.Add("Content-Type", contentType)
}
username, password := bucket.GetBucketCredentials()
if username != "" || password != "" {
req.SetBasicAuth(username, password)
}
return bucket.IoRouter().HttpClient().Do(req)
}
func (bucket *CouchbaseBucketGoCB) GetName() string {
return bucket.Spec.BucketName
}
func (bucket *CouchbaseBucketGoCB) GetRaw(k string) (rv []byte, cas uint64, err error) {
var returnVal []byte
cas, err = bucket.Get(k, &returnVal)
if returnVal == nil {
return nil, cas, err
}
return returnVal, cas, err
}
func (bucket *CouchbaseBucketGoCB) Get(k string, rv interface{}) (cas uint64, err error) {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
worker := func() (shouldRetry bool, err error, value uint64) {
casGoCB, err := bucket.Bucket.Get(k, rv)
shouldRetry = bucket.isRecoverableReadError(err)
return shouldRetry, err, uint64(casGoCB)
}
// Kick off retry loop
err, cas = RetryLoopCas("Get", worker, bucket.Spec.RetrySleeper())
if err != nil {
err = pkgerrors.Wrapf(err, "Error during Get %s", UD(k).Redact())
}
return cas, err
}
// Retry up to the retry limit, then return. Does not retry items if they had CAS failures,
// and it's up to the caller to handle those.
func (bucket *CouchbaseBucketGoCB) SetBulk(entries []*sgbucket.BulkSetEntry) (err error) {
// Create the RetryWorker for BulkSet op
worker := bucket.newSetBulkRetryWorker(entries)
// Kick off retry loop
err, _ = RetryLoop("SetBulk", worker, bucket.Spec.RetrySleeper())
if err != nil {
return pkgerrors.Wrapf(err, "Error performing SetBulk with %v entries", len(entries))
}
return nil
}
func (bucket *CouchbaseBucketGoCB) newSetBulkRetryWorker(entries []*sgbucket.BulkSetEntry) RetryWorker {
worker := func() (shouldRetry bool, err error, value interface{}) {
retryEntries := []*sgbucket.BulkSetEntry{}
// break up into batches
entryBatches := createBatchesEntries(MaxBulkBatchSize, entries)
for _, entryBatch := range entryBatches {
err, retryEntriesForBatch := bucket.processBulkSetEntriesBatch(
entryBatch,
)
retryEntries = append(retryEntries, retryEntriesForBatch...)
if err != nil {
return false, err, nil
}
}
// if there are no keys to retry, then we're done.
if len(retryEntries) == 0 {
return false, nil, nil
}
// otherwise, retry the entries that need to be retried
entries = retryEntries
// return true to signal that this function needs to be retried
return true, nil, nil
}
return worker
}
func (bucket *CouchbaseBucketGoCB) processBulkSetEntriesBatch(entries []*sgbucket.BulkSetEntry) (error, []*sgbucket.BulkSetEntry) {
retryEntries := []*sgbucket.BulkSetEntry{}
var items []gocb.BulkOp
for _, entry := range entries {
switch entry.Cas {
case 0:
// if no CAS val, treat it as an insert (similar to WriteCas())
item := &gocb.InsertOp{
Key: entry.Key,
Value: entry.Value,
}
items = append(items, item)
default:
// otherwise, treat it as a replace
item := &gocb.ReplaceOp{
Key: entry.Key,
Value: entry.Value,
Cas: gocb.Cas(entry.Cas),
}
items = append(items, item)
}
}
// Do the underlying bulk operation
if err := bucket.Do(items); err != nil {
return err, retryEntries
}
for index, item := range items {
entry := entries[index]
switch item := item.(type) {
case *gocb.InsertOp:
entry.Cas = uint64(item.Cas)
entry.Error = item.Err
if bucket.isRecoverableWriteError(item.Err) {
retryEntries = append(retryEntries, entry)
}
case *gocb.ReplaceOp:
entry.Cas = uint64(item.Cas)
entry.Error = item.Err
if bucket.isRecoverableWriteError(item.Err) {
retryEntries = append(retryEntries, entry)
}
}
}
return nil, retryEntries
}
// Retrieve keys in bulk for increased efficiency. If any keys are not found, they
// will not be returned, and so the size of the map may be less than the size of the
// keys slice, and no error will be returned in that case since it's an expected
// situation.
//
// If there is an "overall error" calling the underlying GoCB bulk operation, then
// that error will be returned.
//
// If there are errors on individual keys -- aside from "not found" errors -- such as
// QueueOverflow errors that can be retried successfully, they will be retried
// with a backoff loop.
func (bucket *CouchbaseBucketGoCB) GetBulkRaw(keys []string) (map[string][]byte, error) {
// Create a RetryWorker for the GetBulkRaw operation
worker := bucket.newGetBulkRawRetryWorker(keys)
// Kick off retry loop
err, result := RetryLoop("GetBulkRaw", worker, bucket.Spec.RetrySleeper())
if err != nil {
err = pkgerrors.Wrapf(err, "Error during GetBulkRaw with %v keys", len(keys))
}
// If the RetryLoop returns a nil result, convert to an empty map.
if result == nil {
return map[string][]byte{}, err
}
// Type assertion of result into a map
resultMap, ok := result.(map[string][]byte)
if !ok {
return nil, RedactErrorf("Error doing type assertion of %v into a map", UD(result))
}
return resultMap, err
}
// Retrieve keys in bulk for increased efficiency. If any keys are not found, they
// will not be returned, and so the size of the map may be less than the size of the
// keys slice, and no error will be returned in that case since it's an expected
// situation.
//
// If there is an "overall error" calling the underlying GoCB bulk operation, then
// that error will be returned.
//
// If there are errors on individual keys -- aside from "not found" errors -- such as
// QueueOverflow errors that can be retried successfully, they will be retried
// with a backoff loop.
func (bucket *CouchbaseBucketGoCB) GetBulkCounters(keys []string) (map[string]uint64, error) {
// Create a RetryWorker for the GetBulkRaw operation
worker := bucket.newGetBulkCountersRetryWorker(keys)
// Kick off retry loop
err, result := RetryLoop("GetBulkRaw", worker, bucket.Spec.RetrySleeper())
if err != nil {
err = pkgerrors.Wrapf(err, "Error during GetBulkRaw with %v keys", len(keys))
}
// If the RetryLoop returns a nil result, convert to an empty map.
if result == nil {
return map[string]uint64{}, err
}
// Type assertion of result into a map
resultMap, ok := result.(map[string]uint64)
if !ok {
return nil, RedactErrorf("Error doing type assertion of %v into a map", UD(result))
}
return resultMap, err
}
func (bucket *CouchbaseBucketGoCB) newGetBulkRawRetryWorker(keys []string) RetryWorker {
// resultAccumulator scoped in closure, will accumulate results across multiple worker invocations
resultAccumulator := make(map[string][]byte, len(keys))
// pendingKeys scoped in closure, represents set of keys that still need to be attempted or re-attempted
pendingKeys := keys
worker := func() (shouldRetry bool, err error, value interface{}) {
retryKeys := []string{}
keyBatches := createBatchesKeys(MaxBulkBatchSize, pendingKeys)
for _, keyBatch := range keyBatches {
// process batch and add successful results to resultAccumulator
// and recoverable (non "Not Found") errors to retryKeys
err := bucket.processGetRawBatch(keyBatch, resultAccumulator, retryKeys)
if err != nil {
return false, err, nil
}
}
// if there are no keys to retry, then we're done.
if len(retryKeys) == 0 {
return false, nil, resultAccumulator
}
// otherwise, retry the keys the need to be retried
keys = retryKeys
// return true to signal that this function needs to be retried
return true, nil, nil
}
return worker
}
func (bucket *CouchbaseBucketGoCB) newGetBulkCountersRetryWorker(keys []string) RetryWorker {
// resultAccumulator scoped in closure, will accumulate results across multiple worker invocations
resultAccumulator := make(map[string]uint64, len(keys))
// pendingKeys scoped in closure, represents set of keys that still need to be attempted or re-attempted
pendingKeys := keys
worker := func() (shouldRetry bool, err error, value interface{}) {
retryKeys := []string{}
keyBatches := createBatchesKeys(MaxBulkBatchSize, pendingKeys)
for _, keyBatch := range keyBatches {
// process batch and add successful results to resultAccumulator
// and recoverable (non "Not Found") errors to retryKeys
err := bucket.processGetCountersBatch(keyBatch, resultAccumulator, retryKeys)
if err != nil {
return false, err, nil
}
}
// if there are no keys to retry, then we're done.
if len(retryKeys) == 0 {
return false, nil, resultAccumulator
}
// otherwise, retry the keys the need to be retried
keys = retryKeys
// return true to signal that this function needs to be retried
return true, nil, nil
}
return worker
}
func (bucket *CouchbaseBucketGoCB) processGetRawBatch(keys []string, resultAccumulator map[string][]byte, retryKeys []string) error {
var items []gocb.BulkOp
for _, key := range keys {
var value []byte
item := &gocb.GetOp{Key: key, Value: &value}
items = append(items, item)
}
err := bucket.Do(items)
if err != nil {
return err
}
for _, item := range items {
getOp, ok := item.(*gocb.GetOp)
if !ok {
continue
}
// Ignore any ops with errors.
// NOTE: some of the errors are misleading:
// https://issues.couchbase.com/browse/GOCBC-64
if getOp.Err == nil {
byteValue, ok := getOp.Value.(*[]byte)
if ok {
resultAccumulator[getOp.Key] = *byteValue
} else {
Warnf("Skipping GetBulkRaw result - unable to cast to []byte. Type: %v", reflect.TypeOf(getOp.Value))
}
} else {
// if it's a recoverable error, then throw it in retry collection.
if bucket.isRecoverableReadError(getOp.Err) {
retryKeys = append(retryKeys, getOp.Key)
}
}
}
return nil
}
func (bucket *CouchbaseBucketGoCB) processGetCountersBatch(keys []string, resultAccumulator map[string]uint64, retryKeys []string) error {
var items []gocb.BulkOp
for _, key := range keys {
var value uint64
item := &gocb.GetOp{Key: key, Value: &value}
items = append(items, item)
}
err := bucket.Do(items)
if err != nil {
return err
}
for _, item := range items {
getOp, ok := item.(*gocb.GetOp)
if !ok {
continue
}
// Ignore any ops with errors.
// NOTE: some of the errors are misleading:
// https://issues.couchbase.com/browse/GOCBC-64
if getOp.Err == nil {
intValue, ok := getOp.Value.(*uint64)
if ok {
resultAccumulator[getOp.Key] = *intValue
} else {
Warnf("Skipping GetBulkCounter result - unable to cast to []byte. Type: %v", reflect.TypeOf(getOp.Value))
}
} else {
// if it's a recoverable error, then throw it in retry collection.
if bucket.isRecoverableReadError(getOp.Err) {
retryKeys = append(retryKeys, getOp.Key)
}
}
}
return nil
}
func createBatchesEntries(batchSize uint, entries []*sgbucket.BulkSetEntry) [][]*sgbucket.BulkSetEntry {
// boundary checking
if len(entries) == 0 {
Warnf("createBatchesEnrties called with empty entries")
return [][]*sgbucket.BulkSetEntry{}
}
if batchSize == 0 {
Warnf("createBatchesEntries called with invalid batchSize")
result := [][]*sgbucket.BulkSetEntry{}
return append(result, entries)
}
batches := [][]*sgbucket.BulkSetEntry{}
batch := []*sgbucket.BulkSetEntry{}
for idxEntry, entry := range entries {
batch = append(batch, entry)
isBatchFull := uint(len(batch)) == batchSize
isLastEntry := idxEntry == (len(entries) - 1)
if isBatchFull || isLastEntry {
// this batch is full, add it to batches and start a new batch
batches = append(batches, batch)
batch = []*sgbucket.BulkSetEntry{}
}
}
return batches
}
func createBatchesKeys(batchSize uint, keys []string) [][]string {
// boundary checking
if len(keys) == 0 {
Warnf("createBatchesKeys called with empty keys")
return [][]string{}
}
if batchSize == 0 {
Warnf("createBatchesKeys called with invalid batchSize")
result := [][]string{}
return append(result, keys)
}
batches := [][]string{}
batch := []string{}
for idxKey, key := range keys {
batch = append(batch, key)
isBatchFull := uint(len(batch)) == batchSize
isLastKey := idxKey == (len(keys) - 1)
if isBatchFull || isLastKey {
// this batch is full, add it to batches and start a new batch
batches = append(batches, batch)
batch = []string{}
}
}
return batches
}
// Set this to true to cause isRecoverableGoCBError() to return true
// on the next call. Only useful for unit tests.
var doSingleFakeRecoverableGOCBError = false
// Recoverable errors or timeouts trigger retry for gocb v1 read operations
func (bucket *CouchbaseBucketGoCB) isRecoverableReadError(err error) bool {
if err == nil {
return false
}
if isGoCBTimeoutError(err) {
return true
}
_, ok := recoverableGocbV1Errors[pkgerrors.Cause(err).Error()]
return ok
}
// Recoverable errors trigger retry for gocb v1 write operations
func (bucket *CouchbaseBucketGoCB) isRecoverableWriteError(err error) bool {
if err == nil {
return false
}
_, ok := recoverableGocbV1Errors[pkgerrors.Cause(err).Error()]
if ok {
return ok
}
// In some circumstances we are unable to supply errors in the recoverable error map so need to check the error
// codes
if isKVError(err, memd.StatusSyncWriteInProgress) {
return true
}
return false
}
func isGoCBTimeoutError(err error) bool {
return pkgerrors.Cause(err) == gocb.ErrTimeout
}
// If the error is a net/url.Error and the error message is:
//
// net/http: request canceled while waiting for connection
//
// Then it means that the view request timed out, most likely due to the fact that it's a stale=false query and
// it's rebuilding the index. In that case, it's desirable to return a more informative error than the
// underlying net/url.Error. See https://github.com/couchbase/sync_gateway/issues/2639
func isGoCBQueryTimeoutError(err error) bool {
if err == nil {
return false
}
// If it's not a *url.Error, then it's not a viewtimeout error
netUrlError, ok := pkgerrors.Cause(err).(*url.Error)
if !ok {
return false
}
// If it's a *url.Error and contains the "request canceled" substring, then it's a viewtimeout error.
return strings.Contains(netUrlError.Error(), "request canceled")
}
func (bucket *CouchbaseBucketGoCB) GetAndTouchRaw(k string, exp uint32) (rv []byte, cas uint64, err error) {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
var returnVal []byte
worker := func() (shouldRetry bool, err error, value uint64) {
casGoCB, err := bucket.Bucket.GetAndTouch(k, exp, &returnVal)
shouldRetry = bucket.isRecoverableReadError(err)
return shouldRetry, err, uint64(casGoCB)
}
// Kick off retry loop
err, cas = RetryLoopCas("GetAndTouchRaw", worker, bucket.Spec.MaxRetrySleeper(1000))
if err != nil {
err = pkgerrors.Wrapf(err, fmt.Sprintf("Error during GetAndTouchRaw with key %v", UD(k).Redact()))
}
// If returnVal was never set to anything, return nil or else type assertion below will panic
if returnVal == nil {
return nil, cas, err
}
return returnVal, cas, err
}
func (bucket *CouchbaseBucketGoCB) Touch(k string, exp uint32) (cas uint64, err error) {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
worker := func() (shouldRetry bool, err error, value uint64) {
casGoCB, err := bucket.Bucket.Touch(k, 0, exp)
shouldRetry = bucket.isRecoverableWriteError(err)
return shouldRetry, err, uint64(casGoCB)
}
// Kick off retry loop
err, cas = RetryLoopCas("Touch", worker, bucket.Spec.MaxRetrySleeper(1000))
if err != nil {
err = pkgerrors.Wrapf(err, "Error during Touch for key %v", UD(k).Redact())
}
return cas, err
}
func (bucket *CouchbaseBucketGoCB) Add(k string, exp uint32, v interface{}) (added bool, err error) {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
worker := func() (shouldRetry bool, err error, value interface{}) {
_, err = bucket.Bucket.Insert(k, v, exp)
if bucket.isRecoverableWriteError(err) {
return true, err, nil
}
return false, err, nil
}
err, _ = RetryLoop("CouchbaseBucketGoCB Add()", worker, bucket.Spec.RetrySleeper())
if err != nil && err == gocb.ErrKeyExists {
return false, nil
}
return err == nil, err
}
// GoCB AddRaw writes as BinaryDocument, which results in the document having the
// binary doc common flag set. Callers that want to write JSON documents as raw bytes should
// pass v as []byte to the stanard bucket.Add
func (bucket *CouchbaseBucketGoCB) AddRaw(k string, exp uint32, v []byte) (added bool, err error) {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
worker := func() (shouldRetry bool, err error, value interface{}) {
_, err = bucket.Bucket.Insert(k, bucket.FormatBinaryDocument(v), exp)
if bucket.isRecoverableWriteError(err) {
return true, err, nil
}
return false, err, nil
}
err, _ = RetryLoop("CouchbaseBucketGoCB AddRaw()", worker, bucket.Spec.RetrySleeper())
if err != nil {
if err == gocb.ErrKeyExists {
return false, nil
}
err = pkgerrors.WithStack(err)
}
return err == nil, err
}
func (bucket *CouchbaseBucketGoCB) Append(k string, data []byte) error {
_, err := bucket.Bucket.Append(k, string(data))
return err
}
func (bucket *CouchbaseBucketGoCB) Set(k string, exp uint32, v interface{}) error {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
worker := func() (shouldRetry bool, err error, value interface{}) {
_, err = bucket.Bucket.Upsert(k, v, exp)
if bucket.isRecoverableWriteError(err) {
return true, err, nil
}
return false, err, nil
}
err, _ := RetryLoop("CouchbaseBucketGoCB Set()", worker, bucket.Spec.RetrySleeper())
if err != nil {
err = pkgerrors.WithStack(err)
}
return err
}
func (bucket *CouchbaseBucketGoCB) SetRaw(k string, exp uint32, v []byte) error {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
worker := func() (shouldRetry bool, err error, value interface{}) {
_, err = bucket.Bucket.Upsert(k, bucket.FormatBinaryDocument(v), exp)
if bucket.isRecoverableWriteError(err) {
return true, err, nil
}
return false, err, nil
}
err, _ := RetryLoop("CouchbaseBucketGoCB SetRaw()", worker, bucket.Spec.RetrySleeper())
return err
}
func (bucket *CouchbaseBucketGoCB) Delete(k string) error {
worker := func() (shouldRetry bool, err error, value interface{}) {
_, err = bucket.Remove(k, 0)
if bucket.isRecoverableWriteError(err) {
return true, err, nil
}
return false, err, nil
}
err, _ := RetryLoop("CouchbaseBucketGoCB Delete()", worker, bucket.Spec.RetrySleeper())
return err
}
func (bucket *CouchbaseBucketGoCB) Remove(k string, cas uint64) (casOut uint64, err error) {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps
}()
worker := func() (shouldRetry bool, err error, value interface{}) {
newCas, errRemove := bucket.Bucket.Remove(k, gocb.Cas(cas))
if bucket.isRecoverableWriteError(errRemove) {
return true, errRemove, newCas
}
return false, errRemove, newCas
}
err, newCasVal := RetryLoop("CouchbaseBucketGoCB Remove()", worker, bucket.Spec.RetrySleeper())
if newCasVal != nil {
casOut = uint64(newCasVal.(gocb.Cas))
}
if err != nil {
return casOut, err
}
return casOut, nil
}
func (bucket *CouchbaseBucketGoCB) Write(k string, flags int, exp uint32, v interface{}, opt sgbucket.WriteOptions) error {
Panicf("Unimplemented method: Write()")
return nil
}
func (bucket *CouchbaseBucketGoCB) WriteCas(k string, flags int, exp uint32, cas uint64, v interface{}, opt sgbucket.WriteOptions) (casOut uint64, err error) {
bucket.singleOps <- struct{}{}
defer func() {
<-bucket.singleOps