Skip to main content

airlock/
scope.rs

1//! The Docker resources one case shares: a network, an optional volume, and the containers created in it.
2//!
3//! A [`CaseScope`] computes every name it uses from its ID without talking to Docker, so a caller can record the
4//! scope for reclaim before [`CaseScope::prepare`] creates anything.
5//!
6//! Every resource carries the label `airlock-case=<id>`, so reclaiming one case never removes the containers of
7//! another case. Names start with `airlock-case-`.
8
9use std::collections::HashMap;
10
11use bollard::{
12    models::{Ipam, NetworkCreateRequest, VolumeCreateRequest},
13    Docker,
14};
15use saluki_error::{generic_error, ErrorContext as _, GenericError};
16use tokio::time::{timeout_at, Instant};
17use tracing::debug;
18
19use crate::{
20    removal::{bounded, is_not_found, Group, RequestError},
21    retry::with_transient_error_retry,
22};
23
24const CREATED_BY_LABEL: (&str, &str) = ("created_by", "airlock");
25const CASE_LABEL_KEY: &str = "airlock-case";
26
27/// What a case scope looks like on one container OS.
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub struct ScopePlatform {
30    /// Docker network driver of the case network.
31    pub network_driver: &'static str,
32
33    /// Where every container of the case mounts the case volume, or `None` for a scope with no volume.
34    pub volume_path: Option<&'static str>,
35}
36
37#[cfg(test)]
38impl ScopePlatform {
39    /// Linux containers: a bridge network, and a volume at `/airlock` in every container.
40    pub(crate) const LINUX: Self = Self {
41        network_driver: "bridge",
42        volume_path: Some("/airlock"),
43    };
44}
45
46/// The network and volume of one case, and the label and names of everything created in it.
47#[derive(Clone, Debug)]
48pub struct CaseScope {
49    pub(crate) docker: Docker,
50    pub(crate) id: String,
51    pub(crate) platform: ScopePlatform,
52}
53
54impl CaseScope {
55    /// Creates a scope with the given ID. Nothing is created in Docker until [`Self::prepare`].
56    ///
57    /// The ID must be unique among the scopes that exist on the Docker daemon, and valid in Docker resource names.
58    pub fn new(docker: Docker, id: impl Into<String>, platform: ScopePlatform) -> Self {
59        Self {
60            docker,
61            id: id.into(),
62            platform,
63        }
64    }
65
66    /// Returns the name of the case network, which is also the name of the case volume.
67    pub fn resource_name(&self) -> String {
68        format!("airlock-case-{}", self.id)
69    }
70
71    /// Returns the name of the container for `participant`.
72    pub fn container_name(&self, participant: &str) -> String {
73        format!("airlock-case-{}-{}", self.id, participant)
74    }
75
76    /// Returns the labels every resource of the scope carries.
77    pub(crate) fn labels(&self) -> HashMap<String, String> {
78        let (created_by_key, created_by_value) = CREATED_BY_LABEL;
79        HashMap::from([
80            (created_by_key.to_string(), created_by_value.to_string()),
81            (CASE_LABEL_KEY.to_string(), self.id.clone()),
82        ])
83    }
84
85    /// The label every resource of the scope carries, as a Docker filter: `airlock-case=<id>`.
86    pub(crate) fn case_label(&self) -> String {
87        format!("{}={}", CASE_LABEL_KEY, self.id)
88    }
89
90    /// Creates the case network, then the case volume if the platform has one.
91    ///
92    /// # Errors
93    ///
94    /// Returns an error if a network of that name belongs to another case, if a volume of that name exists, if Docker
95    /// refuses to create a resource, or if `deadline` passes first.
96    pub async fn prepare(&self, deadline: Instant) -> Result<(), GenericError> {
97        let name = self.resource_name();
98
99        let create_network = with_transient_error_retry("network creation", &self.id, || async {
100            // A create that Docker reported as failed can still have made the network (the collision the retry is
101            // for), so every attempt looks for it first. The name holds the case ID, so a network of that name with
102            // this scope's label was made by an earlier attempt.
103            match self.docker.inspect_network(&name, None).await {
104                Ok(network)
105                    if network.labels.as_ref().and_then(|labels| labels.get(CASE_LABEL_KEY)) == Some(&self.id) =>
106                {
107                    return Ok(());
108                }
109                Ok(_) => {
110                    return Err(generic_error!(
111                        "Network '{}' already exists and belongs to another case.",
112                        name
113                    ))
114                }
115                Err(e) if is_not_found(&e) => {}
116                Err(e) => return Err(generic_error!("Failed to look up network '{}': {}", name, e)),
117            }
118            let request = NetworkCreateRequest {
119                name: name.clone(),
120                driver: Some(self.platform.network_driver.to_string()),
121                ipam: Some(Ipam::default()),
122                enable_ipv6: Some(false),
123                labels: Some(self.labels()),
124                ..Default::default()
125            };
126            self.docker
127                .create_network(request)
128                .await
129                .map(|_| ())
130                .with_error_context(|| format!("Failed to create network '{}'.", name))
131        });
132        // The deadline bounds the waits between attempts, too.
133        timeout_at(deadline, create_network).await.unwrap_or_else(|_| {
134            Err(generic_error!(
135                "Failed to create network '{}': {}",
136                name,
137                RequestError::DeadlineExceeded
138            ))
139        })?;
140        debug!("Created network '{}'.", name);
141
142        if self.platform.volume_path.is_some() {
143            // Docker answers the create of an existing volume with that volume, contents and all. The volume create is
144            // not retried, so no earlier attempt of this scope made one.
145            match bounded(Some(deadline), self.docker.inspect_volume(&name)).await {
146                Ok(_) => return Err(generic_error!("Volume '{}' already exists.", name)),
147                Err(e) if e.is_not_found() => {}
148                Err(e) => return Err(generic_error!("Failed to look up volume '{}': {}", name, e)),
149            }
150            let request = VolumeCreateRequest {
151                name: Some(name.clone()),
152                driver: Some("local".to_string()),
153                labels: Some(self.labels()),
154                ..Default::default()
155            };
156            bounded(Some(deadline), self.docker.create_volume(request))
157                .await
158                .map_err(|e| generic_error!("Failed to create volume '{}': {}", name, e))?;
159            debug!("Created volume '{}'.", name);
160        }
161
162        Ok(())
163    }
164
165    /// Removes every container of the scope with its anonymous volumes, then the case volume, then the case network.
166    ///
167    /// Running containers are killed. Every removal is attempted, each bounded by `deadline`, and a resource that is
168    /// already gone counts as removed. A volume or network of the scope's name without the scope's label belongs to
169    /// someone else, so it is not removed.
170    ///
171    /// # Errors
172    ///
173    /// Returns an error listing every resource that could not be removed by the deadline, and every volume or network
174    /// that was not removed because it lacks the scope's label.
175    pub async fn reclaim(&self, deadline: Instant) -> Result<(), GenericError> {
176        let name = self.resource_name();
177        let created_by_label = format!("{}={}", CREATED_BY_LABEL.0, CREATED_BY_LABEL.1);
178        let case_label = self.case_label();
179        let group = Group {
180            labels: &[created_by_label.as_str(), case_label.as_str()],
181            volume: self.platform.volume_path.map(|_| name.as_str()),
182            network: &name,
183            owner_label: Some((CASE_LABEL_KEY, &self.id)),
184            remove_anonymous_volumes: true,
185        };
186        let failures = group.remove(&self.docker, Some(deadline)).await;
187
188        if failures.is_empty() {
189            Ok(())
190        } else {
191            Err(generic_error!(
192                "Failed to remove case scope '{}': {}",
193                self.id,
194                failures.join("; ")
195            ))
196        }
197    }
198}