summaryrefslogtreecommitdiff
path: root/src/client.rs
blob: 515b8c93a6d85a3caeb62275e01085bcbf40b085 (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
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
use crate::checksummer::sha256;
use crate::chunk::DataChunk;
use crate::chunk::GenerationChunk;
use crate::chunker::Chunker;
use crate::chunkid::ChunkId;
use crate::chunkmeta::ChunkMeta;
use crate::error::ObnamError;
use crate::fsentry::{FilesystemEntry, FilesystemKind};
use crate::generation::{FinishedGeneration, LocalGeneration};
use crate::genlist::GenerationList;

use anyhow::Context;
use chrono::{DateTime, Local};
use log::{debug, error, info, trace};
use reqwest::blocking::Client;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};

#[derive(Debug, Deserialize, Clone)]
pub struct ClientConfig {
    pub server_url: String,
    pub root: PathBuf,
    pub log: Option<PathBuf>,
}

impl ClientConfig {
    pub fn read_config(filename: &Path) -> anyhow::Result<Self> {
        trace!("read_config: filename={:?}", filename);
        let config = std::fs::read_to_string(filename)
            .with_context(|| format!("reading configuration file {}", filename.display()))?;
        let config = serde_yaml::from_str(&config)?;
        Ok(config)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ClientError {
    #[error("Server successful response to creating chunk lacked chunk id")]
    NoCreatedChunkId,

    #[error("Server does not have chunk {0}")]
    ChunkNotFound(String),

    #[error("Server does not have generation {0}")]
    GenerationNotFound(String),
}

pub struct BackupClient {
    client: Client,
    base_url: String,
}

impl BackupClient {
    pub fn new(base_url: &str) -> anyhow::Result<Self> {
        let client = Client::builder()
            .danger_accept_invalid_certs(true)
            .build()?;
        Ok(Self {
            client,
            base_url: base_url.to_string(),
        })
    }

    pub fn upload_filesystem_entry(
        &self,
        e: &FilesystemEntry,
        size: usize,
    ) -> anyhow::Result<Vec<ChunkId>> {
        info!("upload entry: {:?}", e);
        let ids = match e.kind() {
            FilesystemKind::Regular => self.read_file(e.pathbuf(), size)?,
            FilesystemKind::Directory => vec![],
            FilesystemKind::Symlink => vec![],
        };
        Ok(ids)
    }

    pub fn upload_generation(&self, filename: &Path, size: usize) -> anyhow::Result<ChunkId> {
        info!("upload SQLite {}", filename.display());
        let ids = self.read_file(filename.to_path_buf(), size)?;
        let gen = GenerationChunk::new(ids);
        let data = gen.to_data_chunk()?;
        let meta = ChunkMeta::new_generation(&sha256(data.data()), &current_timestamp());
        let gen_id = self.upload_gen_chunk(meta.clone(), gen)?;
        info!("uploaded generation {}, meta {:?}", gen_id, meta);
        Ok(gen_id)
    }

    fn read_file(&self, filename: PathBuf, size: usize) -> anyhow::Result<Vec<ChunkId>> {
        info!("upload file {}", filename.display());
        let file = std::fs::File::open(filename)?;
        let chunker = Chunker::new(size, file);
        let chunk_ids = self.upload_new_file_chunks(chunker)?;
        Ok(chunk_ids)
    }

    fn base_url(&self) -> &str {
        &self.base_url
    }

    fn chunks_url(&self) -> String {
        format!("{}/chunks", self.base_url())
    }

    pub fn has_chunk(&self, meta: &ChunkMeta) -> anyhow::Result<Option<ChunkId>> {
        trace!("has_chunk: url={:?}", self.base_url());
        let req = self
            .client
            .get(&self.chunks_url())
            .query(&[("sha256", meta.sha256())])
            .build()?;

        let res = self.client.execute(req)?;
        debug!("has_chunk: status={}", res.status());
        let has = if res.status() != 200 {
            debug!("has_chunk: error from server");
            None
        } else {
            let text = res.text()?;
            debug!("has_chunk: text={:?}", text);
            let hits: HashMap<String, ChunkMeta> = serde_json::from_str(&text)?;
            debug!("has_chunk: hits={:?}", hits);
            let mut iter = hits.iter();
            if let Some((chunk_id, _)) = iter.next() {
                debug!("has_chunk: chunk_id={:?}", chunk_id);
                Some(chunk_id.into())
            } else {
                None
            }
        };

        info!("has_chunk result: {:?}", has);
        Ok(has)
    }

    pub fn upload_chunk(&self, meta: ChunkMeta, chunk: DataChunk) -> anyhow::Result<ChunkId> {
        let res = self
            .client
            .post(&self.chunks_url())
            .header("chunk-meta", meta.to_json())
            .body(chunk.data().to_vec())
            .send()?;
        debug!("upload_chunk: res={:?}", res);
        let res: HashMap<String, String> = res.json()?;
        let chunk_id = if let Some(chunk_id) = res.get("chunk_id") {
            debug!("upload_chunk: id={}", chunk_id);
            chunk_id.parse().unwrap()
        } else {
            return Err(ClientError::NoCreatedChunkId.into());
        };
        info!("uploaded_chunk {} meta {:?}", chunk_id, meta);
        Ok(chunk_id)
    }

    pub fn upload_gen_chunk(
        &self,
        meta: ChunkMeta,
        gen: GenerationChunk,
    ) -> anyhow::Result<ChunkId> {
        let res = self
            .client
            .post(&self.chunks_url())
            .header("chunk-meta", meta.to_json())
            .body(serde_json::to_string(&gen)?)
            .send()?;
        debug!("upload_chunk: res={:?}", res);
        let res: HashMap<String, String> = res.json()?;
        let chunk_id = if let Some(chunk_id) = res.get("chunk_id") {
            debug!("upload_chunk: id={}", chunk_id);
            chunk_id.parse().unwrap()
        } else {
            return Err(ClientError::NoCreatedChunkId.into());
        };
        info!("uploaded_generation chunk {}", chunk_id);
        Ok(chunk_id)
    }

    pub fn upload_new_file_chunks(&self, chunker: Chunker) -> anyhow::Result<Vec<ChunkId>> {
        let mut chunk_ids = vec![];
        for item in chunker {
            let (meta, chunk) = item?;
            if let Some(chunk_id) = self.has_chunk(&meta)? {
                chunk_ids.push(chunk_id.clone());
                info!("reusing existing chunk {}", chunk_id);
            } else {
                let chunk_id = self.upload_chunk(meta, chunk)?;
                chunk_ids.push(chunk_id.clone());
                info!("created new chunk {}", chunk_id);
            }
        }

        Ok(chunk_ids)
    }

    pub fn list_generations(&self) -> anyhow::Result<GenerationList> {
        let url = format!("{}?generation=true", &self.chunks_url());
        trace!("list_generations: url={:?}", url);
        let req = self.client.get(&url).build()?;
        let res = self.client.execute(req)?;
        debug!("list_generations: status={}", res.status());
        let body = res.bytes()?;
        debug!("list_generations: body={:?}", body);
        let map: HashMap<String, ChunkMeta> = serde_yaml::from_slice(&body)?;
        debug!("list_generations: map={:?}", map);
        let finished = map
            .iter()
            .map(|(id, meta)| FinishedGeneration::new(id, meta.ended().map_or("", |s| s)))
            .collect();
        Ok(GenerationList::new(finished))
    }

    pub fn fetch_chunk(&self, chunk_id: &ChunkId) -> anyhow::Result<DataChunk> {
        info!("fetch chunk {}", chunk_id);

        let url = format!("{}/{}", &self.chunks_url(), chunk_id);
        let req = self.client.get(&url).build()?;
        let res = self.client.execute(req)?;
        if res.status() != 200 {
            let err = ClientError::ChunkNotFound(chunk_id.to_string());
            error!("fetching chunk {} failed: {}", chunk_id, err);
            return Err(err.into());
        }

        let headers = res.headers();
        let meta = headers.get("chunk-meta");
        if meta.is_none() {
            let err = ObnamError::NoChunkMeta(chunk_id.clone());
            error!("fetching chunk {} failed: {}", chunk_id, err);
            return Err(err.into());
        }
        let meta = meta.unwrap().to_str()?;
        debug!("fetching chunk {}: meta={:?}", chunk_id, meta);
        let meta: ChunkMeta = serde_json::from_str(meta)?;
        debug!("fetching chunk {}: meta={:?}", chunk_id, meta);

        let body = res.bytes()?;
        let body = body.to_vec();
        let actual = sha256(&body);
        if actual != meta.sha256() {
            let err =
                ObnamError::WrongChecksum(chunk_id.clone(), actual, meta.sha256().to_string());
            error!("fetching chunk {} failed: {}", chunk_id, err);
            return Err(err.into());
        }

        let chunk: DataChunk = DataChunk::new(body);

        Ok(chunk)
    }

    fn fetch_generation_chunk(&self, gen_id: &str) -> anyhow::Result<GenerationChunk> {
        let chunk_id = ChunkId::from_str(gen_id);
        let chunk = self.fetch_chunk(&chunk_id)?;
        let gen = GenerationChunk::from_data_chunk(&chunk)?;
        Ok(gen)
    }

    pub fn fetch_generation(&self, gen_id: &str, dbname: &Path) -> anyhow::Result<LocalGeneration> {
        let gen = self.fetch_generation_chunk(gen_id)?;

        // Fetch the SQLite file, storing it in the named file.
        let mut dbfile = File::create(&dbname)?;
        for id in gen.chunk_ids() {
            let chunk = self.fetch_chunk(id)?;
            dbfile.write_all(chunk.data())?;
        }
        info!("downloaded generation to {}", dbname.display());

        let gen = LocalGeneration::open(dbname)?;
        Ok(gen)
    }
}

fn current_timestamp() -> String {
    let now: DateTime<Local> = Local::now();
    format!("{}", now.format("%Y-%m-%d %H:%M:%S.%f %z"))
}