From 0aab4b1ac2ba9c08b351aa0c0340b887eee7f060 Mon Sep 17 00:00:00 2001 From: Matthew Penner Date: Fri, 8 Jan 2021 08:19:33 -0700 Subject: [PATCH] environment(docker): re-attach to container logs after EOF --- environment/docker/container.go | 41 ++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/environment/docker/container.go b/environment/docker/container.go index 9effb29..1661e1e 100644 --- a/environment/docker/container.go +++ b/environment/docker/container.go @@ -310,23 +310,38 @@ func (e *Environment) followOutput() error { return err } - go func(reader io.ReadCloser) { - defer reader.Close() - - events := e.Events() - - err := system.ScanReader(reader, func(line string) { - events.Publish(environment.ConsoleOutputEvent, line) - }) - - if err != nil && err != io.EOF { - log.WithField("error", err).WithField("container_id", e.Id).Warn("error processing scanner line in console output") - } - }(reader) + go e.scanOutput(reader) return nil } +func (e *Environment) scanOutput(reader io.ReadCloser) { + defer reader.Close() + + events := e.Events() + + err := system.ScanReader(reader, func(line string) { + events.Publish(environment.ConsoleOutputEvent, line) + }) + + if err != nil && err != io.EOF { + log.WithField("error", err).WithField("container_id", e.Id).Warn("error processing scanner line in console output") + return + } + + // Return here if the server is offline or currently stopping. + if e.State() == environment.ProcessStoppingState || e.State() == environment.ProcessOfflineState { + return + } + + // Close the current reader before starting a new one, the defer will still run + // but it will do nothing if we already closed the stream. + _ = reader.Close() + + // Start following the output of the server again. + go e.followOutput() +} + // Pulls the image from Docker. If there is an error while pulling the image from the source // but the image already exists locally, we will report that error to the logger but continue // with the process.