-
Notifications
You must be signed in to change notification settings - Fork 141
/
config.go
740 lines (639 loc) · 26.9 KB
/
config.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
// Copyright (c) 2013 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
package rest
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"runtime"
"strings"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/db"
)
// Register profiling handlers (see Go docs)
import _ "net/http/pprof"
var DefaultInterface = ":4984"
var DefaultAdminInterface = "127.0.0.1:4985" // Only accessible on localhost!
var DefaultServer = "walrus:"
var DefaultPool = "default"
var config *ServerConfig
const (
DefaultMaxCouchbaseConnections = 16
DefaultMaxCouchbaseOverflowConnections = 0
// Default value of ServerConfig.MaxIncomingConnections
DefaultMaxIncomingConnections = 0
// Default value of ServerConfig.MaxFileDescriptors
DefaultMaxFileDescriptors uint64 = 5000
)
type SyncGatewayRunMode uint8
const (
SyncGatewayRunModeNormal SyncGatewayRunMode = iota
SyncGatewayRunModeAccel
)
// JSON object that defines the server configuration.
type ServerConfig struct {
Interface *string `json:",omitempty"` // Interface to bind REST API to, default ":4984"
SSLCert *string `json:",omitempty"` // Path to SSL cert file, or nil
SSLKey *string `json:",omitempty"` // Path to SSL private key file, or nil
ServerReadTimeout *int `json:",omitempty"` // maximum duration.Second before timing out read of the HTTP(S) request
ServerWriteTimeout *int `json:",omitempty"` // maximum duration.Second before timing out write of the HTTP(S) response
AdminInterface *string `json:",omitempty"` // Interface to bind admin API to, default ":4985"
AdminUI *string `json:",omitempty"` // Path to Admin HTML page, if omitted uses bundled HTML
ProfileInterface *string `json:",omitempty"` // Interface to bind Go profile API to (no default)
ConfigServer *string `json:",omitempty"` // URL of config server (for dynamic db discovery)
Persona *PersonaConfig `json:",omitempty"` // Configuration for Mozilla Persona validation
Facebook *FacebookConfig `json:",omitempty"` // Configuration for Facebook validation
Google *GoogleConfig `json:",omitempty"` // Configuration for Google validation
CORS *CORSConfig `json:",omitempty"` // Configuration for allowing CORS
Log []string `json:",omitempty"` // Log keywords to enable
LogFilePath *string `json:",omitempty"` // Path to log file, if missing write to stderr
Pretty bool `json:",omitempty"` // Pretty-print JSON responses?
DeploymentID *string `json:",omitempty"` // Optional customer/deployment ID for stats reporting
StatsReportInterval *float64 `json:",omitempty"` // Optional stats report interval (0 to disable)
MaxCouchbaseConnections *int `json:",omitempty"` // Max # of sockets to open to a Couchbase Server node
MaxCouchbaseOverflow *int `json:",omitempty"` // Max # of overflow sockets to open
CouchbaseKeepaliveInterval *int `json:",omitempty"` // TCP keep-alive interval between SG and Couchbase server
SlowServerCallWarningThreshold *int `json:",omitempty"` // Log warnings if database calls take this many ms
MaxIncomingConnections *int `json:",omitempty"` // Max # of incoming HTTP connections to accept
MaxFileDescriptors *uint64 `json:",omitempty"` // Max # of open file descriptors (RLIMIT_NOFILE)
CompressResponses *bool `json:",omitempty"` // If false, disables compression of HTTP responses
Databases DbConfigMap `json:",omitempty"` // Pre-configured databases, mapped by name
Replications []*ReplicationConfig `json:",omitempty"`
MaxHeartbeat uint64 `json:",omitempty"` // Max heartbeat value for _changes request (seconds)
ClusterConfig *ClusterConfig `json:"cluster_config,omitempty"` // Bucket and other config related to CBGT
SkipRunmodeValidation bool `json:"skip_runmode_validation,omitempty"` // If this is true, skips any config validation regarding accel vs normal mode
Unsupported *UnsupportedServerConfig `json:"unsupported,omitempty"` // Config for unsupported features
}
// Bucket configuration elements - used by db, shadow, index
type BucketConfig struct {
Server *string `json:"server,omitempty"` // Couchbase server URL
Pool *string `json:"pool,omitempty"` // Couchbase pool name, default "default"
Bucket *string `json:"bucket,omitempty"` // Bucket name
Username string `json:"username,omitempty"` // Username for authenticating to server
Password string `json:"password,omitempty"` // Password for authenticating to server
}
type ClusterConfig struct {
BucketConfig
DataDir string `json:"data_dir,omitempty"`
HeartbeatIntervalSeconds *uint16 `json:"heartbeat_interval_seconds,omitempty"`
}
func (c ClusterConfig) CBGTEnabled() bool {
// if we have a non-empty server field, then assume CBGT is enabled.
return c.Server != nil && *c.Server != ""
}
// JSON object that defines a database configuration within the ServerConfig.
type DbConfig struct {
BucketConfig
Name string `json:"name,omitempty"` // Database name in REST API (stored as key in JSON)
Sync *string `json:"sync,omitempty"` // Sync function defines which users can see which data
Users map[string]*db.PrincipalConfig `json:"users,omitempty"` // Initial user accounts
Roles map[string]*db.PrincipalConfig `json:"roles,omitempty"` // Initial roles
RevsLimit *uint32 `json:"revs_limit,omitempty"` // Max depth a document's revision tree can grow to
ImportDocs interface{} `json:"import_docs,omitempty"` // false, true, or "continuous"
Shadow *ShadowConfig `json:"shadow,omitempty"` // External bucket to shadow
EventHandlers interface{} `json:"event_handlers,omitempty"` // Event handlers (webhook)
FeedType string `json:"feed_type,omitempty"` // Feed type - "DCP" or "TAP"; defaults based on Couchbase server version
AllowEmptyPassword bool `json:"allow_empty_password,omitempty"` // Allow empty passwords? Defaults to false
CacheConfig *CacheConfig `json:"cache,omitempty"` // Cache settings
ChannelIndex *ChannelIndexConfig `json:"channel_index,omitempty"` // Channel index settings
RevCacheSize *uint32 `json:"rev_cache_size,omitempty"` // Maximum number of revisions to store in the revision cache
StartOffline bool `json:"offline,omitempty"` // start the DB in the offline state, defaults to false
Unsupported *UnsupportedConfig `json:"unsupported,omitempty"` // Config for unsupported features
OIDCConfig *auth.OIDCOptions `json:"oidc,omitempty"` // Config properties for OpenID Connect authentication
}
type DbConfigMap map[string]*DbConfig
type ReplConfigMap map[string]*ReplicationConfig
type PersonaConfig struct {
Origin string // Canonical server URL for Persona authentication
Register bool // If true, server will register new user accounts
}
type FacebookConfig struct {
Register bool // If true, server will register new user accounts
}
type GoogleConfig struct {
Register bool // If true, server will register new user accounts
AppClientID []string `json:"app_client_id"` // list of enabled client ids
}
type CORSConfig struct {
Origin []string // List of allowed origins, use ["*"] to allow access from everywhere
LoginOrigin []string // List of allowed login origins
Headers []string // List of allowed headers
MaxAge int // Maximum age of the CORS Options request
}
type ShadowConfig struct {
BucketConfig
Doc_id_regex *string `json:"doc_id_regex,omitempty"` // Optional regex that doc IDs must match
FeedType string `json:"feed_type,omitempty"` // Feed type - "DCP" or "TAP"; defaults to TAP
}
type EventHandlerConfig struct {
MaxEventProc uint `json:"max_processes,omitempty"` // Max concurrent event handling goroutines
WaitForProcess string `json:"wait_for_process,omitempty"` // Max wait time when event queue is full (ms)
DocumentChanged []*EventConfig `json:"document_changed,omitempty"` // Document Commit
DBStateChanged []*EventConfig `json:"db_state_changed,omitempty"` // DB state change
}
type EventConfig struct {
HandlerType string `json:"handler"` // Handler type
Url string `json:"url,omitempty"` // Url (webhook)
Filter string `json:"filter,omitempty"` // Filter function (webhook)
Timeout *uint64 `json:"timeout,omitempty"` // Timeout (webhook)
}
type CacheConfig struct {
CachePendingSeqMaxWait *uint32 `json:"max_wait_pending,omitempty"` // Max wait for pending sequence before skipping
CachePendingSeqMaxNum *int `json:"max_num_pending,omitempty"` // Max number of pending sequences before skipping
CacheSkippedSeqMaxWait *uint32 `json:"max_wait_skipped,omitempty"` // Max wait for skipped sequence before abandoning
EnableStarChannel *bool `json:"enable_star_channel"` // Enable star channel
ChannelCacheMaxLength *int `json:"channel_cache_max_length"` // Maximum number of entries maintained in cache per channel
ChannelCacheMinLength *int `json:"channel_cache_min_length"` // Minimum number of entries maintained in cache per channel
ChannelCacheAge *int `json:"channel_cache_expiry"` // Time (seconds) to keep entries in cache beyond the minimum retained
}
type ChannelIndexConfig struct {
BucketConfig
IndexWriter bool `json:"writer,omitempty"` // Whether SG node is a channel index writer
NumShards uint16 `json:"num_shards,omitempty"` // Number of partitions in the channel index
SequenceHashConfig *SequenceHashConfig `json:"seq_hashing,omitempty"` // Sequence hash configuration
}
type SequenceHashConfig struct {
BucketConfig // Bucket used for Sequence hashing
Expiry *uint32 `json:"expiry,omitempty"` // Expiry set for hash values on latest use
Frequency *int `json:"hash_frequency,omitempty"` // Frequency of sequence hashing in changes feeds
}
type UnsupportedConfig struct {
UserViews *UserViewsConfig `json:"user_views,omitempty"` // Config settings for user views
OidcTestProvider *OidcTestProviderConfig `json:"oidc_test_provider,omitempty"` // Config settings for OIDC Provider
}
type UnsupportedServerConfig struct {
Http2Config *Http2Config `json:"http2,omitempty"` // Config settings for HTTP2
}
type OidcTestProviderConfig struct {
Enabled *bool `json:"enabled,omitempty"` // Whether the oidc_test_provider endpoints should be exposed on the public API
}
type UserViewsConfig struct {
Enabled *bool `json:"enabled,omitempty"` // Whether pass-through view query is supported through public API
}
type Http2Config struct {
Enabled *bool `json:"enabled,omitempty"` // Whether HTTP2 support is enabled
}
func (dbConfig *DbConfig) setup(name string) error {
dbConfig.Name = name
if dbConfig.Bucket == nil {
dbConfig.Bucket = &dbConfig.Name
}
if dbConfig.Server == nil {
dbConfig.Server = &DefaultServer
}
if dbConfig.Pool == nil {
dbConfig.Pool = &DefaultPool
}
url, err := url.Parse(*dbConfig.Server)
if err == nil && url.User != nil {
// Remove credentials from URL and put them into the DbConfig.Username and .Password:
if dbConfig.Username == "" {
dbConfig.Username = url.User.Username()
}
if dbConfig.Password == "" {
if password, exists := url.User.Password(); exists {
dbConfig.Password = password
}
}
url.User = nil
urlStr := url.String()
dbConfig.Server = &urlStr
}
if dbConfig.Shadow != nil {
url, err = url.Parse(*dbConfig.Shadow.Server)
if err == nil && url.User != nil {
// Remove credentials from shadow URL and put them into the DbConfig.Shadow.Username and .Password:
if dbConfig.Shadow.Username == "" {
dbConfig.Shadow.Username = url.User.Username()
}
if dbConfig.Shadow.Password == "" {
if password, exists := url.User.Password(); exists {
dbConfig.Shadow.Password = password
}
}
url.User = nil
urlStr := url.String()
dbConfig.Shadow.Server = &urlStr
}
}
if dbConfig.ChannelIndex != nil {
url, err = url.Parse(*dbConfig.ChannelIndex.Server)
if err == nil && url.User != nil {
// Remove credentials from shadow URL and put them into the DbConfig.ChannelIndex.Username and .Password:
if dbConfig.ChannelIndex.Username == "" {
dbConfig.ChannelIndex.Username = url.User.Username()
}
if dbConfig.ChannelIndex.Password == "" {
if password, exists := url.User.Password(); exists {
dbConfig.ChannelIndex.Password = password
}
}
url.User = nil
urlStr := url.String()
dbConfig.ChannelIndex.Server = &urlStr
}
}
return err
}
func (dbConfig DbConfig) validate() error {
// if there is a ChannelIndex being used, then the only valid feed type is DCPSHARD
if dbConfig.ChannelIndex != nil {
if strings.ToLower(dbConfig.FeedType) != strings.ToLower(base.DcpShardFeedType) {
msg := "ChannelIndex declared in config, but the FeedType is %v " +
"rather than expected value of DCPSHARD"
return fmt.Errorf(msg, dbConfig.FeedType)
}
}
// if the feed type is DCPSHARD, then there must be a ChannelIndex
if strings.ToLower(dbConfig.FeedType) == strings.ToLower(base.DcpShardFeedType) {
if dbConfig.ChannelIndex == nil {
msg := "FeedType is DCPSHARD, but no ChannelIndex declared in config"
return fmt.Errorf(msg)
}
}
return nil
}
func (dbConfig *DbConfig) modifyConfig() {
if dbConfig.ChannelIndex != nil {
// if there is NO feed type, set to DCPSHARD, since that's the only
// valid config when a Channel Index is specified
if dbConfig.FeedType == "" {
dbConfig.FeedType = base.DcpShardFeedType
}
}
}
// Implementation of AuthHandler interface for DbConfig
func (dbConfig *DbConfig) GetCredentials() (string, string, string) {
return base.TransformBucketCredentials(dbConfig.Username, dbConfig.Password, *dbConfig.Bucket)
}
// Implementation of AuthHandler interface for ShadowConfig
func (shadowConfig *ShadowConfig) GetCredentials() (string, string, string) {
return base.TransformBucketCredentials(shadowConfig.Username, shadowConfig.Password, *shadowConfig.Bucket)
}
// Implementation of AuthHandler interface for ChannelIndexConfig
func (channelIndexConfig *ChannelIndexConfig) GetCredentials() (string, string, string) {
return base.TransformBucketCredentials(channelIndexConfig.Username, channelIndexConfig.Password, *channelIndexConfig.Bucket)
}
// Reads a ServerConfig from raw data
func ReadServerConfigFromData(data []byte) (*ServerConfig, error) {
data = base.ConvertBackQuotedStrings(data)
var config *ServerConfig
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
// Validation:
if err := config.setupAndValidateDatabases(); err != nil {
return nil, err
}
return config, nil
}
// Reads a ServerConfig from a URL.
func ReadServerConfigFromUrl(url string) (*ServerConfig, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return ReadServerConfigFromData(responseBody)
}
// Reads a ServerConfig from either a JSON file or from a URL.
func ReadServerConfig(path string) (*ServerConfig, error) {
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
return ReadServerConfigFromUrl(path)
} else {
return ReadServerConfigFromFile(path)
}
}
// Reads a ServerConfig from a JSON file.
func ReadServerConfigFromFile(path string) (*ServerConfig, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
data = base.ConvertBackQuotedStrings(data)
var config *ServerConfig
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
// Validation:
if err := config.setupAndValidateDatabases(); err != nil {
return nil, err
}
return config, nil
}
func (config *ServerConfig) setupAndValidateDatabases() error {
for name, dbConfig := range config.Databases {
dbConfig.setup(name)
if err := config.validateDbConfig(dbConfig); err != nil {
return err
}
}
return nil
}
func (config *ServerConfig) validateDbConfig(dbConfig *DbConfig) error {
dbConfig.modifyConfig()
return dbConfig.validate()
}
func (self *ServerConfig) MergeWith(other *ServerConfig) error {
if self.Interface == nil {
self.Interface = other.Interface
}
if self.AdminInterface == nil {
self.AdminInterface = other.AdminInterface
}
if self.ProfileInterface == nil {
self.ProfileInterface = other.ProfileInterface
}
if self.ConfigServer == nil {
self.ConfigServer = other.ConfigServer
}
if self.DeploymentID == nil {
self.DeploymentID = other.DeploymentID
}
if self.Persona == nil {
self.Persona = other.Persona
}
if self.Facebook == nil {
self.Facebook = other.Facebook
}
if self.CORS == nil {
self.CORS = other.CORS
}
for _, flag := range other.Log {
self.Log = append(self.Log, flag)
}
if other.Pretty {
self.Pretty = true
}
for name, db := range other.Databases {
if self.Databases[name] != nil {
return fmt.Errorf("Database %q already specified earlier", name)
}
self.Databases[name] = db
}
return nil
}
// Reads the command line flags and the optional config file.
func ParseCommandLine() {
siteURL := flag.String("personaOrigin", "", "Base URL that clients use to connect to the server")
addr := flag.String("interface", DefaultInterface, "Address to bind to")
authAddr := flag.String("adminInterface", DefaultAdminInterface, "Address to bind admin interface to")
profAddr := flag.String("profileInterface", "", "Address to bind profile interface to")
configServer := flag.String("configServer", "", "URL of server that can return database configs")
deploymentID := flag.String("deploymentID", "", "Customer/project identifier for stats reporting")
couchbaseURL := flag.String("url", DefaultServer, "Address of Couchbase server")
poolName := flag.String("pool", DefaultPool, "Name of pool")
bucketName := flag.String("bucket", "sync_gateway", "Name of bucket")
dbName := flag.String("dbname", "", "Name of Couchbase Server database (defaults to name of bucket)")
pretty := flag.Bool("pretty", false, "Pretty-print JSON responses")
verbose := flag.Bool("verbose", false, "Log more info about requests")
logKeys := flag.String("log", "", "Log keywords, comma separated")
logFilePath := flag.String("logFilePath", "", "Path to log file")
skipRunModeValidation := flag.Bool("skipRunModeValidation", false, "Skip config validation for runmode (accel vs normal sg)")
flag.Parse()
if flag.NArg() > 0 {
// Read the configuration file(s), if any:
for i := 0; i < flag.NArg(); i++ {
filename := flag.Arg(i)
c, err := ReadServerConfig(filename)
if err != nil {
base.LogFatal("Error reading config file %s: %v", filename, err)
}
if config == nil {
config = c
} else {
if err := config.MergeWith(c); err != nil {
base.LogFatal("Error reading config file %s: %v", filename, err)
}
}
}
// Override the config file with global settings from command line flags:
if *addr != DefaultInterface {
config.Interface = addr
}
if *authAddr != DefaultAdminInterface {
config.AdminInterface = authAddr
}
if *profAddr != "" {
config.ProfileInterface = profAddr
}
if *configServer != "" {
config.ConfigServer = configServer
}
if *deploymentID != "" {
config.DeploymentID = deploymentID
}
if *pretty {
config.Pretty = *pretty
}
if config.Log != nil {
base.ParseLogFlags(config.Log)
}
// If the interfaces were not specified in either the config file or
// on the command line, set them to the default values
if config.Interface == nil {
config.Interface = &DefaultInterface
}
if config.AdminInterface == nil {
config.AdminInterface = &DefaultAdminInterface
}
if *logFilePath != "" {
config.LogFilePath = logFilePath
}
if *skipRunModeValidation == true {
config.SkipRunmodeValidation = *skipRunModeValidation
}
} else {
// If no config file is given, create a default config, filled in from command line flags:
if *dbName == "" {
*dbName = *bucketName
}
// At this point the addr is either:
// - A value provided by the user, in which case we want to leave it as is
// - The default value (":4984"), which is actually _not_ the default value we
// want for this case, since we are enabling insecure mode. We want "localhost:4984" instead.
// See #708 for more details
if *addr == DefaultInterface {
*addr = "localhost:4984"
}
config = &ServerConfig{
Interface: addr,
AdminInterface: authAddr,
ProfileInterface: profAddr,
Pretty: *pretty,
Databases: map[string]*DbConfig{
*dbName: {
Name: *dbName,
BucketConfig: BucketConfig{
Server: couchbaseURL,
Bucket: bucketName,
Pool: poolName,
},
Users: map[string]*db.PrincipalConfig{
base.GuestUsername: {
Disabled: false,
ExplicitChannels: base.SetFromArray([]string{"*"}),
},
},
},
},
}
}
if *siteURL != "" {
if config.Persona == nil {
config.Persona = new(PersonaConfig)
}
config.Persona.Origin = *siteURL
}
base.EnableLogKey("HTTP")
if *verbose {
base.EnableLogKey("HTTP+")
}
base.ParseLogFlag(*logKeys)
//return config
}
func SetMaxFileDescriptors(maxP *uint64) {
maxFDs := DefaultMaxFileDescriptors
if maxP != nil {
maxFDs = *maxP
}
_, err := base.SetMaxFileDescriptors(maxFDs)
if err != nil {
base.Warn("Error setting MaxFileDescriptors to %d: %v", maxFDs, err)
}
}
func (config *ServerConfig) Serve(addr string, handler http.Handler) {
maxConns := DefaultMaxIncomingConnections
if config.MaxIncomingConnections != nil {
maxConns = *config.MaxIncomingConnections
}
http2Enabled := false
if config.Unsupported != nil && config.Unsupported.Http2Config != nil {
http2Enabled = *config.Unsupported.Http2Config.Enabled
}
err := base.ListenAndServeHTTP(
addr,
maxConns,
config.SSLCert,
config.SSLKey,
handler,
config.ServerReadTimeout,
config.ServerWriteTimeout,
http2Enabled,
)
if err != nil {
base.LogFatal("Failed to start HTTP server on %s: %v", addr, err)
}
}
func (config *ServerConfig) HasAnyIndexReaderConfiguredDatabases() bool {
numIndexReaders := config.NumIndexReaders()
return numIndexReaders > 0
}
func (config *ServerConfig) HasAnyIndexWriterConfiguredDatabases() bool {
numIndexWriters := config.NumIndexWriters()
return numIndexWriters > 0
}
func (config *ServerConfig) NumIndexReaders() int {
n := 0
for _, dbConfig := range config.Databases {
if dbConfig.ChannelIndex == nil || dbConfig.ChannelIndex.IndexWriter == false {
n += 1
}
}
return n
}
func (config *ServerConfig) NumIndexWriters() int {
n := 0
for _, dbConfig := range config.Databases {
if dbConfig.ChannelIndex != nil && dbConfig.ChannelIndex.IndexWriter == true {
n += 1
}
}
return n
}
// Starts and runs the server given its configuration. (This function never returns.)
func RunServer(config *ServerConfig) {
PrettyPrint = config.Pretty
base.Logf("==== %s ====", LongVersionString)
if os.Getenv("GOMAXPROCS") == "" && runtime.GOMAXPROCS(0) == 1 {
cpus := runtime.NumCPU()
if cpus > 1 {
runtime.GOMAXPROCS(cpus)
base.Logf("Configured Go to use all %d CPUs; setenv GOMAXPROCS to override this", cpus)
}
}
SetMaxFileDescriptors(config.MaxFileDescriptors)
sc := NewServerContext(config)
for _, dbConfig := range config.Databases {
if _, err := sc.AddDatabaseFromConfig(dbConfig); err != nil {
base.LogFatal("Error opening database: %v", err)
}
}
if config.ProfileInterface != nil {
//runtime.MemProfileRate = 10 * 1024
base.Logf("Starting profile server on %s", *config.ProfileInterface)
go func() {
http.ListenAndServe(*config.ProfileInterface, nil)
}()
}
base.Logf("Starting admin server on %s", *config.AdminInterface)
go config.Serve(*config.AdminInterface, CreateAdminHandler(sc))
base.Logf("Starting server on %s ...", *config.Interface)
config.Serve(*config.Interface, CreatePublicHandler(sc))
}
// for now just cycle the logger to allow for log file rotation
func ReloadConf() {
if config.LogFilePath != nil {
base.UpdateLogger(*config.LogFilePath)
}
}
func GetConfig() *ServerConfig {
return config
}
func ValidateConfigOrPanic(runMode SyncGatewayRunMode) {
// if the user passes -skipRunModeValidation on the command line, then skip validation
if config.SkipRunmodeValidation == true {
base.Logf("Skipping runmode (accel vs normal) config validation")
return
}
switch runMode {
case SyncGatewayRunModeNormal:
// if index writer == true for any databases, panic
if config.HasAnyIndexWriterConfiguredDatabases() {
base.LogPanic("SG is running in normal mode but there are databases configured as index writers")
}
case SyncGatewayRunModeAccel:
// if index writer != true for any databases, panic
if config.HasAnyIndexReaderConfiguredDatabases() {
base.LogPanic("SG is running in sg-accelerator mode but there are databases configured as index readers")
}
}
}
// Main entry point for a simple server; you can have your main() function just call this.
// It parses command-line flags, reads the optional configuration file, then starts the server.
func ServerMain(runMode SyncGatewayRunMode) {
ParseCommandLine()
ReloadConf()
ValidateConfigOrPanic(runMode)
RunServer(config)
}