Skip to content
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

Refactor chainbuilder to gracefully handle shutdown signals #4391

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

VolodymyrBg
Copy link

Currently, the chainbuilder tool only shuts down properly if it is allowed to finish its work completely. This is problematic when generating large chains, as users might want to stop the process after some time (e.g., a week) and use what has already been generated, rather than waiting for the entire process to complete.
This PR implements graceful shutdown handling for the chainbuilder tool by:

  1. Adding signal handling (SIGINT, SIGTERM) to detect when a user wants to stop the process
  2. Implementing a unified cleanup function that:
  • Properly closes all channels
  • Waits for goroutines to finish their work
  • Safely closes all databases
  • Prevents duplicate cleanup operations
  1. Using proper error handling to avoid panics during shutdown
  2. Ensuring resources are cleaned up regardless of how the tool terminates

With these changes, users can now safely interrupt the chainbuilder process with Ctrl+C at any point, and the tool will gracefully shut down, preserving the chain generated up to that point.
Closes #4243

@VolodymyrBg VolodymyrBg requested a review from a team as a code owner March 7, 2025 19:19
@VolodymyrBg VolodymyrBg requested review from rootulp and rach-id and removed request for a team March 7, 2025 19:19
Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

📝 Walkthrough

Walkthrough

This pull request introduces graceful shutdown handling in the Run function of the chainbuilder tool. A new channel listens for OS interrupt signals (such as os.Interrupt and syscall.SIGTERM), and a dedicated goroutine cancels the context when these signals are received. Additionally, a cleanup function is implemented to close channels and databases (blockDB, stateDB, and appDB) while logging any errors. The error handling is streamlined by deferring cleanup and modifying the return to always yield nil, removing previous inline error handling.

Changes

File Change Summary
tools/chainbuilder/main.go - Added signal handling by creating a signalCh for interrupts and termination signals.
- Launched a goroutine to cancel context on signal reception.
- Introduced a cleanup function to close channels (dataCh, persistCh) and databases (blockDB, stateDB, appDB), ensuring resources are released.
- Modified the return statement to nil and removed previous error handling logic.

Sequence Diagram(s)

sequenceDiagram
    participant OS as OS Signal
    participant Main as Run Function
    participant SignalHandler as Signal Goroutine
    participant Cleanup as Cleanup Function

    OS->>SignalHandler: Send os.Interrupt/SIGTERM
    SignalHandler->>Main: Cancel context
    Main->>Cleanup: Invoke deferred cleanup
    Cleanup->>Main: Close channels & databases, log errors
    Main->>OS: Return nil (graceful shutdown)
Loading

Possibly related PRs

Suggested reviewers

  • ninabarbakadze
  • evan-forbes
  • rootulp
  • staheri14
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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.

Documentation and Community

  • 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.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (1)
tools/chainbuilder/main.go (1)

364-364: Minor formatting issue.

There appears to be a whitespace formatting issue on this line according to gofumpt.

-	
+
🧰 Tools
🪛 golangci-lint (1.62.2)

364-364: File is not gofumpt-ed

(gofumpt)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 221c68e and 70a2a6f.

📒 Files selected for processing (1)
  • tools/chainbuilder/main.go (5 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
tools/chainbuilder/main.go

364-364: File is not gofumpt-ed

(gofumpt)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (7)
tools/chainbuilder/main.go (7)

7-9: Added necessary imports for signal handling.

The addition of os/signal and syscall packages will enable capturing OS interrupt signals for graceful shutdown.


129-144: Well-implemented signal handling setup.

This addition creates a proper signal handling mechanism that will:

  1. Listen for both SIGINT (Ctrl+C) and SIGTERM signals
  2. Cancel the context to propagate shutdown requests throughout the system
  3. Print a user-friendly message when a termination signal is received

This implementation follows Go best practices for handling OS signals.


319-320: Added cleanup tracking flag.

The boolean flag to track cleanup state will help prevent double-cleanup situations, which is a good defensive programming practice.


322-363: Well-structured resource cleanup function.

The cleanup function is well-designed with:

  • Check to prevent duplicate cleanup operations
  • Proper channel closing
  • Error collection from goroutines
  • Safe database closing with error logging

This ensures all resources are properly released regardless of how the tool is terminated.


365-366: Ensuring cleanup with defer.

Using defer cleanup() guarantees that cleanup will run before the function returns, even in case of panics. This is an excellent practice for resource management.


389-392: Improved context cancellation handling.

The code now properly responds to context cancellation by printing a helpful message and allowing the deferred cleanup function to handle resource cleanup.


494-495: Simplified error return.

The function now always returns nil, relying on the cleanup function to handle errors. This is consistent with the PR objective of graceful shutdown.

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

Successfully merging this pull request may close these issues.

Refactor the chainbuilder so that it shutsdown gracefully
1 participant