-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathserver_context.go
2227 lines (1927 loc) · 84.4 KB
/
server_context.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 rest
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/KimMachineGun/automemlimit/memlimit"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/db/functions"
"github.com/shirou/gopsutil/mem"
"github.com/couchbase/gocbcore/v10"
sgbucket "github.com/couchbase/sg-bucket"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/db"
)
const kDefaultSlowQueryWarningThreshold uint32 = 500 // ms
const KDefaultNumShards = 16
// defaultBytesStatsReportingInterval is the default interval when to report bytes transferred stats
const defaultBytesStatsReportingInterval = 30 * time.Second
const dbLoadedStateChangeMsg = "DB loaded from config"
var errCollectionsUnsupported = base.HTTPErrorf(http.StatusBadRequest, "Named collections specified in database config, but not supported by connected Couchbase Server.")
var ErrSuspendingDisallowed = errors.New("database does not allow suspending")
var allServers = []serverType{publicServer, adminServer, metricsServer, diagnosticServer}
// serverInfo represents an instance of an HTTP server from sync gateway
type serverInfo struct {
server *http.Server // server is the HTTP server instance
addr net.Addr // addr is the addr of the listener, which will be resolvable always, whereas server.Addr can be :0
}
// Shared context of HTTP handlers: primarily a registry of databases by name. It also stores
// the configuration settings so handlers can refer to them.
// This struct is accessed from HTTP handlers running on multiple goroutines, so it needs to
// be thread-safe.
type ServerContext struct {
Config *StartupConfig // The current runtime configuration of the node
initialStartupConfig *StartupConfig // The configuration at startup of the node. Built from config file + flags
persistentConfig bool
dbRegistry map[string]struct{} // registry of dbNames, used to ensure uniqueness even when db isn't active
collectionRegistry map[string]string // map of fully qualified collection name to db name, used for local uniqueness checks
dbConfigs map[string]*RuntimeDatabaseConfig // dbConfigs is a map of db name to the RuntimeDatabaseConfig
databases_ map[string]*db.DatabaseContext // databases_ is a map of dbname to db.DatabaseContext
lock sync.RWMutex
statsContext *statsContext
BootstrapContext *bootstrapContext
HTTPClient *http.Client
cpuPprofFileMutex sync.Mutex // Protect cpuPprofFile from concurrent Start and Stop CPU profiling requests
cpuPprofFile *os.File // An open file descriptor holds the reference during CPU profiling
_httpServers map[serverType]*serverInfo // A list of HTTP servers running under the ServerContext
GoCBAgent *gocbcore.Agent // GoCB Agent to use when obtaining management endpoints
NoX509HTTPClient *http.Client // httpClient for the cluster that doesn't include x509 credentials, even if they are configured for the cluster
hasStarted chan struct{} // A channel that is closed via PostStartup once the ServerContext has fully started
LogContextID string // ID to differentiate log messages from different server context
fetchConfigsLastUpdate time.Time // The last time fetchConfigsWithTTL() updated dbConfigs
allowScopesInPersistentConfig bool // Test only backdoor to allow scopes in persistent config, not supported for multiple databases with different collections targeting the same bucket
DatabaseInitManager *DatabaseInitManager // Manages database initialization (index creation and readiness) independent of database stop/start/reload, when using persistent config
ActiveReplicationsCounter
invalidDatabaseConfigTracking invalidDatabaseConfigs
}
type ActiveReplicationsCounter struct {
activeReplicatorCount int // The count of concurrent active replicators
activeReplicatorLimit int // The limit on number of active replicators allowed
lock sync.RWMutex // Lock for managing access to shared memory location
}
// defaultConfigRetryTimeout is the total retry time when waiting for in-flight config updates. Set as a multiple of kv op timeout,
// based on the maximum of 3 kv ops for a successful config update
const defaultConfigRetryTimeout = 3 * base.DefaultGocbV2OperationTimeout
type bootstrapContext struct {
Connection base.BootstrapConnection
configRetryTimeout time.Duration // configRetryTimeout defines the total amount of time to retry on a registry/config mismatch
terminator chan struct{} // Used to stop the goroutine handling the bootstrap polling
doneChan chan struct{} // doneChan is closed when the bootstrap polling goroutine finishes.
sgVersion base.ComparableBuildVersion // version of Sync Gateway
}
type getOrAddDatabaseConfigOptions struct {
failFast bool // if set, a failure to connect to a bucket of collection will immediately fail
useExisting bool // if true, return an existing DatabaseContext vs return an error
connectToBucketFn db.OpenBucketFn // supply a custom function for buckets, used for testing only
forceOnline bool // force the database to come online, even if startOffline is set
asyncOnline bool // Whether getOrAddDatabaseConfig should block until database is ready, when startOffline=false
loadFromBucket bool // If this is load config from bucket operation
}
func (sc *ServerContext) CreateLocalDatabase(ctx context.Context, dbs DbConfigMap) error {
for _, dbConfig := range dbs {
dbc := dbConfig.ToDatabaseConfig()
_, err := sc._getOrAddDatabaseFromConfig(ctx, *dbc, getOrAddDatabaseConfigOptions{
useExisting: false,
failFast: false,
})
if err != nil {
return err
}
}
return nil
}
func (sc *ServerContext) SetCpuPprofFile(file *os.File) {
sc.cpuPprofFileMutex.Lock()
sc.cpuPprofFile = file
sc.cpuPprofFileMutex.Unlock()
}
func (sc *ServerContext) CloseCpuPprofFile(ctx context.Context) (filename string) {
sc.cpuPprofFileMutex.Lock()
if sc.cpuPprofFile != nil {
filename = sc.cpuPprofFile.Name()
}
if err := sc.cpuPprofFile.Close(); err != nil {
base.WarnfCtx(ctx, "Error closing CPU profile file: %v", err)
}
sc.cpuPprofFile = nil
sc.cpuPprofFileMutex.Unlock()
return filename
}
func NewServerContext(ctx context.Context, config *StartupConfig, persistentConfig bool) *ServerContext {
sc := &ServerContext{
Config: config,
persistentConfig: persistentConfig,
dbRegistry: map[string]struct{}{},
collectionRegistry: map[string]string{},
dbConfigs: map[string]*RuntimeDatabaseConfig{},
databases_: map[string]*db.DatabaseContext{},
DatabaseInitManager: &DatabaseInitManager{},
HTTPClient: http.DefaultClient,
statsContext: &statsContext{heapProfileEnabled: !config.HeapProfileDisableCollection},
BootstrapContext: &bootstrapContext{sgVersion: *base.ProductVersion},
hasStarted: make(chan struct{}),
_httpServers: map[serverType]*serverInfo{},
}
sc.invalidDatabaseConfigTracking = invalidDatabaseConfigs{
dbNames: map[string]*invalidConfigInfo{},
}
if base.ServerIsWalrus(sc.Config.Bootstrap.Server) {
// Disable Admin API authentication when running as walrus on the default admin interface to support dev
// environments.
if sc.Config.API.AdminInterface == DefaultAdminInterface {
sc.Config.API.AdminInterfaceAuthentication = base.Ptr(false)
sc.Config.API.MetricsInterfaceAuthentication = base.Ptr(false)
}
}
if config.Replicator.MaxConcurrentReplications != 0 {
sc.ActiveReplicationsCounter.activeReplicatorLimit = config.Replicator.MaxConcurrentReplications
}
if config.HeapProfileCollectionThreshold != nil {
sc.statsContext.heapProfileCollectionThreshold = *config.HeapProfileCollectionThreshold
} else {
memoryTotal := getTotalMemory(ctx)
if memoryTotal != 0 {
sc.statsContext.heapProfileCollectionThreshold = uint64(float64(memoryTotal) * 0.85)
} else {
base.WarnfCtx(ctx, "Could not determine system memory, disabling automatic heap profile collection")
sc.statsContext.heapProfileEnabled = false
}
}
sc.startStatsLogger(ctx)
return sc
}
func (sc *ServerContext) WaitForRESTAPIs(ctx context.Context) error {
timeout := 30 * time.Second
interval := time.Millisecond * 100
numAttempts := int(timeout / interval)
ctx, cancelFn := context.WithTimeout(ctx, timeout)
defer cancelFn()
err, _ := base.RetryLoop(ctx, "Wait for REST APIs", func() (shouldRetry bool, err error, value interface{}) {
sc.lock.RLock()
defer sc.lock.RUnlock()
if len(sc._httpServers) == len(allServers) {
return false, nil, nil
}
return true, nil, nil
}, base.CreateSleeperFunc(numAttempts, int(interval.Milliseconds())))
return err
}
// getServerAddr returns the address as assigned by the listener. This will return an addressable address, whereas ":0" is a valid value to pass to server.
func (sc *ServerContext) getServerAddr(s serverType) (string, error) {
server, err := sc.getHTTPServer(s)
if err != nil {
return "", err
}
return server.addr.String(), nil
}
func (sc *ServerContext) addHTTPServer(t serverType, s *serverInfo) {
sc.lock.Lock()
defer sc.lock.Unlock()
sc._httpServers[t] = s
}
// getHTTPServer returns information about the given HTTP server.
func (sc *ServerContext) getHTTPServer(t serverType) (*serverInfo, error) {
sc.lock.RLock()
defer sc.lock.RUnlock()
s, ok := sc._httpServers[t]
if !ok {
return nil, fmt.Errorf("server type %q not found running in server context", t)
}
return s, nil
}
// PostStartup runs anything that relies on SG being fully started (i.e. sgreplicate)
func (sc *ServerContext) PostStartup() {
// Delay DatabaseContext processes starting up, e.g. to avoid replication reassignment churn when a Sync Gateway Cluster is being initialized
// TODO: Consider sc.WaitForRESTAPIs for faster startup?
time.Sleep(5 * time.Second)
close(sc.hasStarted)
}
// serverContextStopMaxWait is the maximum amount of time to wait for
// background goroutines to terminate before the server is stopped.
const serverContextStopMaxWait = 30 * time.Second
func (sc *ServerContext) Close(ctx context.Context) {
err := base.TerminateAndWaitForClose(sc.statsContext.terminator, sc.statsContext.doneChan, serverContextStopMaxWait)
if err != nil {
base.InfofCtx(ctx, base.KeyAll, "Couldn't stop stats logger: %v", err)
}
// stop the config polling
err = base.TerminateAndWaitForClose(sc.BootstrapContext.terminator, sc.BootstrapContext.doneChan, serverContextStopMaxWait)
if err != nil {
base.InfofCtx(ctx, base.KeyAll, "Couldn't stop background config update worker: %v", err)
}
sc.lock.Lock()
defer sc.lock.Unlock()
// close cached bootstrap bucket connections
if sc.BootstrapContext != nil && sc.BootstrapContext.Connection != nil {
sc.BootstrapContext.Connection.Close()
}
for _, db := range sc.databases_ {
db.Close(ctx)
_ = db.EventMgr.RaiseDBStateChangeEvent(ctx, db.Name, "offline", "Database context closed", &sc.Config.API.AdminInterface)
}
sc.databases_ = nil
sc.invalidDatabaseConfigTracking.dbNames = nil
for _, s := range sc._httpServers {
if s.server != nil {
base.InfofCtx(ctx, base.KeyHTTP, "Closing HTTP Server: %v", s.addr)
if err := s.server.Close(); err != nil {
base.WarnfCtx(ctx, "Error closing HTTP server %q: %v", s.addr, err)
}
}
}
sc._httpServers = nil
if agent := sc.GoCBAgent; agent != nil {
if err := agent.Close(); err != nil {
base.WarnfCtx(ctx, "Error closing agent connection: %v", err)
}
}
}
// GetDatabase attempts to return the DatabaseContext of the database. It will load the database if necessary.
func (sc *ServerContext) GetDatabase(ctx context.Context, name string) (*db.DatabaseContext, error) {
dbc, err := sc.GetActiveDatabase(name)
if err == base.ErrNotFound {
dbc, _, err := sc.GetInactiveDatabase(ctx, name)
return dbc, err
}
return dbc, err
}
// GetActiveDatabase attempts to return the DatabaseContext of a loaded database. If not found, the database name will be
// validated to make sure it's valid and then an error returned.
func (sc *ServerContext) GetActiveDatabase(name string) (*db.DatabaseContext, error) {
sc.lock.RLock()
dbc := sc.databases_[name]
sc.lock.RUnlock()
if dbc != nil {
return dbc, nil
} else if db.ValidateDatabaseName(name) != nil {
return nil, base.HTTPErrorf(http.StatusBadRequest, "invalid database name %q", name)
}
return nil, base.ErrNotFound
}
// GetInactiveDatabase attempts to load the database and return it's DatabaseContext. It will first attempt to unsuspend the
// database, and if that fails, try to load the database from the buckets.
// This should be used if GetActiveDatabase fails. Turns the database context, a variable to say if the config exists, and an error.
func (sc *ServerContext) GetInactiveDatabase(ctx context.Context, name string) (*db.DatabaseContext, bool, error) {
dbc, err := sc.unsuspendDatabase(ctx, name)
if err != nil && err != base.ErrNotFound && err != ErrSuspendingDisallowed {
return nil, false, err
} else if err == nil {
return dbc, true, nil
}
var dbConfigFound bool
// database not loaded, fallback to fetching it from cluster
if sc.BootstrapContext.Connection != nil {
if sc.Config.IsServerless() {
dbConfigFound, _ = sc.fetchAndLoadDatabaseSince(ctx, name, sc.Config.Unsupported.Serverless.MinConfigFetchInterval)
} else {
dbConfigFound, _ = sc.fetchAndLoadDatabase(base.NewNonCancelCtx(), name, false)
}
if dbConfigFound {
sc.lock.RLock()
defer sc.lock.RUnlock()
dbc := sc.databases_[name]
if dbc != nil {
return dbc, dbConfigFound, nil
}
}
}
// handle the correct error message being returned for a corrupt database config
var httpErr *base.HTTPError
invalidConfig, ok := sc.invalidDatabaseConfigTracking.exists(name)
if !dbConfigFound && ok {
httpErr = sc.buildErrorMessage(name, invalidConfig)
} else {
httpErr = base.HTTPErrorf(http.StatusNotFound, "no such database %q", name)
}
return nil, dbConfigFound, httpErr
}
// buildErrorMessage will build appropriate http error message based on the invalidConfig
func (sc *ServerContext) buildErrorMessage(dbName string, invalidConfig *invalidConfigInfo) *base.HTTPError {
if invalidConfig.databaseError != nil {
err := base.HTTPErrorf(http.StatusNotFound, "Database %s has an invalid configuration: %v. You must update database config immediately through create db process", dbName, invalidConfig.databaseError.ErrMsg)
return err
}
if invalidConfig.collectionConflicts {
err := base.HTTPErrorf(http.StatusNotFound, "Database %s has conflicting collections. You must update database config immediately through create db process", dbName)
return err
}
return base.HTTPErrorf(http.StatusNotFound, "Mismatch in database config for database %s bucket name: %s and backend bucket: %s groupID: %s You must update database config immediately", base.MD(dbName), base.MD(invalidConfig.configBucketName), base.MD(invalidConfig.persistedBucketName), base.MD(sc.Config.Bootstrap.ConfigGroupID))
}
func (sc *ServerContext) GetDbConfig(name string) *DbConfig {
if dbConfig := sc.GetDatabaseConfig(name); dbConfig != nil {
return &dbConfig.DbConfig
}
return nil
}
func (sc *ServerContext) GetDatabaseConfig(name string) *RuntimeDatabaseConfig {
sc.lock.RLock()
config, ok := sc.dbConfigs[name]
sc.lock.RUnlock()
if !ok {
return nil
}
return config
}
func (sc *ServerContext) AllDatabaseNames() []string {
sc.lock.RLock()
defer sc.lock.RUnlock()
names := make([]string, 0, len(sc.databases_))
for name := range sc.databases_ {
names = append(names, name)
}
slices.Sort(names)
return names
}
func (sc *ServerContext) allDatabaseSummaries() []DbSummary {
sc.lock.RLock()
defer sc.lock.RUnlock()
dbs := make([]DbSummary, 0, len(sc.databases_))
for name, dbctx := range sc.databases_ {
state := db.RunStateString[atomic.LoadUint32(&dbctx.State)]
summary := DbSummary{
DBName: name,
Bucket: dbctx.Bucket.GetName(),
State: state,
DatabaseError: dbctx.DatabaseStartupError,
}
if state == db.RunStateString[db.DBOffline] {
if len(dbctx.RequireResync.ScopeAndCollectionNames()) > 0 {
summary.RequireResync = true
}
}
if sc.DatabaseInitManager.HasActiveInitialization(name) {
summary.InitializationActive = true
}
dbs = append(dbs, summary)
}
sc.invalidDatabaseConfigTracking.m.RLock()
defer sc.invalidDatabaseConfigTracking.m.RUnlock()
for name, invalidConfig := range sc.invalidDatabaseConfigTracking.dbNames {
// skip adding any invalid dbs with no error associated with them or that exist in above list
if invalidConfig.databaseError == nil || sc.databases_[name] != nil {
continue
}
summary := DbSummary{
DBName: name,
Bucket: invalidConfig.configBucketName,
State: db.RunStateString[db.DBOffline], // db can always be reported as offline if we have an invalid config
DatabaseError: invalidConfig.databaseError,
}
dbs = append(dbs, summary)
}
sort.Slice(dbs, func(i, j int) bool {
return dbs[i].DBName < dbs[j].DBName
})
return dbs
}
// AllDatabases returns a copy of the databases_ map.
func (sc *ServerContext) AllDatabases() map[string]*db.DatabaseContext {
sc.lock.RLock()
defer sc.lock.RUnlock()
databases := make(map[string]*db.DatabaseContext, len(sc.databases_))
for name, database := range sc.databases_ {
databases[name] = database
}
return databases
}
type PostUpgradeResult map[string]PostUpgradeDatabaseResult
type PostUpgradeDatabaseResult struct {
RemovedDDocs []string `json:"removed_design_docs"`
RemovedIndexes []string `json:"removed_indexes"`
}
// PostUpgrade performs post-upgrade processing for each database
func (sc *ServerContext) PostUpgrade(ctx context.Context, preview bool) (postUpgradeResults PostUpgradeResult, err error) {
sc.lock.RLock()
defer sc.lock.RUnlock()
postUpgradeResults = make(map[string]PostUpgradeDatabaseResult, len(sc.databases_))
for name, database := range sc.databases_ {
// View cleanup
removedDDocs, _ := database.RemoveObsoleteDesignDocs(ctx, preview)
// Index cleanup
var removedIndexes []string
if !base.TestsDisableGSI() {
removedIndexes, _ = database.RemoveObsoleteIndexes(ctx, preview)
}
postUpgradeResults[name] = PostUpgradeDatabaseResult{
RemovedDDocs: removedDDocs,
RemovedIndexes: removedIndexes,
}
}
return postUpgradeResults, nil
}
// Removes and re-adds a database to the ServerContext.
func (sc *ServerContext) _reloadDatabase(ctx context.Context, reloadDbName string, failFast bool, forceOnline bool) (*db.DatabaseContext, error) {
sc._unloadDatabase(ctx, reloadDbName)
config := sc.dbConfigs[reloadDbName]
return sc._getOrAddDatabaseFromConfig(ctx, config.DatabaseConfig, getOrAddDatabaseConfigOptions{
useExisting: true,
failFast: failFast,
forceOnline: forceOnline,
})
}
// Removes and re-adds a database to the ServerContext.
func (sc *ServerContext) ReloadDatabase(ctx context.Context, reloadDbName string, forceOnline bool) (*db.DatabaseContext, error) {
// Obtain write lock during add database, to avoid race condition when creating based on ConfigServer
sc.lock.Lock()
dbContext, err := sc._reloadDatabase(ctx, reloadDbName, false, forceOnline)
sc.lock.Unlock()
return dbContext, err
}
func (sc *ServerContext) ReloadDatabaseWithConfig(nonContextStruct base.NonCancellableContext, config DatabaseConfig) error {
sc.lock.Lock()
defer sc.lock.Unlock()
return sc._reloadDatabaseWithConfig(nonContextStruct.Ctx, config, true, false)
}
func (sc *ServerContext) _reloadDatabaseWithConfig(ctx context.Context, config DatabaseConfig, failFast bool, loadFromBucket bool) error {
sc._removeDatabase(ctx, config.Name)
// use async initialization whenever using persistent config
asyncOnline := sc.persistentConfig
_, err := sc._getOrAddDatabaseFromConfig(ctx, config, getOrAddDatabaseConfigOptions{
useExisting: false,
failFast: failFast,
asyncOnline: asyncOnline,
loadFromBucket: loadFromBucket,
})
return err
}
// Adds a database to the ServerContext. Attempts a read after it gets the write
// lock to see if it's already been added by another process. If so, returns either the
// existing DatabaseContext or an error based on the useExisting flag.
func (sc *ServerContext) getOrAddDatabaseFromConfig(ctx context.Context, config DatabaseConfig, options getOrAddDatabaseConfigOptions) (*db.DatabaseContext, error) {
// Obtain write lock during add database, to avoid race condition when creating based on ConfigServer
sc.lock.Lock()
defer sc.lock.Unlock()
return sc._getOrAddDatabaseFromConfig(ctx, config, options)
}
// GetBucketSpec returns a BucketSpec from a given DatabaseConfig and StartupConfig.
func GetBucketSpec(ctx context.Context, config *DatabaseConfig, serverConfig *StartupConfig) (base.BucketSpec, error) {
var server string
if config.Server != nil {
server = *config.Server
} else {
server = serverConfig.Bootstrap.Server
}
if serverConfig.IsServerless() {
params := base.DefaultServerlessGoCBConnStringParams()
if config.Unsupported != nil {
if config.Unsupported.DCPReadBuffer != 0 {
params.DcpBufferSize = config.Unsupported.DCPReadBuffer
}
if config.Unsupported.KVBufferSize != 0 {
params.KvBufferSize = config.Unsupported.KVBufferSize
}
}
connStr, err := base.GetGoCBConnStringWithDefaults(server, params)
if err != nil {
return base.BucketSpec{}, err
}
server = connStr
}
spec := config.MakeBucketSpec(server)
if serverConfig.Bootstrap.ServerTLSSkipVerify != nil {
spec.TLSSkipVerify = *serverConfig.Bootstrap.ServerTLSSkipVerify
}
if spec.BucketName == "" {
spec.BucketName = config.Name
}
spec.FeedType = strings.ToLower(config.FeedType)
if config.ViewQueryTimeoutSecs != nil {
spec.ViewQueryTimeoutSecs = config.ViewQueryTimeoutSecs
}
spec.UseXattrs = config.UseXattrs()
if !spec.UseXattrs {
base.WarnfCtx(ctx, "Running Sync Gateway without shared bucket access is deprecated. Recommendation: set enable_shared_bucket_access=true")
}
if config.BucketOpTimeoutMs != nil {
operationTimeout := time.Millisecond * time.Duration(*config.BucketOpTimeoutMs)
spec.BucketOpTimeout = &operationTimeout
}
return spec, nil
}
// Adds a database to the ServerContext. Attempts a read after it gets the write
// lock to see if it's already been added by another process. If so, returns either the
// existing DatabaseContext or an error based on the useExisting flag.
// Pass in a bucketFromBucketSpecFn to replace the default ConnectToBucket function. This will cause the failFast argument to be ignored
func (sc *ServerContext) _getOrAddDatabaseFromConfig(ctx context.Context, config DatabaseConfig, options getOrAddDatabaseConfigOptions) (dbcontext *db.DatabaseContext, returnedError error) {
var bucket base.Bucket
// Generate bucket spec and validate whether db already exists
spec, err := GetBucketSpec(ctx, &config, sc.Config)
if err != nil {
return nil, err
}
dbName := config.Name
if dbName == "" {
dbName = spec.BucketName
}
// we do not have per database logging parameters, but it is still useful to have the database name in the log context. This must be set again after dbcOptionsFromConfig is called.
ctx = base.DatabaseLogCtx(ctx, dbName, nil)
defer func() {
if returnedError == nil {
return
}
// database exists in global map, management is deferred to REST api
_, dbRegistered := sc.databases_[dbName]
if dbRegistered {
return
}
if dbcontext != nil {
dbcontext.Close(ctx) // will close underlying bucket
} else if bucket != nil {
bucket.Close(ctx)
}
}()
if err := db.ValidateDatabaseName(dbName); err != nil {
return nil, err
}
previousDatabase := sc.databases_[dbName]
if previousDatabase != nil {
if options.useExisting {
return previousDatabase, nil
}
return nil, base.HTTPErrorf(http.StatusPreconditionFailed, // what CouchDB returns
"Duplicate database name %q", dbName)
}
// Generate database context options from config and server context
contextOptions, err := dbcOptionsFromConfig(ctx, sc, &config.DbConfig, dbName)
if err != nil {
return nil, err
}
// set this early so we have dbName available in db-init related logging, before we have an actual database
ctx = base.DatabaseLogCtx(ctx, dbName, contextOptions.LoggingConfig)
if spec.Server == "" {
spec.Server = sc.Config.Bootstrap.Server
}
// Connect to bucket
base.InfofCtx(ctx, base.KeyAll, "Opening db /%s as bucket %q, pool %q, server <%s>",
base.MD(dbName), base.MD(spec.BucketName), base.SD(base.DefaultPool), base.SD(spec.Server))
// the connectToBucketFn is used for testing seam
if options.connectToBucketFn != nil {
// the connectToBucketFn is used for testing seam
bucket, err = options.connectToBucketFn(ctx, spec, options.failFast)
} else {
bucket, err = db.ConnectToBucket(ctx, spec, options.failFast)
}
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseBucketConnectionError))
}
return nil, err
}
// If using a walrus bucket, force use of views
useViews := base.ValDefault(config.UseViews, false)
if !useViews && spec.IsWalrusBucket() {
base.WarnfCtx(ctx, "Using GSI is not supported when using a walrus bucket - switching to use views. Set 'use_views':true in Sync Gateway's database config to avoid this warning.")
useViews = true
}
hasDefaultCollection := false
collectionsRequiringResync := make([]base.ScopeAndCollectionName, 0)
if len(config.Scopes) > 0 {
if !bucket.IsSupported(sgbucket.BucketStoreFeatureCollections) {
return nil, errCollectionsUnsupported
}
for scopeName, scopeConfig := range config.Scopes {
for collectionName := range scopeConfig.Collections {
scName := base.ScopeAndCollectionName{Scope: scopeName, Collection: collectionName}
if scName.IsDefault() {
hasDefaultCollection = true
}
dataStore, err := base.GetAndWaitUntilDataStoreReady(ctx, bucket, scName, options.failFast)
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseInvalidDatastore))
}
return nil, fmt.Errorf("error attempting to create/update database: %w", err)
}
// Init views now. If we're using GSI we'll use DatabaseInitManager to handle creation later.
if useViews {
if err := db.InitializeViews(ctx, dataStore); err != nil {
return nil, err
}
}
// Verify whether the collection is associated with a different database's metadataID - if so, add to set requiring resync
resyncRequired, err := base.InitSyncInfo(dataStore, config.MetadataID)
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseInitSyncInfoError))
}
return nil, err
}
if resyncRequired {
collectionsRequiringResync = append(collectionsRequiringResync, scName)
}
}
}
}
// no scopes, or the set of collections didn't include `_default` and we'll need to initialize it for metadata.
if !hasDefaultCollection {
ds := bucket.DefaultDataStore()
// No explicitly defined scopes means we'll initialize this as a usable default collection, otherwise it's for metadata only
if len(config.Scopes) == 0 {
scName := base.DefaultScopeAndCollectionName()
resyncRequired, err := base.InitSyncInfo(ds, config.MetadataID)
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseInitSyncInfoError))
}
return nil, err
}
if resyncRequired {
collectionsRequiringResync = append(collectionsRequiringResync, scName)
}
}
if useViews {
if err := db.InitializeViews(ctx, ds); err != nil {
return nil, err
}
}
}
var (
dbInitDoneChan chan error
isAsync bool // blocks reading dbInitDoneChan if false
)
startOffline := base.ValDefault(config.StartOffline, false)
if !useViews {
// Initialize any required indexes
if gsiSupported := bucket.IsSupported(sgbucket.BucketStoreFeatureN1ql); !gsiSupported {
return nil, errors.New("Sync Gateway was unable to connect to a query node on the provided Couchbase Server cluster. Ensure a query node is accessible, or set 'use_views':true in Sync Gateway's database config.")
}
if sc.DatabaseInitManager == nil {
base.AssertfCtx(ctx, "DatabaseInitManager should always be initialized")
return nil, errors.New("DatabaseInitManager not initialized")
}
// If database has been requested to start offline, or there's an active async initialization, use async initialization
isAsync = startOffline || sc.DatabaseInitManager.HasActiveInitialization(dbName)
useLegacySyncDocsIndex := true // decide in CBG-4615
// Initialize indexes using DatabaseInitManager.
dbInitDoneChan, err = sc.DatabaseInitManager.InitializeDatabase(ctx, sc.Config, &config, useLegacySyncDocsIndex)
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseInitializationIndexError))
}
return nil, err
}
}
autoImport, err := config.AutoImportEnabled(ctx)
if err != nil {
return nil, err
}
contextOptions.UseViews = useViews
javascriptTimeout := getJavascriptTimeout(&config.DbConfig)
fqCollections := make([]string, 0)
if len(config.Scopes) > 0 {
if !sc.persistentConfig && !sc.allowScopesInPersistentConfig {
return nil, base.HTTPErrorf(http.StatusBadRequest, "scopes are not allowed with legacy config")
}
contextOptions.Scopes = make(db.ScopesOptions, len(config.Scopes))
for scopeName, scopeCfg := range config.Scopes {
contextOptions.Scopes[scopeName] = db.ScopeOptions{
Collections: make(map[string]db.CollectionOptions, len(scopeCfg.Collections)),
}
for collName, collCfg := range scopeCfg.Collections {
ctx := base.CollectionLogCtx(ctx, scopeName, collName)
var importFilter *db.ImportFilterFunction
if collCfg.ImportFilter != nil {
importFilter = db.NewImportFilterFunction(ctx, *collCfg.ImportFilter, javascriptTimeout)
}
contextOptions.Scopes[scopeName].Collections[collName] = db.CollectionOptions{
Sync: collCfg.SyncFn,
ImportFilter: importFilter,
}
fqCollections = append(fqCollections, base.FullyQualifiedCollectionName(spec.BucketName, scopeName, collName))
}
}
} else {
// Set up default import filter
var importFilter *db.ImportFilterFunction
if config.ImportFilter != nil {
importFilter = db.NewImportFilterFunction(ctx, *config.ImportFilter, javascriptTimeout)
}
contextOptions.Scopes = map[string]db.ScopeOptions{
base.DefaultScope: db.ScopeOptions{
Collections: map[string]db.CollectionOptions{
base.DefaultCollection: {
Sync: config.Sync,
ImportFilter: importFilter,
},
},
},
}
}
// For now, we'll continue writing metadata into `_default`.`_default`, for a few reasons:
// - we know it is supported in all server versions
// - it cannot be dropped by customers, we always know it exists
// - it simplifies RBAC in terms of not having to create a metadata collection
// Once system scope/collection is well-supported, and we have a migration path, we can consider using those.
// contextOptions.MetadataStore = bucket.NamedDataStore(base.ScopeAndCollectionName{base.MobileMetadataScope, base.MobileMetadataCollection})
contextOptions.MetadataStore = bucket.DefaultDataStore()
err = validateMetadataStore(ctx, contextOptions.MetadataStore)
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseInvalidDatastore))
}
return nil, err
}
// If identified as default database, use metadataID of "" so legacy non namespaced docs are used
if config.MetadataID != defaultMetadataID {
contextOptions.MetadataID = config.MetadataID
}
contextOptions.BlipStatsReportingInterval = defaultBytesStatsReportingInterval.Milliseconds()
contextOptions.ImportVersion = config.ImportVersion
// Create the DB Context
dbcontext, err = db.NewDatabaseContext(ctx, dbName, bucket, autoImport, contextOptions)
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseCreateDatabaseContextError))
}
return nil, err
}
dbcontext.BucketSpec = spec
dbcontext.ServerContextHasStarted = sc.hasStarted
dbcontext.NoX509HTTPClient = sc.NoX509HTTPClient
dbcontext.RequireResync = collectionsRequiringResync
if config.CORS != nil {
dbcontext.CORS = config.DbConfig.CORS
} else {
dbcontext.CORS = sc.Config.API.CORS
}
if config.RevsLimit != nil {
dbcontext.RevsLimit = *config.RevsLimit
if dbcontext.AllowConflicts() {
if dbcontext.RevsLimit < 20 {
return nil, fmt.Errorf("The revs_limit (%v) value in your Sync Gateway configuration cannot be set lower than 20.", dbcontext.RevsLimit)
}
if dbcontext.RevsLimit < db.DefaultRevsLimitConflicts {
base.WarnfCtx(ctx, "Setting the revs_limit (%v) to less than %d, whilst having allow_conflicts set to true, may have unwanted results when documents are frequently updated. Please see documentation for details.", dbcontext.RevsLimit, db.DefaultRevsLimitConflicts)
}
} else if dbcontext.RevsLimit <= 0 {
return nil, fmt.Errorf("The revs_limit (%v) value in your Sync Gateway configuration must be greater than zero.", dbcontext.RevsLimit)
}
}
dbcontext.AllowEmptyPassword = base.ValDefault(config.AllowEmptyPassword, false)
dbcontext.ServeInsecureAttachmentTypes = base.ValDefault(config.ServeInsecureAttachmentTypes, false)
dbcontext.Options.ConfigPrincipals = &db.ConfigPrincipals{
Users: config.Users,
Roles: config.Roles,
Guest: config.Guest,
}
// Initialize event handlers
if err := sc.initEventHandlers(ctx, dbcontext, &config.DbConfig); err != nil {
return nil, err
}
cfgReplications, err := dbcontext.SGReplicateMgr.GetReplications()
if err != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseSGRClusterError))
}
return nil, err
}
// PUT replications that do not exist
newReplications := make(map[string]*db.ReplicationConfig)
for name, replication := range config.Replications {
_, ok := cfgReplications[name]
if ok {
continue
}
newReplications[name] = replication
}
replicationErr := dbcontext.SGReplicateMgr.PutReplications(ctx, newReplications)
if replicationErr != nil {
if options.loadFromBucket {
sc._handleInvalidDatabaseConfig(ctx, spec.BucketName, config, db.NewDatabaseError(db.DatabaseCreateReplicationError))
}
return nil, replicationErr
}
// startOnlineProcesses will be set to true if the database should be started, either synchronously or asynchronously
startOnlineProcesses := true
needsResync := len(collectionsRequiringResync) > 0
if needsResync || (startOffline && !options.forceOnline) {
startOnlineProcesses = false
var stateChangeMsg string
if needsResync {
stateChangeMsg = "Resync required for collections"
} else {
stateChangeMsg = dbLoadedStateChangeMsg + " in offline state"
}
// Defer state change event to after the databases are registered. This should not matter because this function holds ServerContext.lock and databases_ can't be read while the lock is present.
defer func() {
atomic.StoreUint32(&dbcontext.State, db.DBOffline)
_ = dbcontext.EventMgr.RaiseDBStateChangeEvent(ctx, dbName, "offline", stateChangeMsg, &sc.Config.API.AdminInterface)
}()
} else {
atomic.StoreUint32(&dbcontext.State, db.DBStarting)
}
// Register it so HTTP handlers can find it:
sc.databases_[dbcontext.Name] = dbcontext
sc.dbConfigs[dbcontext.Name] = &RuntimeDatabaseConfig{DatabaseConfig: config}
sc.dbRegistry[dbName] = struct{}{}
for _, name := range fqCollections {
sc.collectionRegistry[name] = dbName
}
if !startOnlineProcesses {
return dbcontext, nil
}
// If asyncOnline wasn't specified, block until db init is completed, then start online processes
if !options.asyncOnline || !isAsync {
dbcontext.WasInitializedSynchronously = true
base.InfofCtx(ctx, base.KeyAll, "Waiting for database init to complete...")
if dbInitDoneChan != nil {
initError := <-dbInitDoneChan
if initError != nil {
dbcontext.DbStats.DatabaseStats.TotalInitFatalErrors.Add(1)
// report error in building/creating indexes
dbcontext.DatabaseStartupError = db.NewDatabaseError(db.DatabaseInitializationIndexError)
atomic.StoreUint32(&dbcontext.State, db.DBOffline)
_ = dbcontext.EventMgr.RaiseDBStateChangeEvent(ctx, dbName, "offline", dbLoadedStateChangeMsg, &sc.Config.API.AdminInterface)
return nil, initError
}
}
base.InfofCtx(ctx, base.KeyAll, "Database init completed, starting online processes")
if err := dbcontext.StartOnlineProcesses(ctx); err != nil {
dbcontext.DbStats.DatabaseStats.TotalOnlineFatalErrors.Add(1)
atomic.StoreUint32(&dbcontext.State, db.DBOffline)
_ = dbcontext.EventMgr.RaiseDBStateChangeEvent(ctx, dbName, "offline", dbLoadedStateChangeMsg, &sc.Config.API.AdminInterface)
return nil, err
}
atomic.StoreUint32(&dbcontext.State, db.DBOnline)
_ = dbcontext.EventMgr.RaiseDBStateChangeEvent(ctx, dbName, "online", dbLoadedStateChangeMsg, &sc.Config.API.AdminInterface)
return dbcontext, nil
}
// If asyncOnline is requested, set state to Starting and spawn a separate goroutine to wait for init completion
// before going online
base.InfofCtx(ctx, base.KeyAll, "Waiting for database init to complete asynchonously...")
nonCancelCtx := base.NewNonCancelCtxForDatabase(ctx)
go sc.asyncDatabaseOnline(nonCancelCtx, dbcontext, dbInitDoneChan, config.Version)
return dbcontext, nil
}
// asyncDatabaseOnline waits for async initialization to complete (based on doneChan). On successful completion, brings the database online.
// Checks to ensure the database config hasn't been updated while waiting for init to complete - if that happens, doesn't attempt to bring