rustic_core 0.11.0

rustic_core - library for fast, encrypted, deduplicated backups that powers rustic-rs
Documentation
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
use std::io;
use std::process::Command;
use std::thread::sleep;

use backon::{BlockingRetryable, ExponentialBuilder};

use itertools::Itertools;
use log::{debug, error, warn};
use rayon::ThreadPoolBuilder;

use crate::{
    CommandInput, Id, Progress,
    backend::{FileType, ReadBackend},
    error::{ErrorKind, RusticError, RusticResult},
    repository::Repository,
};

pub(super) mod constants {
    use std::time::Duration;

    /// The maximum number of reader threads to use for warm-up.
    pub(super) const MAX_READER_THREADS_NUM: usize = 20;

    /// The maximum number of retries for spawning commands.
    pub(crate) const MAX_RETRIES: usize = 5;

    /// Initial delay for exponential backoff for spawning commands.
    pub(crate) const INITIAL_DELAY: Duration = Duration::from_millis(10);
}

/// Configuration for retrying executing a command that the operating system reports is busy.
/// We believe this is a transient race condition that happens during unit tests when a program
/// is created and then immediately executed.
fn execute_cmd_retry() -> ExponentialBuilder {
    ExponentialBuilder::default()
        .with_min_delay(constants::INITIAL_DELAY)
        .with_max_times(constants::MAX_RETRIES)
}

/// Warm up the repository and wait.
///
/// # Arguments
///
/// * `repo` - The repository to warm up.
/// * `tpe` - The filetype of the ids.
/// * `ids` - The ids to warm up.
///
/// # Errors
///
/// * If the command could not be parsed.
/// * If the thread pool could not be created.
pub(crate) fn warm_up_wait<S>(
    repo: &Repository<S>,
    tpe: FileType,
    ids: impl ExactSizeIterator<Item = Id> + Clone,
) -> RusticResult<()> {
    if ids.len() > 0 {
        warm_up(repo, tpe, ids.clone())?;

        if let Some(warm_up_wait_cmd) = &repo.opts.warm_up_wait_command {
            warm_up_command(
                tpe,
                ids,
                warm_up_wait_cmd,
                repo,
                &WarmUpType::Wait,
                repo.opts.warm_up_batch.unwrap_or(1),
                &repo.be,
            )?;
        } else if let Some(wait) = repo.opts.warm_up_wait {
            let p = repo.progress_spinner(&format!("waiting {wait}..."));
            sleep(
                wait.try_into()
                    // ignore conversation errors, but print out warning
                    .inspect_err(|err| warn!("cannot wait for warm-up: {err}"))
                    .unwrap_or_default(),
            );
            p.finish();
        }
    }
    Ok(())
}

/// Warm up the repository.
///
/// # Arguments
///
/// * `repo` - The repository to warm up.
/// * `tpe` - The filetype of the ids.
/// * `ids` - The ids to warm up.
///
/// # Errors
///
/// * If the command could not be parsed.
/// * If the thread pool could not be created.
pub(crate) fn warm_up<S>(
    repo: &Repository<S>,
    tpe: FileType,
    ids: impl ExactSizeIterator<Item = Id>,
) -> RusticResult<()> {
    if ids.len() > 0 {
        if let Some(warm_up_cmd) = &repo.opts.warm_up_command {
            warm_up_command(
                tpe,
                ids,
                warm_up_cmd,
                repo,
                &WarmUpType::WarmUp,
                repo.opts.warm_up_batch.unwrap_or(1),
                &repo.be,
            )?;
        } else if repo.be.needs_warm_up() {
            warm_up_repo(repo, tpe, ids)?;
        }
    }
    Ok(())
}

#[derive(Debug)]
enum WarmUpType {
    WarmUp,
    Wait,
}

/// Warm up the repository using a command.
///
/// # Arguments
///
/// * `tpe` - The filetype of the ids.
/// * `ids` - The ids to warm up.
/// * `command` - The command to execute.
/// * `pb` - The progress bar to use.
/// * `ty` - The type of warm-up operation.
/// * `batch_size` - The number of ids to process in each batch.
/// * `backend` - The backend to get id paths from.
///
/// # Errors
///
/// * If the command could not be parsed.
fn warm_up_command<S>(
    tpe: FileType,
    ids: impl ExactSizeIterator<Item = Id>,
    command: &CommandInput,
    repo: &Repository<S>,
    ty: &WarmUpType,
    batch_size: usize,
    backend: &impl ReadBackend,
) -> RusticResult<()> {
    let use_plural = command.uses_plural_placeholders()?;

    let total = ids.len();

    let p = repo.progress_counter(&match ty {
        WarmUpType::WarmUp => format!("warming up {tpe}(s)..."),
        WarmUpType::Wait => format!("waiting for {tpe}(s) to be ready..."),
    });
    p.set_length(total as u64);

    let chunks = ids.chunks(batch_size);
    for batch in &chunks {
        let batch: Vec<_> = batch.collect();
        if use_plural {
            warm_up_batch_plural(tpe, &batch, command, ty, backend, &p)?;
        } else {
            warm_up_batch_singular(tpe, &batch, command, ty, backend, &p)?;
        }
    }

    p.finish();
    Ok(())
}

/// Warm up a batch of ids using singular mode (one command per id).
///
/// # Arguments
///
/// * `tpe` - The filetype of the ids.
/// * `batch` - The ids in this batch.
/// * `command` - The command to execute.
/// * `pb` - The progress bar to use.
/// * `ty` - The type of warm-up operation.
/// * `backend` - The backend to get id paths from.
/// * `progress` - The progress bar to update.
///
/// # Errors
///
/// * If the command could not be parsed.
fn warm_up_batch_singular(
    tpe: FileType,
    batch: &[Id],
    command: &CommandInput,
    ty: &WarmUpType,
    backend: &impl ReadBackend,
    progress: &Progress,
) -> RusticResult<()> {
    let file_type = tpe.to_string();
    let children: Vec<_> = batch
        .iter()
        .map(|id| {
            let path = backend.warmup_path(tpe, id);
            let id = id.to_hex().to_string();

            let args: Vec<_> = command
                .args()
                .iter()
                .map(|c| {
                    c.replace("%tpe", &file_type)
                        .replace("%id", &id)
                        .replace("%path", &path)
                })
                .collect();

            debug!("spawning {command:?} for id {id:?}...");

            let child = (|| Command::new(command.command()).args(&args).spawn())
                .retry(execute_cmd_retry())
                .when(|err| err.kind() == io::ErrorKind::ExecutableFileBusy)
                .notify(|err, duration| {
                    debug!("spawn failed with ETXTBSY, retrying in {duration:?}: {err}");
                })
                .call()
                .map_err(|err| {
                    RusticError::with_source(
                        ErrorKind::ExternalCommand,
                        "Error in spawning warm-up command `{command}`.",
                        err,
                    )
                    .attach_context("command", command.to_string())
                    .attach_context("id", &id)
                    .attach_context("type", format!("{ty:?}"))
                })?;

            Ok((child, id))
        })
        .collect::<RusticResult<Vec<_>>>()?;

    let mut failed_ids = Vec::new();

    for (mut child, id) in children {
        debug!("waiting for warm-up command for id {id}...");

        let status = child.wait().map_err(|err| {
            RusticError::with_source(
                ErrorKind::ExternalCommand,
                "Error waiting for warm-up command `{command}`.",
                err,
            )
            .attach_context("command", command.to_string())
            .attach_context("id", &id)
            .attach_context("type", format!("{ty:?}"))
        })?;

        if !status.success() {
            failed_ids.push((id, status));
        }

        progress.inc(1);
    }

    if !failed_ids.is_empty() {
        let error_msg = format!(
            "{ty:?} command failed for {}/{} id(s): {}",
            failed_ids.len(),
            batch.len(),
            failed_ids
                .iter()
                .map(|(id, status)| format!("{id:?} ({status})"))
                .collect::<Vec<_>>()
                .join(", ")
        );

        return Err(RusticError::new(ErrorKind::ExternalCommand, error_msg)
            .attach_context("command", command.to_string())
            .attach_context("failed_ids", failed_ids.len().to_string())
            .attach_context("total_ids", batch.len().to_string())
            .attach_context("type", format!("{ty:?}")));
    }

    Ok(())
}

/// Warm up a batch of ids using plural mode (single command with all values).
///
/// # Arguments
///
/// * `tpe` - The filetype of the ids.
/// * `batch` - The ids in this batch.
/// * `command` - The command to execute.
/// * `pb` - The progress bar to use.
/// * `ty` - The type of warm-up operation.
/// * `backend` - The backend to get id paths from.
/// * `progress` - The progress bar to update.
///
/// # Errors
///
/// * If the command could not be parsed.
fn warm_up_batch_plural(
    tpe: FileType,
    batch: &[Id],
    command: &CommandInput,
    ty: &WarmUpType,
    backend: &impl ReadBackend,
    progress: &Progress,
) -> RusticResult<()> {
    let file_type = tpe.to_string();
    let cmd_str = command.to_string();
    let use_ids = cmd_str.contains("%ids");
    let use_paths = cmd_str.contains("%paths");

    let mut args = Vec::new();

    for arg in command.args() {
        if use_ids && arg.contains("%ids") {
            args.extend(batch.iter().map(|id| id.to_hex().to_string()));
        } else if use_paths && arg.contains("%paths") {
            args.extend(
                batch
                    .iter()
                    .map(|id| backend.warmup_path(FileType::Pack, id)),
            );
        } else {
            args.push(arg.replace("%tpe", &file_type));
        }
    }

    debug!("calling {command:?} with {} id(s)...", batch.len());

    let status = (|| Command::new(command.command()).args(&args).status())
        .retry(execute_cmd_retry())
        .when(|err| err.kind() == io::ErrorKind::ExecutableFileBusy)
        .notify(|err, duration| {
            debug!("spawn failed with ETXTBSY, retrying in {duration:?}: {err}");
        })
        .call()
        .map_err(|err| {
            RusticError::with_source(
                ErrorKind::ExternalCommand,
                "Error in executing warm-up command `{command}`.",
                err,
            )
            .attach_context("command", command.to_string())
            .attach_context("type", format!("{ty:?}"))
        })?;

    if !status.success() {
        return Err(RusticError::new(
            ErrorKind::ExternalCommand,
            format!(
                "{ty:?} command failed for batch of {} id(s). {status}",
                batch.len()
            ),
        )
        .attach_context("command", command.to_string())
        .attach_context("batch_size", batch.len().to_string())
        .attach_context("status", status.to_string())
        .attach_context("type", format!("{ty:?}")));
    }

    progress.inc(batch.len() as u64);
    Ok(())
}

/// Warm up the repository.
///
/// # Arguments
///
/// * `repo` - The repository to warm up.
/// * `tpe` - The filetype of the ids
/// * `ids` - The ids to warm up.
///
/// # Errors
///
/// * If the thread pool could not be created.
fn warm_up_repo<S>(
    repo: &Repository<S>,
    tpe: FileType,
    ids: impl ExactSizeIterator<Item = Id>,
) -> RusticResult<()> {
    let progress_bar = repo.progress_counter("warming up {tpe}(s)...");
    progress_bar.set_length(ids.len() as u64);

    let pool = ThreadPoolBuilder::new()
        .num_threads(constants::MAX_READER_THREADS_NUM)
        .build()
        .map_err(|err| {
            RusticError::with_source(
                ErrorKind::Internal,
                "Failed to create thread pool for warm-up. Please try again.",
                err,
            )
        })?;
    let progress_bar_ref = &progress_bar;
    let backend = &repo.be;
    pool.in_place_scope(|scope| {
        for id in ids {
            scope.spawn(move |_| {
                if let Err(err) = backend.warm_up(tpe, &id) {
                    // FIXME: Use error handling
                    error!("warm-up failed for id {id:?}. {}", err.display_log());
                }
                progress_bar_ref.inc(1);
            });
        }
    });

    progress_bar_ref.finish();

    Ok(())
}