1use 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub struct ScopePlatform {
30 pub network_driver: &'static str,
32
33 pub volume_path: Option<&'static str>,
35}
36
37#[cfg(test)]
38impl ScopePlatform {
39 pub(crate) const LINUX: Self = Self {
41 network_driver: "bridge",
42 volume_path: Some("/airlock"),
43 };
44}
45
46#[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 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 pub fn resource_name(&self) -> String {
68 format!("airlock-case-{}", self.id)
69 }
70
71 pub fn container_name(&self, participant: &str) -> String {
73 format!("airlock-case-{}-{}", self.id, participant)
74 }
75
76 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 pub(crate) fn case_label(&self) -> String {
87 format!("{}={}", CASE_LABEL_KEY, self.id)
88 }
89
90 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 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 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 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 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}