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

feat: Migrate monitor middleware from Fiber v2 to v3 #3125

Closed
wants to merge 1 commit into from

Conversation

Redish101
Copy link

@Redish101 Redish101 commented Sep 7, 2024

Description

Migrate monitor middleware from fiber v2 to v3.

Type of change

  • New feature (non-breaking change which adds functionality)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

@Redish101 Redish101 requested a review from a team as a code owner September 7, 2024 08:28
@Redish101 Redish101 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team September 7, 2024 08:28
Copy link

welcome bot commented Sep 7, 2024

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Sep 7, 2024

Walkthrough

The changes introduce a monitoring middleware for a Fiber web application, encompassing configuration management, a web-based interface, and real-time statistics retrieval. Key components include a configuration structure, an HTML dashboard for metrics visualization, and a middleware function that periodically updates system statistics. This implementation enhances the application's monitoring capabilities by providing insights into resource usage.

Changes

Files Change Summary
middleware/monitor/config.go Introduced Config struct for middleware configuration, ConfigDefault variable, and configDefault function.
middleware/monitor/index.go Added viewBag struct and newIndex function to generate an HTML monitoring interface.
middleware/monitor/monitor.go Implemented New function for middleware initialization, including periodic statistics updates.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Middleware
    participant StatsUpdater
    participant HTMLGenerator

    User->>Middleware: Request monitoring data
    Middleware->>StatsUpdater: Fetch latest statistics
    StatsUpdater-->>Middleware: Return statistics
    Middleware->>HTMLGenerator: Generate HTML page with stats
    HTMLGenerator-->>Middleware: Return HTML page
    Middleware-->>User: Respond with monitoring interface
Loading

🐰 In the meadow, I hop with glee,
New stats and charts, oh what a spree!
Configs and updates, all in a row,
Monitoring magic, watch it glow!
With Fiber's might, we’ll surely see,
The pulse of our system, wild and free! 🌼


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 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.

@Redish101 Redish101 closed this Sep 7, 2024
@Redish101 Redish101 reopened this Sep 7, 2024
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

Commits

Files that changed from the base of the PR and between f668537 and ac0049b.

Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
Files selected for processing (3)
  • middleware/monitor/config.go (1 hunks)
  • middleware/monitor/index.go (1 hunks)
  • middleware/monitor/monitor.go (1 hunks)
Additional context used
golangci-lint
middleware/monitor/config.go

10-10: fieldalignment: struct with 96 pointer bytes could be 80

(govet)

middleware/monitor/index.go

9-9: fieldalignment: struct with 64 pointer bytes could be 56

(govet)

Additional comments not posted (3)
middleware/monitor/config.go (1)

66-132: Review of configDefault function: Well-implemented logic.

The configDefault function is well-implemented, with clear handling of default configurations and conditional updates based on changes to the configuration. The logic to ensure that the refresh rate does not fall below the minimum value is particularly noteworthy.

middleware/monitor/monitor.go (1)

18-35: Struct definitions for stats, statsPID, and statsOS: Appropriately defined.

The struct definitions are well-suited for their purpose in structuring the JSON response for the monitoring API. The use of appropriate data types for the metrics ensures that the data is accurately represented.

middleware/monitor/index.go (1)

17-270: Review of newIndex function and HTML template: Well-implemented and secure.

The newIndex function efficiently generates the HTML index page using strings.NewReplacer, which is a good practice for preventing templating errors. The HTML template is well-structured and appears secure against XSS vulnerabilities, as it does not directly embed user input.

Comment on lines +9 to +47
// Config defines the config for middleware.
type Config struct {
// Metrics page title
//
// Optional. Default: "Fiber Monitor"
Title string

// Refresh period
//
// Optional. Default: 3 seconds
Refresh time.Duration

// Whether the service should expose only the monitoring API.
//
// Optional. Default: false
APIOnly bool

// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool

// Custom HTML Code to Head Section(Before End)
//
// Optional. Default: empty
CustomHead string

// FontURL for specify font resource path or URL . also you can use relative path
//
// Optional. Default: https://fonts.googleapis.com/css2?family=Roboto:wght@400;900&display=swap
FontURL string

// ChartJsURL for specify ChartJS library path or URL . also you can use relative path
//
// Optional. Default: https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.bundle.min.js
ChartJsURL string // TODO: Rename to "ChartJSURL" in v3

index string
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize struct field alignment.

The Config struct could be optimized for memory usage by rearranging its fields. This change can potentially reduce the struct's memory footprint, improving performance especially in environments where many instances of this struct might be created.

Consider rearranging the fields to optimize alignment. Here's a suggested rearrangement:

type Config struct {
	Next       func(c *fiber.Ctx) bool // Move function pointers to the top
	Title      string
	CustomHead string
	FontURL    string
	ChartJsURL string
	Refresh    time.Duration
	APIOnly    bool
	index      string
}

This rearrangement groups the larger string and time.Duration types together, placing the smaller bool and function pointer types appropriately to fit better in memory alignment slots.

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
// Config defines the config for middleware.
type Config struct {
// Metrics page title
//
// Optional. Default: "Fiber Monitor"
Title string
// Refresh period
//
// Optional. Default: 3 seconds
Refresh time.Duration
// Whether the service should expose only the monitoring API.
//
// Optional. Default: false
APIOnly bool
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Custom HTML Code to Head Section(Before End)
//
// Optional. Default: empty
CustomHead string
// FontURL for specify font resource path or URL . also you can use relative path
//
// Optional. Default: https://fonts.googleapis.com/css2?family=Roboto:wght@400;900&display=swap
FontURL string
// ChartJsURL for specify ChartJS library path or URL . also you can use relative path
//
// Optional. Default: https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.bundle.min.js
ChartJsURL string // TODO: Rename to "ChartJSURL" in v3
index string
}
// Config defines the config for middleware.
type Config struct {
Next func(c *fiber.Ctx) bool // Move function pointers to the top
Title string
CustomHead string
FontURL string
ChartJsURL string
Refresh time.Duration
APIOnly bool
index string
}
Tools
golangci-lint

10-10: fieldalignment: struct with 96 pointer bytes could be 80

(govet)

Comment on lines +55 to +103
// New creates a new middleware handler
func New(config ...Config) fiber.Handler {
// Set default config
cfg := configDefault(config...)

// Start routine to update statistics
once.Do(func() {
p, _ := process.NewProcess(int32(os.Getpid())) //nolint:errcheck // TODO: Handle error
numcpu := runtime.NumCPU()
updateStatistics(p, numcpu)

go func() {
for {
time.Sleep(cfg.Refresh)

updateStatistics(p, numcpu)
}
}()
})

// Return new handler
//nolint:errcheck // Ignore the type-assertion errors
return func(c fiber.Ctx) error {
// Don't execute middleware if Next returns true
if cfg.Next != nil && cfg.Next(&c) {
return c.Next()
}

if c.Method() != fiber.MethodGet {
return fiber.ErrMethodNotAllowed
}
if c.Get(fiber.HeaderAccept) == fiber.MIMEApplicationJSON || cfg.APIOnly {
mutex.Lock()
data.PID.CPU, _ = monitPIDCPU.Load().(float64)
data.PID.RAM, _ = monitPIDRAM.Load().(uint64)
data.PID.Conns, _ = monitPIDConns.Load().(int)

data.OS.CPU, _ = monitOSCPU.Load().(float64)
data.OS.RAM, _ = monitOSRAM.Load().(uint64)
data.OS.TotalRAM, _ = monitOSTotalRAM.Load().(uint64)
data.OS.LoadAvg, _ = monitOSLoadAvg.Load().(float64)
data.OS.Conns, _ = monitOSConns.Load().(int)
mutex.Unlock()
return c.Status(fiber.StatusOK).JSON(data)
}
c.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8)
return c.Status(fiber.StatusOK).SendString(cfg.index)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Review of New function: Implement error handling.

The New function correctly uses sync.Once to ensure that the statistics updating routine is started only once, which is a good practice. However, the error from process.NewProcess is not handled, which could lead to uncaught exceptions in production environments.

Consider adding error handling for the process creation to ensure stability:

p, err := process.NewProcess(int32(os.Getpid()))
if err != nil {
    return nil, err // Handle the error appropriately
}

This change will help prevent potential runtime errors and improve the robustness of the middleware.

Committable suggestion was skipped due to low confidence.

@gaby
Copy link
Member

gaby commented Sep 7, 2024

@Redish101 The monitor middleware was removed from v3 on purpose. The end goal is to migrate it to the gofiber/contrib repo.

@Redish101
Copy link
Author

@Redish101 The monitor middleware was removed from v3 on purpose. The end goal is to migrate it to the gofiber/contrib repo.

Well, I will move these changes to gofiber/contrib repo.

@gaby
Copy link
Member

gaby commented Sep 7, 2024

@Redish101 The monitor middleware was removed from v3 on purpose. The end goal is to migrate it to the gofiber/contrib repo.

Well, I will move these changes to gofiber/contrib repo.

Thanks, one thing. You have to fix the gopsutil version, it should be this one https://github.com/shirou/gopsutil/releases/tag/v4.24.8 in the go.mod

@Redish101
Copy link
Author

Redish101 commented Sep 7, 2024

@Redish101 The monitor middleware was removed from v3 on purpose. The end goal is to migrate it to the gofiber/contrib repo.

Well, I will move these changes to gofiber/contrib repo.

Thanks, one thing. You have to fix the gopsutil version, it should be this one https://github.com/shirou/gopsutil/releases/tag/v4.24.8 in the go.mod

I have moved these changes to gofiber/contrib#1172 and updated gopsutils to v4.24.8.

@Redish101 Redish101 closed this Sep 7, 2024
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.

2 participants