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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Docker stats command implementation.
//!
//! This module provides the `docker stats` command for displaying real-time
//! resource usage statistics of containers.
use super::{CommandExecutor, CommandOutput, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
/// Docker stats command builder
///
/// Display a live stream of container(s) resource usage statistics.
///
/// # Example
///
/// ```no_run
/// use docker_wrapper::StatsCommand;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Get stats for all running containers
/// let stats = StatsCommand::new()
/// .run()
/// .await?;
///
/// // Get stats for specific containers
/// let stats = StatsCommand::new()
/// .container("my-container")
/// .container("another-container")
/// .no_stream()
/// .run()
/// .await?;
///
/// // Parse as JSON for programmatic use
/// let json_stats = StatsCommand::new()
/// .format("json")
/// .no_stream()
/// .run()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct StatsCommand {
/// Container names or IDs to monitor (empty = all running containers)
containers: Vec<String>,
/// Show all containers (default shows only running)
all: bool,
/// Pretty print images (default true)
format: Option<String>,
/// Disable streaming stats and only pull the first result
no_stream: bool,
/// Only display numeric IDs
no_trunc: bool,
/// Command executor
pub executor: CommandExecutor,
}
impl StatsCommand {
/// Create a new stats command
///
/// # Example
///
/// ```
/// use docker_wrapper::StatsCommand;
///
/// let cmd = StatsCommand::new();
/// ```
#[must_use]
pub fn new() -> Self {
Self {
containers: Vec::new(),
all: false,
format: None,
no_stream: false,
no_trunc: false,
executor: CommandExecutor::new(),
}
}
/// Add a container to monitor
///
/// # Example
///
/// ```
/// use docker_wrapper::StatsCommand;
///
/// let cmd = StatsCommand::new()
/// .container("web-server")
/// .container("database");
/// ```
#[must_use]
pub fn container(mut self, container: impl Into<String>) -> Self {
self.containers.push(container.into());
self
}
/// Add multiple containers to monitor
#[must_use]
pub fn containers(mut self, containers: Vec<impl Into<String>>) -> Self {
self.containers
.extend(containers.into_iter().map(Into::into));
self
}
/// Show stats for all containers (default shows only running)
///
/// # Example
///
/// ```
/// use docker_wrapper::StatsCommand;
///
/// let cmd = StatsCommand::new().all();
/// ```
#[must_use]
pub fn all(mut self) -> Self {
self.all = true;
self
}
/// Set output format
///
/// # Example
///
/// ```
/// use docker_wrapper::StatsCommand;
///
/// // JSON format for programmatic parsing
/// let cmd = StatsCommand::new().format("json");
///
/// // Table format (default)
/// let cmd = StatsCommand::new().format("table");
/// ```
#[must_use]
pub fn format(mut self, format: impl Into<String>) -> Self {
self.format = Some(format.into());
self
}
/// Disable streaming stats and only pull the first result
///
/// # Example
///
/// ```
/// use docker_wrapper::StatsCommand;
///
/// let cmd = StatsCommand::new().no_stream();
/// ```
#[must_use]
pub fn no_stream(mut self) -> Self {
self.no_stream = true;
self
}
/// Do not truncate output (show full container IDs)
#[must_use]
pub fn no_trunc(mut self) -> Self {
self.no_trunc = true;
self
}
/// Execute the stats command
///
/// # Errors
/// Returns an error if:
/// - The Docker daemon is not running
/// - Any specified container doesn't exist
/// - No containers are running (when no specific containers are specified)
///
/// # Example
///
/// ```no_run
/// use docker_wrapper::StatsCommand;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let result = StatsCommand::new()
/// .container("my-container")
/// .no_stream()
/// .run()
/// .await?;
///
/// if result.success() {
/// println!("Container stats:\n{}", result.output.stdout);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn run(&self) -> Result<StatsResult> {
let output = self.execute().await?;
// Parse stats if JSON format was used
let parsed_stats = if self.format.as_deref() == Some("json") {
Self::parse_json_stats(&output.stdout)
} else {
Vec::new()
};
Ok(StatsResult {
output,
containers: self.containers.clone(),
parsed_stats,
})
}
/// Parse JSON stats output into structured data
fn parse_json_stats(stdout: &str) -> Vec<ContainerStats> {
let mut stats = Vec::new();
// Docker stats JSON output can be either a single object or multiple lines of JSON
for line in stdout.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
if let Ok(stat) = serde_json::from_str::<ContainerStats>(line) {
stats.push(stat);
}
}
stats
}
}
impl Default for StatsCommand {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl DockerCommand for StatsCommand {
type Output = CommandOutput;
fn get_executor(&self) -> &CommandExecutor {
&self.executor
}
fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.executor
}
fn build_command_args(&self) -> Vec<String> {
let mut args = vec!["stats".to_string()];
if self.all {
args.push("--all".to_string());
}
if let Some(ref format) = self.format {
args.push("--format".to_string());
args.push(format.clone());
}
if self.no_stream {
args.push("--no-stream".to_string());
}
if self.no_trunc {
args.push("--no-trunc".to_string());
}
// Add container names/IDs
args.extend(self.containers.clone());
// Add raw arguments from executor
args.extend(self.executor.raw_args.clone());
args
}
async fn execute(&self) -> Result<Self::Output> {
let args = self.build_command_args();
self.execute_command(args).await
}
}
/// Result from the stats command
#[derive(Debug, Clone)]
pub struct StatsResult {
/// Raw command output
pub output: CommandOutput,
/// Containers that were monitored
pub containers: Vec<String>,
/// Parsed stats (when JSON format is used)
pub parsed_stats: Vec<ContainerStats>,
}
impl StatsResult {
/// Check if the stats command was successful
#[must_use]
pub fn success(&self) -> bool {
self.output.success
}
/// Get the monitored container names
#[must_use]
pub fn containers(&self) -> &[String] {
&self.containers
}
/// Get parsed stats (available when JSON format is used)
#[must_use]
pub fn parsed_stats(&self) -> &[ContainerStats] {
&self.parsed_stats
}
/// Get the raw stats output
#[must_use]
pub fn raw_output(&self) -> &str {
&self.output.stdout
}
}
/// Container resource usage statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContainerStats {
/// Container ID
#[serde(alias = "Container")]
pub container_id: String,
/// Container name
#[serde(alias = "Name")]
pub name: String,
/// CPU usage percentage
#[serde(alias = "CPUPerc")]
pub cpu_percent: String,
/// Memory usage
#[serde(alias = "MemUsage")]
pub memory_usage: String,
/// Memory usage percentage
#[serde(alias = "MemPerc")]
pub memory_percent: String,
/// Network I/O
#[serde(alias = "NetIO")]
pub network_io: String,
/// Block I/O
#[serde(alias = "BlockIO")]
pub block_io: String,
/// Number of process IDs (PIDs)
#[serde(alias = "PIDs")]
pub pids: String,
}
impl ContainerStats {
/// Get CPU percentage as a float (removes % sign)
#[must_use]
pub fn cpu_percentage(&self) -> Option<f64> {
self.cpu_percent.trim_end_matches('%').parse().ok()
}
/// Get memory percentage as a float (removes % sign)
#[must_use]
pub fn memory_percentage(&self) -> Option<f64> {
self.memory_percent.trim_end_matches('%').parse().ok()
}
/// Get number of PIDs as integer
#[must_use]
pub fn pid_count(&self) -> Option<u32> {
self.pids.parse().ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stats_basic() {
let cmd = StatsCommand::new();
let args = cmd.build_command_args();
assert_eq!(args, vec!["stats"]);
}
#[test]
fn test_stats_with_containers() {
let cmd = StatsCommand::new().container("web").container("db");
let args = cmd.build_command_args();
assert_eq!(args, vec!["stats", "web", "db"]);
}
#[test]
fn test_stats_with_all_flag() {
let cmd = StatsCommand::new().all();
let args = cmd.build_command_args();
assert_eq!(args, vec!["stats", "--all"]);
}
#[test]
fn test_stats_with_format() {
let cmd = StatsCommand::new().format("json");
let args = cmd.build_command_args();
assert_eq!(args, vec!["stats", "--format", "json"]);
}
#[test]
fn test_stats_no_stream() {
let cmd = StatsCommand::new().no_stream();
let args = cmd.build_command_args();
assert_eq!(args, vec!["stats", "--no-stream"]);
}
#[test]
fn test_stats_no_trunc() {
let cmd = StatsCommand::new().no_trunc();
let args = cmd.build_command_args();
assert_eq!(args, vec!["stats", "--no-trunc"]);
}
#[test]
fn test_stats_all_options() {
let cmd = StatsCommand::new()
.all()
.format("table")
.no_stream()
.no_trunc()
.container("test-container");
let args = cmd.build_command_args();
assert_eq!(
args,
vec![
"stats",
"--all",
"--format",
"table",
"--no-stream",
"--no-trunc",
"test-container"
]
);
}
#[test]
fn test_container_stats_parsing() {
let stats = ContainerStats {
container_id: "abc123".to_string(),
name: "test-container".to_string(),
cpu_percent: "1.23%".to_string(),
memory_usage: "512MiB / 2GiB".to_string(),
memory_percent: "25.00%".to_string(),
network_io: "1.2kB / 3.4kB".to_string(),
block_io: "4.5MB / 6.7MB".to_string(),
pids: "42".to_string(),
};
assert_eq!(stats.cpu_percentage(), Some(1.23));
assert_eq!(stats.memory_percentage(), Some(25.0));
assert_eq!(stats.pid_count(), Some(42));
}
#[test]
fn test_parse_json_stats() {
let json_output = r#"{"Container":"abc123","Name":"test","CPUPerc":"1.23%","MemUsage":"512MiB / 2GiB","MemPerc":"25.00%","NetIO":"1.2kB / 3.4kB","BlockIO":"4.5MB / 6.7MB","PIDs":"42"}"#;
let stats = StatsCommand::parse_json_stats(json_output);
assert_eq!(stats.len(), 1);
assert_eq!(stats[0].name, "test");
assert_eq!(stats[0].container_id, "abc123");
}
#[test]
fn test_parse_json_stats_multiple_lines() {
let json_output = r#"{"Container":"abc123","Name":"test1","CPUPerc":"1.23%","MemUsage":"512MiB / 2GiB","MemPerc":"25.00%","NetIO":"1.2kB / 3.4kB","BlockIO":"4.5MB / 6.7MB","PIDs":"42"}
{"Container":"def456","Name":"test2","CPUPerc":"2.34%","MemUsage":"1GiB / 4GiB","MemPerc":"25.00%","NetIO":"2.3kB / 4.5kB","BlockIO":"5.6MB / 7.8MB","PIDs":"24"}"#;
let stats = StatsCommand::parse_json_stats(json_output);
assert_eq!(stats.len(), 2);
assert_eq!(stats[0].name, "test1");
assert_eq!(stats[1].name, "test2");
}
#[test]
fn test_parse_json_stats_empty() {
let stats = StatsCommand::parse_json_stats("");
assert!(stats.is_empty());
}
}