Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3d96785

Browse files
authored
fix: Add lock around read/write of circular buffer (#1258)
This fixes a race seen in: https://github.com/coder/coder/runs/6260926628?check_suite_focus=true#step:10:666
1 parent 7fb3c57 commit 3d96785

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

agent/agent.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,9 @@ func (a *agent) handleReconnectingPTY(ctx context.Context, rawID string, conn ne
518518
break
519519
}
520520
part := buffer[:read]
521+
rpty.circularBufferMutex.Lock()
521522
_, err = rpty.circularBuffer.Write(part)
523+
rpty.circularBufferMutex.Unlock()
522524
if err != nil {
523525
a.logger.Error(ctx, "reconnecting pty write buffer", slog.Error(err), slog.F("id", id))
524526
break
@@ -545,7 +547,9 @@ func (a *agent) handleReconnectingPTY(ctx context.Context, rawID string, conn ne
545547
a.logger.Error(ctx, "resize reconnecting pty", slog.F("id", id), slog.Error(err))
546548
}
547549
// Write any previously stored data for the TTY.
550+
rpty.circularBufferMutex.RLock()
548551
_, err = conn.Write(rpty.circularBuffer.Bytes())
552+
rpty.circularBufferMutex.RUnlock()
549553
if err != nil {
550554
a.logger.Warn(ctx, "write reconnecting pty buffer", slog.F("id", id), slog.Error(err))
551555
return
@@ -640,9 +644,10 @@ type reconnectingPTY struct {
640644
activeConnsMutex sync.Mutex
641645
activeConns map[string]net.Conn
642646

643-
circularBuffer *circbuf.Buffer
644-
timeout *time.Timer
645-
ptty pty.PTY
647+
circularBuffer *circbuf.Buffer
648+
circularBufferMutex sync.RWMutex
649+
timeout *time.Timer
650+
ptty pty.PTY
646651
}
647652

648653
// Close ends all connections to the reconnecting

0 commit comments

Comments
 (0)