docker_wrapper/
lib.rs

1//! # docker-wrapper
2//!
3//! A type-safe Docker CLI wrapper for Rust.
4//!
5//! This crate provides an idiomatic Rust interface to the Docker command-line tool.
6//! All commands use a builder pattern and async execution via Tokio.
7//!
8//! # Quick Start
9//!
10//! ```rust,no_run
11//! use docker_wrapper::{DockerCommand, RunCommand, StopCommand, RmCommand};
12//!
13//! #[tokio::main]
14//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
15//!     // Run a container
16//!     let container = RunCommand::new("nginx:alpine")
17//!         .name("my-nginx")
18//!         .port(8080, 80)
19//!         .detach()
20//!         .execute()
21//!         .await?;
22//!
23//!     println!("Started: {}", container.short());
24//!
25//!     // Stop and remove
26//!     StopCommand::new("my-nginx").execute().await?;
27//!     RmCommand::new("my-nginx").execute().await?;
28//!
29//!     Ok(())
30//! }
31//! ```
32//!
33//! # Core Concepts
34//!
35//! ## The `DockerCommand` Trait
36//!
37//! All commands implement [`DockerCommand`], which provides the [`execute()`](DockerCommand::execute)
38//! method. You must import this trait to call `.execute()`:
39//!
40//! ```rust
41//! use docker_wrapper::DockerCommand; // Required for .execute()
42//! ```
43//!
44//! ## Builder Pattern
45//!
46//! Commands are configured using method chaining:
47//!
48//! ```rust,no_run
49//! # use docker_wrapper::{DockerCommand, RunCommand};
50//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
51//! RunCommand::new("alpine")
52//!     .name("my-container")
53//!     .env("DATABASE_URL", "postgres://localhost/db")
54//!     .volume("/data", "/app/data")
55//!     .port(3000, 3000)
56//!     .memory("512m")
57//!     .cpus("0.5")
58//!     .detach()
59//!     .rm()  // Auto-remove when stopped
60//!     .execute()
61//!     .await?;
62//! # Ok(())
63//! # }
64//! ```
65//!
66//! ## Error Handling
67//!
68//! All commands return `Result<T, docker_wrapper::Error>`:
69//!
70//! ```rust,no_run
71//! # use docker_wrapper::{DockerCommand, RunCommand, Error};
72//! # async fn example() {
73//! match RunCommand::new("nginx").detach().execute().await {
74//!     Ok(id) => println!("Started: {}", id.short()),
75//!     Err(Error::CommandFailed { stderr, .. }) => {
76//!         eprintln!("Docker error: {}", stderr);
77//!     }
78//!     Err(e) => eprintln!("Error: {}", e),
79//! }
80//! # }
81//! ```
82//!
83//! # Command Categories
84//!
85//! ## Container Lifecycle
86//!
87//! ```rust,no_run
88//! use docker_wrapper::{
89//!     DockerCommand,
90//!     RunCommand,      // docker run
91//!     CreateCommand,   // docker create
92//!     StartCommand,    // docker start
93//!     StopCommand,     // docker stop
94//!     RestartCommand,  // docker restart
95//!     KillCommand,     // docker kill
96//!     RmCommand,       // docker rm
97//!     PauseCommand,    // docker pause
98//!     UnpauseCommand,  // docker unpause
99//! };
100//! ```
101//!
102//! ## Container Inspection
103//!
104//! ```rust,no_run
105//! use docker_wrapper::{
106//!     DockerCommand,
107//!     PsCommand,       // docker ps
108//!     LogsCommand,     // docker logs
109//!     InspectCommand,  // docker inspect
110//!     TopCommand,      // docker top
111//!     StatsCommand,    // docker stats
112//!     PortCommand,     // docker port
113//!     DiffCommand,     // docker diff
114//! };
115//! ```
116//!
117//! ## Container Operations
118//!
119//! ```rust,no_run
120//! use docker_wrapper::{
121//!     DockerCommand,
122//!     ExecCommand,     // docker exec
123//!     AttachCommand,   // docker attach
124//!     CpCommand,       // docker cp
125//!     WaitCommand,     // docker wait
126//!     RenameCommand,   // docker rename
127//!     UpdateCommand,   // docker update
128//!     CommitCommand,   // docker commit
129//!     ExportCommand,   // docker export
130//! };
131//! ```
132//!
133//! ## Images
134//!
135//! ```rust,no_run
136//! use docker_wrapper::{
137//!     DockerCommand,
138//!     ImagesCommand,   // docker images
139//!     PullCommand,     // docker pull
140//!     PushCommand,     // docker push
141//!     BuildCommand,    // docker build
142//!     TagCommand,      // docker tag
143//!     RmiCommand,      // docker rmi
144//!     SaveCommand,     // docker save
145//!     LoadCommand,     // docker load
146//!     ImportCommand,   // docker import
147//!     HistoryCommand,  // docker history
148//!     SearchCommand,   // docker search
149//! };
150//! ```
151//!
152//! ## Networks and Volumes
153//!
154//! ```rust,no_run
155//! use docker_wrapper::{
156//!     DockerCommand,
157//!     NetworkCreateCommand, NetworkLsCommand, NetworkRmCommand,
158//!     VolumeCreateCommand, VolumeLsCommand, VolumeRmCommand,
159//! };
160//! ```
161//!
162//! ## System
163//!
164//! ```rust,no_run
165//! use docker_wrapper::{
166//!     DockerCommand,
167//!     VersionCommand,  // docker version
168//!     InfoCommand,     // docker info
169//!     EventsCommand,   // docker events
170//!     LoginCommand,    // docker login
171//!     LogoutCommand,   // docker logout
172//!     SystemDfCommand, // docker system df
173//!     SystemPruneCommand, // docker system prune
174//! };
175//! ```
176//!
177//! # Feature Flags
178//!
179//! ## `compose` - Docker Compose Support
180//!
181//! ```toml
182//! docker-wrapper = { version = "0.9", features = ["compose"] }
183//! ```
184//!
185//! ```rust,no_run
186//! # #[cfg(feature = "compose")]
187//! use docker_wrapper::{DockerCommand, compose::{ComposeUpCommand, ComposeDownCommand, ComposeCommand}};
188//!
189//! # #[cfg(feature = "compose")]
190//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
191//! // Start services
192//! ComposeUpCommand::new()
193//!     .file("docker-compose.yml")
194//!     .detach()
195//!     .execute()
196//!     .await?;
197//!
198//! // Stop and clean up
199//! ComposeDownCommand::new()
200//!     .volumes()
201//!     .execute()
202//!     .await?;
203//! # Ok(())
204//! # }
205//! ```
206//!
207//! ## `templates` - Pre-configured Containers
208//!
209//! ```toml
210//! docker-wrapper = { version = "0.9", features = ["templates"] }
211//! ```
212//!
213//! Templates provide ready-to-use configurations for common services:
214//!
215//! ```rust,no_run
216//! # #[cfg(feature = "template-redis")]
217//! use docker_wrapper::{RedisTemplate, Template};
218//!
219//! # #[cfg(feature = "template-redis")]
220//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
221//! let redis = RedisTemplate::new("my-redis")
222//!     .port(6379)
223//!     .password("secret")
224//!     .with_persistence("redis-data");
225//!
226//! let id = redis.start().await?;
227//! // ... use Redis ...
228//! redis.stop().await?;
229//! # Ok(())
230//! # }
231//! ```
232//!
233//! Available templates:
234//! - [`RedisTemplate`], [`RedisSentinelTemplate`], [`RedisClusterTemplate`]
235//! - [`PostgresTemplate`], [`MysqlTemplate`], [`MongodbTemplate`]
236//! - [`NginxTemplate`]
237//!
238//! ## `swarm` - Docker Swarm Commands
239//!
240//! ```toml
241//! docker-wrapper = { version = "0.9", features = ["swarm"] }
242//! ```
243//!
244//! ## `manifest` - Multi-arch Manifest Commands
245//!
246//! ```toml
247//! docker-wrapper = { version = "0.9", features = ["manifest"] }
248//! ```
249//!
250//! # Tracing and Debugging
251//!
252//! docker-wrapper integrates with the [`tracing`](https://docs.rs/tracing) ecosystem
253//! to provide comprehensive observability into Docker command execution.
254//!
255//! ## Enabling Tracing
256//!
257//! Add tracing dependencies to your project:
258//!
259//! ```toml
260//! [dependencies]
261//! tracing = "0.1"
262//! tracing-subscriber = { version = "0.3", features = ["env-filter"] }
263//! ```
264//!
265//! Initialize a subscriber in your application:
266//!
267//! ```rust,ignore
268//! use tracing_subscriber::EnvFilter;
269//!
270//! tracing_subscriber::fmt()
271//!     .with_env_filter(EnvFilter::from_default_env())
272//!     .init();
273//!
274//! // Your application code...
275//! ```
276//!
277//! ## Log Levels
278//!
279//! Control verbosity with the `RUST_LOG` environment variable:
280//!
281//! ```bash
282//! # Show all docker-wrapper traces
283//! RUST_LOG=docker_wrapper=trace cargo run
284//!
285//! # Show only command execution info
286//! RUST_LOG=docker_wrapper::command=debug cargo run
287//!
288//! # Show template lifecycle events
289//! RUST_LOG=docker_wrapper::template=debug cargo run
290//!
291//! # Show retry/debug executor activity
292//! RUST_LOG=docker_wrapper::debug=trace cargo run
293//! ```
294//!
295//! ## What Gets Traced
296//!
297//! The library instruments key operations at various levels:
298//!
299//! - **`trace`**: Command arguments, stdout/stderr output, retry delays
300//! - **`debug`**: Command start/completion, health check attempts, retry attempts
301//! - **`info`**: Container lifecycle events (start, stop, ready)
302//! - **`warn`**: Health check failures, retry exhaustion warnings
303//! - **`error`**: Command failures, timeout errors
304//!
305//! ## Instrumented Operations
306//!
307//! ### Command Execution
308//! All Docker commands are traced with:
309//! - Command name and runtime (docker/podman)
310//! - Timeout configuration
311//! - Exit status and duration
312//! - Stdout/stderr output (at trace level)
313//!
314//! ### Template Lifecycle
315//! Template operations include:
316//! - Container start with image and configuration
317//! - Health check polling with attempt counts
318//! - Ready state transitions
319//! - Stop and remove operations
320//!
321//! ### Retry Logic
322//! The debug executor traces:
323//! - Retry policy configuration
324//! - Individual retry attempts with delays
325//! - Backoff calculations
326//! - Final success or exhaustion
327//!
328//! ## Example Output
329//!
330//! With `RUST_LOG=docker_wrapper=debug`:
331//!
332//! ```text
333//! DEBUG docker.command{command="run" runtime="docker"}: starting command
334//! DEBUG docker.command{command="run"}: command completed exit_code=0
335//! INFO  template.start{name="my-redis" image="redis:7-alpine"}: container started
336//! DEBUG template.wait{name="my-redis"}: health check attempt=1 elapsed_ms=50
337//! INFO  template.wait{name="my-redis"}: container ready after 1 attempts
338//! ```
339//!
340//! # Streaming Output
341//!
342//! For long-running commands, stream output in real-time:
343//!
344//! ```rust,no_run
345//! use docker_wrapper::{BuildCommand, StreamHandler, StreamableCommand};
346//!
347//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
348//! let result = BuildCommand::new(".")
349//!     .tag("my-app:latest")
350//!     .stream(StreamHandler::print())
351//!     .await?;
352//!
353//! if result.is_success() {
354//!     println!("Build complete!");
355//! }
356//! # Ok(())
357//! # }
358//! ```
359//!
360//! # Checking Docker Availability
361//!
362//! ```rust,no_run
363//! use docker_wrapper::ensure_docker;
364//!
365//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
366//! let info = ensure_docker().await?;
367//! println!("Docker {}.{}.{}", info.version.major, info.version.minor, info.version.patch);
368//! # Ok(())
369//! # }
370//! ```
371//!
372//! # Why docker-wrapper?
373//!
374//! This crate wraps the Docker CLI rather than calling the Docker API directly
375//! (like [bollard](https://crates.io/crates/bollard)).
376//!
377//! **docker-wrapper advantages:**
378//! - Just needs `docker` in PATH (no socket access required)
379//! - Native `docker compose` support
380//! - Works with Docker, Podman, Colima, and other Docker-compatible CLIs
381//! - Familiar mental model if you know Docker CLI
382//!
383//! **bollard advantages:**
384//! - Direct API calls (no process spawn overhead)
385//! - Lower latency for high-frequency operations
386//! - No external binary dependency
387//!
388//! **Choose docker-wrapper** for CLI tools, dev tooling, Compose workflows, or
389//! when working with Docker alternatives.
390//!
391//! **Choose bollard** for high-performance services with many Docker operations.
392
393#![warn(missing_docs)]
394#![warn(clippy::all)]
395#![warn(clippy::pedantic)]
396
397pub mod command;
398#[cfg(feature = "compose")]
399pub mod compose;
400pub mod debug;
401pub mod error;
402pub mod platform;
403pub mod prerequisites;
404pub mod stream;
405#[cfg(any(
406    feature = "templates",
407    feature = "template-redis",
408    feature = "template-redis-cluster",
409    feature = "template-redis-enterprise",
410    feature = "template-postgres",
411    feature = "template-mysql",
412    feature = "template-mongodb",
413    feature = "template-nginx"
414))]
415/// Container templates module
416///
417/// Provides pre-configured container templates with sensible defaults for common services.
418/// Templates support custom images, platforms, persistence, and resource configuration.
419///
420/// See the [Template Guide](https://github.com/joshrotenberg/docker-wrapper/blob/main/docs/TEMPLATES.md) for comprehensive documentation.
421///
422/// # Available Templates
423///
424/// ## Redis Templates
425/// - [`RedisTemplate`] - Basic Redis server
426/// - [`RedisSentinelTemplate`] - High-availability Redis with Sentinel
427/// - [`RedisClusterTemplate`] - Sharded Redis cluster
428/// - [`RedisEnterpriseTemplate`] - Redis Enterprise with management
429/// - [`RedisInsightTemplate`] - Redis management UI
430///
431/// ## Database Templates
432/// - [`PostgresTemplate`] - PostgreSQL database
433/// - [`MysqlTemplate`] - MySQL database
434/// - [`MongodbTemplate`] - MongoDB document database
435///
436/// ## Web Server Templates
437/// - [`NginxTemplate`] - Nginx web server
438///
439/// # Quick Start
440///
441/// ```rust,no_run
442/// use docker_wrapper::{RedisTemplate, Template};
443///
444/// # #[tokio::main]
445/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
446/// let redis = RedisTemplate::new("my-redis")
447///     .port(6379)
448///     .password("secret")
449///     .with_persistence("redis-data");
450///
451/// let container_id = redis.start().await?;
452/// println!("Redis started: {}", container_id);
453/// # Ok(())
454/// # }
455/// ```
456#[cfg(any(
457    feature = "templates",
458    feature = "template-redis",
459    feature = "template-redis-cluster",
460    feature = "template-redis-enterprise",
461    feature = "template-postgres",
462    feature = "template-mysql",
463    feature = "template-mongodb",
464    feature = "template-nginx"
465))]
466pub mod template;
467
468pub use stream::{OutputLine, StreamHandler, StreamResult, StreamableCommand};
469
470pub use command::{
471    attach::{AttachCommand, AttachResult},
472    bake::BakeCommand,
473    build::{BuildCommand, BuildOutput},
474    builder::{
475        BuilderBuildCommand, BuilderInfo, BuilderPruneCommand, BuilderPruneResult,
476        BuildxCreateCommand, BuildxCreateResult, BuildxInspectCommand, BuildxInspectResult,
477        BuildxLsCommand, BuildxLsResult, BuildxRmCommand, BuildxRmResult, BuildxStopCommand,
478        BuildxStopResult, BuildxUseCommand, BuildxUseResult,
479    },
480    commit::{CommitCommand, CommitResult},
481    container_prune::{ContainerPruneCommand, ContainerPruneResult},
482    context::{
483        ContextCreateCommand, ContextInfo, ContextInspectCommand, ContextLsCommand,
484        ContextRmCommand, ContextUpdateCommand, ContextUseCommand,
485    },
486    cp::{CpCommand, CpResult},
487    create::{CreateCommand, CreateResult},
488    diff::{DiffCommand, DiffResult, FilesystemChange, FilesystemChangeType},
489    events::{DockerEvent, EventActor, EventsCommand, EventsResult},
490    exec::{ExecCommand, ExecOutput},
491    export::{ExportCommand, ExportResult},
492    generic::GenericCommand,
493    history::{HistoryCommand, HistoryResult, ImageLayer},
494    image_prune::{DeletedImage, ImagePruneCommand, ImagePruneResult},
495    images::{ImageInfo, ImagesCommand, ImagesOutput},
496    import::{ImportCommand, ImportResult},
497    info::{DockerInfo as SystemDockerInfo, InfoCommand, InfoOutput, SystemInfo},
498    init::{InitCommand, InitOutput, InitTemplate},
499    inspect::{InspectCommand, InspectOutput},
500    kill::{KillCommand, KillResult},
501    load::{LoadCommand, LoadResult},
502    login::{LoginCommand, LoginOutput},
503    logout::{LogoutCommand, LogoutOutput},
504    logs::LogsCommand,
505    network::{
506        NetworkConnectCommand, NetworkConnectResult, NetworkCreateCommand, NetworkCreateResult,
507        NetworkDisconnectCommand, NetworkDisconnectResult, NetworkInfo, NetworkInspectCommand,
508        NetworkInspectOutput, NetworkLsCommand, NetworkLsOutput, NetworkPruneCommand,
509        NetworkPruneResult, NetworkRmCommand, NetworkRmResult,
510    },
511    pause::{PauseCommand, PauseResult},
512    port::{PortCommand, PortMapping as PortMappingInfo, PortResult},
513    ps::{ContainerInfo, PsCommand, PsFormat, PsOutput},
514    pull::PullCommand,
515    push::PushCommand,
516    rename::{RenameCommand, RenameResult},
517    restart::{RestartCommand, RestartResult},
518    rm::{RmCommand, RmResult},
519    rmi::{RmiCommand, RmiResult},
520    run::{ContainerId, MountType, RunCommand, VolumeMount},
521    save::{SaveCommand, SaveResult},
522    search::{RepositoryInfo, SearchCommand, SearchOutput},
523    start::{StartCommand, StartResult},
524    stats::{ContainerStats, StatsCommand, StatsResult},
525    stop::{StopCommand, StopResult},
526    system::{
527        BuildCacheInfo, BuildCacheUsage, ContainerInfo as SystemContainerInfo, ContainerUsage,
528        DiskUsage, ImageInfo as SystemImageInfo, ImageUsage, PruneResult, SystemDfCommand,
529        SystemPruneCommand, VolumeInfo as SystemVolumeInfo, VolumeUsage,
530    },
531    tag::{TagCommand, TagResult},
532    top::{ContainerProcess, TopCommand, TopResult},
533    unpause::{UnpauseCommand, UnpauseResult},
534    update::{UpdateCommand, UpdateResult},
535    version::{ClientVersion, ServerVersion, VersionCommand, VersionInfo, VersionOutput},
536    volume::{
537        VolumeCreateCommand, VolumeCreateResult, VolumeInfo, VolumeInspectCommand,
538        VolumeInspectOutput, VolumeLsCommand, VolumeLsOutput, VolumePruneCommand,
539        VolumePruneResult, VolumeRmCommand, VolumeRmResult,
540    },
541    wait::{WaitCommand, WaitResult},
542    CommandExecutor, CommandOutput, DockerCommand, EnvironmentBuilder, PortBuilder, PortMapping,
543    Protocol, DEFAULT_COMMAND_TIMEOUT,
544};
545pub use debug::{BackoffStrategy, DebugConfig, DebugExecutor, DryRunPreview, RetryPolicy};
546pub use error::{Error, Result};
547pub use platform::{Platform, PlatformInfo, Runtime};
548
549// Swarm commands (feature-gated)
550#[cfg(feature = "swarm")]
551pub use command::swarm::{
552    SwarmCaCommand, SwarmCaResult, SwarmInitCommand, SwarmInitResult, SwarmJoinCommand,
553    SwarmJoinResult, SwarmJoinTokenCommand, SwarmJoinTokenResult, SwarmLeaveCommand,
554    SwarmLeaveResult, SwarmNodeRole, SwarmUnlockCommand, SwarmUnlockKeyCommand,
555    SwarmUnlockKeyResult, SwarmUnlockResult, SwarmUpdateCommand, SwarmUpdateResult,
556};
557
558// Manifest commands (feature-gated)
559#[cfg(feature = "manifest")]
560pub use command::manifest::{
561    ManifestAnnotateCommand, ManifestAnnotateResult, ManifestCreateCommand, ManifestCreateResult,
562    ManifestInfo, ManifestInspectCommand, ManifestPlatform, ManifestPushCommand,
563    ManifestPushResult, ManifestRmCommand, ManifestRmResult,
564};
565
566pub use prerequisites::{
567    ensure_docker, ensure_docker_with_timeout, DockerInfo, DockerPrerequisites,
568    DEFAULT_PREREQ_TIMEOUT,
569};
570
571#[cfg(any(
572    feature = "templates",
573    feature = "template-redis",
574    feature = "template-redis-cluster",
575    feature = "template-redis-enterprise",
576    feature = "template-postgres",
577    feature = "template-mysql",
578    feature = "template-mongodb",
579    feature = "template-nginx"
580))]
581pub use template::{Template, TemplateBuilder, TemplateConfig, TemplateError};
582
583// Redis templates
584#[cfg(feature = "template-redis")]
585pub use template::redis::{RedisInsightTemplate, RedisTemplate};
586
587#[cfg(feature = "template-redis")]
588pub use template::redis::{RedisSentinelTemplate, SentinelConnectionInfo, SentinelInfo};
589
590#[cfg(feature = "template-redis-cluster")]
591pub use template::redis::{
592    ClusterInfo, NodeInfo, NodeRole, RedisClusterConnection, RedisClusterTemplate,
593};
594
595#[cfg(feature = "template-redis-enterprise")]
596pub use template::redis::{RedisEnterpriseConnectionInfo, RedisEnterpriseTemplate};
597
598// Database templates
599#[cfg(feature = "template-postgres")]
600pub use template::database::{PostgresConnectionString, PostgresTemplate};
601
602#[cfg(feature = "template-mysql")]
603pub use template::database::{MysqlConnectionString, MysqlTemplate};
604
605#[cfg(feature = "template-mongodb")]
606pub use template::database::{MongodbConnectionString, MongodbTemplate};
607
608// Web server templates
609#[cfg(feature = "template-nginx")]
610pub use template::web::NginxTemplate;
611
612/// The version of this crate
613pub const VERSION: &str = env!("CARGO_PKG_VERSION");
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618
619    #[test]
620    fn test_version() {
621        // Verify version follows semver format (major.minor.patch)
622        let parts: Vec<&str> = VERSION.split('.').collect();
623        assert!(parts.len() >= 3, "Version should have at least 3 parts");
624
625        // Verify each part is numeric
626        for part in &parts[0..3] {
627            assert!(
628                part.chars().all(|c| c.is_ascii_digit()),
629                "Version parts should be numeric"
630            );
631        }
632    }
633}