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
|
//! The files this node reads and writes for itself, and how much it did (`/admin/stats`,
//! `disk`): the state file (`swarm::state_file`), the document file
//! (`document::file`) and a backup to recover from (`swarm::bootstrap`). Not the
//! Mycelium daemon's files, configuration or logs.
//!
//! Writes replace a file atomically: a temporary file next to it, flushed to disk, then
//! renamed over it, so a crash leaves the old content or the new one. Appends add to the
//! end and are flushed to disk before they count as done; a crash may leave the last one
//! cut short, which the file's reader has to expect.
use crate::locks::MutexExt;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard};
/// What a file is, for the counts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FileKind {
State,
Document,
Backup,
/// The input of a genesis remake (`--genesis --remake`).
Remake,
}
impl FileKind {
pub(crate) const ALL: [FileKind; 4] = [
FileKind::State,
FileKind::Document,
FileKind::Backup,
FileKind::Remake,
];
pub(crate) fn as_str(self) -> &'static str {
match self {
FileKind::State => "state",
FileKind::Document => "document",
FileKind::Backup => "backup",
FileKind::Remake => "remake",
}
}
fn index(self) -> usize {
self as usize
}
}
/// Counts for one kind of file, since the node started.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Counts {
pub(crate) reads: u64,
pub(crate) read_bytes: u64,
/// Whole files written.
pub(crate) writes: u64,
pub(crate) written_bytes: u64,
pub(crate) appends: u64,
pub(crate) appended_bytes: u64,
/// Reads, writes or appends that failed (a missing file read is no failure).
pub(crate) errors: u64,
}
/// Reads and writes this node's files, counting per kind.
#[derive(Default)]
pub(crate) struct Files {
// A std mutex: every access is short and never spans an await.
counts: Mutex<[Counts; FileKind::ALL.len()]>,
}
impl Files {
fn lock(&self) -> MutexGuard<'_, [Counts; FileKind::ALL.len()]> {
self.counts.lock_or_recover()
}
fn count(&self, kind: FileKind, f: impl FnOnce(&mut Counts)) {
f(&mut self.lock()[kind.index()]);
}
/// The file's content; None if it doesn't exist.
pub(crate) fn read(&self, kind: FileKind, path: &Path) -> std::io::Result<Option<Vec<u8>>> {
match std::fs::read(path) {
Ok(bytes) => {
self.count(kind, |counts| {
counts.reads += 1;
counts.read_bytes += bytes.len() as u64;
});
Ok(Some(bytes))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => {
self.count(kind, |counts| counts.errors += 1);
Err(error)
}
}
}
/// Replaces the file's content atomically (see the module docs).
pub(crate) fn write_atomic(
&self,
kind: FileKind,
path: &Path,
bytes: &[u8],
) -> std::io::Result<()> {
let result = write_atomic(path, bytes);
self.count(kind, |counts| match &result {
Ok(()) => {
counts.writes += 1;
counts.written_bytes += bytes.len() as u64;
}
Err(_) => counts.errors += 1,
});
result
}
/// Adds `bytes` to the end of the file (which must exist), flushed to disk.
pub(crate) fn append(&self, kind: FileKind, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
let result = (|| {
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
file.write_all(bytes)?;
file.sync_data()
})();
self.count(kind, |counts| match &result {
Ok(()) => {
counts.appends += 1;
counts.appended_bytes += bytes.len() as u64;
}
Err(_) => counts.errors += 1,
});
result
}
/// Moves an unusable file aside (`<path><suffix>`), returning where to.
pub(crate) fn move_aside(&self, path: &Path, suffix: &str) -> std::io::Result<PathBuf> {
let aside = with_suffix(path, suffix);
std::fs::rename(path, &aside)?;
Ok(aside)
}
/// The counts per kind.
pub(crate) fn counts(&self) -> Vec<(FileKind, Counts)> {
let counts = *self.lock();
FileKind::ALL
.into_iter()
.map(|kind| (kind, counts[kind.index()]))
.collect()
}
}
fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
let temporary = with_suffix(path, ".tmp");
{
let mut file = std::fs::File::create(&temporary)?;
file.write_all(bytes)?;
file.sync_all()?;
}
std::fs::rename(&temporary, path)?;
sync_parent(path);
Ok(())
}
/// Makes a rename in `path`'s directory durable (best effort: not every platform syncs
/// directories).
fn sync_parent(path: &Path) {
if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty())
&& let Ok(dir) = std::fs::File::open(dir)
{
let _ = dir.sync_all();
}
}
/// A key file's bytes: read from `path`; or with `create`, if there is no file there,
/// `len` random bytes in a new one only its owner may read (then also `true`). Without
/// `create`, a missing file is an error saying to give `create_option` (`what`: which
/// key; `hint`: what a new one means). Never created where a file is: a mistyped path
/// stays an error unless asked.
pub(crate) fn key_file(
path: &Path,
what: &str,
create: bool,
create_option: &str,
hint: &str,
len: usize,
) -> anyhow::Result<(Vec<u8>, bool)> {
use anyhow::Context;
use std::io::Write;
match std::fs::read(path) {
Ok(bytes) => {
warn_if_readable_by_others(path, what);
Ok((bytes, false))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
if !create {
anyhow::bail!(
"The {what} file {} doesn't exist; add --{create_option} to create a new {what} there ({hint})",
path.display()
);
}
let mut bytes = vec![0u8; len];
getrandom::fill(&mut bytes)
.map_err(|error| anyhow::anyhow!("No randomness: {error}"))?;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let written = (|| {
let mut file = options.open(path)?;
file.write_all(&bytes)?;
file.sync_all()
})();
written.with_context(|| format!("Creating the {what} file {}", path.display()))?;
Ok((bytes, true))
}
Err(error) => {
Err(error).with_context(|| format!("Reading the {what} from {}", path.display()))
}
}
}
/// A key is a secret: a file others may read is worth a warning (not an error: a
/// group may be deliberate, e.g. shared with a deployment tool). `what`: which key.
pub(crate) fn warn_if_readable_by_others(path: &Path, what: &str) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Ok(metadata) = std::fs::metadata(path) {
let mode = metadata.permissions().mode();
if mode & 0o077 != 0 {
tracing::warn!(
path = %path.display(),
mode = format!("{:o}", mode & 0o777),
"The {what} file is readable by others than its owner; chmod 600 it"
);
}
}
}
#[cfg(not(unix))]
let _ = (path, what);
}
fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(suffix);
PathBuf::from(name)
}
/// An empty directory for the test `name`: `continuum-<name>-<process ID>` in the
/// temporary directory, emptied first.
#[cfg(test)]
pub(crate) fn scratch_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("continuum-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writes_reads_and_counts() {
let dir = scratch_dir("files");
let path = dir.join("state.json");
let files = Files::default();
assert_eq!(files.read(FileKind::State, &path).unwrap(), None);
files.write_atomic(FileKind::State, &path, b"one").unwrap();
files
.write_atomic(FileKind::State, &path, b"three")
.unwrap();
assert_eq!(
files.read(FileKind::State, &path).unwrap().as_deref(),
Some(&b"three"[..])
);
assert!(!with_suffix(&path, ".tmp").exists());
let (kind, state) = files.counts()[0];
assert_eq!(kind, FileKind::State);
assert_eq!((state.writes, state.written_bytes), (2, 8));
assert_eq!((state.reads, state.read_bytes, state.errors), (1, 5, 0));
files.append(FileKind::State, &path, b"!").unwrap();
assert_eq!(
files.read(FileKind::State, &path).unwrap().as_deref(),
Some(&b"three!"[..])
);
assert_eq!(files.counts()[0].1.appended_bytes, 1);
assert_eq!(files.counts()[1].1.reads, 0);
std::fs::remove_dir_all(&dir).unwrap();
}
}
|