diff --git a/src/internal/server/server.go b/src/internal/server/server.go index 0d4fc31..1bf90ba 100644 --- a/src/internal/server/server.go +++ b/src/internal/server/server.go @@ -18,8 +18,11 @@ type TCPServer struct { service *service.MOSService config *config.Config eventBus *events.EventBus - wg sync.WaitGroup + wg sync.WaitGroup // accept loop and client goroutines shutdownCh chan struct{} + + shutdownOnce sync.Once + shutdownErr error } // NewTCPServer creates a new TCP server instance diff --git a/src/internal/server/server_accept.go b/src/internal/server/server_accept.go new file mode 100644 index 0000000..964668f --- /dev/null +++ b/src/internal/server/server_accept.go @@ -0,0 +1,57 @@ +package server + +import ( + "context" + "errors" + "net" + "time" + + "airshift/openmos/pkg/logger" +) + +// acceptLoop accepts client connections until ctx is cancelled or the +// server shuts down. +func (s *TCPServer) acceptLoop(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case <-s.shutdownCh: + return + default: + // Set accept timeout so we can check for shutdown + tcpListener, ok := s.listener.(*net.TCPListener) + if ok { + tcpListener.SetDeadline(time.Now().Add(time.Second)) + } + + conn, err := s.listener.Accept() + if err != nil { + if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() { + // This is just a timeout from our deadline, continue + continue + } + if errors.Is(err, net.ErrClosed) { + // Listener closed by Shutdown + return + } + logger.Errorf("Error accepting connection: %v", err) + continue + } + + // Create new client connection + client := NewClientConnection(conn, s, s.config) + + // Register client + s.registerClient(client) + + // Handle client in a goroutine. The accept loop's own count keeps + // the wait group above zero here, so Add cannot race with Wait. + s.wg.Add(1) + go func() { + defer s.wg.Done() + client.Start(ctx) + }() + } + } +} diff --git a/src/internal/server/server_lifecycle.go b/src/internal/server/server_lifecycle.go index e31497c..06c945a 100644 --- a/src/internal/server/server_lifecycle.go +++ b/src/internal/server/server_lifecycle.go @@ -3,67 +3,39 @@ package server import ( "context" "fmt" - "net" - "time" "airshift/openmos/pkg/logger" ) -// Start begins accepting connections +// Start accepts connections until ctx is cancelled, then shuts the server +// down and returns the result of Shutdown. func (s *TCPServer) Start(ctx context.Context) error { - defer s.wg.Done() - s.wg.Add(1) - address := s.listener.Addr().String() logger.Infof("Server listening on %s", address) - // Accept connections in a loop + // Accept connections in a loop. Start itself is not counted in the wait + // group, because Shutdown below waits on it. + s.wg.Add(1) go func() { - for { - select { - case <-ctx.Done(): - return - case <-s.shutdownCh: - return - default: - // Set accept timeout so we can check for shutdown - tcpListener, ok := s.listener.(*net.TCPListener) - if ok { - tcpListener.SetDeadline(time.Now().Add(time.Second)) - } - - conn, err := s.listener.Accept() - if err != nil { - if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() { - // This is just a timeout from our deadline, continue - continue - } - logger.Errorf("Error accepting connection: %v", err) - continue - } - - // Create new client connection - client := NewClientConnection(conn, s, s.config) - - // Register client - s.registerClient(client) - - // Handle client in a goroutine - s.wg.Add(1) - go func() { - defer s.wg.Done() - client.Start(ctx) - }() - } - } + defer s.wg.Done() + s.acceptLoop(ctx) }() <-ctx.Done() return s.Shutdown(context.Background()) } -// Shutdown gracefully shuts down the server +// Shutdown gracefully shuts down the server: it stops accepting, closes all +// client connections and waits for their goroutines. It is safe to call more +// than once; later calls return the first call's result. func (s *TCPServer) Shutdown(ctx context.Context) error { + s.shutdownOnce.Do(func() { + s.shutdownErr = s.shutdown(ctx) + }) + return s.shutdownErr +} + +func (s *TCPServer) shutdown(ctx context.Context) error { logger.Info("Shutting down server...") // Signal all goroutines to stop @@ -74,12 +46,18 @@ func (s *TCPServer) Shutdown(ctx context.Context) error { s.listener.Close() } - // Close all client connections - s.clientsMu.Lock() + // Close all client connections. Copy them first: Close unregisters the + // client, which takes clientsMu, so it must not be called under the lock. + s.clientsMu.RLock() + clients := make([]*ClientConnection, 0, len(s.clients)) for _, client := range s.clients { + clients = append(clients, client) + } + s.clientsMu.RUnlock() + + for _, client := range clients { client.Close() } - s.clientsMu.Unlock() // Wait for all goroutines to finish with a timeout shutdownCtx, cancel := context.WithTimeout(ctx, s.config.Server.ShutdownTimeout) diff --git a/src/internal/server/server_lifecycle_test.go b/src/internal/server/server_lifecycle_test.go new file mode 100644 index 0000000..051896d --- /dev/null +++ b/src/internal/server/server_lifecycle_test.go @@ -0,0 +1,114 @@ +package server + +import ( + "context" + "io" + "net" + "testing" + "time" + + "airshift/openmos/internal/config" +) + +// shutdownTimeout is far above the expected shutdown time, so a test that +// only finishes by hitting it fails the "well under the timeout" check. +const shutdownTimeout = 10 * time.Second + +func newListeningServer(t *testing.T) *TCPServer { + t.Helper() + cfg := &config.Config{} + cfg.Server.Host, cfg.Server.Port = "127.0.0.1", 0 + cfg.Server.ShutdownTimeout = shutdownTimeout + cfg.Server.WriteTimeout = time.Second + cfg.MOS.ID = "test.mos" + cfg.MOS.HeartbeatInterval, cfg.MOS.ClientTimeout = time.Minute, time.Minute + + srv, err := NewTCPServer(cfg, nil, nil) + if err != nil { + t.Fatalf("NewTCPServer: %v", err) + } + return srv +} + +func (s *TCPServer) clientCount() int { + s.clientsMu.RLock() + defer s.clientsMu.RUnlock() + return len(s.clients) +} + +func waitForClients(t *testing.T, srv *TCPServer, want int) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for srv.clientCount() != want { + if time.Now().After(deadline) { + t.Fatalf("client count = %d, want %d", srv.clientCount(), want) + } + time.Sleep(10 * time.Millisecond) + } +} + +// Regression test for MOS-30: cancelling the context must shut the server +// down promptly, with or without connected clients, and close every client. +func TestStartShutsDownPromptlyOnCancel(t *testing.T) { + for _, n := range []int{0, 1, 3} { + srv := newListeningServer(t) + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { result <- srv.Start(ctx) }() + + conns := make([]net.Conn, n) + for i := range conns { + c, err := net.Dial("tcp", srv.listener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer c.Close() + conns[i] = c + } + waitForClients(t, srv, n) + + start := time.Now() + cancel() + select { + case err := <-result: + if err != nil { + t.Errorf("%d clients: Start returned %v, want nil", n, err) + } + case <-time.After(shutdownTimeout + 2*time.Second): + t.Fatalf("%d clients: Start did not return (deadlock)", n) + } + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Errorf("%d clients: shutdown took %v, want well under %v", n, elapsed, shutdownTimeout) + } + + if got := srv.clientCount(); got != 0 { + t.Errorf("%d clients: %d still registered after shutdown", n, got) + } + // The server must have closed each connection + for i, c := range conns { + c.SetReadDeadline(time.Now().Add(time.Second)) + if _, err := c.Read(make([]byte, 1)); err != io.EOF { + t.Errorf("%d clients: conn %d read = %v, want EOF", n, i, err) + } + } + } +} + +func TestShutdownIsIdempotent(t *testing.T) { + srv := newListeningServer(t) + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { result <- srv.Start(ctx) }() + + cancel() + select { + case <-result: + case <-time.After(shutdownTimeout + 2*time.Second): + t.Fatal("Start did not return") + } + + // A second Shutdown (e.g. from main) must not panic on the closed channel + if err := srv.Shutdown(context.Background()); err != nil { + t.Errorf("second Shutdown = %v, want nil", err) + } +} diff --git a/src/main.go b/src/main.go index 3b8c457..4347f54 100644 --- a/src/main.go +++ b/src/main.go @@ -62,7 +62,7 @@ func main() { sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) - startServer(ctx, cancel, cfg, tcpServer, log) + serverDone := startServer(ctx, cancel, cfg, tcpServer, log) log.Infof("OpenMOS server is running on %s", cfg.GetServerAddress()) @@ -70,8 +70,10 @@ func main() { sig := <-sigCh log.Infof("Received signal: %v", sig) - // Cancel the server context to start the graceful shutdown + // Cancel the server context to start the graceful shutdown, and wait for + // it so clients are closed before the process exits cancel() + waitForServer(serverDone, cfg, log) // Flush Sentry events before exiting defer sentry.Flush(2 * time.Second) diff --git a/src/wiring.go b/src/wiring.go index 346afb2..f90b34e 100644 --- a/src/wiring.go +++ b/src/wiring.go @@ -2,6 +2,7 @@ package main import ( "context" + "time" "airshift/openmos/internal/config" "airshift/openmos/internal/db" @@ -58,15 +59,19 @@ func newTCPServer(cfg *config.Config, database *db.MongoDB, log *logger.SentryLo } // startServer runs the TCP server in a goroutine inside a Sentry -// transaction; a server error cancels the application context. +// transaction; a server error cancels the application context. The returned +// channel is closed once the server has stopped, including its shutdown. func startServer(ctx context.Context, cancel context.CancelFunc, cfg *config.Config, - tcpServer *server.TCPServer, log *logger.SentryLogger) { + tcpServer *server.TCPServer, log *logger.SentryLogger) <-chan struct{} { // Start server monitoring serverSpan := log.StartTransaction("server_lifecycle", "server") serverSpan.SetTag("server_address", cfg.GetServerAddress()) + done := make(chan struct{}) + // Start server in a goroutine go func() { + defer close(done) defer serverSpan.Finish() if err := tcpServer.Start(ctx); err != nil { @@ -82,4 +87,16 @@ func startServer(ctx context.Context, cancel context.CancelFunc, cfg *config.Con cancel() } }() + + return done +} + +// waitForServer waits for the server to finish shutting down. Shutdown is +// bounded by ShutdownTimeout; the extra grace only guards against a hang. +func waitForServer(done <-chan struct{}, cfg *config.Config, log *logger.SentryLogger) { + select { + case <-done: + case <-time.After(cfg.Server.ShutdownTimeout + 5*time.Second): + log.Errorf("Server did not stop within %v, exiting anyway", cfg.Server.ShutdownTimeout) + } }