From 0945f3d686e6716f07f6cdb6f88fa9331de4ad98 Mon Sep 17 00:00:00 2001 From: kylecarbs Date: Mon, 2 May 2022 17:17:06 +0000 Subject: [PATCH] fix: Add lock around read/write of circular buffer This fixes a race seen in: https://github.com/coder/coder/runs/6260926628?check_suite_focus=true#step:10:666 --- agent/agent.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/agent/agent.go b/agent/agent.go index 53fafe831e30b..b946166056532 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -518,7 +518,9 @@ func (a *agent) handleReconnectingPTY(ctx context.Context, rawID string, conn ne break } part := buffer[:read] + rpty.circularBufferMutex.Lock() _, err = rpty.circularBuffer.Write(part) + rpty.circularBufferMutex.Unlock() if err != nil { a.logger.Error(ctx, "reconnecting pty write buffer", slog.Error(err), slog.F("id", id)) break @@ -545,7 +547,9 @@ func (a *agent) handleReconnectingPTY(ctx context.Context, rawID string, conn ne a.logger.Error(ctx, "resize reconnecting pty", slog.F("id", id), slog.Error(err)) } // Write any previously stored data for the TTY. + rpty.circularBufferMutex.RLock() _, err = conn.Write(rpty.circularBuffer.Bytes()) + rpty.circularBufferMutex.RUnlock() if err != nil { a.logger.Warn(ctx, "write reconnecting pty buffer", slog.F("id", id), slog.Error(err)) return @@ -640,9 +644,10 @@ type reconnectingPTY struct { activeConnsMutex sync.Mutex activeConns map[string]net.Conn - circularBuffer *circbuf.Buffer - timeout *time.Timer - ptty pty.PTY + circularBuffer *circbuf.Buffer + circularBufferMutex sync.RWMutex + timeout *time.Timer + ptty pty.PTY } // Close ends all connections to the reconnecting