summaryrefslogtreecommitdiff
path: root/src/backup_run.rs
blob: b01b365ad0727ed165e313aeaf818f1518a872c4 (plain)
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
use crate::backup_progress::BackupProgress;
use crate::backup_reason::Reason;
use crate::chunkid::ChunkId;
use crate::client::{BackupClient, ClientError};
use crate::config::ClientConfig;
use crate::error::ObnamError;
use crate::fsentry::FilesystemEntry;
use crate::fsiter::{AnnotatedFsEntry, FsIterError, FsIterator};
use crate::generation::{LocalGeneration, LocalGenerationError, NascentError, NascentGeneration};
use crate::policy::BackupPolicy;
use log::{info, warn};
use std::path::{Path, PathBuf};

pub struct BackupRun<'a> {
    client: &'a BackupClient,
    policy: BackupPolicy,
    buffer_size: usize,
    progress: BackupProgress,
}

#[derive(Debug, thiserror::Error)]
pub enum BackupError {
    #[error(transparent)]
    ClientError(#[from] ClientError),

    #[error(transparent)]
    FsIterError(#[from] FsIterError),

    #[error(transparent)]
    LocalGenerationError(#[from] LocalGenerationError),
}

#[derive(Debug)]
pub struct FsEntryBackupOutcome {
    pub entry: FilesystemEntry,
    pub ids: Vec<ChunkId>,
    pub reason: Reason,
    pub is_cachedir_tag: bool,
}

impl<'a> BackupRun<'a> {
    pub fn initial(config: &ClientConfig, client: &'a BackupClient) -> Result<Self, BackupError> {
        Ok(Self {
            client,
            policy: BackupPolicy::default(),
            buffer_size: config.chunk_size,
            progress: BackupProgress::initial(),
        })
    }

    pub fn incremental(
        config: &ClientConfig,
        client: &'a BackupClient,
    ) -> Result<Self, BackupError> {
        Ok(Self {
            client,
            policy: BackupPolicy::default(),
            buffer_size: config.chunk_size,
            progress: BackupProgress::incremental(),
        })
    }

    pub fn start(
        &mut self,
        genid: Option<&str>,
        oldname: &Path,
    ) -> Result<LocalGeneration, ObnamError> {
        match genid {
            None => {
                // Create a new, empty generation.
                NascentGeneration::create(oldname)?;

                // Open the newly created empty generation.
                Ok(LocalGeneration::open(oldname)?)
            }
            Some(genid) => {
                let old = self.fetch_previous_generation(genid, oldname)?;
                self.progress
                    .files_in_previous_generation(old.file_count()? as u64);
                Ok(old)
            }
        }
    }

    fn fetch_previous_generation(
        &self,
        genid: &str,
        oldname: &Path,
    ) -> Result<LocalGeneration, ObnamError> {
        let progress = BackupProgress::download_generation(genid);
        let old = self.client.fetch_generation(genid, &oldname)?;
        progress.finish();
        Ok(old)
    }

    pub fn finish(&self) {
        self.progress.finish();
    }

    pub fn backup_roots(
        &self,
        config: &ClientConfig,
        old: &LocalGeneration,
        newpath: &Path,
        // TODO: turn this tuple into a struct for readability
    ) -> Result<(i64, Vec<BackupError>, Vec<PathBuf>), NascentError> {
        let mut all_warnings = vec![];
        let mut new_cachedir_tags = vec![];
        let count = {
            let mut new = NascentGeneration::create(newpath)?;
            for root in &config.roots {
                let iter = FsIterator::new(root, config.exclude_cache_tag_directories);
                let entries = iter.map(|entry| {
                    if let Ok(ref entry) = entry {
                        let path = entry.inner.pathbuf();
                        if entry.is_cachedir_tag && !old.is_cachedir_tag(&path)? {
                            new_cachedir_tags.push(path);
                        }
                    };
                    self.backup(entry, &old)
                });
                let mut warnings = new.insert_iter(entries)?;
                all_warnings.append(&mut warnings);
            }
            new.file_count()
        };
        self.finish();
        Ok((count, all_warnings, new_cachedir_tags))
    }

    pub fn backup(
        &self,
        entry: Result<AnnotatedFsEntry, FsIterError>,
        old: &LocalGeneration,
    ) -> Result<FsEntryBackupOutcome, BackupError> {
        match entry {
            Err(err) => {
                warn!("backup: {}", err);
                self.found_problem();
                Err(BackupError::FsIterError(err))
            }
            Ok(entry) => {
                let path = &entry.inner.pathbuf();
                info!("backup: {}", path.display());
                self.found_live_file(path);
                let reason = self.policy.needs_backup(&old, &entry.inner);
                match reason {
                    Reason::IsNew
                    | Reason::Changed
                    | Reason::GenerationLookupError
                    | Reason::Unknown => Ok(backup_file(
                        &self.client,
                        &entry,
                        &path,
                        self.buffer_size,
                        reason,
                    )),
                    Reason::Unchanged | Reason::Skipped | Reason::FileError => {
                        let fileno = old.get_fileno(&entry.inner.pathbuf())?;
                        let ids = if let Some(fileno) = fileno {
                            let mut ids = vec![];
                            for id in old.chunkids(fileno)?.iter()? {
                                ids.push(id?);
                            }
                            ids
                        } else {
                            vec![]
                        };
                        Ok(FsEntryBackupOutcome {
                            entry: entry.inner,
                            ids,
                            reason,
                            is_cachedir_tag: entry.is_cachedir_tag,
                        })
                    }
                }
            }
        }
    }

    fn found_live_file(&self, path: &Path) {
        self.progress.found_live_file(path);
    }

    fn found_problem(&self) {
        self.progress.found_problem();
    }
}

fn backup_file(
    client: &BackupClient,
    entry: &AnnotatedFsEntry,
    path: &Path,
    chunk_size: usize,
    reason: Reason,
) -> FsEntryBackupOutcome {
    let ids = client.upload_filesystem_entry(&entry.inner, chunk_size);
    match ids {
        Err(err) => {
            warn!("error backing up {}, skipping it: {}", path.display(), err);
            FsEntryBackupOutcome {
                entry: entry.inner.clone(),
                ids: vec![],
                reason: Reason::FileError,
                is_cachedir_tag: entry.is_cachedir_tag,
            }
        }
        Ok(ids) => FsEntryBackupOutcome {
            entry: entry.inner.clone(),
            ids,
            reason,
            is_cachedir_tag: entry.is_cachedir_tag,
        },
    }
}