1use std::{collections::HashMap, pin::Pin, time::Duration};
8
9use bollard::{
10 container::LogOutput,
11 errors::Error,
12 models::{
13 ContainerCreateBody, ContainerStateStatusEnum, EndpointSettings, HostConfig, HostConfigCgroupnsModeEnum, Mount,
14 MountType, NetworkingConfig, PortBinding,
15 },
16 query_parameters::{
17 CreateContainerOptionsBuilder, LogsOptionsBuilder, RemoveContainerOptionsBuilder, StopContainerOptionsBuilder,
18 WaitContainerOptionsBuilder,
19 },
20 Docker,
21};
22use bytes::Bytes;
23use futures::{Stream, StreamExt as _};
24use saluki_error::{generic_error, ErrorContext as _, GenericError};
25use tokio::time::{timeout_at, Instant};
26
27use crate::{
28 removal::{bounded, RequestError},
29 retry::with_transient_error_retry,
30 scope::CaseScope,
31};
32
33const PUBLISH_HOST_IP: &str = "127.0.0.1";
35
36pub const LINUX_EPHEMERAL_PORT_RANGE: &str = "60000 65535";
39
40#[derive(Clone, Debug, Default)]
42pub struct ContainerSpec {
43 image: String,
44 entrypoint: Option<Vec<String>>,
45 command: Option<Vec<String>>,
46 env: Vec<String>,
47 published_ports: Vec<u16>,
48 mounts: Vec<Mount>,
49 sysctls: HashMap<String, String>,
50 host_pid: bool,
51 host_cgroup_namespace: bool,
52}
53
54impl ContainerSpec {
55 pub fn new(image: impl Into<String>) -> Self {
57 Self {
58 image: image.into(),
59 ..Default::default()
60 }
61 }
62
63 pub fn with_entrypoint(mut self, entrypoint: Vec<String>) -> Self {
65 self.entrypoint = Some(entrypoint);
66 self
67 }
68
69 pub fn with_command(mut self, command: Vec<String>) -> Self {
71 self.command = Some(command);
72 self
73 }
74
75 pub fn with_env_var(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
77 self.env.push(format!("{}={}", key.as_ref(), value.as_ref()));
78 self
79 }
80
81 pub fn with_published_port(mut self, port: u16) -> Self {
83 self.published_ports.push(port);
84 self
85 }
86
87 pub fn with_bind(mut self, host: impl Into<String>, path: impl Into<String>, read_only: bool) -> Self {
89 self.mounts.push(Mount {
90 source: Some(host.into()),
91 target: Some(path.into()),
92 typ: Some(MountType::BIND),
93 read_only: Some(read_only),
94 ..Default::default()
95 });
96 self
97 }
98
99 pub fn with_sysctl(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
101 self.sysctls.insert(key.into(), value.into());
102 self
103 }
104
105 pub fn with_host_pid(mut self) -> Self {
107 self.host_pid = true;
108 self
109 }
110
111 pub fn with_host_cgroup_namespace(mut self) -> Self {
113 self.host_cgroup_namespace = true;
114 self
115 }
116}
117
118#[derive(Clone, Debug, Eq, PartialEq)]
120pub enum Output {
121 Stdout(Bytes),
123 Stderr(Bytes),
125}
126
127impl Output {
128 pub(crate) fn from_log(log: LogOutput) -> Option<Self> {
129 match log {
130 LogOutput::StdOut { message } | LogOutput::Console { message } => Some(Self::Stdout(message)),
131 LogOutput::StdErr { message } => Some(Self::Stderr(message)),
132 LogOutput::StdIn { .. } => None,
133 }
134 }
135}
136
137pub type OutputStream = Pin<Box<dyn Stream<Item = Result<Output, GenericError>> + Send>>;
139
140#[derive(Clone, Debug)]
142pub struct Container {
143 pub(crate) docker: Docker,
144 pub(crate) name: String,
145 pub(crate) id: String,
146 pub(crate) network: String,
148}
149
150#[derive(Clone, Debug, Default, Eq, PartialEq)]
152pub struct Status {
153 pub running: bool,
155 pub ip: Option<String>,
157 pub published_ports: HashMap<u16, u16>,
159}
160
161impl CaseScope {
162 pub async fn create_container(
172 &self, participant: &str, spec: ContainerSpec, deadline: Instant,
173 ) -> Result<Container, GenericError> {
174 let name = self.container_name(participant);
175 let network = self.resource_name();
176
177 let networking_config = NetworkingConfig {
178 endpoints_config: Some(HashMap::from([(
179 network.clone(),
180 EndpointSettings {
181 aliases: Some(vec![participant.to_string()]),
182 ..Default::default()
183 },
184 )])),
185 };
186
187 let binds = self.platform.volume_path.map(|path| {
188 let volume = self.resource_name();
190 vec![format!("{}:{}", volume, path)]
191 });
192
193 let exposed_ports: Vec<String> = spec
194 .published_ports
195 .iter()
196 .map(|port| format!("{}/tcp", port))
197 .collect();
198 let port_bindings: HashMap<String, Option<Vec<PortBinding>>> = exposed_ports
199 .iter()
200 .map(|port| {
201 let binding = PortBinding {
202 host_ip: Some(PUBLISH_HOST_IP.to_string()),
203 host_port: None,
204 };
205 (port.clone(), Some(vec![binding]))
206 })
207 .collect();
208
209 let body = ContainerCreateBody {
210 hostname: Some(participant.to_string()),
211 image: Some(spec.image),
212 entrypoint: spec.entrypoint,
213 cmd: spec.command,
214 env: Some(spec.env),
215 labels: Some(self.labels()),
216 exposed_ports: Some(exposed_ports),
217 host_config: Some(HostConfig {
218 binds,
219 mounts: (!spec.mounts.is_empty()).then_some(spec.mounts),
220 network_mode: Some(network.clone()),
221 port_bindings: Some(port_bindings),
222 sysctls: (!spec.sysctls.is_empty()).then_some(spec.sysctls),
223 pid_mode: spec.host_pid.then(|| "host".to_string()),
224 cgroupns_mode: spec.host_cgroup_namespace.then_some(HostConfigCgroupnsModeEnum::HOST),
225 ..Default::default()
226 }),
227 networking_config: Some(networking_config),
228 ..Default::default()
229 };
230 let options = CreateContainerOptionsBuilder::default().name(&name).build();
231 let created = bounded(Some(deadline), self.docker.create_container(Some(options), body))
232 .await
233 .map_err(|e| generic_error!("Failed to create container '{}': {}", name, e))?;
234
235 Ok(Container {
236 docker: self.docker.clone(),
237 name,
238 id: created.id,
239 network,
240 })
241 }
242}
243
244impl Container {
245 pub async fn existing(docker: &Docker, name: &str, deadline: Instant) -> Result<Self, GenericError> {
252 let inspect = bounded(Some(deadline), docker.inspect_container(name, None))
253 .await
254 .map_err(|e| generic_error!("Failed to inspect container '{}': {}", name, e))?;
255 let id = inspect
256 .id
257 .ok_or_else(|| generic_error!("Docker reports no ID for container '{}'.", name))?;
258 Ok(Self {
259 docker: docker.clone(),
260 name: name.to_string(),
261 id,
262 network: String::new(),
263 })
264 }
265
266 pub fn name(&self) -> &str {
268 &self.name
269 }
270
271 pub fn id(&self) -> &str {
273 &self.id
274 }
275
276 pub async fn start(&self, deadline: Instant) -> Result<(), GenericError> {
283 let start = with_transient_error_retry("container start", &self.name, || async {
285 self.docker
286 .start_container(&self.name, None)
287 .await
288 .with_error_context(|| format!("Failed to start container '{}'.", self.name))
289 });
290 timeout_at(deadline, start).await.unwrap_or_else(|_| {
292 Err(generic_error!(
293 "Failed to start container '{}': {}",
294 self.name,
295 RequestError::DeadlineExceeded
296 ))
297 })
298 }
299
300 pub async fn published_port(&self, port: u16, deadline: Instant) -> Result<u16, GenericError> {
307 self.status(deadline)
308 .await?
309 .published_ports
310 .get(&port)
311 .copied()
312 .ok_or_else(|| {
313 generic_error!(
314 "Docker reports no host port for port {} of container '{}'.",
315 port,
316 self.name
317 )
318 })
319 }
320
321 pub async fn status(&self, deadline: Instant) -> Result<Status, GenericError> {
327 let inspect = bounded(Some(deadline), self.docker.inspect_container(&self.name, None))
328 .await
329 .map_err(|e| generic_error!("Failed to inspect container '{}': {}", self.name, e))?;
330 let running = inspect.state.and_then(|state| state.running).unwrap_or(false);
331 let settings = inspect.network_settings.unwrap_or_default();
332 let ip = settings
333 .networks
334 .and_then(|mut networks| networks.remove(&self.network))
335 .and_then(|endpoint| endpoint.ip_address)
336 .filter(|ip| !ip.is_empty());
337 let published_ports = settings
338 .ports
339 .into_iter()
340 .flatten()
341 .filter_map(|(key, bindings)| {
342 let port = key.strip_suffix("/tcp")?.parse().ok()?;
343 let host_port = bindings
344 .into_iter()
345 .flatten()
346 .filter(|binding| binding.host_ip.as_deref() == Some(PUBLISH_HOST_IP))
347 .find_map(|binding| binding.host_port.and_then(|host_port| host_port.parse().ok()))?;
348 Some((port, host_port))
349 })
350 .collect();
351 Ok(Status {
352 running,
353 ip,
354 published_ports,
355 })
356 }
357
358 pub async fn wait(&self, deadline: Instant) -> Result<i64, GenericError> {
368 let options = WaitContainerOptionsBuilder::default().condition("not-running").build();
369 let waited = match timeout_at(deadline, self.docker.wait_container(&self.name, Some(options)).next()).await {
370 Err(_) => Err(RequestError::DeadlineExceeded.to_string()),
371 Ok(Some(Ok(response))) => match response.error.and_then(|error| error.message).filter(|m| !m.is_empty()) {
372 Some(message) => Err(message),
373 None => Ok(response.status_code),
374 },
375 Ok(Some(Err(Error::DockerContainerWaitError { error, code }))) if error.is_empty() => Ok(code),
377 Ok(Some(Err(Error::DockerContainerWaitError { error, .. }))) => Err(error),
378 Ok(Some(Err(e))) => Err(e.to_string()),
379 Ok(None) => Err("Docker ended the wait without an exit".to_string()),
380 };
381 let code = waited
382 .map_err(|message| generic_error!("Failed to wait for container '{}' to exit: {}", self.name, message))?;
383
384 let state = bounded(Some(deadline), self.docker.inspect_container(&self.name, None))
386 .await
387 .map_err(|e| generic_error!("Failed to inspect container '{}' after its exit: {}", self.name, e))?
388 .state
389 .unwrap_or_default();
390 if state.status == Some(ContainerStateStatusEnum::CREATED) {
391 return Err(generic_error!(
392 "Container '{}' never ran: {}",
393 self.name,
394 state
395 .error
396 .filter(|error| !error.is_empty())
397 .as_deref()
398 .unwrap_or("it was not started")
399 ));
400 }
401 Ok(code)
402 }
403
404 pub fn logs(&self) -> OutputStream {
406 let options = LogsOptionsBuilder::default()
407 .follow(true)
408 .stdout(true)
409 .stderr(true)
410 .build();
411 let name = self.name.clone();
412 let logs = self.docker.logs(&self.name, Some(options)).filter_map(move |log| {
413 let output = match log {
414 Ok(log) => Output::from_log(log).map(Ok),
415 Err(e) => Some(Err(generic_error!(
416 "Failed to read the output of container '{}': {}",
417 name,
418 e
419 ))),
420 };
421 async move { output }
422 });
423 Box::pin(logs)
424 }
425
426 pub async fn stop(&self, grace: Duration, deadline: Instant) -> Result<(), GenericError> {
436 let seconds = grace.as_secs() + u64::from(grace.subsec_nanos() > 0);
437 let grace = i32::try_from(seconds).unwrap_or(i32::MAX);
438 let options = StopContainerOptionsBuilder::default().t(grace).build();
439 match bounded(Some(deadline), self.docker.stop_container(&self.name, Some(options))).await {
440 Err(e) if !e.is_not_found() => Err(generic_error!("Failed to stop container '{}': {}", self.name, e)),
441 _ => Ok(()),
442 }
443 }
444
445 pub async fn remove(&self, deadline: Instant) -> Result<(), GenericError> {
452 let options = RemoveContainerOptionsBuilder::default().force(true).v(true).build();
453 match bounded(Some(deadline), self.docker.remove_container(&self.name, Some(options))).await {
454 Err(e) if !e.is_not_found() => Err(generic_error!("Failed to remove container '{}': {}", self.name, e)),
455 _ => Ok(()),
456 }
457 }
458}