Skip to content

fix(agent): Work around lumberjack reopening log file after close #5941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion cli/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package cli
import (
"context"
"fmt"
"io"
"net/http"
"net/http/pprof"
"net/url"
"os"
"os/signal"
"path/filepath"
"runtime"
"sync"
"time"

"cloud.google.com/go/compute/metadata"
Expand Down Expand Up @@ -91,11 +93,14 @@ func workspaceAgent() *cobra.Command {
// reaper.
go dumpHandler(ctx)

logWriter := &lumberjack.Logger{
ljLogger := &lumberjack.Logger{
Filename: filepath.Join(logDir, "coder-agent.log"),
MaxSize: 5, // MB
}
defer ljLogger.Close()
logWriter := &closeWriter{w: ljLogger}
defer logWriter.Close()

logger := slog.Make(sloghuman.Sink(cmd.ErrOrStderr()), sloghuman.Sink(logWriter)).Leveled(slog.LevelDebug)

version := buildinfo.Version()
Expand Down Expand Up @@ -229,3 +234,30 @@ func serveHandler(ctx context.Context, logger slog.Logger, handler http.Handler,
_ = srv.Close()
}
}

// closeWriter is a wrapper around an io.WriteCloser that prevents
// writes after Close. This is necessary because lumberjack will
// re-open the file on write.
type closeWriter struct {
w io.WriteCloser
mu sync.Mutex // Protects following.
closed bool
}

func (c *closeWriter) Close() error {
c.mu.Lock()
defer c.mu.Unlock()

c.closed = true
return c.w.Close()
}

func (c *closeWriter) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()

if c.closed {
return 0, io.ErrClosedPipe
}
return c.w.Write(p)
}