forked from FerretDB/FerretDB
/
ferretdb.go
247 lines (203 loc) · 6.31 KB
/
ferretdb.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
// Copyright 2021 FerretDB 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 ferretdb provides embeddable FerretDB implementation.
//
// See [github.com/FerretDB/FerretDB/build/version] package documentation
// for information about Go build tags that affect this package.
package ferretdb
import (
"context"
"errors"
"fmt"
"net/url"
"sync"
"go.uber.org/zap"
"github.com/FerretDB/FerretDB/build/version"
"github.com/FerretDB/FerretDB/internal/clientconn"
"github.com/FerretDB/FerretDB/internal/clientconn/connmetrics"
"github.com/FerretDB/FerretDB/internal/handler/registry"
"github.com/FerretDB/FerretDB/internal/util/logging"
"github.com/FerretDB/FerretDB/internal/util/state"
)
// Config represents FerretDB configuration.
type Config struct {
Listener ListenerConfig
// Logger to use; if nil, it uses the default global logger.
Logger *zap.Logger
// Handler to use; one of `postgresql` or `sqlite`.
Handler string
// PostgreSQL connection string for `postgresql` handler.
// See:
// - https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool#ParseConfig
// - https://pkg.go.dev/github.com/jackc/pgx/v5#ParseConfig
// - https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn#ParseConfig
PostgreSQLURL string // For example: `postgres://hostname:5432/ferretdb`.
// SQLite URI (directory) for `sqlite` handler.
// See https://www.sqlite.org/uri.html.
SQLiteURL string // For example: `file:data/`.
}
// ListenerConfig represents listener configuration.
type ListenerConfig struct {
// Listen TCP address.
// If empty, TCP listener is disabled.
TCP string
// Listen Unix domain socket path.
// If empty, Unix listener is disabled.
Unix string
// Listen TLS address.
// If empty, TLS listener is disabled.
TLS string
// Server certificate path.
TLSCertFile string
// Server key path.
TLSKeyFile string
// Root CA certificate path.
TLSCAFile string
}
// FerretDB represents an instance of embeddable FerretDB implementation.
type FerretDB struct {
config *Config
closeBackend func()
l *clientconn.Listener
}
// New creates a new instance of embeddable FerretDB implementation.
func New(config *Config) (*FerretDB, error) {
version.Get().Package = "embedded"
if config.Listener.TCP == "" &&
config.Listener.Unix == "" &&
config.Listener.TLS == "" {
return nil, errors.New("Listener TCP, Unix and TLS are empty")
}
sp, err := state.NewProvider("")
if err != nil {
return nil, fmt.Errorf("failed to construct handler: %s", err)
}
// Telemetry reporter is not created or running anyway,
// but disable telemetry explicitly to disable confusing startupWarnings.
err = sp.Update(func(s *state.State) {
s.DisableTelemetry()
s.TelemetryLocked = true
})
if err != nil {
return nil, fmt.Errorf("failed to construct handler: %s", err)
}
metrics := connmetrics.NewListenerMetrics()
log := config.Logger
if log == nil {
log = getGlobalLogger()
} else {
log = logging.WithHooks(log)
}
h, closeBackend, err := registry.NewHandler(config.Handler, ®istry.NewHandlerOpts{
Logger: log,
ConnMetrics: metrics.ConnMetrics,
StateProvider: sp,
TCPHost: config.Listener.TCP,
PostgreSQLURL: config.PostgreSQLURL,
SQLiteURL: config.SQLiteURL,
TestOpts: registry.TestOpts{
CappedCleanupPercentage: 10, // handler expects it to be a non-zero value
},
})
if err != nil {
return nil, fmt.Errorf("failed to construct handler: %s", err)
}
l := clientconn.NewListener(&clientconn.NewListenerOpts{
TCP: config.Listener.TCP,
Unix: config.Listener.Unix,
TLS: config.Listener.TLS,
TLSCertFile: config.Listener.TLSCertFile,
TLSKeyFile: config.Listener.TLSKeyFile,
TLSCAFile: config.Listener.TLSCAFile,
Mode: clientconn.NormalMode,
Metrics: metrics,
Handler: h,
Logger: log,
})
return &FerretDB{
config: config,
closeBackend: closeBackend,
l: l,
}, nil
}
// Run runs FerretDB until ctx is canceled.
//
// When this method returns, listener and all connections, as well as handler are closed.
//
// It is required to run this method in order to initialize the listeners with their respective
// IP address and port. Calling methods which require the listener's address (eg: [*FerretDB.MongoDBURI]
// requires it for configuring its Host URL) before calling this method might result in a deadlock.
func (f *FerretDB) Run(ctx context.Context) error {
defer f.closeBackend()
err := f.l.Run(ctx)
if errors.Is(err, context.Canceled) {
err = nil
}
if err != nil {
// Do not expose internal error details.
// If you need stable error values and/or types for some cases, please create an issue.
err = errors.New(err.Error())
}
return err
}
// MongoDBURI returns MongoDB URI for this FerretDB instance.
//
// TCP's connection string is returned if both TCP and Unix listeners are enabled.
// TLS is preferred over both.
func (f *FerretDB) MongoDBURI() string {
var u *url.URL
switch {
case f.config.Listener.TLS != "":
q := url.Values{
"tls": []string{"true"},
}
u = &url.URL{
Scheme: "mongodb",
Host: f.l.TLSAddr().String(),
Path: "/",
RawQuery: q.Encode(),
}
case f.config.Listener.TCP != "":
u = &url.URL{
Scheme: "mongodb",
Host: f.l.TCPAddr().String(),
Path: "/",
}
case f.config.Listener.Unix != "":
// MongoDB really wants Unix domain socket path in the host part of the URI
u = &url.URL{
Scheme: "mongodb",
Host: f.l.UnixAddr().String(),
Path: "/",
}
}
return u.String()
}
var (
loggerOnce sync.Once
logger *zap.Logger
)
// getGlobalLogger retrieves or creates a global logger using
// a loggerOnce to ensure it is created only once.
func getGlobalLogger() *zap.Logger {
loggerOnce.Do(func() {
level := zap.ErrorLevel
if version.Get().DebugBuild {
level = zap.DebugLevel
}
logging.Setup(level, "console", "")
logger = zap.L()
})
return logger
}