- Notifications
You must be signed in to change notification settings - Fork1.1k
feat: add boundary log forwarding from agent to coderd#21345
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Draft
zedkipp wants to merge1 commit intomainChoose a base branch fromzedkipp/boundary-logs
base:main
Could not load branches
Branch not found:{{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
+890 −8
Draft
Changes fromall commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
feat: add boundary log forwarding from agent to coderd
Add receiving boundary logs via stream unix socket in the agent, forwardingof boundary audit logs from agent to coderd via agent API, and re-emissionof boundary logs to coderd stderr.Log format example:[API] 2025-12-08 20:58:46.093 [warn] boundary: workspace.id=... decision=deny http.method="GET" http.url="..." time="..."
- Loading branch information
Uh oh!
There was an error while loading.Please reload this page.
commitce980b9fc44c6a585daf6e64af7f422240df689b
There are no files selected for viewing
37 changes: 37 additions & 0 deletionsagent/agent.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
228 changes: 225 additions & 3 deletionsagent/boundarylogproxy/proxy.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,229 @@ | ||
| // Package boundarylogproxy provides a Unix socket server that receives boundary | ||
| // audit logs and forwards them to coderd via the agent API. | ||
| // | ||
| // Wire Format: | ||
| // Boundary sends tag and length prefixed protobuf messages over the Unix socket (TLV). | ||
| // - 4 bits: big-endian tag (always 1 for now) | ||
| // - 28 bits: big-endian length of the protobuf data | ||
| // - length bytes: encoded protobuf data | ||
| package boundarylogproxy | ||
| import ( | ||
| "context" | ||
| "encoding/binary" | ||
| "errors" | ||
| "io" | ||
| "net" | ||
| "os" | ||
| "sync" | ||
| "time" | ||
| "golang.org/x/xerrors" | ||
| "google.golang.org/protobuf/proto" | ||
| "cdr.dev/slog" | ||
| agentproto "github.com/coder/coder/v2/agent/proto" | ||
| ) | ||
| const ( | ||
| // logBufferSize is the size of the channel buffer for incoming log requests | ||
| // from workspaces. This buffer size is intended to handle short bursts of workspaces | ||
| // forwarding batches of logs in parallel. | ||
| logBufferSize = 100 | ||
| ) | ||
| // Reporter reports boundary logs from workspaces. | ||
| type Reporter interface { | ||
| ReportBoundaryLogs(ctx context.Context, req *agentproto.ReportBoundaryLogsRequest) (*agentproto.ReportBoundaryLogsResponse, error) | ||
| } | ||
| // Server listens on a Unix socket for boundary log messages and buffers them | ||
| // for forwarding to coderd. The socket server and the forwarder are decoupled: | ||
| // - Start() creates the socket and accepts a connection from boundary | ||
| // - RunForwarder() drains the buffer and sends logs to coderd via AgentAPI | ||
| type Server struct { | ||
| logger slog.Logger | ||
| socketPath string | ||
| listener net.Listener | ||
| cancel context.CancelFunc | ||
| wg sync.WaitGroup | ||
| // logs buffers incoming log requests for the forwarder to drain. | ||
| logs chan *agentproto.ReportBoundaryLogsRequest | ||
| } | ||
| // NewServer creates a new boundary log proxy server. | ||
| func NewServer(logger slog.Logger, socketPath string) *Server { | ||
| return &Server{ | ||
| logger: logger.Named("boundary-log-proxy"), | ||
| socketPath: socketPath, | ||
| logs: make(chan *agentproto.ReportBoundaryLogsRequest, logBufferSize), | ||
| } | ||
| } | ||
| // Start begins listening for connections on the Unix socket, and handles new | ||
| // connections in a separate goroutine. Incoming logs from connections are | ||
| // buffered until RunForwarder drains them. | ||
| func (s *Server) Start() error { | ||
| if err := os.Remove(s.socketPath); err != nil && !os.IsNotExist(err) { | ||
| return xerrors.Errorf("remove existing socket: %w", err) | ||
| } | ||
| listener, err := net.Listen("unix", s.socketPath) | ||
| if err != nil { | ||
| return xerrors.Errorf("listen on socket: %w", err) | ||
| } | ||
| s.listener = listener | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| s.cancel = cancel | ||
| s.wg.Add(1) | ||
| go s.acceptLoop(ctx) | ||
| s.logger.Info(ctx, "boundary log proxy started", slog.F("socket_path", s.socketPath)) | ||
| return nil | ||
| } | ||
| // RunForwarder drains the log buffer and forwards logs to coderd. | ||
| // This should be called via startAgentAPI to ensure the API client is always | ||
| // current and to handle reconnections properly. It blocks until ctx is canceled. | ||
| func (s *Server) RunForwarder(ctx context.Context, sender Reporter) error { | ||
| s.logger.Debug(ctx, "boundary log forwarder started") | ||
| var intervalForwardCount, intervalTotalLogCount uint32 | ||
| forwardCounterInterval := 30 * time.Second | ||
| forwardCountDebugLogTimer := time.NewTicker(forwardCounterInterval) | ||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| return ctx.Err() | ||
| case <-forwardCountDebugLogTimer.C: | ||
| s.logger.Debug(ctx, "forwarded boundary logs", | ||
| slog.F("log_count", intervalForwardCount), | ||
| slog.F("interval", forwardCounterInterval)) | ||
| intervalForwardCount = 0 | ||
| intervalTotalLogCount = 0 | ||
| case req := <-s.logs: | ||
| intervalForwardCount++ | ||
| intervalTotalLogCount += uint32(len(req.Logs)) | ||
| _, err := sender.ReportBoundaryLogs(ctx, req) | ||
| if err != nil { | ||
| s.logger.Warn(ctx, "failed to forward boundary logs", | ||
| slog.Error(err), | ||
| slog.F("log_count", len(req.Logs))) | ||
| // Continue forwarding other logs. The current batch is lost, | ||
| //but the socket stays alive. | ||
| } | ||
| } | ||
| } | ||
| } | ||
| func (s *Server) acceptLoop(ctx context.Context) { | ||
| defer s.wg.Done() | ||
| for { | ||
| conn, err := s.listener.Accept() | ||
| if err != nil { | ||
| if ctx.Err() != nil { | ||
| return | ||
| } | ||
| s.logger.Warn(ctx, "accept error", slog.Error(err)) | ||
| continue | ||
| } | ||
| s.wg.Add(1) | ||
| go s.handleConnection(ctx, conn) | ||
| } | ||
| } | ||
| func (s *Server) handleConnection(ctx context.Context, conn net.Conn) { | ||
| defer s.wg.Done() | ||
| ctx, cancel := context.WithCancel(ctx) | ||
| defer cancel() | ||
| s.wg.Add(1) | ||
| go func() { | ||
| defer s.wg.Done() | ||
| <-ctx.Done() | ||
| _ = conn.Close() | ||
| }() | ||
| // Even though the length of data received can be larger than maxMsgSize, | ||
| // practically they are not expected to be. This is a sanity check and | ||
| // allows re-using a small fixed size read buffer. | ||
| const maxMsgSize = 1 << 15 | ||
| buf := make([]byte, maxMsgSize) | ||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| return | ||
| default: | ||
| } | ||
| var header uint32 | ||
| if err := binary.Read(conn, binary.BigEndian, &header); err != nil { | ||
| if errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) { | ||
| return | ||
| } | ||
| s.logger.Warn(ctx, "read length error", slog.Error(err)) | ||
| return | ||
| } | ||
| length := header & 0x0FFFFFFF | ||
| tag := header >> 28 | ||
| if tag != 1 { | ||
| s.logger.Warn(ctx, "invalid tag", slog.F("tag", tag)) | ||
| return | ||
| } | ||
| if length > maxMsgSize { | ||
| s.logger.Warn(ctx, "message too large", slog.F("length", length)) | ||
| return | ||
| } | ||
| if _, err := io.ReadFull(conn, buf[:length]); err != nil { | ||
| s.logger.Warn(ctx, "read body error", slog.Error(err)) | ||
| return | ||
| } | ||
| var req agentproto.ReportBoundaryLogsRequest | ||
| if err := proto.Unmarshal(buf[:length], &req); err != nil { | ||
| s.logger.Warn(ctx, "unmarshal error", slog.Error(err)) | ||
| continue | ||
| } | ||
| select { | ||
| case s.logs <- &req: | ||
| default: | ||
| s.logger.Warn(ctx, "dropping boundary logs, buffer full", | ||
| slog.F("log_count", len(req.Logs))) | ||
| } | ||
| } | ||
| } | ||
| // Close stops the server and blocks until resources have been cleaned up. | ||
| // It must be called after Start. | ||
| func (s *Server) Close() error { | ||
| if s.cancel != nil { | ||
| s.cancel() | ||
| } | ||
| if s.listener != nil { | ||
| _ = s.listener.Close() | ||
| } | ||
| s.wg.Wait() | ||
| err := os.Remove(s.socketPath) | ||
| if err != nil && !errors.Is(err, os.ErrNotExist) { | ||
| return err | ||
| } | ||
| return nil | ||
| } | ||
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.