diff --git a/lib/syncthing/syncthing.go b/lib/syncthing/syncthing.go index 6e8518b43..bdedd0889 100644 --- a/lib/syncthing/syncthing.go +++ b/lib/syncthing/syncthing.go @@ -110,16 +110,6 @@ func New(cfg config.Wrapper, dbBackend backend.Backend, evLogger events.Logger, // e.g. the API is ready for use. // Must be called once only. func (a *App) Start() error { - if err := a.startup(); err != nil { - a.stopWithErr(ExitError, err) - return err - } - a.stopped = make(chan struct{}) - go a.run() - return nil -} - -func (a *App) startup() error { // Create a main service manager. We'll add things to this as we go along. // We want any logging it does to go through our log system. a.mainService = suture.New("main", suture.Spec{ @@ -128,8 +118,22 @@ func (a *App) startup() error { }, PassThroughPanics: true, }) - a.mainService.Add(a.ll) + + // Start the supervisor and wait for it to stop to handle cleanup. + a.stopped = make(chan struct{}) a.mainService.ServeBackground() + go a.run() + + if err := a.startup(); err != nil { + a.stopWithErr(ExitError, err) + return err + } + + return nil +} + +func (a *App) startup() error { + a.mainService.Add(a.ll) if a.opts.AuditWriter != nil { a.mainService.Add(newAuditService(a.opts.AuditWriter, a.evLogger)) diff --git a/lib/syncthing/syncthing_test.go b/lib/syncthing/syncthing_test.go index d1de4f021..b45f8f3a2 100644 --- a/lib/syncthing/syncthing_test.go +++ b/lib/syncthing/syncthing_test.go @@ -78,7 +78,8 @@ func TestStartupFail(t *testing.T) { }, events.NoopLogger) defer os.Remove(cfg.ConfigPath()) - app := New(cfg, backend.OpenMemory(), events.NoopLogger, cert, Options{}) + db := backend.OpenMemory() + app := New(cfg, db, events.NoopLogger, cert, Options{}) startErr := app.Start() if startErr == nil { t.Fatal("Expected an error from Start, got nil") @@ -104,4 +105,11 @@ func TestStartupFail(t *testing.T) { if err = app.Error(); err != startErr { t.Errorf(`Got different errors "%v" from Start and "%v" from Error`, startErr, err) } + + if trans, err := db.NewReadTransaction(); err == nil { + t.Error("Expected error due to db being closed, got nil") + trans.Release() + } else if !backend.IsClosed(err) { + t.Error("Expected error due to db being closed, got", err) + } }