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
use {
crate::{
cache, docker, failure,
failure::Failure,
tar,
toastfile::{command, location, user, Task, Toastfile},
},
std::{
collections::{HashMap, HashSet},
io::{Seek, SeekFrom},
path::PathBuf,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
},
tempfile::tempfile,
};
// A context is an image that may need to be cleaned up.
#[derive(Clone)]
pub struct Context {
pub docker_cli: String,
pub image: String,
pub persist: bool,
pub interrupted: Arc<AtomicBool>,
}
impl Drop for Context {
fn drop(&mut self) {
// Delete the image if needed.
if !self.persist {
if let Err(e) = docker::delete_image(&self.docker_cli, &self.image, &self.interrupted) {
error!("{}", e);
}
}
}
}
// Run a task in a given context and return a new context. The returned context should not be `None`
// if `need_context` is `true` and `Err(Failure::Interrupted | Failure::System(_, _))` was not
// returned.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
pub fn run(
settings: &super::Settings,
environment: &HashMap<String, String>,
interrupted: &Arc<AtomicBool>,
active_containers: &Arc<Mutex<HashSet<String>>>,
toastfile: &Toastfile,
task: &Task,
caching_enabled: bool,
context: Context,
need_context: bool,
) -> (Result<(), Failure>, Option<Context>) {
// All relative paths are relative to where the toastfile lives.
let mut toastfile_dir = PathBuf::from(&settings.toastfile_path);
toastfile_dir.pop();
// Apply defaults.
let location = location(toastfile, task);
let user = user(toastfile, task);
let command = command(toastfile, task);
// Create a temporary archive for the input file contents.
let tar_file = match tempfile() {
Ok(tar_file) => tar_file,
Err(e) => {
return (
Err(failure::system("Unable to create temporary file.")(e)),
Some(context),
)
}
};
// Write to the archive.
let (mut tar_file, input_files_hash) = match tar::create(
"Reading files\u{2026}",
tar_file,
&task.input_paths,
&task.excluded_input_paths,
&toastfile_dir,
&location,
interrupted,
) {
Ok((tar_file, input_files_hash)) => (tar_file, input_files_hash),
Err(e) => return (Err(e), Some(context)),
};
// Seek back to the beginning of the archive to prepare for copying it into the container.
if let Err(e) = tar_file.seek(SeekFrom::Start(0)) {
return (
Err(failure::system("Unable to seek temporary file.")(e)),
Some(context),
);
};
// Compute the name of the image that this task produces.
let image = cache::image_name(
&context.image,
&settings.docker_repo,
toastfile,
task,
&input_files_hash,
environment,
);
// If we need to return the same image as the one that was passed in, we should be careful to
// reuse the given context rather than constructing a new one. Otherwise, the given context will
// be dropped at the end of this function, which may delete the image that we need to return.
// This variable will be used to determine whether that situation applies.
let context_unchanged = image == context.image;
// Construct the environment.
let mut task_environment = HashMap::<String, String>::new();
for variable in task.environment.keys() {
// [ref:environment_valid]
task_environment.insert(variable.clone(), environment[variable].clone());
}
// Check the cache, if applicable.
let mut cached = false;
if caching_enabled {
// Check the local cache.
cached = settings.read_local_cache
&& match docker::image_exists(&settings.docker_cli, &image, interrupted) {
Ok(exists) => exists,
Err(e) => return (Err(e), Some(context)),
};
// Check the remote cache.
if !cached && settings.read_remote_cache {
if let Err(e) = docker::pull_image(&settings.docker_cli, &image, interrupted) {
// If the pull failed, it could be because the user killed the child process (e.g.,
// by hitting CTRL+C).
if interrupted.load(Ordering::SeqCst) {
return (Err(e), Some(context));
}
} else {
cached = true;
}
}
}
// If the task is cached, extract the output files if applicable.
if cached {
// The task is cached. Check if there are any output files.
if !task.output_paths.is_empty() {
// We need to create a container from which we can extract the output files.
let container = match docker::create_container(
&settings.docker_cli,
&image,
&toastfile_dir,
&task_environment,
&task.mount_paths,
task.mount_readonly,
&task.ports,
&location,
&user,
&command,
&task.extra_docker_arguments,
interrupted,
) {
Ok(container) => container,
Err(e) => return (Err(e), Some(context)),
};
// Delete the container when we're done.
defer! {{
if let Err(e) = docker::delete_container(
&settings.docker_cli,
&container,
interrupted
) {
error!("{}", e);
}
}}
// Extract the output files from the container.
if let Err(e) = docker::copy_from_container(
&settings.docker_cli,
&container,
&task.output_paths,
&location,
&toastfile_dir,
interrupted,
) {
return (Err(e), Some(context));
}
}
// The cached image becomes the new context.
(
Ok(()),
Some(if context_unchanged {
context
} else {
Context {
image,
persist: true,
interrupted: interrupted.clone(),
docker_cli: settings.docker_cli.clone(),
}
}),
)
} else {
// Pull the image if necessary. Note that this is not considered reading from the remote
// cache.
if !match docker::image_exists(&settings.docker_cli, &context.image, interrupted) {
Ok(exists) => exists,
Err(e) => return (Err(e), Some(context)),
} {
if let Err(e) = docker::pull_image(&settings.docker_cli, &context.image, interrupted) {
return (Err(e), Some(context));
}
}
// Create a container from the image.
let container = match docker::create_container(
&settings.docker_cli,
&context.image,
&toastfile_dir,
&task_environment,
&task.mount_paths,
task.mount_readonly,
&task.ports,
&location,
&user,
&command,
&task.extra_docker_arguments,
interrupted,
) {
Ok(container) => container,
Err(e) => return (Err(e), Some(context)),
};
// If the user interrupts the program, kill the container. The `unwrap` will only fail if a
// panic already occurred.
{
active_containers.lock().unwrap().insert(container.clone());
}
// Delete the container when we're done.
defer! {{
// If the user interrupts the program, don't bother killing the container. We're about to
// kill it here. The `unwrap` will only fail if a panic already occurred.
{
active_containers.lock().unwrap().remove(&container);
}
// Delete the container.
if let Err(e) = docker::delete_container(&settings.docker_cli, &container, interrupted) {
error!("{}", e);
}
}}
// Copy files into the container. If `task.input_paths` is empty, then this will just create
// a directory for `location`.
if let Err(e) = docker::copy_into_container(
&settings.docker_cli,
&container,
&mut tar_file,
interrupted,
) {
return (Err(e), Some(context));
}
// Start the container to run the command.
let result = docker::start_container(&settings.docker_cli, &container, interrupted)
.map_err(|e| match e {
Failure::Interrupted => e,
Failure::System(_, _) | Failure::User(_, _) => {
Failure::User("Command failed.".to_owned(), None)
}
});
// Copy files from the container, if applicable.
match result {
Ok(_) if !task.output_paths.is_empty() => {
if let Err(e) = docker::copy_from_container(
&settings.docker_cli,
&container,
&task.output_paths,
&location,
&toastfile_dir,
interrupted,
) {
return (Err(e), Some(context));
}
}
Err(_) if !task.output_paths_on_failure.is_empty() => {
if let Err(e) = docker::copy_from_container(
&settings.docker_cli,
&container,
&task.output_paths_on_failure,
&location,
&toastfile_dir,
interrupted,
) {
return (Err(e), Some(context));
}
}
_ => {}
}
// Decide whether to the image needs to be persisted.
let cacheable = result.is_ok() && caching_enabled;
let persist_locally = cacheable && settings.write_local_cache;
let persist_remotely = cacheable && settings.write_remote_cache;
let failed_fatally = matches!(result, Err(Failure::Interrupted | Failure::System(_, _)));
// Only commit the container if we actually need to return a context.
if (need_context || persist_locally || persist_remotely) && !failed_fatally {
// Commit the container.
if let Err(e) =
docker::commit_container(&settings.docker_cli, &container, &image, interrupted)
{
return (Err(e), Some(context));
}
// Construct a new context, if needed.
let new_context = if context_unchanged {
context
} else {
Context {
image,
persist: persist_locally,
interrupted: interrupted.clone(),
docker_cli: settings.docker_cli.clone(),
}
};
// Write to remote cache, if applicable.
if persist_remotely {
if let Err(e) =
docker::push_image(&settings.docker_cli, &new_context.image, interrupted)
{
return (Err(e), Some(new_context));
}
}
// Return the new context.
(result.map(|_| ()), Some(new_context))
} else {
// The caller doesn't need a context to be returned.
(result.map(|_| ()), None)
}
}
}