Documentation
¶
Index ¶
- Constants
- Variables
- func AddGoRuntimeStats()
- func CreateAdminHandler(sc *ServerContext) http.Handler
- func CreateAdminHandlerForRouter(sc *ServerContext, r *mux.Router) http.Handler
- func CreateAdminRouter(sc *ServerContext) *mux.Router
- func CreatePublicHandler(sc *ServerContext) http.Handler
- func FixQuotedSlashes(rq *http.Request)
- func GetBucketSpec(config *DbConfig) (spec base.BucketSpec, err error)
- func GetGZipWriter(writer io.Writer) *gzip.Writer
- func GetTLSVersionFromString(stringV *string) uint16
- func HandleSighup()
- func NewHTTPTestServerOnListener(h http.Handler, l net.Listener) *httptest.Server
- func NewLoggerTeeResponseWriter(wrappedResponseWriter http.ResponseWriter, logKey base.LogKey, ...) http.ResponseWriter
- func NewTeeReadCloser(r io.ReadCloser, w io.Writer) io.ReadCloser
- func ReadJSONFromMIME(headers http.Header, input io.ReadCloser, into interface{}) error
- func ReadMultipartDocument(reader *multipart.Reader) (db.Body, error)
- func RegisterSignalHandler()
- func ReturnGZipWriter(gz *gzip.Writer)
- func RunServer(config *ServerConfig)
- func ServerMain()
- func SetMaxFileDescriptors(maxP *uint64) error
- func WaitWithTimeout(wg *sync.WaitGroup, timeout time.Duration) error
- func WriteMultipartDocument(ctx context.Context, cblReplicationPullStats *expvar.Map, body db.Body, ...)
- func WriteRevisionAsPart(ctx context.Context, cblReplicationPullStats *expvar.Map, revBody db.Body, ...) error
- type AuthState
- type AuthorizeParameters
- type BlipTester
- func (bt BlipTester) Close()
- func (bt BlipTester) DatabaseContext() *db.DatabaseContext
- func (bt *BlipTester) GetChanges() (changes [][]interface{})
- func (bt *BlipTester) GetDocAtRev(requestedDocID, requestedDocRev string) (resultDoc RestDocument, err error)
- func (bt *BlipTester) PullDocs() (docs map[string]RestDocument)
- func (bt *BlipTester) SendRev(docId, docRev string, body []byte, properties blip.Properties) (sent bool, req, res *blip.Message, err error)
- func (bt *BlipTester) SendRevWithAttachment(input SendRevWithAttachmentInput) (sent bool, req, res *blip.Message)
- func (bt *BlipTester) SendRevWithHistory(docId, docRev string, revHistory []string, body []byte, ...) (sent bool, req, res *blip.Message, err error)
- func (bt *BlipTester) SetCheckpoint(client string, checkpointRev string, body []byte) (sent bool, req *db.SetCheckpointMessage, res *db.SetCheckpointResponse, ...)
- func (bt *BlipTester) SubscribeToChanges(continuous bool, changes chan<- *blip.Message)
- func (bt *BlipTester) WaitForNumChanges(numChangesExpected int) (changes [][]interface{})
- func (bt *BlipTester) WaitForNumDocsViaChanges(numDocsExpected int) (docs map[string]RestDocument, ok bool)
- type BlipTesterSpec
- type BucketConfig
- type CORSConfig
- type CacheConfig
- type ChannelCacheConfig
- type ClusterConfig
- type CustomClaims
- type DatabaseRoot
- type DatabaseStatus
- type DbConfig
- type DbConfigMap
- type DeltaSyncConfig
- type DeprecatedCacheConfig
- type DeprecatedOptions
- type EncodedResponseWriter
- type EventConfig
- type EventHandlerConfig
- type ExpectedChange
- type FacebookConfig
- type FacebookResponse
- type GoogleConfig
- type GoogleResponse
- type Http2Config
- type LoggingTeeResponseWriter
- type OIDCTokenResponse
- type OidcTokenResponse
- type Page
- type PostUpgradeDatabaseResult
- type PostUpgradeResponse
- type PostUpgradeResult
- type RawResponse
- type ReplConfigMap
- type ReplicateV1Config
- type RestDocument
- func (d RestDocument) GetAttachments() (db.AttachmentMap, error)
- func (d RestDocument) ID() string
- func (d RestDocument) IsRemoved() bool
- func (d RestDocument) RevID() string
- func (d RestDocument) SetAttachments(attachments db.AttachmentMap)
- func (d RestDocument) SetID(docId string)
- func (d RestDocument) SetRevID(revId string)
- type RestTester
- func (rt *RestTester) Bucket() base.Bucket
- func (rt *RestTester) Close()
- func (rt *RestTester) CreateWaitForChangesRetryWorker(numChangesExpected int, changesUrl, username string, useAdminPort bool) (worker base.RetryWorker)
- func (rt *RestTester) GetDatabase() *db.DatabaseContext
- func (rt *RestTester) GetDocumentSequence(key string) (sequence uint64)
- func (rt *RestTester) MustWaitForDoc(docid string, t testing.TB)
- func (rt *RestTester) PutDocumentWithRevID(docID string, newRevID string, parentRevID string, body db.Body) (response *TestResponse, err error)
- func (rt *RestTester) Send(request *http.Request) *TestResponse
- func (rt *RestTester) SendAdminRequest(method, resource string, body string) *TestResponse
- func (rt *RestTester) SendAdminRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse
- func (rt *RestTester) SendRequest(method, resource string, body string) *TestResponse
- func (rt *RestTester) SendRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse
- func (rt *RestTester) SendUserRequestWithHeaders(method, resource string, body string, headers map[string]string, ...) *TestResponse
- func (rt *RestTester) SequenceForDoc(docid string) (seq uint64, err error)
- func (rt *RestTester) ServerContext() *ServerContext
- func (rt *RestTester) SetAdminParty(partyTime bool)
- func (rt *RestTester) TestAdminHandler() http.Handler
- func (rt *RestTester) TestAdminHandlerNoConflictsMode() http.Handler
- func (rt *RestTester) TestPublicHandler() http.Handler
- func (rt *RestTester) WaitForChanges(numChangesExpected int, changesUrl, username string, useAdminPort bool) (changes changesResults, err error)
- func (rt *RestTester) WaitForCondition(successFunc func() bool) error
- func (rt *RestTester) WaitForDBOnline() (err error)
- func (rt *RestTester) WaitForDoc(docid string) (err error)
- func (rt *RestTester) WaitForNAdminViewResults(numResultsExpected int, viewUrlPath string) (viewResult sgbucket.ViewResult, err error)
- func (rt *RestTester) WaitForNUserViewResults(numResultsExpected int, viewUrlPath string, user auth.User, password string) (viewResult sgbucket.ViewResult, err error)
- func (rt *RestTester) WaitForNViewResults(numResultsExpected int, viewUrlPath string, user auth.User, password string) (viewResult sgbucket.ViewResult, err error)
- func (rt *RestTester) WaitForPendingChanges() error
- func (rt *RestTester) WaitForSequence(seq uint64) error
- func (rt *RestTester) WaitForViewAvailable(viewURLPath string) (err error)
- type RestTesterConfig
- type RevCacheConfig
- type SendRevWithAttachmentInput
- type ServerConfig
- type ServerContext
- func (sc *ServerContext) AddDatabaseFromConfig(config *DbConfig) (*db.DatabaseContext, error)
- func (sc *ServerContext) AllDatabaseNames() []string
- func (sc *ServerContext) AllDatabases() map[string]*db.DatabaseContext
- func (sc *ServerContext) Close()
- func (sc *ServerContext) CloseCpuPprofFile()
- func (sc *ServerContext) Database(name string) *db.DatabaseContext
- func (sc *ServerContext) GetConfig() *ServerConfig
- func (sc *ServerContext) GetDatabase(name string) (*db.DatabaseContext, error)
- func (sc *ServerContext) GetDatabaseConfig(name string) *DbConfig
- func (sc *ServerContext) PostStartup()
- func (sc *ServerContext) PostUpgrade(preview bool) (postUpgradeResults PostUpgradeResult, err error)
- func (sc *ServerContext) ReloadDatabaseFromConfig(reloadDbName string) (*db.DatabaseContext, error)
- func (sc *ServerContext) RemoveDatabase(dbName string) bool
- func (sc *ServerContext) SetCpuPprofFile(file *os.File)
- func (sc *ServerContext) TakeDbOnline(database *db.DatabaseContext)
- type SharedBucketError
- type SimpleSync
- type SlowResponseRecorder
- type Status
- type TeeReadCloser
- type TestResponse
- type TokenRequestType
- type UnsupportedServerConfig
- type UserAgentVersion
- type Vendor
Constants ¶
const ( // Default value of ServerConfig.MaxIncomingConnections DefaultMaxIncomingConnections = 0 // Default value of ServerConfig.MaxFileDescriptors DefaultMaxFileDescriptors uint64 = 5000 // Default number of index replicas DefaultNumIndexReplicas = uint(1) )
const DefaultStatsLogFrequencySecs = 60
const KDefaultNumShards = 16
Variables ¶
var ( DefaultInterface = ":4984" DefaultAdminInterface = "127.0.0.1:4985" // Only accessible on localhost! DefaultServer = "walrus:" DefaultPool = "default" DefaultMinimumTLSVersionConst = tls.VersionTLS10 )
var ( // ErrNoStateCookie is returned by handler's handleOIDCCallback method when // the state cookie is not found during OpenID Connect Auth callback. ErrNoStateCookie = base.HTTPErrorf(http.StatusBadRequest, "OIDC Auth Failure: No state cookie found, client needs to support cookies when OIDC callback state is enabled") // ErrStateMismatch is returned by handler's handleOIDCCallback method when // the state cookie value doesn't match with state param in the callback URL // during OpenID Connect Auth callback. ErrStateMismatch = base.HTTPErrorf(http.StatusBadRequest, "OIDC Auth Failure: State mismatch") // ErrReadStateCookie is returned by handler's handleOIDCCallback method when // there is failure reading state cookie value during OpenID Connect Auth callback. ErrReadStateCookie = base.HTTPErrorf(http.StatusBadRequest, "OIDC Auth Failure: Couldn't read state") )
var ( // ErrSGCollectInfoAlreadyRunning is returned if sgcollect_info is already running. ErrSGCollectInfoAlreadyRunning = errors.New("already running") // ErrSGCollectInfoNotRunning is returned if sgcollect_info is not running. ErrSGCollectInfoNotRunning = errors.New("not running") )
var DebugMultipart bool = false
If set to true, diagnostic data will be dumped if there's a problem with MIME multipart data
var MaxGoroutinesSeen uint64
The peak number of goroutines observed during lifetime of program
var PrettyPrint bool = false
If set to true, JSON output will be pretty-printed.
Functions ¶
func AddGoRuntimeStats ¶
func AddGoRuntimeStats()
func CreateAdminHandler ¶
func CreateAdminHandler(sc *ServerContext) http.Handler
Creates the HTTP handler for the PRIVATE admin API of a gateway server.
func CreateAdminHandlerForRouter ¶
func CreateAdminHandlerForRouter(sc *ServerContext, r *mux.Router) http.Handler
func CreateAdminRouter ¶
func CreateAdminRouter(sc *ServerContext) *mux.Router
Creates the HTTP handler for the PRIVATE admin API of a gateway server.
func CreatePublicHandler ¶
func CreatePublicHandler(sc *ServerContext) http.Handler
Creates the HTTP handler for the public API of a gateway server.
func FixQuotedSlashes ¶
func GetBucketSpec ¶
func GetBucketSpec(config *DbConfig) (spec base.BucketSpec, err error)
func GetGZipWriter ¶
Gets a gzip writer from the pool, or creates a new one if the pool is empty:
func GetTLSVersionFromString ¶
func HandleSighup ¶
func HandleSighup()
func NewHTTPTestServerOnListener ¶
NewHTTPTestServerOnListener returns a new httptest server, which is configured to listen on the given listener. This is useful when you need to know the listen address before you start up a server.
func NewTeeReadCloser ¶
func NewTeeReadCloser(r io.ReadCloser, w io.Writer) io.ReadCloser
func ReadJSONFromMIME ¶
func ReadJSONFromMIME(headers http.Header, input io.ReadCloser, into interface{}) error
Parses a JSON MIME body, unmarshaling it into "into". Closes the input io.ReadCloser once done.
func RegisterSignalHandler ¶
func RegisterSignalHandler()
func ReturnGZipWriter ¶
Closes a gzip writer and returns it to the pool:
func RunServer ¶
func RunServer(config *ServerConfig)
Starts and runs the server given its configuration. (This function never returns.)
func ServerMain ¶
func ServerMain()
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 SetMaxFileDescriptors ¶
func WaitWithTimeout ¶
Wait for the WaitGroup, or return an error if the wg.Wait() doesn't return within timeout
func WriteMultipartDocument ¶
func WriteMultipartDocument(ctx context.Context, cblReplicationPullStats *expvar.Map, body db.Body, writer *multipart.Writer, compress bool)
Writes a revision to a MIME multipart writer, encoding large attachments as separate parts.
func WriteRevisionAsPart ¶
func WriteRevisionAsPart(ctx context.Context, cblReplicationPullStats *expvar.Map, revBody db.Body, isError bool, compressPart bool, writer *multipart.Writer) error
Adds a new part to the given multipart writer, containing the given revision. The revision will be written as a nested multipart body if it has attachments.
Types ¶
type AuthorizeParameters ¶
type BlipTester ¶
type BlipTester struct {
// contains filtered or unexported fields
}
State associated with a BlipTester Note that it's not safe to have multiple goroutines access a single BlipTester due to the fact that certain methods register profile handlers on the BlipContext
func NewBlipTester ¶
func NewBlipTester(tb testing.TB) (*BlipTester, error)
Create a BlipTester using the default spec
func NewBlipTesterFromSpec ¶
func NewBlipTesterFromSpec(tb testing.TB, spec BlipTesterSpec) (*BlipTester, error)
Create a BlipTester using the given spec
func (BlipTester) DatabaseContext ¶
func (bt BlipTester) DatabaseContext() *db.DatabaseContext
Returns database context for blipTester (assumes underlying rest tester is based on a single db - returns first it finds)
func (*BlipTester) GetChanges ¶
func (bt *BlipTester) GetChanges() (changes [][]interface{})
Returns changes in form of [[sequence, docID, revID, deleted], [sequence, docID, revID, deleted]] Warning: this can only be called from a single goroutine, given the fact it registers profile handlers.
func (*BlipTester) GetDocAtRev ¶
func (bt *BlipTester) GetDocAtRev(requestedDocID, requestedDocRev string) (resultDoc RestDocument, err error)
Get a doc at a particular revision from Sync Gateway.
Warning: this can only be called from a single goroutine, given the fact it registers profile handlers.
If that is not found, it will return an empty resultDoc with no errors.
- Call subChanges (continuous=false) endpoint to get all changes from Sync Gateway - Respond to each "change" request telling the other side to send the revision
- NOTE: this could be made more efficient by only requesting the revision for the docid/revid pair passed in the parameter.
- If the rev handler is called back with the desired docid/revid pair, save that into a variable that will be returned - Block until all pending operations are complete - Return the resultDoc or an empty resultDoc
func (*BlipTester) PullDocs ¶
func (bt *BlipTester) PullDocs() (docs map[string]RestDocument)
Get all documents and their attachments via the following steps:
- Invoking one-shot subChanges request - Responding to all incoming "changes" requests from peer to request the changed rev, and accumulate rev body - Responding to all incoming "rev" requests from peer to get all attachments, and accumulate them - Return accumulated docs + attachements to caller
It is basically a pull replication without the checkpointing Warning: this can only be called from a single goroutine, given the fact it registers profile handlers.
func (*BlipTester) SendRev ¶
func (bt *BlipTester) SendRev(docId, docRev string, body []byte, properties blip.Properties) (sent bool, req, res *blip.Message, err error)
func (*BlipTester) SendRevWithAttachment ¶
func (bt *BlipTester) SendRevWithAttachment(input SendRevWithAttachmentInput) (sent bool, req, res *blip.Message)
Warning: this can only be called from a single goroutine, given the fact it registers profile handlers.
func (*BlipTester) SendRevWithHistory ¶
func (bt *BlipTester) SendRevWithHistory(docId, docRev string, revHistory []string, body []byte, properties blip.Properties) (sent bool, req, res *blip.Message, err error)
The docHistory should be in the same format as expected by db.PutExistingRevWithBody(), or empty if this is the first revision
func (*BlipTester) SetCheckpoint ¶
func (bt *BlipTester) SetCheckpoint(client string, checkpointRev string, body []byte) (sent bool, req *db.SetCheckpointMessage, res *db.SetCheckpointResponse, err error)
func (*BlipTester) SubscribeToChanges ¶
func (bt *BlipTester) SubscribeToChanges(continuous bool, changes chan<- *blip.Message)
func (*BlipTester) WaitForNumChanges ¶
func (bt *BlipTester) WaitForNumChanges(numChangesExpected int) (changes [][]interface{})
func (*BlipTester) WaitForNumDocsViaChanges ¶
func (bt *BlipTester) WaitForNumDocsViaChanges(numDocsExpected int) (docs map[string]RestDocument, ok bool)
type BlipTesterSpec ¶
type BlipTesterSpec struct {
// contains filtered or unexported fields
}
The parameters used to create a BlipTester
type BucketConfig ¶
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
CertPath string `json:"certpath,omitempty"` // Cert path (public key) for X.509 bucket auth
KeyPath string `json:"keypath,omitempty"` // Key path (private key) for X.509 bucket auth
CACertPath string `json:"cacertpath,omitempty"` // Root CA cert path for X.509 bucket auth
KvTLSPort int `json:"kv_tls_port,omitempty"` // Memcached TLS port, if not default (11207)
}
Bucket configuration elements - used by db, index
func (*BucketConfig) GetCredentials ¶
func (bucketConfig *BucketConfig) GetCredentials() (username string, password string, bucketname string)
Implementation of AuthHandler interface for BucketConfig
func (*BucketConfig) MakeBucketSpec ¶
func (bc *BucketConfig) MakeBucketSpec() base.BucketSpec
type CORSConfig ¶
type CacheConfig ¶
type CacheConfig struct {
RevCacheConfig *RevCacheConfig `json:"rev_cache"` // Revision Cache Config Settings
ChannelCacheConfig *ChannelCacheConfig `json:"channel_cache"` // Channel Cache Config Settings
DeprecatedCacheConfig
}
type ChannelCacheConfig ¶
type ChannelCacheConfig struct {
MaxNumber *int `json:"max_number,omitempty"` // Maximum number of channel caches which will exist at any one point
HighWatermarkPercent *int `json:"compact_high_watermark_pct,omitempty"` // High watermark for channel cache eviction (percent)
LowWatermarkPercent *int `json:"compact_low_watermark_pct,omitempty"` // Low watermark for channel cache eviction (percent)
MaxWaitPending *uint32 `json:"max_wait_pending,omitempty"` // Max wait for pending sequence before skipping
MaxNumPending *int `json:"max_num_pending,omitempty"` // Max number of pending sequences before skipping
MaxWaitSkipped *uint32 `json:"max_wait_skipped,omitempty"` // Max wait for skipped sequence before abandoning
EnableStarChannel *bool `json:"enable_star_channel,omitempty"` // Enable star channel
MaxLength *int `json:"max_length,omitempty"` // Maximum number of entries maintained in cache per channel
MinLength *int `json:"min_length,omitempty"` // Minimum number of entries maintained in cache per channel
ExpirySeconds *int `json:"expiry_seconds,omitempty"` // Time (seconds) to keep entries in cache beyond the minimum retained
QueryLimit *int `json:"query_limit,omitempty"` // Limit used for channel queries, if not specified by client
}
type ClusterConfig ¶
type ClusterConfig struct {
BucketConfig
DataDir string `json:"data_dir,omitempty"`
HeartbeatIntervalSeconds *uint16 `json:"heartbeat_interval_seconds,omitempty"`
}
func (ClusterConfig) CBGTEnabled ¶
func (c ClusterConfig) CBGTEnabled() bool
func (*ClusterConfig) GetCredentials ¶
func (clusterConfig *ClusterConfig) GetCredentials() (string, string, string)
Implementation of AuthHandler interface for ClusterConfig
type CustomClaims ¶
type DatabaseRoot ¶
type DatabaseRoot struct {
DBName string `json:"db_name"`
SequenceNumber uint64 `json:"update_seq"`
CommittedUpdateSequenceNumber uint64 `json:"committed_update_seq"` // Used by perf tests, shouldn't be removed
InstanceStartTime int64 `json:"instance_start_time"`
CompactRunning bool `json:"compact_running"`
PurgeSequenceNumber uint64 `json:"purge_seq"`
DiskFormatVersion uint64 `json:"disk_format_version"`
State string `json:"state"`
ServerUUID string `json:"server_uuid,omitempty"`
}
type DatabaseStatus ¶
type DatabaseStatus struct {
SequenceNumber uint64 `json:"seq"`
ServerUUID string `json:"server_uuid"`
State string `json:"state"`
ReplicationStatus []*db.ReplicationStatus `json:"replication_status"`
SGRCluster *db.SGRCluster `json:"cluster"`
}
type DbConfig ¶
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
AutoImport interface{} `json:"import_docs,omitempty"` // Whether to automatically import Couchbase Server docs into SG. Xattrs must be enabled. true or "continuous" both enable this.
ImportPartitions *uint16 `json:"import_partitions,omitempty"` // Number of partitions for import sharding. Impacts the total DCP concurrency for import
ImportFilter *string `json:"import_filter,omitempty"` // Filter function (import)
ImportBackupOldRev bool `json:"import_backup_old_rev"` // Whether import should attempt to create a temporary backup of the previous revision body, when available.
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
DeprecatedRevCacheSize *uint32 `json:"rev_cache_size,omitempty"` // Maximum number of revisions to store in the revision cache (deprecated, CBG-356)
StartOffline bool `json:"offline,omitempty"` // start the DB in the offline state, defaults to false
Unsupported db.UnsupportedOptions `json:"unsupported,omitempty"` // Config for unsupported features
Deprecated DeprecatedOptions `json:"deprecated,omitempty"` // Config for Deprecated features
OIDCConfig *auth.OIDCOptions `json:"oidc,omitempty"` // Config properties for OpenID Connect authentication
OldRevExpirySeconds *uint32 `json:"old_rev_expiry_seconds,omitempty"` // The number of seconds before old revs are removed from CBS bucket
ViewQueryTimeoutSecs *uint32 `json:"view_query_timeout_secs,omitempty"` // The view query timeout in seconds
LocalDocExpirySecs *uint32 `json:"local_doc_expiry_secs,omitempty"` // The _local doc expiry time in seconds
EnableXattrs *bool `json:"enable_shared_bucket_access,omitempty"` // Whether to use extended attributes to store _sync metadata
SecureCookieOverride *bool `json:"session_cookie_secure,omitempty"` // Override cookie secure flag
SessionCookieName string `json:"session_cookie_name"` // Custom per-database session cookie name
SessionCookieHTTPOnly bool `json:"session_cookie_http_only"` // HTTP only cookies
AllowConflicts *bool `json:"allow_conflicts,omitempty"` // False forbids creating conflicts
NumIndexReplicas *uint `json:"num_index_replicas"` // Number of GSI index replicas used for core indexes
UseViews bool `json:"use_views"` // Force use of views instead of GSI
SendWWWAuthenticateHeader *bool `json:"send_www_authenticate_header,omitempty"` // If false, disables setting of 'WWW-Authenticate' header in 401 responses
BucketOpTimeoutMs *uint32 `json:"bucket_op_timeout_ms,omitempty"` // How long bucket ops should block returning "operation timed out". If nil, uses GoCB default. GoCB buckets only.
DeltaSync *DeltaSyncConfig `json:"delta_sync,omitempty"` // Config for delta sync
CompactIntervalDays *float32 `json:"compact_interval_days,omitempty"` // Interval between scheduled compaction runs (in days) - 0 means don't run
SGReplicateEnabled *bool `json:"sgreplicate_enabled,omitempty"` // When false, node will not be assigned replications
SGReplicateWebsocketPingInterval *int `json:"sgreplicate_websocket_heartbeat_secs,omitempty"` // If set, uses this duration as a custom heartbeat interval for websocket ping frames
Replications map[string]*db.ReplicationConfig `json:"replications,omitempty"` // sg-replicate replication definitions
ServeInsecureAttachmentTypes bool `json:"serve_insecure_attachment_types,omitempty"` // Attachment content type will bypass the content-disposition handling, default false
}
JSON object that defines a database configuration within the ServerConfig.
func (*DbConfig) AutoImportEnabled ¶
func (*DbConfig) ConflictsAllowed ¶
func (*DbConfig) GetCredentials ¶
Implementation of AuthHandler interface for DbConfig
type DbConfigMap ¶
type DeltaSyncConfig ¶
type DeprecatedCacheConfig ¶
type DeprecatedCacheConfig struct {
DeprecatedCachePendingSeqMaxWait *uint32 `json:"max_wait_pending,omitempty"` // Max wait for pending sequence before skipping
DeprecatedCachePendingSeqMaxNum *int `json:"max_num_pending,omitempty"` // Max number of pending sequences before skipping
DeprecatedCacheSkippedSeqMaxWait *uint32 `json:"max_wait_skipped,omitempty"` // Max wait for skipped sequence before abandoning
DeprecatedEnableStarChannel *bool `json:"enable_star_channel,omitempty"` // Enable star channel
DeprecatedChannelCacheMaxLength *int `json:"channel_cache_max_length,omitempty"` // Maximum number of entries maintained in cache per channel
DeprecatedChannelCacheMinLength *int `json:"channel_cache_min_length,omitempty"` // Minimum number of entries maintained in cache per channel
DeprecatedChannelCacheAge *int `json:"channel_cache_expiry,omitempty"` // Time (seconds) to keep entries in cache beyond the minimum retained
}
***************************************************************
Kept around for CBG-356 backwards compatability
***************************************************************
type DeprecatedOptions ¶
type DeprecatedOptions struct {
}
type EncodedResponseWriter ¶
type EncodedResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
An implementation of http.ResponseWriter that wraps another instance and transparently applies GZip compression when appropriate.
func NewEncodedResponseWriter ¶
func NewEncodedResponseWriter(response http.ResponseWriter, rq *http.Request) *EncodedResponseWriter
Creates a new EncodedResponseWriter, or returns nil if the request doesn't allow encoded responses.
func (*EncodedResponseWriter) Close ¶
func (w *EncodedResponseWriter) Close()
The writer should be closed when output is complete, to flush the GZip encoder buffer.
func (*EncodedResponseWriter) CloseNotify ¶
func (w *EncodedResponseWriter) CloseNotify() <-chan bool
func (*EncodedResponseWriter) Flush ¶
func (w *EncodedResponseWriter) Flush()
Flushes the GZip encoder buffer, and if possible flushes output to the network.
func (*EncodedResponseWriter) WriteHeader ¶
func (w *EncodedResponseWriter) WriteHeader(status int)
type EventConfig ¶
type EventHandlerConfig ¶
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 ExpectedChange ¶
type ExpectedChange struct {
// contains filtered or unexported fields
}
Helper for comparing BLIP changes received with expected BLIP changes
func (ExpectedChange) Equals ¶
func (e ExpectedChange) Equals(change []interface{}) error
type FacebookConfig ¶
type FacebookConfig struct {
Register bool // If true, server will register new user accounts
}
type FacebookResponse ¶
type GoogleConfig ¶
type GoogleResponse ¶
type Http2Config ¶
type Http2Config struct {
Enabled *bool `json:"enabled,omitempty"` // Whether HTTP2 support is enabled
}
type LoggingTeeResponseWriter ¶
type LoggingTeeResponseWriter struct {
http.ResponseWriter
LogKey base.LogKey // The log key to use, eg base.KeyHTTP
SerialNumber string // The request ID
Request *http.Request // The request
QueryValues url.Values // A cached copy of the URL query values
}
A ResponseWriter that wraps another ResponseWriter, and dumps a copy of everything to the logging key
type OIDCTokenResponse ¶
type OIDCTokenResponse struct {
IDToken string `json:"id_token,omitempty"` // ID token, from OP
RefreshToken string `json:"refresh_token,omitempty"` // Refresh token, from OP
SessionID string `json:"session_id,omitempty"` // Sync Gateway session ID
Username string `json:"name,omitempty"` // Sync Gateway user name
AccessToken string `json:"access_token,omitempty"` // Access token, from OP
TokenType string `json:"token_type,omitempty"` // Access token type, from OP
Expires int `json:"expires_in,omitempty"` // Access token expiry, from OP
}
type OidcTokenResponse ¶
type PostUpgradeResponse ¶
type PostUpgradeResponse struct {
Result PostUpgradeResult `json:"post_upgrade_results"`
Preview bool `json:"preview,omitempty"`
}
type PostUpgradeResult ¶
type PostUpgradeResult map[string]PostUpgradeDatabaseResult
type RawResponse ¶
type RawResponse struct {
Sync SimpleSync `json:"_sync"`
}
type ReplConfigMap ¶
type ReplConfigMap map[string]*ReplicateV1Config
type ReplicateV1Config ¶
type ReplicateV1Config struct {
Source string `json:"source"`
Target string `json:"target"`
Continuous bool `json:"continuous"`
CreateTarget bool `json:"create_target"`
DocIds []string `json:"doc_ids"`
Filter string `json:"filter"`
Proxy string `json:"proxy"`
QueryParams interface{} `json:"query_params"`
Cancel bool `json:"cancel"`
Async bool `json:"async"`
ChangesFeedLimit *int `json:"changes_feed_limit"`
ReplicationId string `json:"replication_id"`
// contains filtered or unexported fields
}
type RestDocument ¶
type RestDocument map[string]interface{}
Model "CouchDB" style REST documents which define the following special fields:
- _id - _rev - _removed - _deleted (not accounted for yet) - _attachments
This struct wraps a map and provides convenience methods for getting at the special fields with the appropriate types (string in the id/rev case, db.AttachmentMap in the attachments case). Currently only used in tests, but if similar functionality needed in primary codebase, could be moved.
func NewRestDocument ¶
func NewRestDocument() *RestDocument
func (RestDocument) GetAttachments ¶
func (d RestDocument) GetAttachments() (db.AttachmentMap, error)
func (RestDocument) ID ¶
func (d RestDocument) ID() string
func (RestDocument) IsRemoved ¶
func (d RestDocument) IsRemoved() bool
func (RestDocument) RevID ¶
func (d RestDocument) RevID() string
func (RestDocument) SetAttachments ¶
func (d RestDocument) SetAttachments(attachments db.AttachmentMap)
func (RestDocument) SetID ¶
func (d RestDocument) SetID(docId string)
func (RestDocument) SetRevID ¶
func (d RestDocument) SetRevID(revId string)
type RestTester ¶
type RestTester struct {
*RestTesterConfig
RestTesterServerContext *ServerContext
AdminHandler http.Handler
PublicHandler http.Handler
// contains filtered or unexported fields
}
func NewRestTester ¶
func NewRestTester(tb testing.TB, restConfig *RestTesterConfig) *RestTester
func (*RestTester) Bucket ¶
func (rt *RestTester) Bucket() base.Bucket
func (*RestTester) Close ¶
func (rt *RestTester) Close()
func (*RestTester) CreateWaitForChangesRetryWorker ¶
func (rt *RestTester) CreateWaitForChangesRetryWorker(numChangesExpected int, changesUrl, username string, useAdminPort bool) (worker base.RetryWorker)
func (*RestTester) GetDatabase ¶
func (rt *RestTester) GetDatabase() *db.DatabaseContext
Returns first database found for server context.
func (*RestTester) GetDocumentSequence ¶
func (rt *RestTester) GetDocumentSequence(key string) (sequence uint64)
GetDocumentSequence looks up the sequence for a document using the _raw endpoint. Used by tests that need to validate sequences (for grants, etc)
func (*RestTester) MustWaitForDoc ¶
func (rt *RestTester) MustWaitForDoc(docid string, t testing.TB)
func (*RestTester) PutDocumentWithRevID ¶
func (rt *RestTester) PutDocumentWithRevID(docID string, newRevID string, parentRevID string, body db.Body) (response *TestResponse, err error)
PutDocumentWithRevID builds a new_edits=false style put to create a revision with the specified revID. If parentRevID is not specified, treated as insert
func (*RestTester) Send ¶
func (rt *RestTester) Send(request *http.Request) *TestResponse
func (*RestTester) SendAdminRequest ¶
func (rt *RestTester) SendAdminRequest(method, resource string, body string) *TestResponse
func (*RestTester) SendAdminRequestWithHeaders ¶
func (rt *RestTester) SendAdminRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse
func (*RestTester) SendRequest ¶
func (rt *RestTester) SendRequest(method, resource string, body string) *TestResponse
func (*RestTester) SendRequestWithHeaders ¶
func (rt *RestTester) SendRequestWithHeaders(method, resource string, body string, headers map[string]string) *TestResponse
func (*RestTester) SendUserRequestWithHeaders ¶
func (rt *RestTester) SendUserRequestWithHeaders(method, resource string, body string, headers map[string]string, username string, password string) *TestResponse
func (*RestTester) SequenceForDoc ¶
func (rt *RestTester) SequenceForDoc(docid string) (seq uint64, err error)
func (*RestTester) ServerContext ¶
func (rt *RestTester) ServerContext() *ServerContext
func (*RestTester) SetAdminParty ¶
func (rt *RestTester) SetAdminParty(partyTime bool)
func (*RestTester) TestAdminHandler ¶
func (rt *RestTester) TestAdminHandler() http.Handler
func (*RestTester) TestAdminHandlerNoConflictsMode ¶
func (rt *RestTester) TestAdminHandlerNoConflictsMode() http.Handler
func (*RestTester) TestPublicHandler ¶
func (rt *RestTester) TestPublicHandler() http.Handler
func (*RestTester) WaitForChanges ¶
func (rt *RestTester) WaitForChanges(numChangesExpected int, changesUrl, username string, useAdminPort bool) (changes changesResults, err error)
func (*RestTester) WaitForCondition ¶
func (rt *RestTester) WaitForCondition(successFunc func() bool) error
WaitForCondition runs a retry loop that evaluates the provided function, and terminates when the function returns true.
func (*RestTester) WaitForDBOnline ¶
func (rt *RestTester) WaitForDBOnline() (err error)
func (*RestTester) WaitForDoc ¶
func (rt *RestTester) WaitForDoc(docid string) (err error)
func (*RestTester) WaitForNAdminViewResults ¶
func (rt *RestTester) WaitForNAdminViewResults(numResultsExpected int, viewUrlPath string) (viewResult sgbucket.ViewResult, err error)
func (*RestTester) WaitForNUserViewResults ¶
func (rt *RestTester) WaitForNUserViewResults(numResultsExpected int, viewUrlPath string, user auth.User, password string) (viewResult sgbucket.ViewResult, err error)
func (*RestTester) WaitForNViewResults ¶
func (rt *RestTester) WaitForNViewResults(numResultsExpected int, viewUrlPath string, user auth.User, password string) (viewResult sgbucket.ViewResult, err error)
Wait for a certain number of results to be returned from a view query viewUrlPath: is the path to the view, including the db name. Eg: "/db/_design/foo/_view/bar"
func (*RestTester) WaitForPendingChanges ¶
func (rt *RestTester) WaitForPendingChanges() error
func (*RestTester) WaitForSequence ¶
func (rt *RestTester) WaitForSequence(seq uint64) error
Wait for sequence to be buffered by the channel cache
func (*RestTester) WaitForViewAvailable ¶
func (rt *RestTester) WaitForViewAvailable(viewURLPath string) (err error)
Waits for view to be defined on the server. Used to avoid view_undefined errors.
type RestTesterConfig ¶
type RestTesterConfig struct {
SyncFn string // put the sync() function source in here (optional)
DatabaseConfig *DbConfig // Supports additional config options. BucketConfig, Name, Sync, Unsupported will be ignored (overridden)
InitSyncSeq uint64 // If specified, initializes _sync:seq on bucket creation. Not supported when running against walrus
EnableNoConflictsMode bool // Enable no-conflicts mode. By default, conflicts will be allowed, which is the default behavior
TestBucket *base.TestBucket // If set, use this bucket instead of requesting a new one.
// contains filtered or unexported fields
}
type RevCacheConfig ¶
type SendRevWithAttachmentInput ¶
type SendRevWithAttachmentInput struct {
// contains filtered or unexported fields
}
type ServerConfig ¶
type ServerConfig struct {
TLSMinVersion *string `json:"tls_minimum_version,omitempty"` // Set TLS Version
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
ReadHeaderTimeout *int `json:",omitempty"` // The amount of time allowed to read request headers.
IdleTimeout *int `json:",omitempty"` // The maximum amount of time to wait for the next request when keep-alives are enabled.
AdminInterface *string `json:",omitempty"` // Interface to bind admin API to, default "localhost: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)
Facebook *FacebookConfig `json:",omitempty"` // Configuration for Facebook validation
Google *GoogleConfig `json:",omitempty"` // Configuration for Google validation
CORS *CORSConfig `json:",omitempty"` // Configuration for allowing CORS
DeprecatedLog []string `json:"log,omitempty"` // Log keywords to enable
DeprecatedLogFilePath *string `json:"logFilePath,omitempty"` // Path to log file, if missing write to stderr
Logging *base.LoggingConfig `json:",omitempty"` // Configuration for logging with optional log file rotation
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)
CouchbaseKeepaliveInterval *int `json:",omitempty"` // TCP keep-alive interval between SG and Couchbase server
SlowQueryWarningThreshold *int `json:",omitempty"` // Log warnings if N1QL queries 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 []*ReplicateV1Config `json:",omitempty"` // sg-replicate replication definitions
MaxHeartbeat uint64 `json:",omitempty"` // Max heartbeat value for _changes request (seconds)
ClusterConfig *ClusterConfig `json:"cluster_config,omitempty"` // Bucket and other config related to CBGT
Unsupported *UnsupportedServerConfig `json:"unsupported,omitempty"` // Config for unsupported features
ReplicatorCompression *int `json:"replicator_compression,omitempty"` // BLIP data compression level (0-9)
BcryptCost int `json:"bcrypt_cost,omitempty"` // bcrypt cost to use for password hashes - Default: bcrypt.DefaultCost
}
JSON object that defines the server configuration.
func GetConfig ¶
func GetConfig() *ServerConfig
func LoadServerConfig ¶
func LoadServerConfig(path string) (config *ServerConfig, err error)
LoadServerConfig loads a ServerConfig from either a JSON file or from a URL
func ParseCommandLine ¶
func ParseCommandLine(args []string, handling flag.ErrorHandling) (*ServerConfig, error)
Reads the command line flags and the optional config file.
func (*ServerConfig) MergeWith ¶
func (self *ServerConfig) MergeWith(other *ServerConfig) error
func (*ServerConfig) SetupAndValidateLogging ¶
func (config *ServerConfig) SetupAndValidateLogging() (warnings []base.DeferredLogFn, err error)
setupAndValidateLogging sets up and validates logging, and returns a slice of deferred logs to execute later.
type ServerContext ¶
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.
func NewServerContext ¶
func NewServerContext(config *ServerConfig) *ServerContext
func (*ServerContext) AddDatabaseFromConfig ¶
func (sc *ServerContext) AddDatabaseFromConfig(config *DbConfig) (*db.DatabaseContext, error)
Adds a database to the ServerContext given its configuration. If an existing config is found for the name, returns an error.
func (*ServerContext) AllDatabaseNames ¶
func (sc *ServerContext) AllDatabaseNames() []string
func (*ServerContext) AllDatabases ¶
func (sc *ServerContext) AllDatabases() map[string]*db.DatabaseContext
AllDatabases returns a copy of the databases_ map.
func (*ServerContext) Close ¶
func (sc *ServerContext) Close()
func (*ServerContext) CloseCpuPprofFile ¶
func (sc *ServerContext) CloseCpuPprofFile()
func (*ServerContext) Database ¶
func (sc *ServerContext) Database(name string) *db.DatabaseContext
For test use
func (*ServerContext) GetConfig ¶
func (sc *ServerContext) GetConfig() *ServerConfig
func (*ServerContext) GetDatabase ¶
func (sc *ServerContext) GetDatabase(name string) (*db.DatabaseContext, error)
Returns the DatabaseContext with the given name
func (*ServerContext) GetDatabaseConfig ¶
func (sc *ServerContext) GetDatabaseConfig(name string) *DbConfig
func (*ServerContext) PostStartup ¶
func (sc *ServerContext) PostStartup()
PostStartup runs anything that relies on SG being fully started (i.e. sgreplicate)
func (*ServerContext) PostUpgrade ¶
func (sc *ServerContext) PostUpgrade(preview bool) (postUpgradeResults PostUpgradeResult, err error)
PostUpgrade performs post-upgrade processing for each database
func (*ServerContext) ReloadDatabaseFromConfig ¶
func (sc *ServerContext) ReloadDatabaseFromConfig(reloadDbName string) (*db.DatabaseContext, error)
Removes and re-adds a database to the ServerContext.
func (*ServerContext) RemoveDatabase ¶
func (sc *ServerContext) RemoveDatabase(dbName string) bool
func (*ServerContext) SetCpuPprofFile ¶
func (sc *ServerContext) SetCpuPprofFile(file *os.File)
func (*ServerContext) TakeDbOnline ¶
func (sc *ServerContext) TakeDbOnline(database *db.DatabaseContext)
type SharedBucketError ¶
type SharedBucketError struct {
// contains filtered or unexported fields
}
func (*SharedBucketError) Error ¶
func (e *SharedBucketError) Error() string
func (*SharedBucketError) GetSharedBucket ¶
func (e *SharedBucketError) GetSharedBucket() sharedBucket
type SimpleSync ¶
type SlowResponseRecorder ¶
type SlowResponseRecorder struct {
*httptest.ResponseRecorder
// contains filtered or unexported fields
}
func NewSlowResponseRecorder ¶
func NewSlowResponseRecorder(responseDelay time.Duration, responseRecorder *httptest.ResponseRecorder) *SlowResponseRecorder
func (*SlowResponseRecorder) WaitForResponseToFinish ¶
func (s *SlowResponseRecorder) WaitForResponseToFinish()
func (*SlowResponseRecorder) WaitForResponseToStart ¶
func (s *SlowResponseRecorder) WaitForResponseToStart()
type TeeReadCloser ¶
type TeeReadCloser struct {
// contains filtered or unexported fields
}
A TeeReader wrapper that can wrap an io.ReadCloser as opposed to just wrapping an io.Reader
func (*TeeReadCloser) Close ¶
func (t *TeeReadCloser) Close() error
type TestResponse ¶
type TestResponse struct {
*httptest.ResponseRecorder
Req *http.Request
// contains filtered or unexported fields
}
func (TestResponse) BodyBytes ¶
func (r TestResponse) BodyBytes() []byte
BodyBytes takes a copy of the bytes in the response buffer, and saves them for future callers.
func (TestResponse) DumpBody ¶
func (r TestResponse) DumpBody()
func (TestResponse) GetRestDocument ¶
func (r TestResponse) GetRestDocument() RestDocument
type TokenRequestType ¶
type TokenRequestType uint8
const ( TokenRequestAuthCode TokenRequestType = iota TokenRequestRefresh )
type UnsupportedServerConfig ¶
type UnsupportedServerConfig struct {
Http2Config *Http2Config `json:"http2,omitempty"` // Config settings for HTTP2
StatsLogFrequencySecs *uint `json:"stats_log_freq_secs,omitempty"` // How often should stats be written to stats logs
UseStdlibJSON *bool `json:"use_stdlib_json,omitempty"` // Bypass the jsoniter package and use Go's stdlib instead
}
type UserAgentVersion ¶
type UserAgentVersion struct {
// contains filtered or unexported fields
}
func NewUserAgentVersion ¶
func NewUserAgentVersion(requestHeader string) *UserAgentVersion
func (UserAgentVersion) IsBefore ¶
func (uav UserAgentVersion) IsBefore(otherMajorVersion, otherMinorVersion int) bool
func (UserAgentVersion) IsEqualToOrAfter ¶
func (uav UserAgentVersion) IsEqualToOrAfter(otherMajorVersion, otherMinorVersion int) bool
func (UserAgentVersion) MajorVersion ¶
func (uav UserAgentVersion) MajorVersion() int
func (UserAgentVersion) MinorVersion ¶
func (uav UserAgentVersion) MinorVersion() int
Source Files
¶
- admin_api.go
- api.go
- blip_sync.go
- bulk_api.go
- changes_api.go
- config.go
- debug.go
- doc_api.go
- encoded_response_writer.go
- facebook.go
- google.go
- handler.go
- ioutil.go
- multipart.go
- oidc_api.go
- oidc_test_provider.go
- routing.go
- server_context.go
- session_api.go
- sgcollect.go
- stats_context.go
- user_agent_version.go
- utilities_testing.go
- view_api.go