Skip to content

Conversation

edsiper
Copy link
Member

@edsiper edsiper commented Aug 28, 2025

This PR extends the downstream interface with two new functions to pause and resume the acceptance of connections. Once paused, the downstream simply accept and close the socket, on resume it keeps accepting.

Input plugins that uses downstream interface as listeners can now use these news functions from their pause/resume callbacks for better handling of connections.

In addition, this PR extends TCP input plugin and adds a default I/O timeout to HTTP output.


Fluent Bit is licensed under Apache 2.0, by submitting this pull request I understand that this code will be released under the terms of that license.

Summary by CodeRabbit

  • New Features

    • Added ability to pause and resume the TCP input without restart, preventing new connections while gracefully handling existing ones.
    • Introduced programmatic controls to pause/resume downstream connections for maintenance or backpressure scenarios.
  • Bug Fixes

    • Reduced noisy error logs when connections drop unexpectedly by treating them as normal events.
    • Improved connection lifecycle handling to avoid stalls and ensure reliable cleanup when pausing or closing connections.

Copy link

coderabbitai bot commented Aug 28, 2025

Walkthrough

Adds a pause/resume mechanism to downstreams and integrates it into the in_tcp input. Introduces a paused state in downstreams, APIs to control it, and connection-level busy/pending_close flags. The TCP plugin wires pause/resume callbacks, adjusts collect behavior when connections drop, and refactors connection event handling for consistent cleanup.

Changes

Cohort / File(s) Summary of Changes
Downstream pause/resume API
include/fluent-bit/flb_downstream.h, src/flb_downstream.c
Adds paused field to flb_downstream, implements flb_downstream_pause/resume. flb_downstream_conn_get returns NULL when paused and proactively closes pending server_fd connections for non-UDP/UNIX_DGRAM.
TCP input plugin pause/resume & collect tweaks
plugins/in_tcp/tcp.c
Adds in_tcp_pause/in_tcp_resume; registers .cb_pause/.cb_resume in plugin. On collect with missing connection, returns 0 (no error). Pause marks busy conns for pending_close or deletes idle ones; resume resumes downstream.
TCP connection state and event refactor
plugins/in_tcp/tcp_conn.h, plugins/in_tcp/tcp_conn.c
Adds busy and pending_close fields to tcp_conn. Refactors tcp_conn_event to centralized cleanup with uniform busy flag handling. Initializes new fields in tcp_conn_add; honors pending_close during cleanup to delete connection safely.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant IM as Input Manager
  participant TCP as in_tcp_plugin
  participant DS as Downstream
  participant Conn as tcp_conn (many)

  IM->>TCP: cb_pause()
  TCP->>DS: flb_downstream_pause(stream)
  loop for each active connection
    TCP->>Conn: if busy: set pending_close<br/>else: delete connection
  end
  Note over TCP,Conn: New: defer close when busy

  IM->>TCP: cb_resume()
  TCP->>DS: flb_downstream_resume(stream)
Loading
sequenceDiagram
  autonumber
  participant EP as Event Loop
  participant Conn as tcp_conn
  participant DS as Downstream

  EP->>DS: flb_downstream_conn_get()
  alt stream paused
    DS-->>EP: return NULL (and drop server_fd pending accept)
  else not paused
    DS-->>EP: return connection
  end

  EP->>Conn: tcp_conn_event()
  Note over Conn: busy = true
  alt read/process success
    Conn-->>EP: ret = bytes
  else error/invalid
    Conn-->>EP: ret = -1
  end
  alt pending_close set
    Conn->>EP: delete connection
    EP-->>Conn: finalize
  end
  Note over Conn: busy = false (on cleanup)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I tap my paws—pause!—the streams go still,
Connections sip their last, then chill.
Busy burrows finish, then close with grace,
Resume! and packets race apace.
A hop, a skip, new flags in tow—
Downstream dreams pause, then flow. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch reload-http-hang

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@edsiper edsiper added this to the Fluent Bit v4.1 milestone Aug 30, 2025
@edsiper edsiper marked this pull request as ready for review August 30, 2025 03:16
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
plugins/in_tcp/tcp_conn.h (1)

53-55: Add brief concurrency note for the new flags

Clarify in a comment that busy is only toggled within the event handler and pending_close may be set from pause callbacks; helps future maintainers reason about races.

-    int busy;                         /* Connection is being processed     */
-    int pending_close;                /* Defer closing until processing ends */
+    int busy;          /* Toggled in tcp_conn_event() during processing */
+    int pending_close; /* Set by pause path; tcp_conn_event() will close on exit */
src/flb_downstream.c (2)

286-296: Paused mode: UDP/unix_dgram may spin

When paused and transport is dgram, returning NULL without draining can cause the FD to stay readable and the collector to fire repeatedly. Consider dropping one datagram to relieve pressure, or temporarily disabling the event while paused.

-    if (stream->paused) {
-        if (transport != FLB_TRANSPORT_UDP &&
-            transport != FLB_TRANSPORT_UNIX_DGRAM) {
+    if (stream->paused) {
+        if (transport != FLB_TRANSPORT_UDP &&
+            transport != FLB_TRANSPORT_UNIX_DGRAM) {
             connection_fd = flb_net_accept(stream->server_fd);
             if (connection_fd >= 0) {
                 flb_socket_close(connection_fd);
             }
-        }
+        }
+        else {
+            /* Drain one datagram to avoid hot loop while paused */
+            char discard[512];
+            (void) recvfrom(stream->server_fd, discard, sizeof(discard), MSG_DONTWAIT, NULL, NULL);
+        }
         return NULL;
     }

372-384: Guard pause/resume with stream lock; init paused explicitly

Tiny race window exists setting paused without a lock. Also, initialize paused to FLB_FALSE in setup for non-calloc callers.

 void flb_downstream_pause(struct flb_downstream *stream)
 {
     if (stream) {
-        stream->paused = FLB_TRUE;
+        flb_stream_acquire_lock(&stream->base, FLB_TRUE);
+        stream->paused = FLB_TRUE;
+        flb_stream_release_lock(&stream->base);
     }
 }
 
 void flb_downstream_resume(struct flb_downstream *stream)
 {
     if (stream) {
-        stream->paused = FLB_FALSE;
+        flb_stream_acquire_lock(&stream->base, FLB_TRUE);
+        stream->paused = FLB_FALSE;
+        flb_stream_release_lock(&stream->base);
     }
 }

Additionally, set default in setup:

 int flb_downstream_setup(struct flb_downstream *stream,
@@
     stream->server_fd = FLB_INVALID_SOCKET;
     stream->host = flb_strdup(host);
     stream->port = port;
+    stream->paused = FLB_FALSE;
include/fluent-bit/flb_downstream.h (1)

49-51: Public contract: document paused semantics

Add a brief comment that paused only affects acceptance of new connections; existing connections are left intact until closed by the plugin (or flagged pending_close).

-    /* pause state */
-    int paused;
+    /* pause state: when true, new connections are accepted-and-closed (streaming)
+     * or dropped (dgram). Existing active connections are not forcibly terminated. */
+    int paused;

Also applies to: 82-84

plugins/in_tcp/tcp.c (1)

147-167: Pause path: verify callback threading and list safety

Ensure cb_pause runs on the same engine thread that drives tcp_conn_event; otherwise, iterating ctx->connections while events may fire risks races. If multi-worker or cross-thread invocations are possible, guard with an appropriate lock or quiesce the collector before iterating.

 static void in_tcp_pause(void *data, struct flb_config *config)
 {
     struct flb_in_tcp_config *ctx = data;
@@
-    flb_downstream_pause(ctx->downstream);
+    flb_downstream_pause(ctx->downstream);
+    /* If cb_pause can be called off-thread, pause collector here */
+    /* flb_input_collector_pause(ctx->ins, ctx->collector_id); */
@@
         if (conn->busy) {
             conn->pending_close = FLB_TRUE;
             continue;
         }
 
         tcp_conn_del(conn);
     }
 }
plugins/in_tcp/tcp_conn.c (1)

370-372: Return 0 on normal read to match event-loop expectations

Returning bytes is unnecessary; zero is typical for “handled” without teardown.

-        ret = bytes;
+        ret = 0;
         goto cleanup;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7445e38 and 8db61eb.

📒 Files selected for processing (5)
  • include/fluent-bit/flb_downstream.h (2 hunks)
  • plugins/in_tcp/tcp.c (3 hunks)
  • plugins/in_tcp/tcp_conn.c (6 hunks)
  • plugins/in_tcp/tcp_conn.h (1 hunks)
  • src/flb_downstream.c (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
include/fluent-bit/flb_downstream.h (1)
src/flb_downstream.c (2)
  • flb_downstream_pause (372-377)
  • flb_downstream_resume (379-384)
plugins/in_tcp/tcp_conn.c (1)
src/flb_pack.c (2)
  • flb_pack_state_reset (385-395)
  • flb_pack_state_init (354-383)
src/flb_downstream.c (1)
src/flb_network.c (1)
  • flb_net_accept (1850-1877)
plugins/in_tcp/tcp.c (2)
src/flb_downstream.c (2)
  • flb_downstream_pause (372-377)
  • flb_downstream_resume (379-384)
plugins/in_tcp/tcp_conn.c (1)
  • tcp_conn_del (462-484)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (24)
  • GitHub Check: pr-windows-build / call-build-windows-package (Windows 32bit, x86, x86-windows-static, 3.31.6)
  • GitHub Check: pr-windows-build / call-build-windows-package (Windows 64bit, x64, x64-windows-static, 3.31.6)
  • GitHub Check: pr-windows-build / call-build-windows-package (Windows 64bit (Arm64), amd64_arm64, -DCMAKE_SYSTEM_NAME=Windows -DCMA...
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SANITIZE_MEMORY=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SIMD=Off, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SIMD=On, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_JEMALLOC=Off, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_ARROW=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DSANITIZE_UNDEFINED=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DSANITIZE_ADDRESS=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SMALL=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_JEMALLOC=On, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_COVERAGE=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SANITIZE_THREAD=On, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SIMD=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SIMD=Off, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SANITIZE_MEMORY=On, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SANITIZE_THREAD=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DSANITIZE_ADDRESS=On, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_JEMALLOC=Off, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DSANITIZE_UNDEFINED=On, 3.31.6, clang, clang++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_JEMALLOC=On, 3.31.6, gcc, g++)
  • GitHub Check: run-ubuntu-unit-tests (-DFLB_SMALL=On, 3.31.6, clang, clang++)
  • GitHub Check: PR - fuzzing test
🔇 Additional comments (5)
plugins/in_tcp/tcp.c (3)

45-47: Correct handling when downstream is paused

Returning 0 (no error) here is right; avoids disabling the collector while paused.


169-176: Resume hook looks good

No additional work needed; downstream resumes accepting connections.


216-218: Plugin wires pause/resume correctly

cb_pause/cb_resume registration aligns with the new API.

plugins/in_tcp/tcp_conn.c (2)

383-391: Cleanup path is solid

busy is cleared and pending_close honored; this integrates well with the pause flow.


456-458: Init new flags

Good default initialization of busy/pending_close.

Comment on lines 289 to 293
if (!tmp) {
conn->busy = FLB_FALSE;
flb_errno();
return -1;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Realloc failure leaks the live connection

On allocation failure, the connection remains registered; return -1 without deleting will leave a stuck FD. Close the connection before returning.

-            if (!tmp) {
-                conn->busy = FLB_FALSE;
-                flb_errno();
-                return -1;
-            }
+            if (!tmp) {
+                conn->busy = FLB_FALSE;
+                flb_errno();
+                tcp_conn_del(conn);
+                return -1;
+            }
🤖 Prompt for AI Agents
In plugins/in_tcp/tcp_conn.c around lines 289-293, the realloc failure path
returns -1 while leaving the live connection registered, leaking the open FD;
fix by closing and fully cleaning up the connection before returning: close the
socket/FD, unregister the connection from the event loop/io subsystem, free any
allocated buffers and connection state, mark conn as not busy (or remove it from
the active list) and then return -1 so no stray FD remains.

Comment on lines 331 to 336
ret_payload = parse_payload_json(conn);
if (ret_payload == 0) {
/* Incomplete JSON message, we need more data */
return -1;
ret = -1;
goto cleanup;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Do not return -1 on incomplete payloads

For partial JSON/raw frames you now set ret = -1 and exit via cleanup, which risks the engine treating this as an error. Keep the connection alive and return 0 so we await more data.

-            if (ret_payload == 0) {
-                /* Incomplete JSON message, we need more data */
-                ret = -1;
-                goto cleanup;
-            }
+            if (ret_payload == 0) {
+                /* Incomplete JSON message, wait for more data */
+                ret = 0;
+                goto cleanup;
+            }
@@
-            if (ret_payload == 0) {
-                ret = -1;
-                goto cleanup;
-            }
+            if (ret_payload == 0) {
+                ret = 0;
+                goto cleanup;
+            }
-            else if (ret_payload == -1) {
+            else if (ret_payload == -1) {
                 conn->buf_len = 0;
-                ret = -1;
+                /* Keep the connection; skip the invalid chunk */
+                ret = 0;
                 goto cleanup;
             }

Also applies to: 348-355

🤖 Prompt for AI Agents
In plugins/in_tcp/tcp_conn.c around lines 331-336 (and similarly for 348-355),
the code treats an incomplete JSON/raw payload as an error by setting ret = -1
and jumping to cleanup; instead keep the connection alive and indicate we need
more data by setting ret = 0 (or returning 0) and avoid the cleanup/error path
so the caller will wait for additional bytes; update both spots to not set -1 or
call cleanup on incomplete payloads and ensure any buffers/state remain intact
for subsequent reads.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant