-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathcompose.rs
More file actions
328 lines (285 loc) · 10.8 KB
/
Copy pathcompose.rs
File metadata and controls
328 lines (285 loc) · 10.8 KB
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
//! Docker compose command wrapper.
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::time::{Duration, Instant};
use tokio::time::sleep;
#[derive(Clone, Debug)]
pub struct DockerCompose {
file: PathBuf,
project: String,
env_vars: Vec<(String, String)>,
}
#[derive(Debug)]
pub struct RunningCompose {
compose: DockerCompose,
is_active: bool,
}
impl Drop for RunningCompose {
fn drop(&mut self) {
if !self.is_active {
return;
}
if let Err(error) = self.compose.down() {
tracing::error!(
"Failed to stop compose project '{}' from '{}': {error}",
self.compose.project,
self.compose.file.display()
);
}
}
}
impl RunningCompose {
/// Returns the compose project name for this running stack.
#[must_use]
pub fn project(&self) -> &str {
&self.compose.project
}
/// Disables the automatic teardown so containers are left running after this
/// guard is dropped. Useful for post-run debugging.
pub fn keep(&mut self) {
self.is_active = false;
}
}
impl DockerCompose {
#[must_use]
pub fn new(file: &Path, project: &str) -> Self {
Self {
file: file.to_path_buf(),
project: project.to_string(),
env_vars: vec![],
}
}
#[must_use]
pub fn with_env(mut self, key: &str, value: &str) -> Self {
self.env_vars.push((key.to_string(), value.to_string()));
self
}
/// Runs docker compose up and returns a guard that will always run `down --volumes` on drop.
///
/// # Errors
///
/// Returns an error when docker compose fails to start all services.
pub fn up(&self, no_build: bool) -> io::Result<RunningCompose> {
let mut args = vec!["up", "--wait", "--detach"];
if no_build {
args.push("--no-build");
}
let output = self.run_compose(&args)?;
if output.status.success() {
Ok(RunningCompose {
compose: self.clone(),
is_active: true,
})
} else {
Err(io::Error::other(format!(
"docker compose up failed for file '{}' and project '{}': {}",
self.file.display(),
self.project,
String::from_utf8_lossy(&output.stderr)
)))
}
}
/// Builds images defined in the compose file.
///
/// Build output is streamed live to stdout/stderr so progress is visible.
///
/// # Errors
///
/// Returns an error when docker compose build fails.
pub fn build(&self) -> io::Result<()> {
let mut command = Command::new("docker");
command.envs(self.env_vars.iter().map(|(key, value)| (key, value)));
command.arg("compose");
command.arg("-f").arg(&self.file);
command.arg("-p").arg(&self.project);
command.arg("build");
tracing::info!("Running docker compose command: {:?}", command);
let status = command.status()?;
if status.success() {
Ok(())
} else {
Err(io::Error::other(format!(
"docker compose build failed for file '{}' and project '{}'",
self.file.display(),
self.project,
)))
}
}
/// Runs docker compose down --volumes.
///
/// # Errors
///
/// Returns an error when docker compose cannot stop and remove resources.
pub fn down(&self) -> io::Result<()> {
let output = self.run_compose(&["down", "--volumes"])?;
if output.status.success() {
Ok(())
} else {
Err(io::Error::other(format!(
"docker compose down failed for file '{}' and project '{}': {}",
self.file.display(),
self.project,
String::from_utf8_lossy(&output.stderr)
)))
}
}
/// Resolves an ephemeral host port from a service published container port.
///
/// # Errors
///
/// Returns an error when the compose command fails or port parsing fails.
pub fn port(&self, service: &str, container_port: u16) -> io::Result<u16> {
let output = self.run_compose(&["port", service, &container_port.to_string()])?;
if !output.status.success() {
return Err(io::Error::other(format!(
"docker compose port failed for file '{}' and project '{}', service '{}' and port '{}': stderr: {} stdout: {}",
self.file.display(),
self.project,
service,
container_port,
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
)));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let first_line = stdout
.lines()
.next()
.ok_or_else(|| io::Error::other("docker compose port returned no output"))?;
let host_port = first_line
.rsplit(':')
.next()
.ok_or_else(|| io::Error::other("docker compose port output has no ':' separator"))?
.parse::<u16>()
.map_err(|_| io::Error::other(format!("invalid host port in output: '{first_line}'")))?;
Ok(host_port)
}
/// Waits until a service has a resolved host port mapping.
///
/// This helper retries `docker compose port` until it succeeds, the timeout
/// expires, or the target service exits.
///
/// # Errors
///
/// Returns an error when the service exits, port mapping cannot be resolved
/// before timeout, or compose commands fail while gathering diagnostics.
pub async fn wait_for_port_mapping(
&self,
service: &str,
container_port: u16,
timeout: Duration,
poll_interval: Duration,
extra_log_services: &[&str],
) -> io::Result<u16> {
let deadline = Instant::now() + timeout;
loop {
if let Ok(ps_output) = self.ps()
&& compose_service_has_exited(&ps_output, service)
{
let logs_output = self
.logs(&[service])
.unwrap_or_else(|error| format!("failed to collect compose logs output: {error}"));
return Err(io::Error::other(format!(
"compose service '{service}' exited while waiting for port mapping '{container_port}'.\nCompose ps:\n{ps_output}\nCompose logs:\n{logs_output}"
)));
}
match self.port(service, container_port) {
Ok(host_port) => return Ok(host_port),
Err(_) => {
tracing::info!("Waiting for compose port mapping for service '{service}'");
}
}
if Instant::now() >= deadline {
let ps_output = self
.ps()
.unwrap_or_else(|error| format!("failed to collect compose ps output: {error}"));
let mut log_services = Vec::with_capacity(1 + extra_log_services.len());
log_services.push(service);
for extra_service in extra_log_services {
if *extra_service != service {
log_services.push(*extra_service);
}
}
let logs_output = self
.logs(&log_services)
.unwrap_or_else(|error| format!("failed to collect compose logs output: {error}"));
return Err(io::Error::new(
io::ErrorKind::TimedOut,
format!(
"timed out waiting for compose port mapping for service '{service}' and port '{container_port}'.\nCompose ps:\n{ps_output}\nCompose logs:\n{logs_output}"
),
));
}
sleep(poll_interval).await;
}
}
/// Runs `docker compose exec` in non-interactive mode for scripted commands.
///
/// # Errors
///
/// Returns an error when command execution fails.
pub fn exec(&self, service: &str, cmd: &[&str]) -> io::Result<Output> {
let mut args = vec!["exec".to_string(), "-T".to_string(), service.to_string()];
args.extend(cmd.iter().map(|value| (*value).to_string()));
self.run_compose_strings(&args)
}
/// Runs `docker compose ps -a` and returns stdout.
///
/// # Errors
///
/// Returns an error when the compose command fails.
pub fn ps(&self) -> io::Result<String> {
let output = self.run_compose(&["ps", "-a"])?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
Err(io::Error::other(format!(
"docker compose ps failed for file '{}' and project '{}': {}",
self.file.display(),
self.project,
String::from_utf8_lossy(&output.stderr)
)))
}
}
/// Runs `docker compose logs --no-color <services...>` and returns stdout.
///
/// # Errors
///
/// Returns an error when the compose command fails.
pub fn logs(&self, services: &[&str]) -> io::Result<String> {
let mut args = vec!["logs".to_string(), "--no-color".to_string()];
args.extend(services.iter().map(|service| (*service).to_string()));
let output = self.run_compose_strings(&args)?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
Err(io::Error::other(format!(
"docker compose logs failed for file '{}' and project '{}': {}",
self.file.display(),
self.project,
String::from_utf8_lossy(&output.stderr)
)))
}
}
fn run_compose(&self, args: &[&str]) -> io::Result<Output> {
let args_as_strings: Vec<String> = args.iter().map(|value| (*value).to_string()).collect();
self.run_compose_strings(&args_as_strings)
}
fn run_compose_strings(&self, args: &[String]) -> io::Result<Output> {
let mut command = Command::new("docker");
command.envs(self.env_vars.iter().map(|(key, value)| (key, value)));
command.arg("compose");
command.arg("-f").arg(&self.file);
command.arg("-p").arg(&self.project);
command.args(args);
tracing::info!("Running docker compose command: {:?}", command);
command.output()
}
}
fn compose_service_has_exited(ps_output: &str, service_name: &str) -> bool {
ps_output.lines().any(|line| {
line.contains(service_name)
&& (line.contains("exited") || line.contains("dead") || line.contains("created") || line.contains("removing"))
})
}