Feat/docker cpu monitoring #2302

Merged
mfreeman451 merged 22 commits from refs/pull/2302/head into main 2025-10-11 04:59:41 +00:00
mfreeman451 commented 2025-10-10 05:55:21 +00:00 (Migrated from github.com)
Owner

Imported from GitHub pull request.

Original GitHub pull request: #1736
Original author: @mfreeman451
Original URL: https://github.com/carverauto/serviceradar/pull/1736
Original created: 2025-10-10T05:55:21Z
Original updated: 2025-10-11T04:59:50Z
Original head: carverauto/serviceradar:feat/docker_cpu_monitoring
Original base: main
Original merged: 2025-10-11T04:59:41Z by @mfreeman451

PR Type

Enhancement


Description

  • Add CPU frequency monitoring to sysmon metrics

  • Create dedicated sysmon-vm gRPC checker service

  • Implement CPU frequency collector using sysfs/procfs

  • Extend database schema with frequency_hz column


Diagram Walkthrough

flowchart LR
  A["cpufreq collector"] --> B["sysmon-vm service"]
  B --> C["gRPC AgentService"]
  C --> D["agent poller"]
  D --> E["core metrics storage"]
  E --> F["cpu_metrics table"]
  F --> G["API endpoints"]

File Walkthrough

Relevant files
Enhancement
11 files
main.go
New sysmon-vm checker service main entry point                     
+78/-0   
service.go
gRPC service implementation with CPU metrics                         
+185/-0 
sysmon.go
Add frequency_hz to CPU metrics API                                           
+5/-2     
metrics.go
Include frequency data in sysmon processing                           
+3/-0     
collector.go
CPU frequency collector using sysfs/procfs                             
+118/-0 
metrics.go
Update database queries for frequency column                         
+5/-5     
sysmon.go
Add frequency field to metrics storage                                     
+1/-0     
metrics.go
Add FrequencyHz field to CPUMetric model                                 
+2/-0     
00000000000001_consolidated_serviceradar_schema.up.sql
Add frequency_hz column to base schema                                     
+1/-0     
00000000000006_cpu_frequency_column.down.sql
Migration rollback for frequency column                                   
+2/-0     
00000000000006_cpu_frequency_column.up.sql
Migration to add frequency column                                               
+2/-0     
Configuration changes
3 files
registry.go
Register sysmon-vm service in agent registry                         
+2/-0     
config.go
Configuration structure for sysmon-vm checker                       
+45/-0   
sysmon-vm.json.example
Example configuration file for sysmon-vm                                 
+9/-0     
Formatting
1 files
agent_poller.go
Code formatting improvements in poller                                     
+22/-22 
Documentation
2 files
README.md
Documentation for sysmon-vm checker deployment                     
+49/-0   
cpu_plan.md
Implementation plan and operational checklist                       
+154/-0 
Dependencies
2 files
go.mod
Add gopsutil dependency for system metrics                             
+8/-0     
go.sum
Update dependency checksums for gopsutil                                 
+23/-0   

Imported from GitHub pull request. Original GitHub pull request: #1736 Original author: @mfreeman451 Original URL: https://github.com/carverauto/serviceradar/pull/1736 Original created: 2025-10-10T05:55:21Z Original updated: 2025-10-11T04:59:50Z Original head: carverauto/serviceradar:feat/docker_cpu_monitoring Original base: main Original merged: 2025-10-11T04:59:41Z by @mfreeman451 --- ### **PR Type** Enhancement ___ ### **Description** - Add CPU frequency monitoring to sysmon metrics - Create dedicated `sysmon-vm` gRPC checker service - Implement CPU frequency collector using sysfs/procfs - Extend database schema with `frequency_hz` column ___ ### Diagram Walkthrough ```mermaid flowchart LR A["cpufreq collector"] --> B["sysmon-vm service"] B --> C["gRPC AgentService"] C --> D["agent poller"] D --> E["core metrics storage"] E --> F["cpu_metrics table"] F --> G["API endpoints"] ``` <details> <summary><h3> File Walkthrough</h3></summary> <table><thead><tr><th></th><th align="left">Relevant files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><details><summary>11 files</summary><table> <tr> <td><strong>main.go</strong><dd><code>New sysmon-vm checker service main entry point</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-b1ab49590901666d7536778838bbf3eda1cac7c33257e8e89cb3ab74df8ae376">+78/-0</a>&nbsp; &nbsp; </td> </tr> <tr> <td><strong>service.go</strong><dd><code>gRPC service implementation with CPU metrics</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-02211c03421188a7a92d44ce12a4ee8d9f09b224d7176b8713fcefac759ee989">+185/-0</a>&nbsp; </td> </tr> <tr> <td><strong>sysmon.go</strong><dd><code>Add frequency_hz to CPU metrics API</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-4879e8b367ee55413c6cb006f23bb912261df5310c640d3af352033cf97ffc84">+5/-2</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>metrics.go</strong><dd><code>Include frequency data in sysmon processing</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-6d98e853ce17576c088e77956ae4ecfa8078019e0bff107a79d8d1d6ed2443ad">+3/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>collector.go</strong><dd><code>CPU frequency collector using sysfs/procfs</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-35e6ecb698e97eb56fac27c2c42a1cb402cb477e408fc5bf08d7a7b233241b55">+118/-0</a>&nbsp; </td> </tr> <tr> <td><strong>metrics.go</strong><dd><code>Update database queries for frequency column</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-2cf937853ac86eb9a879bd370cbe22b835ee0c48be6771b48b0276d93cc2ae93">+5/-5</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>sysmon.go</strong><dd><code>Add frequency field to metrics storage</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-aa961b7342ce9c95d32ab147ed3e44f9702e6d7a649ef7528c48288a4cd6049d">+1/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>metrics.go</strong><dd><code>Add FrequencyHz field to CPUMetric model</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-1c5e2a501867b2fe257cc13a4ec0a49edf5b97f7c8c1c511e0787803fa692314">+2/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>00000000000001_consolidated_serviceradar_schema.up.sql</strong><dd><code>Add frequency_hz column to base schema</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-1e05de747238f2112bb2230aac8db388e4c80eebe84c071eb78e035d64e67eb6">+1/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>00000000000006_cpu_frequency_column.down.sql</strong><dd><code>Migration rollback for frequency column</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-5f623c51a28d1cc3d72a0da50871c503daddb44859fdd990c3f3f6d4f15870cb">+2/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>00000000000006_cpu_frequency_column.up.sql</strong><dd><code>Migration to add frequency column</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-29254199b4448c6d86227ec8ad74ff5d3c5839bff9a065a12cfe181501cac20a">+2/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> </table></details></td></tr><tr><td><strong>Configuration changes</strong></td><td><details><summary>3 files</summary><table> <tr> <td><strong>registry.go</strong><dd><code>Register sysmon-vm service in agent registry</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-9ea3b939dfe069a8743ce6d9b53e9601b8dd4cc680a249c1994a95a9c119102f">+2/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>config.go</strong><dd><code>Configuration structure for sysmon-vm checker</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-759162c1c3008b74e820561e4a8d6ff2802a072e056f91ee7f52089702a2bce2">+45/-0</a>&nbsp; &nbsp; </td> </tr> <tr> <td><strong>sysmon-vm.json.example</strong><dd><code>Example configuration file for sysmon-vm</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-48004400818e27aa9658afe57b85efabc0cbcfdd1914b1699a40f29856236dac">+9/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> </table></details></td></tr><tr><td><strong>Formatting</strong></td><td><details><summary>1 files</summary><table> <tr> <td><strong>agent_poller.go</strong><dd><code>Code formatting improvements in poller</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-7cdaae416a1e7b5d39ad75f138c49fa0aca12fc38e8ab0b26bb59c64446da15c">+22/-22</a>&nbsp; </td> </tr> </table></details></td></tr><tr><td><strong>Documentation</strong></td><td><details><summary>2 files</summary><table> <tr> <td><strong>README.md</strong><dd><code>Documentation for sysmon-vm checker deployment</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-f72d7c40673ad7eb78ef313ce5aa05442176de542f531a96ca5776156ac41d4b">+49/-0</a>&nbsp; &nbsp; </td> </tr> <tr> <td><strong>cpu_plan.md</strong><dd><code>Implementation plan and operational checklist</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-c0dc94ab36dba7fcd11ecff636aa9814b5a34f935329473e01dc648a84ea8cb1">+154/-0</a>&nbsp; </td> </tr> </table></details></td></tr><tr><td><strong>Dependencies</strong></td><td><details><summary>2 files</summary><table> <tr> <td><strong>go.mod</strong><dd><code>Add gopsutil dependency for system metrics</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-33ef32bf6c23acb95f5902d7097b7a1d5128ca061167ec0716715b0b9eeaa5f6">+8/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>go.sum</strong><dd><code>Update dependency checksums for gopsutil</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td> <td><a href="https://github.com/carverauto/serviceradar/pull/1736/files#diff-3295df7234525439d778f1b282d146a4f1ff6b415248aaac074e8042d9f42d63">+23/-0</a>&nbsp; &nbsp; </td> </tr> </table></details></td></tr></tr></tbody></table> </details> ___
qodo-code-review[bot] commented 2025-10-10 05:56:03 +00:00 (Migrated from github.com)
Author
Owner

Imported GitHub PR comment.

Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/1736#issuecomment-3388390549
Original created: 2025-10-10T05:56:03Z

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
External network dial

Description: The function localIP() dials an external UDP address ("8.8.8.8:80") to infer the local IP,
which can leak network metadata and may fail or hang in restricted environments; consider
using local interface inspection instead.
service.go [172-185]

Referred Code
func localIP() string {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		return "unknown"
	}
	defer conn.Close()

	localAddr, ok := conn.LocalAddr().(*net.UDPAddr)
	if !ok {
		return "unknown"
	}

	return localAddr.IP.String()
}
SQL injection

Description: Building SQL with fmt.Sprintf that interpolates device_id and timestamps directly risks
SQL injection if any value is untrusted; use parameterized queries instead.
sysmon.go [394-402]

Referred Code
func (s *APIServer) getCPUMetricsForDevice(
	ctx context.Context, _ db.SysmonMetricsProvider, deviceID string, start, end time.Time) (interface{}, error) {
	// Query cpu_metrics table directly for per-core data by device_id
	query := fmt.Sprintf(`
		SELECT timestamp, agent_id, host_id, core_id, usage_percent, frequency_hz
		FROM table(cpu_metrics)
		WHERE device_id = '%s' AND timestamp BETWEEN '%s' AND '%s'
		ORDER BY timestamp DESC, core_id ASC`,
		deviceID, start.Format(time.RFC3339), end.Format(time.RFC3339))
Path traversal

Description: Reading from /sys/devices/system/cpu/.../scaling_cur_freq without constraining core to
expected bounds could allow path probing if core count is spoofed upstream; validate
indices strictly against cpu.Counts and construct paths defensively.
collector.go [98-117]

Referred Code
func readSysfs(core int) (float64, bool) {
	path := filepath.Join(sysfsCpufreqPath, fmt.Sprintf("cpu%d/cpufreq/scaling_cur_freq", core))

	data, err := os.ReadFile(path)
	if err != nil {
		return 0, false
	}

	raw := strings.TrimSpace(string(data))
	if raw == "" {
		return 0, false
	}

	// scaling_cur_freq is reported in kHz.
	val, err := strconv.ParseFloat(raw, 64)
	if err != nil {
		return 0, false
	}

	return val * 1_000, true
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
No custom compliance provided

Follow the guide to enable custom compliance check.

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
- Requires Further Human Verification
🏷️ - Compliance label
Imported GitHub PR comment. Original author: @qodo-code-review[bot] Original URL: https://github.com/carverauto/serviceradar/pull/1736#issuecomment-3388390549 Original created: 2025-10-10T05:56:03Z --- ## PR Compliance Guide 🔍 <!-- https://github.com/carverauto/serviceradar/commit/c63e7a17b79d918aba99de8a65e2b86a504bb30e --> Below is a summary of compliance checks for this PR:<br> <table><tbody><tr><td colspan='2'><strong>Security Compliance</strong></td></tr> <tr><td rowspan=3>⚪</td> <td><details><summary><strong>External network dial </strong></summary><br> <b>Description:</b> The function <code>localIP()</code> dials an external UDP address ("8.8.8.8:80") to infer the local IP, <br>which can leak network metadata and may fail or hang in restricted environments; consider <br>using local interface inspection instead.<br> <strong><a href='https://github.com/carverauto/serviceradar/pull/1736/files#diff-02211c03421188a7a92d44ce12a4ee8d9f09b224d7176b8713fcefac759ee989R172-R185'>service.go [172-185]</a></strong><br> <details open><summary>Referred Code</summary> ```go func localIP() string { conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { return "unknown" } defer conn.Close() localAddr, ok := conn.LocalAddr().(*net.UDPAddr) if !ok { return "unknown" } return localAddr.IP.String() } ``` </details></details></td></tr> <tr><td><details><summary><strong>SQL injection </strong></summary><br> <b>Description:</b> Building SQL with fmt.Sprintf that interpolates <code>device_id</code> and timestamps directly risks <br>SQL injection if any value is untrusted; use parameterized queries instead.<br> <strong><a href='https://github.com/carverauto/serviceradar/pull/1736/files#diff-4879e8b367ee55413c6cb006f23bb912261df5310c640d3af352033cf97ffc84R394-R402'>sysmon.go [394-402]</a></strong><br> <details open><summary>Referred Code</summary> ```go func (s *APIServer) getCPUMetricsForDevice( ctx context.Context, _ db.SysmonMetricsProvider, deviceID string, start, end time.Time) (interface{}, error) { // Query cpu_metrics table directly for per-core data by device_id query := fmt.Sprintf(` SELECT timestamp, agent_id, host_id, core_id, usage_percent, frequency_hz FROM table(cpu_metrics) WHERE device_id = '%s' AND timestamp BETWEEN '%s' AND '%s' ORDER BY timestamp DESC, core_id ASC`, deviceID, start.Format(time.RFC3339), end.Format(time.RFC3339)) ``` </details></details></td></tr> <tr><td><details><summary><strong>Path traversal </strong></summary><br> <b>Description:</b> Reading from <code>/sys/devices/system/cpu/.../scaling_cur_freq</code> without constraining <code>core</code> to <br>expected bounds could allow path probing if core count is spoofed upstream; validate <br>indices strictly against <code>cpu.Counts</code> and construct paths defensively.<br> <strong><a href='https://github.com/carverauto/serviceradar/pull/1736/files#diff-35e6ecb698e97eb56fac27c2c42a1cb402cb477e408fc5bf08d7a7b233241b55R98-R117'>collector.go [98-117]</a></strong><br> <details open><summary>Referred Code</summary> ```go func readSysfs(core int) (float64, bool) { path := filepath.Join(sysfsCpufreqPath, fmt.Sprintf("cpu%d/cpufreq/scaling_cur_freq", core)) data, err := os.ReadFile(path) if err != nil { return 0, false } raw := strings.TrimSpace(string(data)) if raw == "" { return 0, false } // scaling_cur_freq is reported in kHz. val, err := strconv.ParseFloat(raw, 64) if err != nil { return 0, false } return val * 1_000, true ``` </details></details></td></tr> <tr><td colspan='2'><strong>Ticket Compliance</strong></td></tr> <tr><td>⚪</td><td><details><summary>🎫 <strong>No ticket provided </summary></strong> - [ ] Create ticket/issue <!-- /create_ticket --create_ticket=true --> </details></td></tr> <tr><td colspan='2'><strong>Codebase Duplication Compliance</strong></td></tr> <tr><td>⚪</td><td><details><summary><strong>Codebase context is not defined </strong></summary> Follow the <a href='https://qodo-merge-docs.qodo.ai/core-abilities/rag_context_enrichment/'>guide</a> to enable codebase context checks. </details></td></tr> <tr><td colspan='2'><strong>Custom Compliance</strong></td></tr> <tr><td>⚪</td><td><details><summary><strong>No custom compliance provided</strong></summary> Follow the <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/'>guide</a> to enable custom compliance check. </details></td></tr> <tr><td align="center" colspan="2"> - [ ] Update <!-- /compliance --update_compliance=true --> </td></tr></tbody></table> <details><summary>Compliance status legend</summary> 🟢 - Fully Compliant<br> 🟡 - Partial Compliant<br> 🔴 - Not Compliant<br> ⚪ - Requires Further Human Verification<br> 🏷️ - Compliance label<br> </details>
qodo-code-review[bot] commented 2025-10-10 05:57:19 +00:00 (Migrated from github.com)
Author
Owner

Imported GitHub PR comment.

Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/1736#issuecomment-3388392458
Original created: 2025-10-10T05:57:19Z

PR Code Suggestions

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Improve local IP address discovery

Improve the localIP function by removing its dependency on an external server.
The suggested implementation iterates over the host's network interfaces to find
a suitable non-loopback IP address, making it more robust.

pkg/checker/sysmonvm/service.go [172-185]

 func localIP() string {
-	conn, err := net.Dial("udp", "8.8.8.8:80")
+	addrs, err := net.InterfaceAddrs()
 	if err != nil {
 		return "unknown"
 	}
-	defer conn.Close()
 
-	localAddr, ok := conn.LocalAddr().(*net.UDPAddr)
-	if !ok {
-		return "unknown"
+	for _, address := range addrs {
+		// Check the address type and if it is not a loopback, return it.
+		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
+			if ipnet.IP.To4() != nil {
+				return ipnet.IP.String()
+			}
+		}
 	}
-
-	return localAddr.IP.String()
+	return "unknown"
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that dialing an external address to find the local IP is fragile and proposes a more robust, dependency-free alternative by iterating over local network interfaces. This improves the reliability of the checker in environments without internet access.

Medium
Improve file reading performance for sysfs

Optimize the readSysfs function for better performance when reading small sysfs
files. Replace os.ReadFile with os.Open and a fixed-size buffer to reduce memory
allocations.

pkg/cpufreq/collector.go [98-118]

 func readSysfs(core int) (float64, bool) {
 	path := filepath.Join(sysfsCpufreqPath, fmt.Sprintf("cpu%d/cpufreq/scaling_cur_freq", core))
 
-	data, err := os.ReadFile(path)
+	f, err := os.Open(path)
 	if err != nil {
 		return 0, false
 	}
+	defer f.Close()
 
-	raw := strings.TrimSpace(string(data))
+	// Buffer is sufficient for frequency values.
+	buf := make([]byte, 32)
+	n, err := f.Read(buf)
+	if err != nil || n == 0 {
+		return 0, false
+	}
+
+	raw := strings.TrimSpace(string(buf[:n]))
 	if raw == "" {
 		return 0, false
 	}
 
 	// scaling_cur_freq is reported in kHz.
 	val, err := strconv.ParseFloat(raw, 64)
 	if err != nil {
 		return 0, false
 	}
 
 	return val * 1_000, true
 }
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion offers a valid micro-optimization for reading small sysfs files by using os.Open and a buffer instead of os.ReadFile. While correct, the performance impact is likely minimal given the small file size and context of the application.

Low
  • Update
Imported GitHub PR comment. Original author: @qodo-code-review[bot] Original URL: https://github.com/carverauto/serviceradar/pull/1736#issuecomment-3388392458 Original created: 2025-10-10T05:57:19Z --- ## PR Code Suggestions ✨ <!-- c63e7a1 --> Explore these optional code suggestions: <table><thead><tr><td><strong>Category</strong></td><td align=left><strong>Suggestion&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </strong></td><td align=center><strong>Impact</strong></td></tr><tbody><tr><td rowspan=2>General</td> <td> <details><summary>Improve local IP address discovery<!-- not_implemented --></summary> ___ **Improve the <code>localIP</code> function by removing its dependency on an external server. <br>The suggested implementation iterates over the host's network interfaces to find <br>a suitable non-loopback IP address, making it more robust.** [pkg/checker/sysmonvm/service.go [172-185]](https://github.com/carverauto/serviceradar/pull/1736/files#diff-02211c03421188a7a92d44ce12a4ee8d9f09b224d7176b8713fcefac759ee989R172-R185) ```diff func localIP() string { - conn, err := net.Dial("udp", "8.8.8.8:80") + addrs, err := net.InterfaceAddrs() if err != nil { return "unknown" } - defer conn.Close() - localAddr, ok := conn.LocalAddr().(*net.UDPAddr) - if !ok { - return "unknown" + for _, address := range addrs { + // Check the address type and if it is not a loopback, return it. + if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ipnet.IP.To4() != nil { + return ipnet.IP.String() + } + } } - - return localAddr.IP.String() + return "unknown" } ``` - [ ] **Apply / Chat** <!-- /improve --apply_suggestion=0 --> <details><summary>Suggestion importance[1-10]: 7</summary> __ Why: The suggestion correctly identifies that dialing an external address to find the local IP is fragile and proposes a more robust, dependency-free alternative by iterating over local network interfaces. This improves the reliability of the checker in environments without internet access. </details></details></td><td align=center>Medium </td></tr><tr><td> <details><summary>Improve file reading performance for sysfs<!-- not_implemented --></summary> ___ **Optimize the <code>readSysfs</code> function for better performance when reading small sysfs <br>files. Replace <code>os.ReadFile</code> with <code>os.Open</code> and a fixed-size buffer to reduce memory <br>allocations.** [pkg/cpufreq/collector.go [98-118]](https://github.com/carverauto/serviceradar/pull/1736/files#diff-35e6ecb698e97eb56fac27c2c42a1cb402cb477e408fc5bf08d7a7b233241b55R98-R118) ```diff func readSysfs(core int) (float64, bool) { path := filepath.Join(sysfsCpufreqPath, fmt.Sprintf("cpu%d/cpufreq/scaling_cur_freq", core)) - data, err := os.ReadFile(path) + f, err := os.Open(path) if err != nil { return 0, false } + defer f.Close() - raw := strings.TrimSpace(string(data)) + // Buffer is sufficient for frequency values. + buf := make([]byte, 32) + n, err := f.Read(buf) + if err != nil || n == 0 { + return 0, false + } + + raw := strings.TrimSpace(string(buf[:n])) if raw == "" { return 0, false } // scaling_cur_freq is reported in kHz. val, err := strconv.ParseFloat(raw, 64) if err != nil { return 0, false } return val * 1_000, true } ``` - [ ] **Apply / Chat** <!-- /improve --apply_suggestion=1 --> <details><summary>Suggestion importance[1-10]: 4</summary> __ Why: The suggestion offers a valid micro-optimization for reading small sysfs files by using `os.Open` and a buffer instead of `os.ReadFile`. While correct, the performance impact is likely minimal given the small file size and context of the application. </details></details></td><td align=center>Low </td></tr> <tr><td align="center" colspan="2"> - [ ] Update <!-- /improve_multi --more_suggestions=true --> </td><td></td></tr></tbody></table>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
carverauto/serviceradar!2302
No description provided.