ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Bandwidth Testing (iperf-style)
//!
//! Provides network throughput measurement utilities inspired by iperf.
//! Can run as client connecting to a remote server, or measure local
//! network interface throughput.
//!
//! # Examples
//!
//! ## TCP Bandwidth Test
//!
//! ```no_run
//! use ironmonitor::bandwidth::{bandwidth_test, BandwidthConfig, BandwidthResult};
//! use std::time::Duration;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Test download bandwidth from a server
//! let config = BandwidthConfig::default()
//!     .with_duration(Duration::from_secs(5));
//!
//! let result = bandwidth_test("speedtest.example.com", 5201, &config)?;
//! if let Some(mbps) = result.bandwidth_mbps {
//!     println!("Bandwidth: {:.2} Mbps", mbps);
//! }
//! # Ok(())
//! # }
//! ```

use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::{Duration, Instant};

/// Default test port (same as iperf3)
pub const DEFAULT_PORT: u16 = 5201;

/// Default test duration in seconds
pub const DEFAULT_DURATION_SECS: u64 = 10;

/// Default buffer size in bytes
pub const DEFAULT_BUFFER_SIZE: usize = 128 * 1024; // 128 KB

/// Bandwidth test configuration
#[derive(Debug, Clone)]
pub struct BandwidthConfig {
    /// Test duration
    pub duration: Duration,
    /// Buffer size for transfers
    pub buffer_size: usize,
    /// Number of parallel streams
    pub parallel_streams: u8,
    /// Connection timeout
    pub connect_timeout: Duration,
    /// Whether to test upload (true) or download (false)
    pub upload: bool,
}

impl Default for BandwidthConfig {
    fn default() -> Self {
        Self {
            duration: Duration::from_secs(DEFAULT_DURATION_SECS),
            buffer_size: DEFAULT_BUFFER_SIZE,
            parallel_streams: 1,
            connect_timeout: Duration::from_secs(10),
            upload: false,
        }
    }
}

impl BandwidthConfig {
    /// Set test duration
    pub fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    /// Set buffer size
    pub fn with_buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size;
        self
    }

    /// Set number of parallel streams
    pub fn with_parallel_streams(mut self, streams: u8) -> Self {
        self.parallel_streams = streams.max(1);
        self
    }

    /// Set connection timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Set upload mode
    pub fn upload_mode(mut self) -> Self {
        self.upload = true;
        self
    }

    /// Set download mode
    pub fn download_mode(mut self) -> Self {
        self.upload = false;
        self
    }
}

/// Bandwidth test result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BandwidthResult {
    /// Target host
    pub host: String,
    /// Target port
    pub port: u16,
    /// Whether this was an upload test
    pub upload: bool,
    /// Test duration in seconds. `None` for a test that failed before it ran;
    /// this was `0.0`, a duration nothing measured.
    pub duration_secs: Option<f64>,
    /// Total bytes transferred. `None` where it was not counted: a test that
    /// failed before it ran, or a loopback test whose receiver failed. This was
    /// `0`, which reads as a measured stall.
    pub bytes_transferred: Option<u64>,
    /// Bandwidth in bits per second. `None` where no rate was measured: a
    /// failed test, or one with zero elapsed time. Not `0.0`, which reads as
    /// a measured stall.
    pub bandwidth_bps: Option<f64>,
    /// Bandwidth in megabits per second (`None` as for `bandwidth_bps`)
    pub bandwidth_mbps: Option<f64>,
    /// Bandwidth in megabytes per second (`None` as for `bandwidth_bps`)
    pub bandwidth_mbytes_per_sec: Option<f64>,
    /// Number of successful transfers
    pub transfer_count: u64,
    /// Connection time in milliseconds, `None` where the connection was not
    /// timed (a failed test)
    pub connect_time_ms: Option<f64>,
    /// Whether the test succeeded
    pub success: bool,
    /// Error message (if failed)
    pub error: Option<String>,
}

impl BandwidthResult {
    /// Create a failed result
    fn failed(host: &str, port: u16, error: &str) -> Self {
        Self {
            host: host.to_string(),
            port,
            upload: false,
            duration_secs: None,
            bytes_transferred: None,
            bandwidth_bps: None,
            bandwidth_mbps: None,
            bandwidth_mbytes_per_sec: None,
            transfer_count: 0,
            connect_time_ms: None,
            success: false,
            error: Some(error.to_string()),
        }
    }
}

/// Perform a bandwidth test to a remote host
///
/// This performs a simple TCP throughput test. For accurate results,
/// the remote host should have an iperf3 server or similar running.
///
/// Note: This is a simplified implementation. For full iperf compatibility,
/// consider using the actual iperf3 binary.
pub fn bandwidth_test(host: &str, port: u16, config: &BandwidthConfig) -> Result<BandwidthResult> {
    let addr = format!("{}:{}", host, port);
    let socket_addr = addr
        .to_socket_addrs()
        .map_err(|e| IronError::Other(format!("Failed to resolve {}: {}", addr, e)))?
        .next()
        .ok_or_else(|| IronError::Other(format!("No addresses found for {}", addr)))?;

    // Measure connection time
    let connect_start = Instant::now();
    let mut stream = TcpStream::connect_timeout(&socket_addr, config.connect_timeout)
        .map_err(|e| IronError::Other(format!("Failed to connect to {}: {}", addr, e)))?;
    let connect_time = connect_start.elapsed();

    // Set socket options
    stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
    stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
    stream.set_nodelay(true).ok();

    let buffer = vec![0u8; config.buffer_size];
    let mut total_bytes: u64 = 0;
    let mut transfer_count: u64 = 0;

    let test_start = Instant::now();

    if config.upload {
        // Upload test - send data
        while test_start.elapsed() < config.duration {
            match stream.write(&buffer) {
                Ok(n) => {
                    total_bytes += n as u64;
                    transfer_count += 1;
                }
                Err(e) => {
                    if e.kind() != std::io::ErrorKind::WouldBlock {
                        return Ok(BandwidthResult::failed(
                            host,
                            port,
                            &format!("Write error: {}", e),
                        ));
                    }
                }
            }
        }
    } else {
        // Download test - receive data
        let mut read_buffer = vec![0u8; config.buffer_size];
        while test_start.elapsed() < config.duration {
            match stream.read(&mut read_buffer) {
                Ok(0) => break, // Connection closed
                Ok(n) => {
                    total_bytes += n as u64;
                    transfer_count += 1;
                }
                Err(e) => {
                    if e.kind() == std::io::ErrorKind::WouldBlock
                        || e.kind() == std::io::ErrorKind::TimedOut
                    {
                        continue;
                    }
                    break;
                }
            }
        }
    }

    let duration = test_start.elapsed();
    let duration_secs = duration.as_secs_f64();

    // Calculate bandwidth. A zero-length test has no rate, so the rate is
    // `None` rather than 0.0.
    let bits_transferred = total_bytes * 8;
    let bandwidth_bps = (duration_secs > 0.0).then(|| bits_transferred as f64 / duration_secs);
    let bandwidth_mbps = bandwidth_bps.map(|bps| bps / 1_000_000.0);
    let bandwidth_mbytes =
        (duration_secs > 0.0).then(|| total_bytes as f64 / duration_secs / 1_000_000.0);

    Ok(BandwidthResult {
        host: host.to_string(),
        port,
        upload: config.upload,
        duration_secs: Some(duration_secs),
        bytes_transferred: Some(total_bytes),
        bandwidth_bps,
        bandwidth_mbps,
        bandwidth_mbytes_per_sec: bandwidth_mbytes,
        transfer_count,
        connect_time_ms: Some(connect_time.as_secs_f64() * 1000.0),
        success: total_bytes > 0,
        error: None,
    })
}

/// Simple local loopback bandwidth test
///
/// Tests how fast data can be transferred through the loopback interface.
/// Useful for measuring system overhead.
pub fn loopback_test(duration: Duration) -> Result<BandwidthResult> {
    use std::net::TcpListener;
    use std::thread;

    // Bind to a random port
    let listener = TcpListener::bind("127.0.0.1:0").map_err(|e| IronError::Other(e.to_string()))?;
    let port = listener
        .local_addr()
        .map_err(|e| IronError::Other(format!("failed to get local address: {}", e)))?
        .port();

    let buffer_size = DEFAULT_BUFFER_SIZE;
    let test_duration = duration;

    // Spawn receiver thread
    let receiver = thread::spawn(move || -> std::io::Result<u64> {
        let (mut stream, _) = listener.accept()?;
        stream
            .set_read_timeout(Some(Duration::from_millis(100)))
            .ok();

        let mut buffer = vec![0u8; buffer_size];
        let mut total_bytes: u64 = 0;
        let start = Instant::now();

        while start.elapsed() < test_duration + Duration::from_secs(1) {
            match stream.read(&mut buffer) {
                Ok(0) => break,
                Ok(n) => total_bytes += n as u64,
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
                Err(e) if e.kind() == std::io::ErrorKind::TimedOut => continue,
                Err(_) => break,
            }
        }

        Ok(total_bytes)
    });

    // Give the listener time to start
    thread::sleep(Duration::from_millis(50));

    // Connect and send data
    let connect_start = Instant::now();
    let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port))
        .map_err(|e| IronError::Other(e.to_string()))?;
    let connect_time_ms = connect_start.elapsed().as_secs_f64() * 1000.0;
    stream.set_nodelay(true).ok();

    let buffer = vec![0xABu8; buffer_size];
    let mut total_sent: u64 = 0;
    let start = Instant::now();

    while start.elapsed() < test_duration {
        match stream.write(&buffer) {
            Ok(n) => total_sent += n as u64,
            Err(_) => break,
        }
    }

    drop(stream);

    // A receiver that failed or panicked is an error. `unwrap_or(0)` made it a
    // measured zero with no error attached.
    let (total_received, receive_error) = match receiver.join() {
        Ok(Ok(n)) => (Some(n), None),
        Ok(Err(e)) => (None, Some(format!("loopback receiver failed: {e}"))),
        Err(_) => (None, Some("loopback receiver thread panicked".to_string())),
    };
    let duration_secs = start.elapsed().as_secs_f64();

    // Use the minimum of sent/received for conservative estimate. With no
    // receiver count there is nothing to take the minimum of, so no bytes
    // are reported.
    let bytes_transferred = total_received.map(|received| total_sent.min(received));
    let counted = bytes_transferred.filter(|_| receive_error.is_none() && duration_secs > 0.0);
    let bandwidth_bps = counted.map(|b| (b * 8) as f64 / duration_secs);
    let bandwidth_mbytes = counted.map(|b| b as f64 / duration_secs / 1_000_000.0);
    let success = bytes_transferred.is_some_and(|b| b > 0) && receive_error.is_none();

    Ok(BandwidthResult {
        host: "127.0.0.1".to_string(),
        port,
        upload: true,
        duration_secs: Some(duration_secs),
        bytes_transferred,
        bandwidth_bps,
        bandwidth_mbps: bandwidth_bps.map(|bps| bps / 1_000_000.0),
        bandwidth_mbytes_per_sec: bandwidth_mbytes,
        transfer_count: bytes_transferred.map_or(0, |b| b / buffer_size as u64),
        connect_time_ms: Some(connect_time_ms),
        success,
        error: receive_error,
    })
}

/// Measure memory bandwidth (simple test)
///
/// This performs a basic memory copy test to estimate memory bandwidth.
pub fn memory_bandwidth_test(duration: Duration) -> MemoryBandwidthResult {
    let buffer_size = 64 * 1024 * 1024; // 64 MB
    let src = vec![0xABu8; buffer_size];
    let mut dst = vec![0u8; buffer_size];

    let start = Instant::now();
    let mut iterations = 0u64;
    let mut checksum = 0u8;

    while start.elapsed() < duration {
        dst.copy_from_slice(&src);
        // Prevent optimization by using the result
        checksum = checksum.wrapping_add(dst[iterations as usize % buffer_size]);
        iterations += 1;
    }

    // Use checksum to prevent it being optimized away
    let _ = std::hint::black_box(checksum);

    let duration_secs = start.elapsed().as_secs_f64();
    let total_bytes = iterations * buffer_size as u64 * 2; // Read + Write
                                                           // A zero duration, or a run that never completed an iteration, means the timer
                                                           // did not resolve the run, which is not a measured rate. This used to report
                                                           // `0.0` GB/s in that case, indistinguishable from a real stall, so the rate is
                                                           // `None` instead.
    let bandwidth_gbps = (duration_secs > 0.0 && iterations > 0)
        .then(|| (total_bytes as f64 / duration_secs) / 1_000_000_000.0);

    MemoryBandwidthResult {
        duration_secs,
        total_bytes_copied: total_bytes,
        iterations,
        bandwidth_gbytes_per_sec: bandwidth_gbps,
    }
}

/// Memory bandwidth test result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryBandwidthResult {
    /// Test duration in seconds
    pub duration_secs: f64,
    /// Total bytes copied (read + write)
    pub total_bytes_copied: u64,
    /// Number of iterations
    pub iterations: u64,
    /// Bandwidth in GB/s. `None` when the run took no measurable time; this was
    /// `0.0`, which reads as a measured stall.
    pub bandwidth_gbytes_per_sec: Option<f64>,
}

/// Quick bandwidth check to common public servers
///
/// Returns estimated download bandwidth in Mbps
pub fn quick_bandwidth_estimate() -> Option<f64> {
    // Try to connect to well-known servers and measure throughput
    let servers = [
        ("8.8.8.8", 53),        // Google DNS
        ("1.1.1.1", 53),        // Cloudflare DNS
        ("208.67.222.222", 53), // OpenDNS
    ];

    let config = BandwidthConfig::default().with_duration(Duration::from_secs(2));

    for (host, port) in &servers {
        if let Ok(result) = bandwidth_test(host, *port, &config) {
            if let Some(mbps) = result.bandwidth_mbps.filter(|m| result.success && *m > 0.0) {
                return Some(mbps);
            }
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_loopback() {
        let result = loopback_test(Duration::from_secs(1));
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.bandwidth_mbps.is_some_and(|m| m > 0.0));
        println!("Loopback bandwidth: {:?} Mbps", result.bandwidth_mbps);
    }

    #[test]
    fn test_memory_bandwidth() {
        let result = memory_bandwidth_test(Duration::from_secs(1));
        assert!(result.bandwidth_gbytes_per_sec.is_some_and(|g| g > 0.0));
        println!(
            "Memory bandwidth: {:?} GB/s",
            result.bandwidth_gbytes_per_sec
        );
    }

    #[test]
    fn zero_duration_memory_run_reports_no_rate() {
        // A zero-length run is a timer that did not resolve the run, not a stall.
        let result = memory_bandwidth_test(Duration::ZERO);
        assert_eq!(result.bandwidth_gbytes_per_sec, None);
    }
}