Skip to content

Feat: Current Read/Write Data #54

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

Merged

Conversation

Br0wnHammer
Copy link
Member

@Br0wnHammer Br0wnHammer commented Mar 16, 2025

Description

This PR introduces metrics such as ReadBytes, WriteBytes, ReadTime and WriteTime in the disk api.
This api was tested on a Mac environment. Hence the values are 0.

Fixes

#8

Screenshot 2025-03-16 at 10 18 12 PM

Summary by CodeRabbit

  • New Features
    • Enhanced disk performance monitoring by integrating additional I/O statistics, including detailed read/write byte counts and timings.
    • Improved error handling during metrics collection to ensure uninterrupted monitoring.

Copy link
Contributor

coderabbitai bot commented Mar 16, 2025

Walkthrough

The changes update the disk metrics collection by enhancing the DiskData structure and its usage. Four new fields—ReadBytes, WriteBytes, ReadTime, and WriteTime—have been added. In internal/metric/disk.go, the CollectDiskMetrics function now calls disk.IOCounters for each disk device and assigns the retrieved I/O values to these new fields, while gracefully handling errors. Additionally, obsolete trial code has been removed. The same new fields have been defined in internal/metric/metric.go as pointers to uint64 for detailed metric reporting.

Changes

Files Change Summary
internal/metric/disk.go and internal/metric/metric.go Added four new disk I/O metric fields (ReadBytes, WriteBytes, ReadTime, WriteTime) to the DiskData struct. In disk.go, updated CollectDiskMetrics to retrieve and assign these metrics via disk.IOCounters with corresponding error handling and removal of unused trial code.

Sequence Diagram(s)

sequenceDiagram
    participant CM as CollectDiskMetrics
    participant IOC as disk.IOCounters
    participant DD as DiskData
    participant Logger as Error Logger

    CM->>IOC: Request I/O stats for disk device
    alt Error occurs
        IOC-->>CM: Return error
        CM->>Logger: Append CustomErr with device info
        Note over CM: Continue to next partition
    else Success
        IOC-->>CM: Return I/O stats\n(ReadBytes, WriteBytes, ReadTime, WriteTime)
        CM->>DD: Update DiskData with new I/O fields
    end
Loading

Poem

I hopped along the data stream,
Adding metrics like a dream.
Read and write, time in tow,
Errors logged as on I go.
I’m a rabbit with code so keen –
Hoppin’ through disks, ever serene!
🐇💻

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 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 41f1e19 and eba4946.

📒 Files selected for processing (2)
  • internal/metric/disk.go (3 hunks)
  • internal/metric/metric.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/metric/metric.go
  • internal/metric/disk.go

🪧 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.
  • @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: 0

🧹 Nitpick comments (1)
internal/metric/disk.go (1)

45-55: Check map key existence before accessing

The code correctly collects disk I/O metrics, but doesn't verify if the device exists in the diskIOCounts map before accessing it at line 54. Map access returns zero values when keys don't exist, but it's better to check explicitly.

- stats, _ := diskIOCounts[p.Device]
+ stats, exists := diskIOCounts[p.Device]
+ if !exists {
+    diskErrors = append(diskErrors, CustomErr{
+        Metric: []string{"disk.read_bytes", "disk.write_bytes", "disk.read_time", "disk.write_time"},
+        Error:  "Device not found in IO counters: " + p.Device,
+    })
+    continue
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e19a589 and b59cd92.

📒 Files selected for processing (2)
  • internal/metric/disk.go (3 hunks)
  • internal/metric/metric.go (1 hunks)
🔇 Additional comments (3)
internal/metric/metric.go (1)

55-58: Implementation of new disk I/O metrics looks good!

The newly added fields for tracking disk I/O operations (ReadBytes, WriteBytes, ReadTime, WriteTime) are well-defined and properly documented. The use of pointer types is consistent with the existing pattern for fields like TotalBytes and FreeBytes.

internal/metric/disk.go (2)

16-20: Proper initialization of new fields

The initialization of the new fields in the defaultDiskData structure matches the existing pattern and is correctly set to nil.


70-74: Consider handling zero values for Mac environment

The PR objective mentions that on Mac environments, these values were recorded as zero. Consider adding a comment about platform-specific behavior or check if these values are zero and add appropriate handling.

Could you verify if the gopsutil library supports these metrics across different operating systems? If not, it might be worth handling this case explicitly in the code or documenting this limitation.

Copy link
Member

@mertssmnoglu mertssmnoglu left a comment

Choose a reason for hiding this comment

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

Thank you so much @Br0wnHammer. We should remove the /dev/ prefix to get real data.

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)
internal/metric/disk.go (1)

16-19: Consider adding unit tests for the new metrics.

The PR adds several new fields to collect disk I/O metrics. Consider adding unit tests to verify that these metrics are correctly collected and reported.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b59cd92 and 41f1e19.

📒 Files selected for processing (2)
  • internal/metric/disk.go (3 hunks)
  • internal/metric/metric.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/metric/metric.go
🔇 Additional comments (5)
internal/metric/disk.go (5)

16-16: Fix indentation inconsistency.

There's a tab indentation inconsistency in the ReadBytes field declaration compared to the other fields that use spaces.

-			ReadBytes:	nil,
+			ReadBytes:    nil,

45-52: LGTM! Good error handling for I/O metrics.

The error handling for disk I/O metrics is well implemented. The code correctly captures errors when attempting to collect read/write metrics and provides clear error information including both the error message and the device name.


54-55: LGTM! Correctly handles device name prefix.

The code properly handles the device name by trimming the "/dev/" prefix before accessing the diskIOCounts map, which is the correct approach since the library stores data without this prefix.


71-74: LGTM! Properly populates the new disk I/O metrics.

The implementation correctly assigns pointers to the disk I/O statistics to the corresponding fields in the DiskData structure.


16-19:

❓ Verification inconclusive

Verify metrics collection works across different operating systems.

The PR objectives mentioned that testing in a Mac environment resulted in zero values for these metrics. Consider adding cross-platform testing to ensure these metrics work as expected across different operating systems.


🏁 Script executed:

#!/bin/bash
# Check how different OS platforms handle disk I/O metrics with gopsutil

# Print Go version and OS information
go version
uname -a

# Create a simple test program to test disk I/O metrics collection
cat > test_disk_io.go << 'EOF'
package main

import (
	"fmt"
	"github.com/shirou/gopsutil/v4/disk"
	"strings"
)

func main() {
	partitions, err := disk.Partitions(true)
	if err != nil {
		fmt.Printf("Error getting partitions: %v\n", err)
		return
	}

	for _, p := range partitions {
		if !strings.HasPrefix(p.Device, "/dev") || strings.HasPrefix(p.Device, "/dev/loop") {
			continue
		}

		fmt.Printf("Device: %s\n", p.Device)
		
		// Get disk I/O counters
		diskIOCounts, err := disk.IOCounters(p.Device)
		if err != nil {
			fmt.Printf("  Error getting I/O counters: %v\n", err)
			continue
		}

		deviceName := strings.TrimPrefix(p.Device, "/dev/")
		stats, exists := diskIOCounts[deviceName]
		if !exists {
			fmt.Printf("  No stats found for device: %s\n", deviceName)
			// Try to print all available keys in the map
			fmt.Printf("  Available keys: ")
			for k := range diskIOCounts {
				fmt.Printf("%s ", k)
			}
			fmt.Println()
			continue
		}

		fmt.Printf("  ReadBytes: %d\n", stats.ReadBytes)
		fmt.Printf("  WriteBytes: %d\n", stats.WriteBytes)
		fmt.Printf("  ReadTime: %d\n", stats.ReadTime)
		fmt.Printf("  WriteTime: %d\n", stats.WriteTime)
	}
}
EOF

# Build and run the test program
go mod init diskiotest
go get github.com/shirou/gopsutil/v4/disk
go run test_disk_io.go

Length of output: 1076


Action Required: Enhance cross-platform handling for disk I/O metrics.

The test run indicates that on Linux (in the current jail/sandbox environment), the disk metrics collection fails due to an inability to open /proc/self/mounts, resulting in an error instead of returning metrics. Since the PR noted that testing on macOS produced zero values for these metrics, it's clear that the current approach may not be robust across different operating systems.

Please consider the following:

  • Cross-Platform Testing:
    Augment the test suite to cover multiple OS environments (including macOS and Linux) to confirm the behavior and reliability of disk I/O metrics collection.

  • Error Handling:
    Implement or improve error handling in internal/metric/disk.go (around lines 16–19) to gracefully address cases where system-specific files (e.g., /proc/self/mounts) are unavailable.

  • Fallback Mechanisms:
    Consider adding fallback logic or corrections for environments where the expected metrics cannot be retrieved due to OS limitations.

@Br0wnHammer
Copy link
Member Author

Hey @mertssmnoglu, have implemented the said changes. Should be fine for merging now.

@mertssmnoglu mertssmnoglu added the enhancement New feature or request label Mar 17, 2025
@mertssmnoglu mertssmnoglu removed their assignment Mar 17, 2025
@mertssmnoglu mertssmnoglu merged commit 472e7be into bluewave-labs:develop Mar 17, 2025
2 checks passed
@mertssmnoglu mertssmnoglu linked an issue Mar 17, 2025 that may be closed by this pull request
@Br0wnHammer Br0wnHammer deleted the feat/disk-current-read branch March 17, 2025 12:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Disk current read/write datas
2 participants