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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Utilities for director-based tools.
//!
//! Tools written using this crate usually have other tasks related to management of the job files.
//! These functions are meant to be used in the tools so that these tasks are built into the tool
//! rather than managed using external scripts.

use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Duration;

use chrono::Utc;
use log::{error, warn};
use lzma::LzmaWriter;
use rand::Rng;
use serde::Serialize;
use serde_json::{json, Value};
use tar::Builder;
use tempfile::TempDir;
use thiserror::Error;

use crate::Outbox;

/// An error creating a utiltiy job.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum JobError {
    /// Failure to create a job.
    #[error("failed to create job {}: {}", filepath.display(), source)]
    Create {
        /// The path to the job.
        filepath: PathBuf,
        /// The source of the error.
        #[source]
        source: io::Error,
    },
    /// Failure to serialize a job.
    #[error("failed to write job file {}: {}", filepath.display(), source)]
    Write {
        /// The path to the job.
        filepath: PathBuf,
        /// The source of the error.
        #[source]
        source: serde_json::Error,
    },
}

impl JobError {
    fn create(filepath: PathBuf, source: io::Error) -> Self {
        JobError::Create {
            filepath,
            source,
        }
    }

    fn write(filepath: PathBuf, source: serde_json::Error) -> Self {
        JobError::Write {
            filepath,
            source,
        }
    }
}

type JobResult<T> = Result<T, JobError>;

/// Write a job object to a new file in a directory.
fn write_job(queue: &Path, data: &Value) -> JobResult<()> {
    let rndpart = rand::thread_rng()
        .sample_iter(&rand::distributions::Alphanumeric)
        .map(char::from)
        .take(12)
        .collect::<String>();
    let filename = format!("{}-{}.json", Utc::now().to_rfc3339(), rndpart);
    let job_file = queue.join(filename);

    // Write and close the job file.
    {
        // XXX(nightly): Result::unwrap_or_else API (rust-lang/rust#53268)
        let mut file =
            File::create(&job_file).map_err(|err| JobError::create(job_file.clone(), err))?;
        serde_json::to_writer(&mut file, data)
            .map_err(|err| JobError::write(job_file.clone(), err))?;
    }

    // Wait for the job to have been processed.
    while job_file.exists() {
        thread::sleep(Duration::from_millis(100));
    }

    loop {
        // Wait for the job to have been processed.
        if !job_file.exists() {
            break;
        }

        thread::sleep(Duration::from_millis(100));
    }

    Ok(())
}

/// Write a job to the given queue.
pub fn drop_job<Q, K, V>(queue: Q, kind: K, data: V) -> JobResult<()>
where
    Q: AsRef<Path>,
    K: AsRef<str>,
    V: Serialize,
{
    let job = json!({
        "kind": kind.as_ref(),
        "data": data,
    });
    write_job(queue.as_ref(), &job)
}

/// Write a restart job to the given queue.
pub fn restart<Q>(queue: Q) -> JobResult<()>
where
    Q: AsRef<Path>,
{
    drop_job(queue, "watchdog:restart", json!({}))
}

/// Write an exit job to the given queue.
pub fn exit<Q>(queue: Q) -> JobResult<()>
where
    Q: AsRef<Path>,
{
    drop_job(queue, "watchdog:exit", json!({}))
}

/// Log that a temporary directory containing jobs moved for archiving but left unarchived due to
/// an error still exists.
fn log_tempdir(tempdir: TempDir) {
    error!(
        "archival failed mid-stream; in-progress archival job files may be found in {}",
        tempdir.into_path().display(),
    );
}

/// An error archiving a queue.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ArchiveQueueError {
    /// Failure to create an output file.
    #[error("failed to create archive file {}: {}", path.display(), source)]
    CreateOutput {
        #[doc(hidden)]
        outbox: Outbox,
        /// The path to the archive file.
        path: PathBuf,
        /// The source of the error.
        #[source]
        source: io::Error,
    },
    /// Failure to create a compressor for the archive.
    #[error("failed to create compressor: {}", source)]
    CreateCompressor {
        #[doc(hidden)]
        outbox: Outbox,
        /// The source of the error.
        #[source]
        source: lzma::LzmaError,
    },
    /// Failure when archiving jobs.
    #[error("failed to archive the {} outbox: {}", outbox, source)]
    Archive {
        #[doc(hidden)]
        outbox: Outbox,
        /// The source of the error.
        #[source]
        source: ArchiveError,
    },
    /// Failure when finishing the archive.
    #[error("failed to finish the {} archive: {}", outbox, source)]
    FinishArchive {
        #[doc(hidden)]
        outbox: Outbox,
        /// The source of the error.
        #[source]
        source: lzma::LzmaError,
    },
    /// Failure to remove an incomplete archive.
    #[error("failed to remove an incomplete {} archive: {}", outbox, source)]
    RemoveIncompleteArchive {
        #[doc(hidden)]
        outbox: Outbox,
        /// The source of the error.
        #[source]
        source: io::Error,
    },
}

impl ArchiveQueueError {
    /// The outbox being archived when the error occurred.
    pub fn outbox(&self) -> Outbox {
        match self {
            ArchiveQueueError::CreateOutput {
                outbox, ..
            }
            | ArchiveQueueError::CreateCompressor {
                outbox, ..
            }
            | ArchiveQueueError::Archive {
                outbox, ..
            }
            | ArchiveQueueError::FinishArchive {
                outbox, ..
            }
            | ArchiveQueueError::RemoveIncompleteArchive {
                outbox, ..
            } => *outbox,
        }
    }

    fn create_output(outbox: Outbox, path: PathBuf, source: io::Error) -> Self {
        ArchiveQueueError::CreateOutput {
            outbox,
            path,
            source,
        }
    }

    fn create_compressor(outbox: Outbox, source: lzma::LzmaError) -> Self {
        ArchiveQueueError::CreateCompressor {
            outbox,
            source,
        }
    }

    fn archive(outbox: Outbox, source: ArchiveError) -> Self {
        ArchiveQueueError::Archive {
            outbox,
            source,
        }
    }

    fn finish_archive(tempdir: TempDir, outbox: Outbox, source: lzma::LzmaError) -> Self {
        log_tempdir(tempdir);
        ArchiveQueueError::FinishArchive {
            outbox,
            source,
        }
    }

    fn remove_incomplete_archive(outbox: Outbox, source: io::Error) -> Self {
        ArchiveQueueError::RemoveIncompleteArchive {
            outbox,
            source,
        }
    }
}

/// The LZMA compression level to use for archiving.
const LZMA_COMPRESSION: u32 = 6;

/// Archive the jobs in the given queue into a tarball in the output directory.
///
/// Each subdirectory, `accept`, `fail`, and `reject` will be archived separately.
pub fn archive_queue<Q, O>(queue: Q, output: O) -> Result<(), ArchiveQueueError>
where
    Q: AsRef<Path>,
    O: AsRef<Path>,
{
    archive_queue_impl(queue.as_ref(), output.as_ref())
}

fn archive_queue_impl(queue: &Path, output: &Path) -> Result<(), ArchiveQueueError> {
    for outbox in [Outbox::Accept, Outbox::Fail, Outbox::Reject]
        .iter()
        .cloned()
    {
        let (filename, file) = archive_file(output, outbox)?;
        let opt_writer = archive_directory(queue, output, outbox, file)
            .map_err(|err| ArchiveQueueError::archive(outbox, err))?;
        if let Some((tempdir, writer)) = opt_writer {
            writer
                .finish()
                .map_err(|err| ArchiveQueueError::finish_archive(tempdir, outbox, err))?;
        } else {
            fs::remove_file(filename)
                .map_err(|err| ArchiveQueueError::remove_incomplete_archive(outbox, err))?;
        }
    }

    Ok(())
}

/// An error when writing to an archive.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ArchiveError {
    /// Failure to create a temporary directory for working.
    #[error("failed to create temporary directory: {}", source)]
    CreateTempdir {
        /// The source of the error.
        #[source]
        source: io::Error,
    },
    /// Failure to add the root directory to the archive.
    #[error("failed to add directory: {}", source)]
    AddDirectory {
        /// The source of the error.
        #[source]
        source: io::Error,
    },
    /// Failure to read the directory for processed job files.
    #[error("failed to read directory: {}", source)]
    ReadDirectory {
        /// The source of the error.
        #[source]
        source: io::Error,
    },
    /// Failure to append a job to the archive.
    #[error("failed to append job: {}", source)]
    AppendJob {
        /// The file that could not be appended.
        path: PathBuf,
        /// The source of the error.
        #[source]
        source: io::Error,
    },
    /// Failure to finish the tar stream.
    #[error("failed to finish tar stream: {}", source)]
    FinishTar {
        /// The source of the error.
        #[source]
        source: io::Error,
    },
}

impl ArchiveError {
    fn create_tempdir(source: io::Error) -> Self {
        ArchiveError::CreateTempdir {
            source,
        }
    }

    fn add_directory(source: io::Error) -> Self {
        ArchiveError::AddDirectory {
            source,
        }
    }

    fn read_directory(source: io::Error) -> Self {
        ArchiveError::ReadDirectory {
            source,
        }
    }

    fn append_job(tempdir: TempDir, path: PathBuf, source: io::Error) -> Self {
        log_tempdir(tempdir);
        ArchiveError::AppendJob {
            path,
            source,
        }
    }

    fn finish_tar(tempdir: TempDir, source: io::Error) -> Self {
        log_tempdir(tempdir);
        ArchiveError::FinishTar {
            source,
        }
    }
}

/// Create an archive file stream in the given path for the `outbox` files.
fn archive_file(
    path: &Path,
    outbox: Outbox,
) -> Result<(PathBuf, LzmaWriter<File>), ArchiveQueueError> {
    let now = Utc::now();
    let filepath = path.join(format!("{}-{}.tar.xz", now.to_rfc3339(), outbox));
    let file = File::create(&filepath)
        .map_err(|err| ArchiveQueueError::create_output(outbox, filepath.clone(), err))?;
    let writer = LzmaWriter::new_compressor(file, LZMA_COMPRESSION)
        .map_err(|err| ArchiveQueueError::create_compressor(outbox, err))?;

    Ok((filepath, writer))
}

/// Archive a directory into an output stream.
fn archive_directory<O>(
    path: &Path,
    workdir: &Path,
    outbox: Outbox,
    output: O,
) -> Result<Option<(TempDir, O)>, ArchiveError>
where
    O: Write,
{
    let tempdir = TempDir::new_in(workdir).map_err(ArchiveError::create_tempdir)?;
    let outbox_name = outbox.name();
    let outbox_path = PathBuf::from(outbox_name);
    let mut archive = Builder::new(output);
    archive
        .append_dir(outbox_name, &tempdir)
        .map_err(ArchiveError::add_directory)?;

    // Any errors after this point will need to perform `tempdir.into_path()` to prevent it from
    // removing any job files which have been staged there in preparation for removal because the
    // archive will not be successful at this point.

    let entries = fs::read_dir(path.join(outbox_name)).map_err(ArchiveError::read_directory)?;
    let mut is_empty = true;
    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(err) => {
                warn!("failed to read directory entry; skipping: {:?}", err);
                continue;
            },
        };
        let path = entry.path();
        let file_name = entry.file_name();
        if let Err(err) = archive.append_path_with_name(&path, outbox_path.join(&file_name)) {
            // The state of `archive` is unknown if an error occurs when adding data to it; it
            // cannot be trusted anymore, so bail out.
            //
            // See https://github.com/alexcrichton/tar-rs/issues/213
            return Err(ArchiveError::append_job(tempdir, path, err));
        }
        // The file has been added to the archive; move it to the staging directory.
        let target_path = tempdir.path().join(&file_name);
        match fs::rename(&path, &target_path) {
            Ok(()) => is_empty = false,
            Err(err) => {
                warn!(
                    "failed to rename {} to {}: {:?}",
                    path.display(),
                    target_path.display(),
                    err,
                )
            },
        }
    }

    if is_empty {
        // All good to let `tempdir` be destructed here; we didn't move anything to staging
        // directory anyways.
        return Ok(None);
    }

    // Both branches here need to pass on `tempdir`. The `Ok` path might still have an error before
    // everything is good to go.
    match archive.into_inner() {
        Ok(output) => Ok(Some((tempdir, output))),
        Err(err) => Err(ArchiveError::finish_tar(tempdir, err)),
    }
}