Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
2226 lines (1925 loc) · 75.9 KB
/
Copy pathmain.go
File metadata and controls
2226 lines (1925 loc) · 75.9 KB
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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/google/uuid"
"github.com/urfave/cli/v3"
"github.com/fclairamb/dbbat/internal/api"
"github.com/fclairamb/dbbat/internal/approval"
"github.com/fclairamb/dbbat/internal/cache"
"github.com/fclairamb/dbbat/internal/config"
"github.com/fclairamb/dbbat/internal/crypto"
"github.com/fclairamb/dbbat/internal/dump"
"github.com/fclairamb/dbbat/internal/dump/decode"
"github.com/fclairamb/dbbat/internal/events"
"github.com/fclairamb/dbbat/internal/notify"
"github.com/fclairamb/dbbat/internal/proxy/mongodb"
"github.com/fclairamb/dbbat/internal/proxy/mssql"
"github.com/fclairamb/dbbat/internal/proxy/mysql"
"github.com/fclairamb/dbbat/internal/proxy/oracle"
"github.com/fclairamb/dbbat/internal/proxy/postgresql"
"github.com/fclairamb/dbbat/internal/proxy/shared"
"github.com/fclairamb/dbbat/internal/store"
)
const shutdownTimeout = 30 * time.Second
// setupLogger creates the logger, optionally writing to a file in test mode.
// Returns the logger and a cleanup function to close the log file (if any).
func setupLogger(runMode config.RunMode, level slog.Level) (*slog.Logger, func()) {
var writer io.Writer = os.Stdout
var cleanup func()
if runMode == config.RunModeTest {
writer, cleanup = setupTestLogFile()
}
logger := slog.New(slog.NewJSONHandler(writer, &slog.HandlerOptions{
Level: level,
}))
return logger, cleanup
}
// setupTestLogFile creates a log file for test mode and returns a writer and cleanup function.
func setupTestLogFile() (io.Writer, func()) {
logDir := "logs"
if err := os.MkdirAll(logDir, 0o755); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to create logs directory: %v\n", err)
return os.Stdout, nil
}
dateTimePrefix := time.Now().Format("2006-01-02_15-04-05")
logFileName := filepath.Join(logDir, fmt.Sprintf("%s_dbbat.log", dateTimePrefix))
logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to create log file: %v\n", err)
return os.Stdout, nil
}
return io.MultiWriter(os.Stdout, logFile), func() { _ = logFile.Close() }
}
// cliFlags holds CLI flag values that will override config.
type cliFlags struct {
listenAddr string
apiAddr string
dsn string
key string
keyFile string
configFile string
logLevel string
}
func main() {
CmdRun()
}
func CmdRun() {
flags := &cliFlags{}
cmd := &cli.Command{
Name: "dbbat",
Usage: "PostgreSQL observability proxy with controlled access",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "listen-addr",
Aliases: []string{"l"},
Usage: "Proxy listen address",
Destination: &flags.listenAddr,
},
&cli.StringFlag{
Name: "api-addr",
Aliases: []string{"a"},
Usage: "REST API listen address",
Destination: &flags.apiAddr,
},
&cli.StringFlag{
Name: "dsn",
Aliases: []string{"d"},
Usage: "PostgreSQL DSN for DBBat storage",
Destination: &flags.dsn,
},
&cli.StringFlag{
Name: "key",
Aliases: []string{"k"},
Usage: "Base64-encoded AES-256 encryption key",
Destination: &flags.key,
},
&cli.StringFlag{
Name: "keyfile",
Usage: "Path to file containing encryption key",
Destination: &flags.keyFile,
},
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Usage: "Path to config file (YAML, JSON, or TOML)",
Destination: &flags.configFile,
},
&cli.StringFlag{
Name: "log-level",
Usage: "Log level (debug, info, warn, error)",
Sources: cli.EnvVars("DBB_LOG_LEVEL"),
Destination: &flags.logLevel,
},
},
Commands: []*cli.Command{
{
Name: "serve",
Usage: "Start DBBat server (default)",
Action: func(ctx context.Context, _ *cli.Command) error {
return runServer(ctx, flags)
},
},
{
Name: "db",
Usage: "Server migration commands",
Commands: []*cli.Command{
{
Name: "migrate",
Usage: "Run pending migrations",
Action: func(ctx context.Context, _ *cli.Command) error {
return runMigrate(ctx, flags)
},
},
{
Name: "rollback",
Usage: "Rollback the last migration group",
Action: func(ctx context.Context, _ *cli.Command) error {
return runRollback(ctx, flags)
},
},
{
Name: "status",
Usage: "Show migration status",
Action: func(ctx context.Context, _ *cli.Command) error {
return runMigrationStatus(ctx, flags)
},
},
},
},
dumpCommand(),
auditCommand(flags),
},
Action: func(ctx context.Context, _ *cli.Command) error {
// Default action is to serve
return runServer(ctx, flags)
},
}
// Use a basic logger for CLI errors (before config is loaded)
basicLogger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
if err := cmd.Run(context.Background(), os.Args); err != nil {
basicLogger.ErrorContext(context.Background(), "Application error", slog.Any("error", err))
os.Exit(1)
}
}
// buildCLIOverrides creates a config override function from CLI flags.
func buildCLIOverrides(flags *cliFlags) func(*config.Config) {
return func(cfg *config.Config) {
if flags.listenAddr != "" {
cfg.ListenPG = flags.listenAddr
}
if flags.apiAddr != "" {
cfg.ListenAPI = flags.apiAddr
}
if flags.dsn != "" {
cfg.DSN = flags.dsn
}
if flags.key != "" {
cfg.Key = flags.key
}
if flags.keyFile != "" {
cfg.KeyFile = flags.keyFile
}
if flags.configFile != "" {
cfg.ConfigFile = flags.configFile
}
if flags.logLevel != "" {
cfg.LogLevel = flags.logLevel
}
}
}
// loadConfigWithCLI loads configuration with CLI flag overrides.
func loadConfigWithCLI(flags *cliFlags) (*config.Config, error) {
opts := config.LoadOptions{
ConfigFile: flags.configFile,
}
return config.Load(opts, buildCLIOverrides(flags))
}
// warnStatementTimeout says out loud that a malformed statement timeout
// disables the limit rather than shortening it (see Config.StatementTimeout):
// the operator asked for a bound and silently has none.
func warnStatementTimeout(ctx context.Context, cfg *config.Config, logger *slog.Logger) {
if cfg.StatementTimeoutMisconfigured() {
logger.WarnContext(ctx, "Invalid DBB_STATEMENT_TIMEOUT, no instance-wide statement limit is applied",
slog.String("value", cfg.StatementTimeout),
slog.String("hint", "use a Go duration such as 30s or 5m"))
}
}
func runServer(ctx context.Context, flags *cliFlags) error {
// Load configuration first
cfg, err := loadConfigWithCLI(flags)
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
// Setup logger with run mode and log level from config
logLevel := config.ParseLogLevel(cfg.LogLevel)
logger, logCleanup := setupLogger(cfg.RunMode, logLevel)
if logCleanup != nil {
defer logCleanup()
}
slog.SetDefault(logger)
logger.InfoContext(ctx, "Starting DBBat")
logger.InfoContext(ctx, "Configuration loaded",
slog.String("proxy_addr", cfg.ListenPG),
slog.String("api_addr", cfg.ListenAPI),
slog.Any("run_mode", cfg.RunMode),
slog.String("log_level", cfg.LogLevel),
slog.String("instance_id", cfg.InstanceID),
)
// Initialize store (with table drop if in test or demo mode)
storeOpts := store.Options{
DropTablesFirst: cfg.RunMode == config.RunModeTest || cfg.RunMode == config.RunModeDemo,
InstanceID: cfg.InstanceID,
// Seals the audit and query chains. The store keeps only an HKDF
// subkey of this; see docs/audit-chain.md.
EncryptionKey: cfg.EncryptionKey,
// Not what drives the sweep (startRetentionSweeper owns that) —
// what lets chain verification and the connection detail API tell a
// session retention emptied from one somebody emptied. The **query**
// window, resolved: the ledger window only decides whether the session
// row survives, and an incoherent pair resolves both to zero, which is
// also what the sweep does.
QueryRetention: cfg.RetentionWindows().Queries,
ArchiveRetention: cfg.RetentionWindows().QueriesArchive,
}
if cfg.RunMode == config.RunModeTest {
logger.InfoContext(ctx, "Test mode enabled, will drop all tables before migration")
}
if cfg.RunMode == config.RunModeDemo {
logger.WarnContext(ctx, "WARNING: Running in DEMO mode. Do not use in production environments.")
logger.InfoContext(ctx, "Demo mode enabled, will drop all tables before migration")
}
dataStore, err := store.New(ctx, cfg.DSN, storeOpts)
if err != nil {
return fmt.Errorf("failed to initialize store: %w", err)
}
defer dataStore.Close()
logger.InfoContext(ctx, "Server connection established")
// Check for database configurations that match the storage DSN
checkDatabaseConfigurations(ctx, dataStore, logger)
// Announce this process, then close what dead processes left open. Both
// must happen before any proxy accepts.
heartbeat := registerAndReconcile(ctx, dataStore, logger)
// Ensure default admin exists
defaultPassword := "admin"
passwordHash, err := crypto.HashPassword(defaultPassword)
if err != nil {
return fmt.Errorf("failed to hash default admin password: %w", err)
}
created, err := dataStore.EnsureDefaultAdmin(ctx, passwordHash)
if err != nil {
return fmt.Errorf("failed to ensure default admin: %w", err)
}
if created {
logger.InfoContext(ctx, "Default admin user created (username: admin, password: admin)")
}
// Provision test data if in test mode
if cfg.RunMode == config.RunModeTest {
if err := provisionTestData(ctx, dataStore, cfg.EncryptionKey, logger); err != nil {
return fmt.Errorf("failed to provision test data: %w", err)
}
}
// Provision demo data if in demo mode
if cfg.RunMode == config.RunModeDemo {
if err := provisionDemoData(ctx, dataStore, cfg, logger); err != nil {
return fmt.Errorf("failed to provision demo data: %w", err)
}
}
// One capture uploader for the whole process (nil when
// DBB_DUMP_UPLOAD_URL is unset, which is the default and means captures
// stay on local disk).
dumpUploader, err := startDumpUploader(ctx, cfg, dataStore, logger)
if err != nil {
return err
}
apiServer, approvals, approvalDeps := buildEventPlumbing(ctx, cfg, dataStore, logger)
apiServer.SetDumpStorage(dumpUploader)
// The six listener goroutines in this file — this one and the five protocol
// servers below — are the *only* goroutines in the process deliberately left
// without a panic guard, and the reason does not generalise to anything else
// here. Each one is a listener's accept loop, and each already treats its own
// failure as fatal: the os.Exit(1) below says the process without this
// listener is not a process worth keeping. Recovering would leave dbbat
// running while silently serving nothing on that port. Per-connection panics
// never reach here — handleConnection recovers them one session at a time.
//
// Everything else in package main that runs on a goroutine is guarded: see
// retention.go and heartbeat.go, both of which are ordinary maintenance loops
// under safe.RunMaintenance.
go func() {
if err := apiServer.Start(cfg.ListenAPI); err != nil {
logger.ErrorContext(context.Background(), "API server error", slog.Any("error", err))
os.Exit(1)
}
}()
logger.InfoContext(ctx, "API server started", slog.String("addr", cfg.ListenAPI))
// One result-row writer for the whole process (see shared.RowWriter).
rowWriter := shared.NewRowWriter(dataStore, logger)
// Create auth cache for proxy server (shared cache config with API)
proxyAuthCache := cache.NewAuthCache(cache.AuthCacheConfig{
Enabled: cfg.AuthCache.Enabled,
TTLSeconds: cfg.AuthCache.TTLSeconds,
MaxSize: cfg.AuthCache.MaxSize,
})
warnStatementTimeout(ctx, cfg, logger)
// The proxies count login failures in the API's own tracker; test mode
// counts but never refuses, as the API skips its backoff there.
loginThrottles := loginThrottleFactory(apiServer.AuthFailureTracker(), dataStore, logger, cfg.RunMode != config.RunModeTest)
proxies := startProxies(ctx, cfg, dataStore, proxyAuthCache, approvalDeps, rowWriter, dumpUploader, loginThrottles, logger)
sweeper, err := startRetention(ctx, cfg, dataStore, apiServer, logger)
if err != nil {
return err
}
// Expired OAuth/device/login-exchange states are purged whatever the
// retention settings: unauthenticated endpoints create them.
oauthPurger := startOAuthStatePurge(ctx, dataStore, logger)
// Draining releases parked queries first, then stops the servers.
servers := collectServers(approvalDrain{approvals, logger}, apiServer, proxies.postgres,
proxies.oracle, proxies.mysql, proxies.mongo, proxies.mssql,
rowWriter, sweeper, oauthPurger, heartbeat, dumpUploader)
return awaitShutdown(ctx, logger, servers...)
}
// loginThrottleFactory returns the constructor of each listener's login
// throttle, all of them on the one tracker the REST API uses: a dbbat password
// is one secret whichever port it is guessed on, and two counters would double
// the guessing budget.
func loginThrottleFactory(
tracker *cache.AuthFailureTracker, dataStore *store.Store, logger *slog.Logger, enforce bool,
) func(listener string) *shared.LoginThrottle {
var auditStore shared.LoginAuditStore
if dataStore != nil {
auditStore = dataStore
}
return func(listener string) *shared.LoginThrottle {
return shared.NewLoginThrottle(tracker, auditStore, logger, listener, enforce)
}
}
// proxySet holds the protocol listeners this process started. Every field
// except postgres is nil when its listen address is empty.
type proxySet struct {
postgres *postgresql.Server
oracle *oracle.Server
mysql *mysql.Server
mongo *mongodb.Server
mssql *mssql.Server
}
// startProxies brings up every configured protocol listener and hands each one
// the process-wide capture uploader.
func startProxies(
ctx context.Context,
cfg *config.Config,
dataStore *store.Store,
authCache *cache.AuthCache,
approvalDeps shared.ApprovalDeps,
rowWriter *shared.RowWriter,
dumpUploader *dump.Uploader,
loginThrottles func(listener string) *shared.LoginThrottle,
logger *slog.Logger,
) proxySet {
set := proxySet{
postgres: startPostgresProxy(ctx, cfg, dataStore, authCache, approvalDeps, rowWriter, loginThrottles, logger),
oracle: startOracleProxy(ctx, cfg, dataStore, authCache, approvalDeps, rowWriter, logger),
mysql: startMySQLProxy(ctx, cfg, dataStore, authCache, approvalDeps, rowWriter, loginThrottles, logger),
mongo: startMongoProxy(ctx, cfg, dataStore, authCache, approvalDeps, rowWriter, loginThrottles, logger),
mssql: startMSSQLProxy(ctx, cfg, dataStore, authCache, approvalDeps, rowWriter, loginThrottles, logger),
}
// One resolver for the whole process: the store memoizes the parameters,
// so five resolvers would share one cache anyway, but building them here
// keeps the "who imposes the limit / who decides the tag" wiring in one
// place.
statementTimeouts := shared.NewStatementTimeoutResolver(dataStore, cfg)
queryTagging := shared.NewQueryTaggingResolver(dataStore, cfg)
set.postgres.SetStatementTimeouts(statementTimeouts)
set.postgres.SetQueryTaggingResolver(queryTagging)
if set.oracle != nil {
set.oracle.SetStatementTimeouts(statementTimeouts)
set.oracle.SetQueryTaggingResolver(queryTagging)
}
if set.mysql != nil {
set.mysql.SetStatementTimeouts(statementTimeouts)
set.mysql.SetQueryTaggingResolver(queryTagging)
}
if set.mongo != nil {
set.mongo.SetStatementTimeouts(statementTimeouts)
set.mongo.SetQueryTaggingResolver(queryTagging)
}
if set.mssql != nil {
set.mssql.SetStatementTimeouts(statementTimeouts)
}
// The dbbat identity tag, on the three protocols that have somewhere to put
// it: a sqlcommenter-style comment on PostgreSQL and MySQL/MariaDB, the
// `comment` command field on MongoDB. Oracle is deliberately absent —
// V$SQL deduplicates on statement text, so a per-connection tag would
// defeat its shared-cursor cache — and so is SQL Server.
//
// These SetQueryTagging calls now only carry the DBB_QUERY_TAGGING
// *default* each proxy falls back to when the store is unreadable; the
// resolvers installed above decide per session, from the tagging.*
// parameters the Settings page edits.
if cfg.QueryTagging.Enabled {
set.postgres.SetQueryTagging(true)
if set.mysql != nil {
set.mysql.SetQueryTagging(true)
}
if set.mongo != nil {
set.mongo.SetQueryTagging(true)
}
logger.InfoContext(ctx, "statement tagging enabled",
slog.String("protocols", "postgresql,mysql,mongodb"))
}
set.postgres.SetDumpUploader(dumpUploader)
if set.oracle != nil {
set.oracle.SetDumpUploader(dumpUploader)
}
if set.mysql != nil {
set.mysql.SetDumpUploader(dumpUploader)
}
if set.mongo != nil {
set.mongo.SetDumpUploader(dumpUploader)
}
if set.mssql != nil {
set.mssql.SetDumpUploader(dumpUploader)
}
return set
}
// registerAndReconcile puts this process in the instance registry and then
// clears the connection rows left behind by processes that are gone.
//
// The order matters twice over. The reconcile reads the registry, so our own
// row has to be there first; and every other replica reads the registry to
// decide whether our connections are live, so the row must exist before this
// process opens any. Both therefore run before any proxy accepts — a session
// opened by this run can never be caught by its own reconcile.
//
// Returns the heartbeat that keeps our row fresh, for the shutdown sequence to
// stop last of all. Nil when there is no instance id to register.
func registerAndReconcile(ctx context.Context, dataStore *store.Store, logger *slog.Logger) *instanceHeartbeat {
heartbeat := startInstanceHeartbeat(ctx, dataStore, logger)
reconcileOrphanedConnections(ctx, dataStore, logger)
return heartbeat
}
// reconcileOrphanedConnections closes the connection rows left open by a
// process that is no longer running. Without it a crash, a kill or a pod
// reschedule leaves disconnected_at NULL forever, and the retention sweep —
// which deliberately never reaps a connection that still looks open — can never
// remove those rows.
//
// It covers this instance id's own leftovers (DBB_INSTANCE_ID, defaulting to
// the hostname) plus those of any instance the registry proves is gone. dbbat
// runs with more than one replica against a shared store, so a blanket update
// would let a starting replica close another replica's live sessions; liveness,
// tracked by the instance heartbeat, is what makes widening it safe. See
// store.CloseOrphanedConnections.
//
// The two counts are logged separately, and reclaims are logged even when the
// own count is zero: connections reclaimed from another instance mean a process
// died without shutting down, which is worth noticing on its own.
//
// This is the startup pass only. The reclaim half also runs periodically on the
// heartbeat loop (instanceHeartbeat.reclaim), because an instance that dies
// while this deployment stays up would otherwise not be noticed by anyone: its
// registry row is fresh when its replacement starts, and stale only long after.
//
// A failure here is logged, not fatal: stale bookkeeping must not stop the
// proxy from serving traffic.
func reconcileOrphanedConnections(ctx context.Context, dataStore *store.Store, logger *slog.Logger) {
closed, err := dataStore.CloseOrphanedConnections(ctx)
if err != nil {
logger.ErrorContext(ctx, "failed to reconcile orphaned connections", slog.Any("error", err))
return
}
if closed.Own > 0 {
// Worth info level: a large count means a previous run did not shut
// down cleanly. Zero does not mean the opposite — a run that crashed
// moments ago still looks alive in the registry, and its rows are
// picked up by a later reclaim rather than here.
logger.InfoContext(ctx, "Closed connections left open by a previous run",
slog.Int64("connections", closed.Own),
slog.String("instance_id", dataStore.InstanceID()),
slog.String("run_id", dataStore.RunID()))
}
logReclaimedConnections(ctx, logger, closed.Reclaimed)
// Housekeeping, after the reclaim so it still saw the rows it judged.
pruneStaleInstances(ctx, dataStore, logger)
}
// logReclaimedConnections reports connections closed on behalf of an instance
// that is provably gone. Shared by the startup reconcile and the periodic
// reclaim on the heartbeat loop so both read identically in the logs: whenever
// it happens, a non-zero count means a process died without shutting down.
func logReclaimedConnections(ctx context.Context, logger *slog.Logger, reclaimed int64) {
if reclaimed <= 0 {
return
}
logger.InfoContext(ctx, "Reclaimed connections left open by instances that are gone",
slog.Int64("connections", reclaimed),
slog.Duration("stale_after", store.InstanceStaleAfter))
}
// pruneStaleInstances drops registry rows whose owner is past the grace period.
// Pure housekeeping — a stale row and a missing row mean the same thing to the
// reclaim — so a failure is a warning and the count is only worth debug level.
// Always call it after a reclaim, never before, so the reclaim still sees the
// rows it is judging.
func pruneStaleInstances(ctx context.Context, dataStore *store.Store, logger *slog.Logger) {
pruned, err := dataStore.PruneStaleInstances(ctx)
if err != nil {
logger.WarnContext(ctx, "failed to prune stale instances", slog.Any("error", err))
return
}
if pruned > 0 {
logger.DebugContext(ctx, "Pruned stale instance registrations", slog.Int64("instances", pruned))
}
}
// shutdownable is implemented by servers that support graceful shutdown.
type shutdownable interface {
Shutdown(ctx context.Context) error
}
// awaitShutdown waits for an OS interrupt signal and then gracefully shuts down all servers.
func awaitShutdown(ctx context.Context, logger *slog.Logger, servers ...shutdownable) error {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
<-sigChan
logger.InfoContext(ctx, "Shutdown signal received, gracefully shutting down...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
for _, srv := range servers {
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.ErrorContext(shutdownCtx, "server shutdown error", slog.Any("error", err))
}
}
logger.InfoContext(shutdownCtx, "Shutdown complete")
return nil
}
// startPostgresProxy builds and starts the PostgreSQL proxy. Unlike the other
// three it has no listener-disabled case: PostgreSQL is dbbat's default
// protocol and DBB_LISTEN_PG always has a value.
func startPostgresProxy(
ctx context.Context,
cfg *config.Config,
dataStore *store.Store,
authCache *cache.AuthCache,
approvalDeps shared.ApprovalDeps,
rowWriter *shared.RowWriter,
loginThrottles func(listener string) *shared.LoginThrottle,
logger *slog.Logger,
) *postgresql.Server {
srv, err := postgresql.NewServer(dataStore, cfg.EncryptionKey, cfg.QueryStorage, cfg.Dump, authCache, cfg.PG, logger)
if err != nil {
logger.ErrorContext(ctx, "PostgreSQL proxy server init failed", slog.Any("error", err))
os.Exit(1)
}
srv.SetLoginThrottle(loginThrottles(store.ProtocolPostgreSQL))
srv.SetApprovalDeps(approvalDeps)
srv.SetRowWriter(rowWriter)
go func() {
if err := srv.Start(cfg.ListenPG); err != nil {
logger.ErrorContext(context.Background(), "Proxy server error", slog.Any("error", err))
os.Exit(1)
}
}()
logger.InfoContext(ctx, "Proxy server started",
slog.String("addr", cfg.ListenPG),
slog.Bool("tls", !cfg.PG.TLS.Disable))
return srv
}
func startOracleProxy(
ctx context.Context,
cfg *config.Config,
dataStore *store.Store,
authCache *cache.AuthCache,
approvalDeps shared.ApprovalDeps,
rowWriter *shared.RowWriter,
logger *slog.Logger,
) *oracle.Server {
if cfg.ListenOracle == "" {
return nil
}
// A typo here is a startup failure rather than a silent "off": the absence
// of a tag looks exactly like the feature being disabled, so an operator
// who asked for attribution and got none would have no way to tell.
tagging, err := cfg.QueryTagging.ResolveOracle()
if err != nil {
logger.ErrorContext(ctx, "Oracle statement tagging misconfigured", slog.Any("error", err))
os.Exit(1)
}
srv := oracle.NewServer(dataStore, cfg.EncryptionKey, authCache, cfg.QueryStorage, cfg.Dump, logger)
srv.SetApprovalDeps(approvalDeps)
srv.SetRowWriter(rowWriter)
srv.SetStatementTagging(tagging)
go func() {
if err := srv.Start(cfg.ListenOracle); err != nil {
logger.ErrorContext(context.Background(), "Oracle proxy server error", slog.Any("error", err))
os.Exit(1)
}
}()
logger.InfoContext(ctx, "Oracle proxy server started", slog.String("addr", cfg.ListenOracle))
return srv
}
func startMySQLProxy(
ctx context.Context,
cfg *config.Config,
dataStore *store.Store,
authCache *cache.AuthCache,
approvalDeps shared.ApprovalDeps,
rowWriter *shared.RowWriter,
loginThrottles func(listener string) *shared.LoginThrottle,
logger *slog.Logger,
) *mysql.Server {
if cfg.ListenMySQL == "" {
return nil
}
srv, err := mysql.NewServer(dataStore, cfg.EncryptionKey, cfg.QueryStorage, cfg.Dump, authCache, cfg.MySQL, logger)
if err != nil {
logger.ErrorContext(ctx, "MySQL proxy server init failed", slog.Any("error", err))
os.Exit(1)
}
srv.SetLoginThrottle(loginThrottles(store.ProtocolMySQL))
srv.SetApprovalDeps(approvalDeps)
srv.SetRowWriter(rowWriter)
go func() {
if err := srv.Start(cfg.ListenMySQL); err != nil {
logger.ErrorContext(context.Background(), "MySQL proxy server error", slog.Any("error", err))
os.Exit(1)
}
}()
logger.InfoContext(ctx, "MySQL proxy server started",
slog.String("addr", cfg.ListenMySQL),
slog.Bool("tls", !cfg.MySQL.TLS.Disable))
return srv
}
func startMongoProxy(
ctx context.Context,
cfg *config.Config,
dataStore *store.Store,
authCache *cache.AuthCache,
approvalDeps shared.ApprovalDeps,
rowWriter *shared.RowWriter,
loginThrottles func(listener string) *shared.LoginThrottle,
logger *slog.Logger,
) *mongodb.Server {
if cfg.ListenMongo == "" {
return nil
}
srv, err := mongodb.NewServer(dataStore, cfg.EncryptionKey, cfg.QueryStorage, cfg.Dump, authCache, cfg.Mongo, logger)
if err != nil {
logger.ErrorContext(ctx, "MongoDB proxy server init failed", slog.Any("error", err))
os.Exit(1)
}
srv.SetLoginThrottle(loginThrottles(store.ProtocolMongoDB))
srv.SetApprovalDeps(approvalDeps)
srv.SetRowWriter(rowWriter)
go func() {
if err := srv.Start(cfg.ListenMongo); err != nil {
logger.ErrorContext(context.Background(), "MongoDB proxy server error", slog.Any("error", err))
os.Exit(1)
}
}()
logger.InfoContext(ctx, "MongoDB proxy server started",
slog.String("addr", cfg.ListenMongo),
slog.Bool("tls", !cfg.Mongo.TLS.Disable))
return srv
}
// startMSSQLProxy starts the SQL Server (TDS) proxy when a listen address is
// configured.
func startMSSQLProxy(
ctx context.Context,
cfg *config.Config,
dataStore *store.Store,
authCache *cache.AuthCache,
approvalDeps shared.ApprovalDeps,
rowWriter *shared.RowWriter,
loginThrottles func(listener string) *shared.LoginThrottle,
logger *slog.Logger,
) *mssql.Server {
if cfg.ListenMSSQL == "" {
return nil
}
srv, err := mssql.NewServer(dataStore, cfg.EncryptionKey, cfg.QueryStorage, cfg.Dump, authCache, cfg.MSSQL, logger)
if err != nil {
logger.ErrorContext(ctx, "SQL Server proxy init failed", slog.Any("error", err))
os.Exit(1)
}
srv.SetLoginThrottle(loginThrottles(store.ProtocolMSSQL))
srv.SetApprovalDeps(approvalDeps)
srv.SetRowWriter(rowWriter)
go func() {
if err := srv.Start(cfg.ListenMSSQL); err != nil {
logger.ErrorContext(context.Background(), "SQL Server proxy error", slog.Any("error", err))
os.Exit(1)
}
}()
logger.InfoContext(ctx, "SQL Server proxy started",
slog.String("addr", cfg.ListenMSSQL),
slog.Bool("tls", !cfg.MSSQL.TLS.Disable))
return srv
}
func runMigrate(ctx context.Context, flags *cliFlags) error {
cfg, err := loadConfigWithCLI(flags)
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
logLevel := config.ParseLogLevel(cfg.LogLevel)
logger, logCleanup := setupLogger(cfg.RunMode, logLevel)
if logCleanup != nil {
defer logCleanup()
}
slog.SetDefault(logger)
logger.InfoContext(ctx, "Running migrations")
dataStore, err := store.New(ctx, cfg.DSN)
if err != nil {
return fmt.Errorf("failed to initialize store: %w", err)
}
defer dataStore.Close()
if err := dataStore.Migrate(ctx); err != nil {
return fmt.Errorf("migration failed: %w", err)
}
logger.InfoContext(ctx, "Migrations completed successfully")
return nil
}
func runRollback(ctx context.Context, flags *cliFlags) error {
cfg, err := loadConfigWithCLI(flags)
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
logLevel := config.ParseLogLevel(cfg.LogLevel)
logger, logCleanup := setupLogger(cfg.RunMode, logLevel)
if logCleanup != nil {
defer logCleanup()
}
slog.SetDefault(logger)
logger.InfoContext(ctx, "Rolling back migrations")
dataStore, err := store.New(ctx, cfg.DSN)
if err != nil {
return fmt.Errorf("failed to initialize store: %w", err)
}
defer dataStore.Close()
if err := dataStore.Rollback(ctx); err != nil {
return fmt.Errorf("rollback failed: %w", err)
}
logger.InfoContext(ctx, "Rollback completed successfully")
return nil
}
func runMigrationStatus(ctx context.Context, flags *cliFlags) error {
cfg, err := loadConfigWithCLI(flags)
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
logLevel := config.ParseLogLevel(cfg.LogLevel)
logger, logCleanup := setupLogger(cfg.RunMode, logLevel)
if logCleanup != nil {
defer logCleanup()
}
slog.SetDefault(logger)
dataStore, err := store.New(ctx, cfg.DSN)
if err != nil {
return fmt.Errorf("failed to initialize store: %w", err)
}
defer dataStore.Close()
migrationInfos, err := dataStore.MigrationStatus(ctx)
if err != nil {
return fmt.Errorf("failed to get migration status: %w", err)
}
logger.InfoContext(ctx, "Migration status")
for _, m := range migrationInfos {
status := "pending"
if !m.MigratedAt.IsZero() {
status = fmt.Sprintf("applied at %s", m.MigratedAt.Format(time.RFC3339))
}
logger.InfoContext(ctx, "Migration", slog.String("name", m.Name), slog.String("status", status))
}
return nil
}
func provisionTestData(ctx context.Context, dataStore *store.Store, encryptionKey []byte, logger *slog.Logger) error {
logger.InfoContext(ctx, "Test mode: provisioning test data...")
// 1. Update admin password to "admintest" and mark as changed
adminUser, err := dataStore.GetUserByUsername(ctx, "admin")
if err != nil {
return fmt.Errorf("failed to get admin user: %w", err)
}
adminTestPasswordHash, err := crypto.HashPassword("admintest")
if err != nil {
return fmt.Errorf("failed to hash admintest password: %w", err)
}
err = dataStore.UpdateUser(ctx, adminUser.UID, store.UserUpdate{
PasswordHash: &adminTestPasswordHash,
})
if err != nil {
return fmt.Errorf("failed to update admin password: %w", err)
}
logger.InfoContext(ctx, "Updated admin password to 'admintest'")
// 2. Create viewer user (viewer role only)
viewerPasswordHash, err := crypto.HashPassword("viewer")
if err != nil {
return fmt.Errorf("failed to hash viewer password: %w", err)
}
viewerUser, err := dataStore.CreateUser(ctx, "viewer", viewerPasswordHash, []string{store.RoleViewer})
if err != nil {
return fmt.Errorf("failed to create viewer user: %w", err)
}
// Mark password as changed so the user can log in immediately
err = dataStore.UpdateUser(ctx, viewerUser.UID, store.UserUpdate{
PasswordHash: &viewerPasswordHash,
})
if err != nil {
return fmt.Errorf("failed to mark viewer password as changed: %w", err)
}
logger.InfoContext(ctx, "Created viewer user (username: viewer, password: viewer)")
// 3. Create connector user (connector role only)
connectorPasswordHash, err := crypto.HashPassword("connector")
if err != nil {
return fmt.Errorf("failed to hash connector password: %w", err)
}
connectorUser, err := dataStore.CreateUser(ctx, "connector", connectorPasswordHash, []string{store.RoleConnector})
if err != nil {
return fmt.Errorf("failed to create connector user: %w", err)
}
// Mark password as changed so the user can log in immediately
err = dataStore.UpdateUser(ctx, connectorUser.UID, store.UserUpdate{
PasswordHash: &connectorPasswordHash,
})
if err != nil {
return fmt.Errorf("failed to mark connector password as changed: %w", err)
}
logger.InfoContext(ctx, "Created connector user (username: connector, password: connector)")
// 4. Create proxy_target database configuration
targetDB, err := dataStore.CreateServer(ctx, &store.Server{
Name: "proxy_target",