/
couchbase.go
2347 lines (2001 loc) · 63.9 KB
/
couchbase.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 2014-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 couchbase provides a couchbase-server implementation of the datastore
package.
*/
package couchbase
import (
"encoding/binary"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/couchbase/cbauth"
"github.com/couchbase/gomemcached"
"github.com/couchbase/gomemcached/client" // package name is memcached
gsi "github.com/couchbase/indexing/secondary/queryport/n1ql"
ftsclient "github.com/couchbase/n1fty"
"github.com/couchbase/query/auth"
"github.com/couchbase/query/datastore"
"github.com/couchbase/query/datastore/couchbase/gcagent"
"github.com/couchbase/query/datastore/virtual"
"github.com/couchbase/query/errors"
"github.com/couchbase/query/logging"
cb "github.com/couchbase/query/primitives/couchbase"
"github.com/couchbase/query/server"
"github.com/couchbase/query/transactions"
"github.com/couchbase/query/util"
"github.com/couchbase/query/value"
)
var REQUIRE_CBAUTH bool // Connection to authorization system must succeed.
var _SKIP_IMPERSONATE bool = true // don't send actual user names
// cbPoolMap and cbPoolServices implement a local cache of the datastore's topology
type cbPoolMap struct {
sync.RWMutex
poolServices map[string]cbPoolServices
}
type cbPoolServices struct {
name string
rev int
nodeServices map[string]interface{}
}
var _POOLMAP cbPoolMap
const (
PRIMARY_INDEX = "#primary"
_TRAN_CLEANUP_INTERVAL = 1 * time.Minute
)
func init() {
// MB-27415 have a larger overflow pool and close overflow connections asynchronously
cb.SetConnectionPoolParams(64, 64)
cb.EnableAsynchronousCloser(true)
val, err := strconv.ParseBool(os.Getenv("REQUIRE_CBAUTH"))
if err != nil {
REQUIRE_CBAUTH = val
} else {
REQUIRE_CBAUTH = true // default
}
// enable data type response
cb.EnableDataType = true
// enable xattrs
cb.EnableXattr = true
// start the fetch workers for servicing the BulkGet operations
cb.InitBulkGet()
_POOLMAP.poolServices = make(map[string]cbPoolServices, 1)
// Enable sync replication (durability)
cb.EnableSyncReplication = true
// Enable collections
cb.EnableCollections = true
// Enable Preserve Expiry
cb.EnablePreserveExpiry = true
// Enable KV Error maps
cb.EnableXerror = true
// transaction cache initialization
transactions.TranContextCacheInit(_TRAN_CLEANUP_INTERVAL)
}
// store is the root for the couchbase datastore
type store struct {
client cb.Client // instance of primitives/couchbase client
gcClient *gcagent.Client
namespaceCache map[string]*namespace // map of pool-names and IDs
CbAuthInit bool // whether cbAuth is initialized
inferencer datastore.Inferencer // what we use to infer schemas
statUpdater datastore.StatUpdater // what we use to update statistics
connectionUrl string // where to contact ns_server
connSecConfig *datastore.ConnectionSecurityConfig
nslock sync.RWMutex
}
func (s *store) Id() string {
return s.URL()
}
func (s *store) URL() string {
return s.client.BaseURL.String()
}
func (s *store) Info() datastore.Info {
info := &infoImpl{client: &s.client}
return info
}
type infoImpl struct {
client *cb.Client
}
func (info *infoImpl) Version() string {
return info.client.Info.ImplementationVersion
}
func fullhostName(n string) string {
hostName, portVal := server.HostNameandPort(n)
if hostName != "" && portVal != "" {
return n
}
if portVal != "" {
portVal = ":" + portVal
}
return server.GetIP(true) + portVal
}
func (info *infoImpl) Topology() ([]string, []errors.Error) {
var nodes []string
var errs []errors.Error
for _, p := range info.client.Info.Pools {
pool, err := info.client.GetPool(p.Name)
if err == nil {
for _, node := range pool.Nodes {
nodes = append(nodes, fullhostName(node.Hostname))
}
pool.Close()
} else {
errs = append(errs, errors.NewDatastoreClusterError(err, p.Name))
}
}
return nodes, errs
}
func (info *infoImpl) Services(node string) (map[string]interface{}, []errors.Error) {
var errs []errors.Error
isReadLock := true
_POOLMAP.RLock()
defer func() {
if isReadLock {
_POOLMAP.RUnlock()
} else {
_POOLMAP.Unlock()
}
}()
// scan the pools
for _, p := range info.client.Info.Pools {
pool, err := info.client.GetPool(p.Name)
poolServices, pErr := info.client.GetPoolServices(p.Name)
if err == nil && pErr == nil {
var found bool = false
var services cbPoolServices
services, ok := _POOLMAP.poolServices[p.Name]
found = ok && (services.rev == poolServices.Rev)
// missing the information, rebuild
if !found {
// promote the lock
if isReadLock {
_POOLMAP.RUnlock()
_POOLMAP.Lock()
isReadLock = false
// now that we have promoted the lock, did we get beaten by somebody else to it?
services, ok = _POOLMAP.poolServices[p.Name]
found = ok && (services.rev == poolServices.Rev)
if found {
continue
}
}
newPoolServices := cbPoolServices{name: p.Name, rev: poolServices.Rev}
nodeServices := make(map[string]interface{}, len(pool.Nodes))
// go through all the nodes in the pool
for _, n := range pool.Nodes {
var servicesCopy []interface{}
newServices := make(map[string]interface{}, 3)
newServices["name"] = fullhostName(n.Hostname)
for _, s := range n.Services {
servicesCopy = append(servicesCopy, s)
}
newServices["services"] = servicesCopy
// go through all bucket independet services in the pool
for _, ns := range poolServices.NodesExt {
mgmtPort := ns.Services["mgmt"]
if mgmtPort == 0 {
// shouldn't happen, there should always be a mgmt port on each node
// we should return an error
msg := fmt.Sprintf("NodeServices does not report mgmt endpoint for "+
"this node: %v", node)
errs = append(errs, errors.NewAdminGetNodeError(nil, msg))
continue
}
nsHostname := ""
if ns.Hostname != "" {
nsHostname = ns.Hostname + ":" + strconv.Itoa(mgmtPort)
}
// if we can positively match nodeServices and node, add ports
if n.Hostname == nsHostname ||
(nsHostname == "" && ns.ThisNode && n.ThisNode) {
ports := make(map[string]interface{}, len(ns.Services))
// only add the ports for those services that are advertised
for _, s := range n.Services {
for pn, p := range ns.Services {
if strings.Index(pn, s) == 0 {
ports[pn] = p
}
}
}
newServices["ports"] = ports
break
}
}
nodeServices[fullhostName(n.Hostname)] = newServices
}
newPoolServices.nodeServices = nodeServices
_POOLMAP.poolServices[p.Name] = newPoolServices
services = newPoolServices
}
nodeServices, ok := services.nodeServices[node]
if ok {
return nodeServices.(map[string]interface{}), errs
}
} else {
if err != nil {
errs = append(errs, errors.NewDatastoreClusterError(err, p.Name))
}
if pErr != nil {
errs = append(errs, errors.NewDatastoreClusterError(pErr, p.Name))
}
}
if err == nil {
pool.Close()
}
}
return map[string]interface{}{}, errs
}
func (s *store) NamespaceIds() ([]string, errors.Error) {
return s.NamespaceNames()
}
func (s *store) NamespaceNames() ([]string, errors.Error) {
return []string{"default"}, nil
}
func (s *store) NamespaceById(id string) (p datastore.Namespace, e errors.Error) {
return s.NamespaceByName(id)
}
func (s *store) NamespaceByName(name string) (p datastore.Namespace, e errors.Error) {
p, ok := s.namespaceCache[name]
if !ok {
var err errors.Error
p, err = loadNamespace(s, name)
if err != nil {
return nil, err
}
s.namespaceCache[name] = p.(*namespace)
}
return p, nil
}
// The ns_server admin API is open iff we can access the /pools API without a password.
func (s *store) adminIsOpen() bool {
url := s.connectionUrl + "/pools"
resp, err := http.Get(url)
if err != nil {
return false
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return false
}
return true
}
func (s *store) auth(user, pwd string) (cbauth.Creds, error) {
return cbauth.Auth(user, pwd)
}
func (s *store) authWebCreds(req *http.Request) (cbauth.Creds, error) {
return cbauth.AuthWebCreds(req)
}
func (s *store) Authorize(privileges *auth.Privileges, credentials *auth.Credentials) (auth.AuthenticatedUsers, errors.Error) {
if s.CbAuthInit == false {
// cbauth is not initialized. Access to SASL protected buckets will be
// denied by the couchbase server
logging.Warnf("CbAuth not intialized")
return nil, nil
}
return cbAuthorize(s, privileges, credentials)
}
func (s *store) GetUserUUID(credentials *auth.Credentials) string {
if s.CbAuthInit == false {
// cbauth is not initialized. Access to SASL protected buckets will be
// denied by the couchbase server
logging.Warnf("CbAuth not intialized")
return ""
}
if credentials.HttpRequest == nil {
return ""
}
creds, _ := cbauth.AuthWebCreds(credentials.HttpRequest)
if creds != nil {
res, _ := creds.Uuid()
return res
}
return ""
}
func (s *store) PreAuthorize(privileges *auth.Privileges) {
cbPreAuthorize(privileges)
}
func (s *store) CredsString(req *http.Request) string {
if req != nil {
creds, err := cbauth.AuthWebCreds(req)
if err == nil {
return creds.Name()
}
}
return ""
}
func (s *store) SetLogLevel(level logging.Level) {
for _, n := range s.namespaceCache {
defer n.lock.Unlock()
n.lock.Lock()
for _, k := range n.keyspaceCache {
if k.cbKeyspace == nil {
continue
}
indexers, _ := k.cbKeyspace.Indexers()
if len(indexers) > 0 {
for _, idxr := range indexers {
idxr.SetLogLevel(level)
}
return
}
}
}
}
// Ignore the name parameter for now
func (s *store) Inferencer(name datastore.InferenceType) (datastore.Inferencer, errors.Error) {
return s.inferencer, nil
}
func (s *store) Inferencers() ([]datastore.Inferencer, errors.Error) {
return []datastore.Inferencer{s.inferencer}, nil
}
func (s *store) StatUpdater() (datastore.StatUpdater, errors.Error) {
return s.statUpdater, nil
}
func (s *store) AuditInfo() (*datastore.AuditInfo, errors.Error) {
auditSpec, err := s.client.GetAuditSpec()
if err != nil {
return nil, errors.NewSystemUnableToRetrieveError(err)
}
users := make(map[datastore.UserInfo]bool, len(auditSpec.DisabledUsers))
for _, u := range auditSpec.DisabledUsers {
ui := datastore.UserInfo{Name: u.Name, Domain: u.Domain}
users[ui] = true
}
events := make(map[uint32]bool, len(auditSpec.Disabled))
for _, eid := range auditSpec.Disabled {
events[eid] = true
}
ret := &datastore.AuditInfo{
EventDisabled: events,
UserWhitelisted: users,
AuditEnabled: auditSpec.AuditdEnabled,
Uid: auditSpec.Uid,
}
return ret, nil
}
func (s *store) ProcessAuditUpdateStream(callb func(uid string) error) errors.Error {
f := func(data interface{}) error {
d, ok := data.(*DefaultObject)
if !ok {
return fmt.Errorf("Unable to convert received object to proper type: %T", data)
}
return callb(d.Uid)
}
do := DefaultObject{}
err := s.client.ProcessStream("/poolsStreaming/default", f, &do)
if err != nil {
return errors.NewAuditStreamHandlerFailed(err)
}
return nil
}
func (s *store) EnableStorageAudit(val bool) {
_SKIP_IMPERSONATE = !val
}
type DefaultObject struct {
Uid string `json:"auditUid"`
}
func (s *store) UserInfo() (value.Value, errors.Error) {
data, err := s.client.GetUserRoles()
if err != nil {
return nil, errors.NewSystemUnableToRetrieveError(err)
}
return value.NewValue(data), nil
}
func (s *store) GetUserInfoAll() ([]datastore.User, errors.Error) {
sourceUsers, err := s.client.GetUserInfoAll()
if err != nil {
return nil, errors.NewSystemUnableToRetrieveError(err)
}
resultUsers := make([]datastore.User, len(sourceUsers))
for i, u := range sourceUsers {
resultUsers[i].Name = u.Name
resultUsers[i].Id = u.Id
resultUsers[i].Domain = u.Domain
roles := make([]datastore.Role, len(u.Roles))
for j, r := range u.Roles {
roles[j].Name = r.Role
if r.CollectionName != "" && r.CollectionName != "*" {
roles[j].Target = r.BucketName + ":" + r.ScopeName + ":" + r.CollectionName
} else if r.ScopeName != "" && r.ScopeName != "*" {
roles[j].Target = r.BucketName + ":" + r.ScopeName
} else if r.BucketName != "" {
roles[j].Target = r.BucketName
}
}
resultUsers[i].Roles = roles
}
return resultUsers, nil
}
func (s *store) PutUserInfo(u *datastore.User) errors.Error {
var outputUser cb.User
outputUser.Name = u.Name
outputUser.Id = u.Id
outputUser.Roles = make([]cb.Role, len(u.Roles))
outputUser.Domain = u.Domain
for i, r := range u.Roles {
outputUser.Roles[i].Role = r.Name
if len(r.Target) > 0 {
outputUser.Roles[i].BucketName = r.Target
}
}
err := s.client.PutUserInfo(&outputUser)
if err != nil {
return errors.NewSystemUnableToUpdateError(err)
}
return nil
}
func (s *store) GetRolesAll() ([]datastore.Role, errors.Error) {
roleDescList, err := s.client.GetRolesAll()
if err != nil {
return nil, errors.NewDatastoreUnableToRetrieveRoles(err)
}
roles := make([]datastore.Role, len(roleDescList))
for i, rd := range roleDescList {
roles[i].Name = rd.Role
roles[i].Target = rd.BucketName
}
return roles, nil
}
func (s *store) SetClientConnectionSecurityConfig() (err error) {
if s.connSecConfig != nil &&
s.connSecConfig.ClusterEncryptionConfig.EncryptData {
// For every initTLS call when info is refreshed pass the
// cert and key info along with passphrase to client.
err = s.client.InitTLS(s.connSecConfig.CAFile,
s.connSecConfig.CertFile,
s.connSecConfig.KeyFile,
s.connSecConfig.ClusterEncryptionConfig.DisableNonSSLPorts,
s.connSecConfig.TLSConfig.PrivateKeyPassphrase)
if err == nil && s.gcClient != nil {
err = s.gcClient.InitTLS(s.connSecConfig.CAFile,
s.connSecConfig.CertFile,
s.connSecConfig.KeyFile,
s.connSecConfig.TLSConfig.PrivateKeyPassphrase)
}
if err != nil {
if len(s.connSecConfig.CAFile) > 0 {
err = fmt.Errorf("Unable to initialize TLS using certificate %s. Aborting security update. Error:%v",
s.connSecConfig.CAFile, err)
} else {
err = fmt.Errorf("Unable to initialize TLS using certificate %s. Aborting security update. Error:%v",
s.connSecConfig.CertFile, err)
}
logging.Errorf("%v", err)
return
}
} else {
s.client.ClearTLS()
if s.gcClient != nil {
s.gcClient.ClearTLS()
}
}
return
}
func (s *store) SetConnectionSecurityConfig(connSecConfig *datastore.ConnectionSecurityConfig) {
s.connSecConfig = connSecConfig
if err := s.SetClientConnectionSecurityConfig(); err != nil {
return
}
gsi.SetConnectionSecurityConfig(connSecConfig)
// for any active buckets set new security config
for _, n := range s.namespaceCache {
// force a full pool refresh
n.refreshFully()
n.lock.Lock()
for _, k := range n.keyspaceCache {
if k.cbKeyspace == nil {
continue
}
// Make new TLS settings take effect in the buckets.
if k.cbKeyspace.agentProvider != nil {
k.cbKeyspace.agentProvider.Refresh()
}
// Pass new settings to indexers.
indexers, _ := k.cbKeyspace.Indexers()
if len(indexers) > 0 {
for _, idxr := range indexers {
idxr.SetConnectionSecurityConfig(connSecConfig)
}
}
}
n.lock.Unlock()
}
}
func initCbAuth(url string) (*cb.Client, error) {
transport := cbauth.WrapHTTPTransport(cb.HTTPTransport, nil)
cb.HTTPClient.Transport = transport
client, err := cb.ConnectWithAuth(url, cbauth.NewAuthHandler(nil))
if err != nil {
return nil, err
}
logging.Infof(" Initialization of cbauth succeeded ")
return &client, nil
}
func parseUrl(u string) (host string, username string, password string, err error) {
url, err := url.Parse(u)
if err != nil {
return "", "", "", err
}
if url.User == nil {
return "", "", "", fmt.Errorf("Unusable url %s. No user information.", u)
}
password, _ = url.User.Password()
if password == "" {
logging.Warnf("No password found in url <ud>%s</ud>", u)
}
if url.User.Username() == "" {
logging.Warnf("No username found in url <ud>%s</ud>", u)
}
return url.Host, url.User.Username(), password, nil
}
// NewStore creates a new Couchbase store for the given url.
// In the main server, and error return here will cause the server to shut down.
func NewDatastore(u string) (s datastore.Datastore, e errors.Error) {
var client cb.Client
var cbAuthInit bool
var err error
var connectionUrl string
// initialize cbauth
c, err := initCbAuth(u)
if err != nil {
logging.Errorf("Unable to initialize cbauth. Error %v", err)
// intialize cb_auth variables manually
host, username, password, err := parseUrl(u)
if err != nil {
logging.Warnf("Unable to parse url <ud>%s</ud>: %v", u, err)
} else {
set, err := cbauth.InternalRetryDefaultInit(host, username, password)
if set == false || err != nil {
logging.Errorf("Unable to initialize cbauth variables. Error %v", err)
} else {
c, err = initCbAuth("http://" + host)
if err != nil {
logging.Errorf("Unable to initialize cbauth. Error %v", err)
} else {
client = *c
cbAuthInit = true
connectionUrl = "http://" + host
}
}
}
} else {
client = *c
cbAuthInit = true
connectionUrl = u
}
if !cbAuthInit {
if REQUIRE_CBAUTH {
return nil, errors.NewUnableToInitCbAuthError(err)
}
// connect without auth
logging.Warnf("Unable to initialize cbAuth, access to couchbase buckets may be restricted")
cb.HTTPClient = &http.Client{}
client, err = cb.Connect(u)
if err != nil {
return nil, errors.NewCbConnectionError(err, "url "+u)
}
}
store := &store{
client: client,
namespaceCache: make(map[string]*namespace),
CbAuthInit: cbAuthInit,
connectionUrl: connectionUrl,
}
// get the schema inferencer
var er errors.Error
store.inferencer, er = GetDefaultInferencer(store)
if er != nil {
return nil, er
}
// get statistics updater
store.statUpdater, er = GetDefaultStatUpdater(store)
if er != nil {
return nil, er
}
// initialize the default pool.
// TODO can couchbase server contain more than one pool ?
defaultPool, er := loadNamespace(store, "default")
if er != nil {
logging.Errorf("Cannot connect to default pool: %v", er)
return nil, er
}
store.namespaceCache["default"] = defaultPool
logging.Infof("New store created with url %s", u)
return store, nil
}
func loadNamespace(s *store, name string) (*namespace, errors.Error) {
cbpool, err := s.client.GetPool(name)
if err != nil {
if name == "default" {
// if default pool is not available, try reconnecting to the server
url := s.URL()
var client cb.Client
if s.CbAuthInit == true {
client, err = cb.ConnectWithAuth(url, cbauth.NewAuthHandler(nil))
} else {
client, err = cb.Connect(url)
}
if err != nil {
return nil, errors.NewCbNamespaceNotFoundError(err, name)
}
// check if the default pool exists
cbpool, err = client.GetPool(name)
if err != nil {
return nil, errors.NewCbNamespaceNotFoundError(err, name)
}
s.client = client
err = s.SetClientConnectionSecurityConfig()
if err != nil {
return nil, errors.NewCbNamespaceNotFoundError(err, name)
}
} else {
logging.Errorf(" Error while retrieving pool %v", err)
}
}
rv := namespace{
store: s,
name: name,
cbNamespace: &cbpool,
keyspaceCache: make(map[string]*keyspaceEntry),
}
return &rv, nil
}
// full name representation of a bucket / scope / keyspace for error message purposes
func fullName(elems ...string) string {
switch len(elems) {
case 1:
return elems[0]
case 2:
return elems[0] + ":" + elems[1]
default:
res := elems[0] + ":" + elems[1]
for i := 2; i < len(elems); i++ {
res = res + "." + elems[i]
}
return res
}
}
// a namespace represents a couchbase pool
type namespace struct {
store *store
name string
cbNamespace *cb.Pool
last util.Time // last time we refreshed the pool
keyspaceCache map[string]*keyspaceEntry
version uint64
lock sync.RWMutex // lock to guard the keyspaceCache
nslock sync.RWMutex // lock for this structure
}
type keyspaceEntry struct {
sync.Mutex
cbKeyspace *keyspace
errCount int
errTime util.Time
lastUse util.Time
}
const (
_MIN_ERR_INTERVAL time.Duration = 5 * time.Second
_THROTTLING_TIMEOUT time.Duration = 10 * time.Millisecond
_CLEANUP_INTERVAL time.Duration = time.Hour
_NAMESPACE_REFRESH_THRESHOLD time.Duration = 100 * time.Millisecond
_STATS_REFRESH_THRESHOLD time.Duration = 1 * time.Second
)
func (p *namespace) DatastoreId() string {
return p.store.Id()
}
func (p *namespace) Id() string {
return p.Name()
}
func (p *namespace) Name() string {
return p.name
}
func (p *namespace) KeyspaceIds() ([]string, errors.Error) {
return p.KeyspaceNames()
}
func (p *namespace) KeyspaceNames() ([]string, errors.Error) {
p.refresh()
p.nslock.RLock()
rv := make([]string, len(p.cbNamespace.BucketMap))
i := 0
for name, _ := range p.cbNamespace.BucketMap {
rv[i] = name
i++
}
p.nslock.RUnlock()
return rv, nil
}
func (p *namespace) Objects(preload bool) ([]datastore.Object, errors.Error) {
p.refresh()
p.nslock.RLock()
rv := make([]datastore.Object, len(p.cbNamespace.BucketMap))
i := 0
for name, _ := range p.cbNamespace.BucketMap {
var defaultCollection datastore.Keyspace
o := datastore.Object{name, name, false, false}
p.lock.RLock()
entry := p.keyspaceCache[name]
if entry != nil && entry.cbKeyspace != nil {
defaultCollection = entry.cbKeyspace.defaultCollection
}
p.lock.RUnlock()
if preload && defaultCollection == nil {
ks, err := p.KeyspaceByName(name)
if ks != nil && err == nil {
defaultCollection = ks.(*keyspace).defaultCollection
}
}
// if we have loaded the bucket, check if the bucket has a default collection
// if we haven't loaded the bucket, see if you can get the default collection id
// the bucket is a keyspace if the default collection exists
if defaultCollection != nil {
switch k := defaultCollection.(type) {
case *collection:
o.IsKeyspace = (k != nil)
o.IsBucket = true
case *keyspace:
o.IsKeyspace = (k != nil)
o.IsBucket = false
}
} else if !preload {
bucket, _ := p.cbNamespace.GetBucket(name)
if bucket != nil {
_, _, err := bucket.GetCollectionCID("_default", "_default", time.Time{})
if err == nil {
o.IsKeyspace = true
}
}
o.IsBucket = true
}
rv[i] = o
i++
}
p.nslock.RUnlock()
return rv, nil
}
func (p *namespace) KeyspaceByName(name string) (datastore.Keyspace, errors.Error) {
return p.keyspaceByName(name)
}
func (p *namespace) VirtualKeyspaceByName(path []string) (datastore.Keyspace, errors.Error) {
return virtual.NewVirtualKeyspace(p, path)
}
func (p *namespace) keyspaceByName(name string) (*keyspace, errors.Error) {
var err errors.Error
var keyspace *keyspace
// make sure that no one is deleting the keyspace as we check
p.lock.RLock()
entry := p.keyspaceCache[name]
if entry != nil {
keyspace = entry.cbKeyspace
}
p.lock.RUnlock()
if keyspace != nil {
// shortcut if good, or only manifest needed
switch keyspace.flags {
case _NEEDS_MANIFEST:
// avoid a race condition where we read a manifest while the uid is increased
// by the bucket update callback
for {
mani, err := keyspace.cbbucket.GetCollectionsManifest()
if err == nil {
// see later: another case for shared optimistic locks.
// only the first one in gets to change scopes, every one else's work is wasted
scopes, defaultCollection := refreshScopesAndCollections(mani, keyspace)
// if any other flag has been set in the interim, we go the reload route
keyspace.Lock()
if keyspace.flags == _NEEDS_MANIFEST {
// another manifest arrived in the interim, and we've loaded the old one
// try again
if mani.Uid < keyspace.newCollectionsManifestUid {
keyspace.Unlock()
continue
}
// do not update if somebody has already done it
if mani.Uid > keyspace.collectionsManifestUid ||
keyspace.collectionsManifestUid == _INVALID_MANIFEST_UID {
keyspace.collectionsManifestUid = mani.Uid
keyspace.scopes = scopes
logging.Infof("Refreshed manifest for bucket %v id %v", name, mani.Uid)
// if there's no scopes fall back to bucket access
if len(scopes) == 0 {
keyspace.defaultCollection = keyspace
} else {
keyspace.defaultCollection = defaultCollection
}
keyspace.flags = 0
}
}
keyspace.Unlock()
if keyspace.flags == 0 {
return keyspace, nil
}
} else {
logging.Infof("Unable to retrieve collections info for bucket %s: %v", name, err)
}
break
}
case 0:
return keyspace, nil
}
}
// MB-19601 we haven't found the keyspace, so we have to load it,
// however, there might be a flood of other requests coming in, all
// wanting to do use the same keyspace and all needing to load it.
// In the previous implementation all requests would first create
// and refresh the keyspace, refreshing the indexes, etc
// In YCSB enviroments this resulted in thousends of requests
// flooding ns_server with buckets and ddocs load at the same time.
// What we want instead is for one request to do the work, and all the
// others waiting and benefiting from that work.
// This is the exact scenario for using Shared Optimistic Locks, but,
// sadly, they are patented by IBM, so clearly it's no go for us.
// What we do is create the keyspace entry, and record that we are priming
// it by locking that entry.
// Everyone else will have to wait on the lock, and once they get it,
// they can check on the keyspace again - if all is fine, just continue
// if not try and load again.
// Shared Optimistic Locks by stealth, although not as efficient (there
// might be sequencing of would be loaders on the keyspace lock after
// the initial keyspace loading has been done).
// If we fail, again! then there's something wrong with the keyspace,
// which means that retrying over and over again, we'll be loading ns_server
// so what we do is throttle the reloads and log errors, so that the
// powers that be are alerted that there's some resource issue.
// Finally, since we are having to use two locks rather than one, make sure
// that the locking sequence is predictable.
// keyspace lock is always locked outside of the keyspace cache lock.
// 1) create the entry if necessary, record time of loading attempt
p.lock.Lock()
entry = p.keyspaceCache[name]
if entry == nil {
// adding a new keyspace does not force the namespace version to change