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

fix metrics server shutdown #761

Merged
merged 2 commits into from
Feb 19, 2025
Merged

Conversation

janezpodhostnik
Copy link
Contributor

@janezpodhostnik janezpodhostnik commented Feb 19, 2025

Closes: #???

Description

In some cases, like in e2e tests here: #760 the metrics server didn't properly shut down.

This adds a wrapper that encapsulates the metrics server start and stop, and adds an explicit context cancel in case it wasn't already cancelled.


For contributor use:

  • Targeted PR against master branch
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the standards mentioned here.
  • Updated relevant documentation
  • Re-reviewed Files changed in the Github PR explorer
  • Added appropriate labels

Summary by CodeRabbit

  • Refactor
    • Enhanced the system’s metrics functionality with a streamlined process for starting and stopping, resulting in improved error handling and a more robust monitoring experience.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Walkthrough

The changes introduce a new metricsWrapper structure that encapsulates the existing flowMetrics.Server to manage its lifecycle. The Bootstrap struct's metrics field is updated to use the new wrapper. Additionally, the StartMetricsServer and StopMetricsServer methods are modified to call the new Start and Stop functions respectively on the wrapper. This update enhances the control of error handling, logging, and graceful shutdown of the metrics server.

Changes

File(s) Change Summary
bootstrap/bootstrap.go - Introduced metricsWrapper to encapsulate flowMetrics.Server
- Updated Bootstrap.metrics from *flowMetrics.Server to *metricsWrapper
- Modified StartMetricsServer and StopMetricsServer to use the new wrapper methods
- Added newMetricsWrapper, Start, and Stop methods

Sequence Diagram(s)

sequenceDiagram
    participant B as Bootstrap
    participant MW as metricsWrapper
    participant MS as flowMetrics.Server

    B->>+MW: newMetricsWrapper(logger, port)
    B->>+MW: Start(ctx)
    MW->>MS: Initialize and start metrics server
    MS-->>MW: Metrics server running
    B->>MW: Stop()
    MW->>MS: Shutdown metrics server
Loading

Suggested labels

Improvement, Technical Debt

Suggested reviewers

  • peterargue
  • m-Peter
  • devbugging

Poem

I'm but a little rabbit, hopping through code,
With a smile on my face and a payload to load.
New wrappers and methods, a dance of delight,
Keeping the metrics in check, day and night.
Enjoy the fresh changes, let your code shine bright!
🐰✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03790ff and d48c663.

📒 Files selected for processing (1)
  • bootstrap/bootstrap.go (3 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
bootstrap/bootstrap.go

708-708: m.Ready undefined (type *metricsWrapper has no field or method Ready)

(typecheck)


742-742: m.Done undefined (type *metricsWrapper has no field or method Done)

(typecheck)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test
🔇 Additional comments (4)
bootstrap/bootstrap.go (4)

75-75: LGTM!

The field type change from *flowMetrics.Server to *metricsWrapper is appropriate for encapsulating the metrics server lifecycle management.


374-378: LGTM!

The StartMetricsServer implementation is now cleaner and more concise, delegating the lifecycle management to the wrapper.


380-382: LGTM!

The StopMetricsServer implementation correctly delegates to the wrapper's Stop method.


734-743: LGTM!

The Stop method implementation is correct and includes proper nil checks and cleanup.

🧰 Tools
🪛 golangci-lint (1.62.2)

742-742: m.Done undefined (type *metricsWrapper has no field or method Done)

(typecheck)

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. 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. (Beta)
  • @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.

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

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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6f4a6cb and 03790ff.

📒 Files selected for processing (1)
  • bootstrap/bootstrap.go (3 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
bootstrap/bootstrap.go

708-708: m.Ready undefined (type *metricsWrapper has no field or method Ready)

(typecheck)


737-737: m.Done undefined (type *metricsWrapper has no field or method Done)

(typecheck)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test
🔇 Additional comments (3)
bootstrap/bootstrap.go (3)

75-75: LGTM! Good encapsulation of metrics server.

The change to use metricsWrapper improves the lifecycle management of the metrics server.


374-378: LGTM! Improved metrics server lifecycle management.

The changes simplify the lifecycle methods while improving error handling and shutdown logic through proper delegation to the wrapper.

Also applies to: 380-382


729-738: LGTM! Clean shutdown implementation.

The Stop method properly handles nil checks and ensures the server is fully stopped by waiting for the Done signal.

🧰 Tools
🪛 golangci-lint (1.62.2)

737-737: m.Done undefined (type *metricsWrapper has no field or method Done)

(typecheck)

Comment on lines +685 to +691
// metricsWrapper is needed since the metric server is a component.
// We need to start and stop it manually.
type metricsWrapper struct {
*flowMetrics.Server
log zerolog.Logger
stopFN func()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix method accessibility in metricsWrapper.

The wrapper embeds *flowMetrics.Server but doesn't properly expose the Ready() and Done() methods, causing compilation errors. Add method forwarding to fix this.

Apply this diff:

type metricsWrapper struct {
	*flowMetrics.Server
	log    zerolog.Logger
	stopFN func()
}

+// Ready forwards to the embedded Server's Ready method
+func (m *metricsWrapper) Ready() <-chan struct{} {
+	return m.Server.Ready()
+}

+// Done forwards to the embedded Server's Done method
+func (m *metricsWrapper) Done() <-chan struct{} {
+	return m.Server.Done()
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// metricsWrapper is needed since the metric server is a component.
// We need to start and stop it manually.
type metricsWrapper struct {
*flowMetrics.Server
log zerolog.Logger
stopFN func()
}
// metricsWrapper is needed since the metric server is a component.
// We need to start and stop it manually.
type metricsWrapper struct {
*flowMetrics.Server
log zerolog.Logger
stopFN func()
}
// Ready forwards to the embedded Server's Ready method
func (m *metricsWrapper) Ready() <-chan struct{} {
return m.Server.Ready()
}
// Done forwards to the embedded Server's Done method
func (m *metricsWrapper) Done() <-chan struct{} {
return m.Server.Done()
}

Comment on lines 701 to 727
func (m *metricsWrapper) Start(ctx context.Context) error {
m.log.Info().Msg("bootstrap starting metrics server")

ctx, cancel := context.WithCancel(ctx)
m.stopFN = cancel
ictx, errCh := irrecoverable.WithSignaler(ctx)
m.Server.Start(ictx)
if err := util.WaitClosed(ctx, m.Ready()); err != nil {
return fmt.Errorf("failed to start metrics server: %w", err)
}
select {
case err := <-errCh:
// there might be an error already if the startup failed
return err
default:
}

go func() {
err := <-errCh
if err != nil {
m.log.Err(err).Msg("error in metrics server")
panic(err)
}
}()

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling in Start method.

The error handling could be improved to ensure proper cleanup in case of failures:

  1. The context cancellation function should be called if startup fails
  2. The panic in the goroutine could lead to unhandled crashes

Apply this diff:

func (m *metricsWrapper) Start(ctx context.Context) error {
	m.log.Info().Msg("bootstrap starting metrics server")

	ctx, cancel := context.WithCancel(ctx)
-	m.stopFN = cancel
+	defer func() {
+		if err := recover(); err != nil {
+			cancel()
+			m.log.Error().Interface("panic", err).Msg("panic in metrics server")
+		}
+	}()
	ictx, errCh := irrecoverable.WithSignaler(ctx)
	m.Server.Start(ictx)
	if err := util.WaitClosed(ctx, m.Ready()); err != nil {
+		cancel()
		return fmt.Errorf("failed to start metrics server: %w", err)
	}
	select {
	case err := <-errCh:
		// there might be an error already if the startup failed
+		cancel()
		return err
	default:
	}

+	m.stopFN = cancel
	go func() {
		err := <-errCh
		if err != nil {
			m.log.Err(err).Msg("error in metrics server")
-			panic(err)
+			cancel()
		}
	}()

	return nil
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (m *metricsWrapper) Start(ctx context.Context) error {
m.log.Info().Msg("bootstrap starting metrics server")
ctx, cancel := context.WithCancel(ctx)
m.stopFN = cancel
ictx, errCh := irrecoverable.WithSignaler(ctx)
m.Server.Start(ictx)
if err := util.WaitClosed(ctx, m.Ready()); err != nil {
return fmt.Errorf("failed to start metrics server: %w", err)
}
select {
case err := <-errCh:
// there might be an error already if the startup failed
return err
default:
}
go func() {
err := <-errCh
if err != nil {
m.log.Err(err).Msg("error in metrics server")
panic(err)
}
}()
return nil
}
func (m *metricsWrapper) Start(ctx context.Context) error {
m.log.Info().Msg("bootstrap starting metrics server")
ctx, cancel := context.WithCancel(ctx)
defer func() {
if err := recover(); err != nil {
cancel()
m.log.Error().Interface("panic", err).Msg("panic in metrics server")
}
}()
ictx, errCh := irrecoverable.WithSignaler(ctx)
m.Server.Start(ictx)
if err := util.WaitClosed(ctx, m.Ready()); err != nil {
cancel()
return fmt.Errorf("failed to start metrics server: %w", err)
}
select {
case err := <-errCh:
// there might be an error already if the startup failed
cancel()
return err
default:
}
m.stopFN = cancel
go func() {
err := <-errCh
if err != nil {
m.log.Err(err).Msg("error in metrics server")
cancel()
}
}()
return nil
}
🧰 Tools
🪛 golangci-lint (1.62.2)

708-708: m.Ready undefined (type *metricsWrapper has no field or method Ready)

(typecheck)

Copy link
Collaborator

@m-Peter m-Peter left a comment

Choose a reason for hiding this comment

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

Awesome 💯

@janezpodhostnik janezpodhostnik merged commit f8efaff into main Feb 19, 2025
2 checks passed
@m-Peter m-Peter deleted the janez/fix-metrics-server-shutdown branch February 19, 2025 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants