forked from FerretDB/FerretDB
/
main.go
273 lines (221 loc) · 7.94 KB
/
main.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
// 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 main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/alecthomas/kong"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/expfmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/maps"
"github.com/FerretDB/FerretDB/internal/clientconn"
"github.com/FerretDB/FerretDB/internal/clientconn/connmetrics"
"github.com/FerretDB/FerretDB/internal/handlers/common"
"github.com/FerretDB/FerretDB/internal/handlers/registry"
"github.com/FerretDB/FerretDB/internal/util/debug"
"github.com/FerretDB/FerretDB/internal/util/logging"
"github.com/FerretDB/FerretDB/internal/util/state"
"github.com/FerretDB/FerretDB/internal/util/version"
)
// The cli struct represents all command-line commands, fields and flags.
// It's used for parsing the user input.
var cli struct {
ListenAddr string `default:"127.0.0.1:27017" help:"Listen address."`
ProxyAddr string `default:"127.0.0.1:37017" help:"Proxy address."`
DebugAddr string `default:"127.0.0.1:8088" help:"${help_debug_addr}"`
StateDir string `default:"." help:"Process state directory."`
Mode string `default:"${default_mode}" help:"${help_mode}" enum:"${enum_mode}"`
Log struct {
Level string `default:"${default_log_level}" help:"${help_log_level}"`
UUID bool `default:"false" help:"Add instance UUID to all log messages."`
} `embed:"" prefix:"log-"`
MetricsUUID bool `default:"false" help:"Add instance UUID to all metrics."`
Handler string `default:"pg" help:"${help_handler}"`
PostgreSQLURL string `name:"postgresql-url" default:"${default_postgresql_url}" help:"PostgreSQL URL for 'pg' handler."`
// Put flags for other handlers there, between --postgresql-url and --version in the help output.
kong.Plugins
Version bool `default:"false" help:"Print version to stdout and exit."`
Test struct {
ConnTimeout time.Duration `default:"0" help:"Testing flag: client connection timeout."`
RecordsDir string `default:"" help:"Testing flag: directory for record files."`
} `embed:"" prefix:"test-"`
}
// The tigrisFlags struct represents flags that are used specifically for a "tigris" handler.
//
// See main_tigris.go.
var tigrisFlags struct {
TigrisURL string `default:"127.0.0.1:8081" help:"Tigris URL for 'tigris' handler."`
TigrisClientID string `default:"" help:"Tigris Client ID."`
TigrisClientSecret string `default:"" help:"Tigris Client secret."`
TigrisToken string `default:"" help:"Tigris token."`
}
// Additional variables for the kong parsers.
var (
logLevels = []string{
zap.DebugLevel.String(),
zap.InfoLevel.String(),
zap.WarnLevel.String(),
zap.ErrorLevel.String(),
}
kongOptions = []kong.Option{
kong.Vars{
"default_log_level": zap.DebugLevel.String(),
"default_mode": clientconn.AllModes[0],
"default_postgresql_url": "postgres://postgres@127.0.0.1:5432/ferretdb",
"help_debug_addr": "Debug address for /debug/metrics, /debug/pprof, and similar HTTP handlers.",
"help_log_level": fmt.Sprintf(
"Log level: '%s'. Debug level also enables development mode.",
strings.Join(logLevels, "', '"),
),
"help_mode": fmt.Sprintf("Operation mode: '%s'.", strings.Join(clientconn.AllModes, "', '")),
"help_handler": fmt.Sprintf("Backend handler: '%s'.", strings.Join(registry.Handlers(), "', '")),
"enum_mode": strings.Join(clientconn.AllModes, ","),
},
kong.DefaultEnvars("FERRETDB"),
}
)
func main() {
kong.Parse(&cli, kongOptions...)
run()
}
// setupState setups state provider.
func setupState() (*state.Provider, string) {
f, err := filepath.Abs(filepath.Join(cli.StateDir, "state.json"))
if err != nil {
log.Fatalf("Failed to get path for state file: %s.", err)
}
p, err := state.NewProvider(f)
if err != nil {
log.Fatalf("Failed to create state provider: %s.", err)
}
s, err := p.Get()
if err != nil {
log.Fatalf("Failed to get state: %s.", err)
}
return p, s.UUID
}
// setupMetrics setups Prometheus metrics registerer with some metrics.
func setupMetrics(stateProvider *state.Provider, uuid string) prometheus.Registerer {
r := prometheus.WrapRegistererWith(
prometheus.Labels{"uuid": uuid},
prometheus.DefaultRegisterer,
)
m := stateProvider.MetricsCollector(false)
// Unless requested, don't add UUID to all metrics, but add it to one.
// See https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels
if !cli.MetricsUUID {
r = prometheus.DefaultRegisterer
m = stateProvider.MetricsCollector(true)
}
r.MustRegister(m)
return r
}
// setupLogger setups zap logger.
func setupLogger(uuid string) *zap.Logger {
info := version.Get()
logUUID := uuid
startupFields := []zap.Field{
zap.String("version", info.Version),
zap.String("commit", info.Commit),
zap.String("branch", info.Branch),
zap.Bool("dirty", info.Dirty),
zap.Bool("debug", info.Debug),
zap.Reflect("buildEnvironment", info.BuildEnvironment.Map()),
}
// Similarly to Prometheus, unless requested, don't add UUID to all messages, but log it once at startup.
if !cli.Log.UUID {
logUUID = ""
startupFields = append(startupFields, zap.String("uuid", uuid))
}
level, err := zapcore.ParseLevel(cli.Log.Level)
if err != nil {
log.Fatal(err)
}
logging.Setup(level, logUUID)
l := zap.L()
l.Info("Starting FerretDB "+info.Version+"...", startupFields...)
return l
}
// run sets up environment based on provided flags and runs FerretDB.
func run() {
if cli.Version {
info := version.Get()
fmt.Fprintln(os.Stdout, "version:", info.Version)
fmt.Fprintln(os.Stdout, "commit:", info.Commit)
fmt.Fprintln(os.Stdout, "branch:", info.Branch)
fmt.Fprintln(os.Stdout, "dirty:", info.Dirty)
return
}
stateProvider, uuid := setupState()
metricsRegisterer := setupMetrics(stateProvider, uuid)
logger := setupLogger(uuid)
ctx, stop := notifyAppTermination(context.Background())
go func() {
<-ctx.Done()
logger.Info("Stopping...")
stop()
}()
go debug.RunHandler(ctx, cli.DebugAddr, metricsRegisterer, logger.Named("debug"))
cmdsList := maps.Keys(common.Commands)
sort.Strings(cmdsList)
metrics := connmetrics.NewListenerMetrics(cmdsList)
h, err := registry.NewHandler(cli.Handler, ®istry.NewHandlerOpts{
Ctx: ctx,
Logger: logger,
Metrics: metrics.ConnMetrics,
PostgreSQLURL: cli.PostgreSQLURL,
TigrisClientID: tigrisFlags.TigrisClientID,
TigrisClientSecret: tigrisFlags.TigrisClientSecret,
TigrisToken: tigrisFlags.TigrisToken,
TigrisURL: tigrisFlags.TigrisURL,
})
if err != nil {
logger.Fatal(err.Error())
}
defer h.Close()
l := clientconn.NewListener(&clientconn.NewListenerOpts{
ListenAddr: cli.ListenAddr,
ProxyAddr: cli.ProxyAddr,
Mode: clientconn.Mode(cli.Mode),
Handler: h,
Metrics: metrics,
Logger: logger,
TestConnTimeout: cli.Test.ConnTimeout,
TestRecordsDir: cli.Test.RecordsDir,
})
metricsRegisterer.MustRegister(l)
err = l.Run(ctx)
if err == nil || err == context.Canceled {
logger.Info("Listener stopped")
} else {
logger.Error("Listener stopped", zap.Error(err))
}
mfs, err := prometheus.DefaultGatherer.Gather()
if err != nil {
panic(err)
}
for _, mf := range mfs {
if _, err := expfmt.MetricFamilyToText(os.Stderr, mf); err != nil {
panic(err)
}
}
}