camel-component-container 0.8.2

Docker/Container component for rust-camel — run, manage and listen to container events via the Camel routing engine
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# camel-component-container

> Docker container component for [rust-camel]https://github.com/kennycallado/rust-camel

## Overview

The Container component provides Docker container lifecycle management for rust-camel routes. It supports **producer** operations (list, run, start, stop, remove, exec, network management) and **consumer** mode (subscribe to Docker events).

## Features

- **Batteries Included**: Auto-pull images, auto-remove containers, sensible defaults
- **Container Lifecycle**: Create, start, stop, and remove containers
- **Volume Mounts**: Bind-mount host paths into containers
- **Command Exec**: Execute commands inside running containers
- **Network Management**: Create, connect, disconnect, list, and remove Docker networks
- **Event Streaming**: Subscribe to Docker daemon events (formatted for readability)
- **Container Tracking**: Track created containers for cleanup on shutdown (hot-reload safe)
- **Header-based Control**: Override operations and parameters via exchange headers
- **Automatic Cleanup**: Orphaned containers are removed if start fails after create
- **Reconnection**: Consumer automatically reconnects on connection failures
- **Graceful Shutdown**: Clean cancellation via `CancellationToken`

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
camel-component-container = "*"
```

## URI Format

```
container:<operation>[?options]
```

## Operations

| Operation            | Mode     | Description                                |
| -------------------- | -------- | ------------------------------------------ |
| `list`               | Producer | List all containers                        |
| `run`                | Producer | Create and start a container from an image |
| `start`              | Producer | Start an existing container                |
| `stop`               | Producer | Stop a running container                   |
| `remove`             | Producer | Remove a container                         |
| `exec`               | Producer | Execute a command inside a running container |
| `network-create`     | Producer | Create a Docker network                    |
| `network-connect`    | Producer | Connect a container to a network           |
| `network-disconnect` | Producer | Disconnect a container from a network      |
| `network-remove`     | Producer | Remove a Docker network                    |
| `network-list`       | Producer | List Docker networks                       |
| `events`             | Consumer | Subscribe to Docker daemon events          |
| `logs`               | Consumer | Stream logs from a container               |

## URI Options

| Option        | Default                       | Description                                                                                                   |
| ------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `image`       | -                             | Container image for `run` operation                                                                           |
| `name`        | -                             | Container name for `run` operation                                                                            |
| `cmd`         | -                             | Command to run in container (e.g., `sleep 30`)                                                                |
| `ports`       | -                             | Port mappings in format `hostPort:containerPort` (e.g., `8080:80,8443:443`)                                   |
| `env`         | -                             | Environment variables in format `KEY=value` (e.g., `FOO=bar,BAZ=qux`)                                         |
| `network`     | -                             | Network mode (`bridge`, `host`, `none`, or custom network name). When unset, Docker uses `bridge` by default. |
| `volumes`     | -                             | Volume mounts in format `source:target[:ro\|rw]` separated by `,`                                             |
| `user`        | -                             | User for exec operation                                                                                       |
| `workdir`     | -                             | Working directory for exec operation                                                                          |
| `detach`      | `false`                       | Run exec in background                                                                                        |
| `driver`      | `bridge`                      | Network driver for `network-create`                                                                           |
| `force`       | `false`                       | Force network-disconnect                                                                                      |
| `containerId` | -                             | Container ID or name for `logs` consumer                                                                      |
| `follow`      | `true`                        | Follow log output (logs consumer only)                                                                        |
| `timestamps`  | `false`                       | Include timestamps in logs (logs consumer only)                                                               |
| `tail`        | `all`                         | Number of lines to show from end of logs (e.g., `100`)                                                        |
| `autoPull`    | `true`                        | Automatically pull image if not present locally                                                               |
| `autoRemove`  | `true`                        | Automatically remove container when it exits                                                                  |
| `host`        | `unix:///var/run/docker.sock` | Docker host (Unix socket only)                                                                                |

## Headers

### Input Headers (for operations)

| Header                   | Description                                                                       |
| ------------------------ | --------------------------------------------------------------------------------- |
| `CamelContainerAction`   | Override operation (`list`, `run`, `start`, `stop`, `remove`, `exec`, `network-create`, etc.) |
| `CamelContainerImage`    | Container image (required for `run`)                                              |
| `CamelContainerId`       | Container ID (required for `start`, `stop`, `remove`)                             |
| `CamelContainerName`     | Container name (optional for `run`)                                               |
| `CamelContainerCmd`      | Override exec command                                                             |
| `CamelContainerNetwork`  | Network name/ID (network operations)                                              |
| `CamelContainerVolumes`  | Override volume mounts (`run` operation)                                          |

### Output Headers (from responses)

| Header                       | Description                                                         |
| ---------------------------- | ------------------------------------------------------------------- |
| `CamelContainerActionResult` | Operation result (`success`)                                        |
| `CamelContainerId`           | Created container ID (from `run`), or container ID for logs         |
| `CamelContainerExecId`       | Exec instance ID (detached exec)                                    |
| `CamelContainerExitCode`     | Command exit code (`exec` operation)                                |
| `CamelContainerNetwork`      | Created network ID (`network-create`)                               |
| `CamelContainerLogStream`    | Log stream type: `stdout`, `stderr`, `console` (logs consumer only) |
| `CamelContainerLogTimestamp` | Log timestamp when `timestamps=true` (logs consumer only)           |

## Usage

### Simple Container Run (Batteries Included)

The simplest way to run a container - just specify the image:

```rust
use camel_builder::{RouteBuilder, StepAccumulator};
use camel_component_container::ContainerComponent;

let route = RouteBuilder::from("timer:tick?period=60000")
    .to("container:run?image=alpine:latest&cmd=sleep 30&autoRemove=true")
    .to("log:info?showHeaders=true")
    .build()?;
```

This will:

1. Pull `alpine:latest` if not present (`autoPull=true` by default)
2. Run `sleep 30` in the container
3. Auto-remove the container when it exits (`autoRemove=true`)

### Listing Containers

```rust
use camel_builder::{RouteBuilder, StepAccumulator};
use camel_component_container::ContainerComponent;

let route = RouteBuilder::from("timer:tick?period=60000")
    .to("container:list")
    .to("log:info?showBody=true")
    .build()?;
```

### Running a Container with Custom Name

```rust
let route = RouteBuilder::from("direct:run-container")
    .set_header("CamelContainerImage", Value::String("alpine:latest".into()))
    .set_header("CamelContainerName", Value::String("my-alpine".into()))
    .to("container:run")
    .to("log:info?showHeaders=true")
    .build()?;
```

### Running a Web Server with Port Mapping

```rust
// Run nginx with port 8080 on host → 80 in container
let route = RouteBuilder::from("timer:start?delay=5000&repeatCount=1")
    .to("container:run?image=nginx:latest&ports=8080:80&autoRemove=false")
    .to("log:info?message=Web server running at http://localhost:8080")
    .build()?;
```

> **Note**: If port mapping doesn't work on your system (firewall issues), use `network=host` instead. The container will share the host's network stack and ports don't need mapping:
>
> ```rust
> .to("container:run?image=nginx:latest&network=host&autoRemove=false")
> // nginx will be accessible at http://localhost:80
> ```

### Running a Container with Environment Variables

```rust
// Run a container with custom environment variables
let route = RouteBuilder::from("timer:start?delay=5000&repeatCount=1")
    .to("container:run?image=postgres:15&env=POSTGRES_PASSWORD=secret,POSTGRES_DB=mydb&ports=5432:5432")
    .to("log:info?message=Database running on localhost:5432")
    .build()?;
```

### Stopping and Removing a Container

```rust
let route = RouteBuilder::from("direct:cleanup")
    .set_header("CamelContainerId", Value::String("container-123".into()))
    .to("container:stop")
    .to("container:remove")
    .build()?;
```

### Subscribing to Docker Events

Events are formatted for readability:

```
[CREATE] Container my-container (alpine:latest)
[START]  Container my-container
[DIE]    Container my-container (exit: 0)
[DESTROY] Container my-container
```

```rust
let route = RouteBuilder::from("container:events")
    .to("log:info?showBody=true")
    .build()?;
```

### Dynamic Operation via Header

```rust
// Override operation at runtime
let route = RouteBuilder::from("direct:container-op")
    .set_header("CamelContainerAction", Value::String("list".into()))
    .to("container:run")  // Base URI, overridden by header
    .build()?;
```

### Streaming Container Logs

The `logs` consumer streams log output from a container:

```rust
// Stream logs from a container
let route = RouteBuilder::from("container:logs?containerId=my-app&timestamps=true")
    .to("log:info?showHeaders=true")
    .build()?;
```

Each log line becomes an exchange with:

- **Body**: The log line content
- **CamelContainerId**: Container ID/name
- **CamelContainerLogStream**: `stdout` or `stderr`
- **CamelContainerLogTimestamp**: Timestamp (when `timestamps=true`)

Options:

- `follow=true` (default): Stream new logs as they arrive
- `follow=false`: Get historical logs and exit
- `tail=100`: Get last 100 lines only
- `timestamps=true`: Include Docker timestamps

```yaml
# YAML DSL example
routes:
  - id: "nginx-logs"
    from: "container:logs?containerId=nginx-demo&timestamps=true"
    steps:
      - log: "[${header.CamelContainerLogStream}] ${body}"
```

### Running a Container with Volumes

```rust
let route = RouteBuilder::from("timer:start?delay=5000&repeatCount=1")
    .to("container:run?image=nginx:latest&volumes=/host/html:/usr/share/nginx/html:ro&ports=8080:80&autoRemove=false")
    .to("log:info?message=nginx serving from /host/html")
    .build()?;
```

Multiple volumes are comma-separated:

```rust
.to("container:run?image=postgres:15&volumes=/data/pg:/var/lib/postgresql/data,/data/backup:/backup&autoRemove=false")
```

### Executing Commands in Containers

Attached (waits for output):

```rust
let route = RouteBuilder::from("direct:exec")
    .set_header("CamelContainerId", Value::String("my-container".into()))
    .set_header("CamelContainerCmd", Value::String("uname -a".into()))
    .to("container:exec")
    .to("log:info?showBody=true")
    .build()?;
```

Detached (runs in background):

```rust
let route = RouteBuilder::from("direct:exec-bg")
    .set_header("CamelContainerId", Value::String("my-container".into()))
    .to("container:exec?cmd=sleep 60&detach=true")
    .to("log:info?showHeaders=true")
    .build()?;
```

With user and working directory:

```rust
let route = RouteBuilder::from("direct:exec-user")
    .set_header("CamelContainerId", Value::String("my-container".into()))
    .to("container:exec?cmd=ls -la&user=root&workdir=/app")
    .to("log:info?showBody=true")
    .build()?;
```

### Network Operations

```rust
let route = RouteBuilder::new()
    .route_id("network-demo")
    .from("direct:net-create")
    .to("container:network-create?driver=bridge")
    .set_header("CamelContainerNetwork", Value::String("my-net".into()))
    .to("log:info?showHeaders=true")
    .build()?;

let route = RouteBuilder::new()
    .route_id("network-connect")
    .from("direct:net-connect")
    .set_header("CamelContainerId", Value::String("my-container".into()))
    .set_header("CamelContainerNetwork", Value::String("my-net".into()))
    .to("container:network-connect")
    .build()?;

let route = RouteBuilder::new()
    .route_id("network-list")
    .from("timer:tick?period=60000")
    .to("container:network-list")
    .to("log:info?showBody=true")
    .build()?;

let route = RouteBuilder::new()
    .route_id("network-disconnect")
    .from("direct:net-disconnect")
    .set_header("CamelContainerId", Value::String("my-container".into()))
    .set_header("CamelContainerNetwork", Value::String("my-net".into()))
    .to("container:network-disconnect?force=true")
    .build()?;

let route = RouteBuilder::new()
    .route_id("network-remove")
    .from("direct:net-remove")
    .set_header("CamelContainerNetwork", Value::String("my-net".into()))
    .to("container:network-remove")
    .build()?;
```

## Error Handling

The component provides clear, actionable error messages:

- **Image not found**: `Image 'foo' not found locally. Set autoPull=true to pull automatically, or run: docker pull foo`
- **Auth required**: `Authentication required for image 'private/image'. Configure Docker credentials: docker login`
- **Container conflict**: `Container name 'my-container' already exists. Use a unique name or remove the existing container first`
- **Missing headers**: Specific messages indicating which header is required
- **Connection failures**: Clear Docker daemon connection errors

## Known Limitations

- **Unix socket only**: TCP/TLS Docker hosts are not supported
- **No event filtering**: The `events` consumer receives all Docker events
- **No SELinux labels**: Volume mount options `:z` and `:Z` are not supported
- **No image operations**: `pull`, `build`, `push`, `tag` are not implemented (use `autoPull=true` instead)

## Example: Full Lifecycle

```rust
use std::time::{SystemTime, UNIX_EPOCH};
use camel_component_api::{CamelError, Value};
use camel_builder::{RouteBuilder, StepAccumulator};
use camel_component_container::{ContainerComponent, HEADER_CONTAINER_NAME};
use camel_component_direct::DirectComponent;
use camel_component_log::LogComponent;
use camel_component_timer::TimerComponent;
use camel_core::context::CamelContext;

#[tokio::main]
async fn main() -> Result<(), CamelError> {
    let mut ctx = CamelContext::new();
    ctx.register_component(TimerComponent::new());
    ctx.register_component(LogComponent::new());
    ctx.register_component(DirectComponent::new());
    ctx.register_component(ContainerComponent::new());

    // Run a container every 20s with auto-pull and auto-remove
    let route = RouteBuilder::from("timer:lifecycle?period=20000")
        .route_id("container-lifecycle")
        .process(|mut exchange| async move {
            let timestamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_millis();
            let name = format!("example-{}", timestamp);
            exchange.input.set_header(HEADER_CONTAINER_NAME, Value::String(name));
            Ok(exchange)
        })
        .to("container:run?image=alpine:latest&cmd=sleep 15&autoRemove=true")
        .to("log:info?showHeaders=true")
        .build()?;

    ctx.add_route_definition(route).await?;
    ctx.start().await?;

    tokio::signal::ctrl_c().await.ok();
    ctx.stop().await?;
    Ok(())
}
```

## YAML DSL

The container component works with the YAML DSL:

```yaml
routes:
  - id: "container-monitor"
    from: "timer:tick?period=60000"
    steps:
      - log: "Listing containers..."
      - to: "container:list"
      - to: "log:info?showBody=true"

  - id: "run-container"
    from: "timer:run?period=30000"
    steps:
      - to: "container:run?image=alpine:latest&cmd=sleep 10&autoRemove=true"
      - to: "log:info?showHeaders=true"

  - id: "container-events"
    from: "container:events"
    steps:
      - log: "${body}"
```

## Cleanup on Shutdown

Containers created via `run` operation are tracked globally. Call `cleanup_tracked_containers()` on shutdown to force-remove any containers that are still running:

```rust
use camel_component_container::cleanup_tracked_containers;

#[tokio::main]
async fn main() -> Result<(), CamelError> {
    // ... setup routes and context ...

    ctx.start().await?;

    tokio::signal::ctrl_c().await.ok();
    ctx.stop().await?;

    // Cleanup any tracked containers (important for hot-reload)
    cleanup_tracked_containers().await;

    Ok(())
}
```

This is especially important for:

- **Hot-reload scenarios**: Prevents orphaned containers when the application restarts
- **Long-running containers**: Ensures cleanup even if containers haven't finished naturally
- **Graceful shutdown**: Guarantees no containers are left behind

Note: With `autoRemove=true` (the default), Docker will automatically remove containers when they exit naturally. The cleanup function handles cases where the application exits before containers finish.

## Global Configuration

Configure default Docker host in `Camel.toml` that applies to all Container endpoints:

```toml
[default.components.container]
docker_host = "unix:///var/run/docker.sock"  # Docker daemon socket (default)
```

### Remote Docker Host

```toml
[production.components.container]
docker_host = "tcp://docker-proxy:2375"  # TCP socket (note: only Unix sockets fully supported)
```

URI parameter `host` always overrides global default:

```rust
// Uses global docker_host
.to("container:list")

// Overrides to use different host
.to("container:list?host=unix:///var/run/docker.sock")
```

## Documentation

- [API Documentation]https://docs.rs/camel-component-container
- [Repository]https://github.com/kennycallado/rust-camel

## License

Apache-2.0

## Contributing

Contributions are welcome! Please see the [main repository](https://github.com/kennycallado/rust-camel) for details.