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
|
//! Snapshots on disk, and the views in place (docs/design.md, 5.8).
//!
//! ```text
//! STATE/lock
//! STATE/channels/CHANNEL/current -> snapshots/ID
//! STATE/channels/CHANNEL/snapshots/ID/snapshot.json id, and the id it was built on
//! STATE/channels/CHANNEL/snapshots/ID/schema.json the schema it was accepted under
//! STATE/channels/CHANNEL/snapshots/ID/entries/SLOT
//! STATE/channels/CHANNEL/snapshots/ID/kept/SLOT what no slot wanted, types in snapshot.json
//! STATE/incoming/NAME/ submissions for the next --migrate
//! STATE/refused/NAME/ those it refused
//! STATE/migrate-due something was staged for the next switch
//! RUN/views/VIEW -> .generations/VIEW.ID
//! RUN/tmp/ scratch
//! ```
//!
//! Entries are root's (mode 0600). A new snapshot or view generation is written
//! next to the old one and put in place by replacing a symbolic link, so a reader
//! sees one or the other, never a mix.
use std::fs::File;
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use crate::content::{self, Content};
use crate::scratch::Scratch;
/// Entries kept: by slot name, the type each had, and the entry.
pub type Kept = std::collections::BTreeMap<String, (String, Vec<u8>)>;
pub struct Store {
pub state: PathBuf,
pub run: PathBuf,
}
#[derive(Debug, Clone)]
pub struct Snapshot {
pub id: String,
pub base: Option<String>,
pub content: Content,
/// Entries no slot of the schema it was accepted under wanted, by slot name, with
/// the types they had (docs/design.md, section 6).
pub kept: Kept,
/// The schema it was accepted under, as it was.
pub schema: Vec<u8>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SnapshotFile {
id: String,
channel: String,
base: Option<String>,
/// The types of the entries in `kept/`.
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
kept: std::collections::BTreeMap<String, String>,
}
/// Held while the store is used; released when dropped.
pub struct Lock(#[allow(dead_code)] File);
impl Store {
/// The store in `state` and `run`, made absolute: programs run in a directory of
/// their own.
pub fn new(state: &Path, run: &Path) -> Self {
let absolute = |path: &Path| std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
Self {
state: absolute(state),
run: absolute(run),
}
}
/// Waits for, and takes, the store's lock: one receptor at a time.
pub fn lock(&self) -> Result<Lock> {
create_dir(&self.state, 0o700)?;
let path = self.state.join("lock");
let file = File::options()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.with_context(|| format!("opening {}", path.display()))?;
file.lock()
.with_context(|| format!("locking {}", path.display()))?;
Ok(Lock(file))
}
/// Where programs get their scratch directories.
pub fn scratch(&self) -> PathBuf {
self.run.join("tmp")
}
fn channel_dir(&self, channel: &str) -> PathBuf {
self.state.join("channels").join(channel)
}
/// The channels that have a snapshot.
pub fn channels(&self) -> Result<Vec<String>> {
let dir = self.state.join("channels");
let mut channels = Vec::new();
match std::fs::read_dir(&dir) {
Ok(entries) => {
for entry in entries {
if let Ok(name) = entry?.file_name().into_string() {
channels.push(name);
}
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())),
}
channels.sort();
Ok(channels)
}
/// The current snapshot of `channel`, if there is one.
pub fn current(&self, channel: &str) -> Result<Option<Snapshot>> {
let link = self.channel_dir(channel).join("current");
let target = match std::fs::read_link(&link) {
Ok(target) => target,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error).with_context(|| format!("reading {}", link.display())),
};
let dir = self.channel_dir(channel).join(target);
let path = dir.join("snapshot.json");
let file: SnapshotFile = serde_json::from_slice(
&std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
)
.with_context(|| format!("reading {}", path.display()))?;
if file.channel != channel {
bail!("{} is of channel {}", path.display(), file.channel);
}
let schema = std::fs::read(dir.join("schema.json"))
.with_context(|| format!("reading {}", dir.join("schema.json").display()))?;
let mut kept_entries = content::read_dir(&dir.join("kept"))?;
let mut kept = Kept::new();
for (slot, media_type) in file.kept {
let bytes = kept_entries
.remove(&slot)
.with_context(|| format!("{}: kept {slot} is missing", dir.display()))?;
kept.insert(slot, (media_type, bytes));
}
if let Some(slot) = kept_entries.keys().next() {
bail!("{}: kept {slot} has no type", dir.display());
}
Ok(Some(Snapshot {
id: file.id,
base: file.base,
content: content::read_dir(&dir.join("entries"))?,
kept,
schema,
}))
}
/// Makes `content`, and `kept`, the current snapshot of `channel`, accepted under
/// `schema`, built on `base`; returns its id. The snapshot it replaces is removed.
pub fn commit(
&self,
channel: &str,
content: &Content,
kept: &Kept,
base: Option<&str>,
schema: &[u8],
) -> Result<String> {
let id = crate::new_id()?;
let snapshots = self.channel_dir(channel).join("snapshots");
create_dir(&snapshots, 0o700)?;
let new = snapshots.join(format!(".{id}.new"));
create_dir(&new, 0o700)?;
let file = SnapshotFile {
id: id.clone(),
channel: channel.to_owned(),
base: base.map(str::to_owned),
kept: kept
.iter()
.map(|(slot, (media_type, _))| (slot.clone(), media_type.clone()))
.collect(),
};
content::write_file(
&new.join("snapshot.json"),
&serde_json::to_vec_pretty(&file)?,
0o600,
)?;
content::write_file(&new.join("schema.json"), schema, 0o600)?;
content::write_dir(content, &new.join("entries"), 0o600)?;
if !kept.is_empty() {
let kept: Content = kept
.iter()
.map(|(slot, (_, bytes))| (slot.clone(), bytes.clone()))
.collect();
content::write_dir(&kept, &new.join("kept"), 0o600)?;
}
std::fs::rename(&new, snapshots.join(&id))?;
let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok();
replace_link(
&self.channel_dir(channel).join("current"),
&Path::new("snapshots").join(&id),
)?;
if let Some(old) = old {
std::fs::remove_dir_all(self.channel_dir(channel).join(old))?;
}
Ok(id)
}
/// Where submissions wait for the next `--migrate`, each in a directory of its own,
/// taken in the order of their names.
pub fn incoming_dir(&self) -> PathBuf {
self.state.join("incoming")
}
/// Where `--migrate` moves incoming submissions it refused.
pub fn refused_dir(&self) -> PathBuf {
self.state.join("refused")
}
/// A marker that a submission was staged, so the next switch serves the views
/// anew (`--migrate`), even if the schema doesn't change. `--migrate` removes it.
pub fn migrate_due(&self) -> PathBuf {
self.state.join("migrate-due")
}
/// The submissions waiting in the incoming directory, in order.
pub fn incoming(&self) -> Result<Vec<PathBuf>> {
let dir = self.incoming_dir();
let mut submissions = Vec::new();
match std::fs::read_dir(&dir) {
Ok(entries) => {
for entry in entries {
let entry = entry?;
if entry.file_type()?.is_dir()
&& !entry.file_name().to_string_lossy().starts_with('.')
{
submissions.push(entry.path());
}
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())),
}
submissions.sort();
Ok(submissions)
}
/// A copy of the snapshots in `dir`, as a store with the same views: for a dry run
/// that applies submissions without changing anything.
pub fn copy_to(&self, dir: &Path) -> Result<Store> {
copy_tree(&self.state.join("channels"), &dir.join("channels"))?;
Ok(Store {
state: dir.to_owned(),
run: self.run.clone(),
})
}
/// The views in place.
pub fn installed_views(&self) -> Result<Vec<String>> {
let views = self.run.join("views");
let mut names = Vec::new();
let entries = match std::fs::read_dir(&views) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(names),
Err(error) => {
return Err(error).with_context(|| format!("reading {}", views.display()));
}
};
for entry in entries {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
if entry.file_type()?.is_symlink() && !name.ends_with(".new-link") {
names.push(name);
}
}
names.sort();
Ok(names)
}
/// The directory the view `name` is in place at, if it is.
pub fn installed_view(&self, name: &str) -> Option<PathBuf> {
let link = self.run.join("views").join(name);
std::fs::read_link(&link).ok()?;
Some(link)
}
/// Puts what was rendered for the view `name` in place (or, if nothing was, takes
/// it away), readable by root only if it is secret.
pub fn install_view(&self, name: &str, rendered: Option<Scratch>, secret: bool) -> Result<()> {
let views = self.run.join("views");
create_dir(&views, 0o755)?;
let link = views.join(name);
let old = std::fs::read_link(&link).ok();
match rendered {
Some(rendered) => {
let generations = views.join(".generations");
create_dir(&generations, 0o755)?;
let mode = if secret { 0o600 } else { 0o644 };
rendered.set_modes(mode)?;
let target = Path::new(".generations").join(format!("{name}.{}", crate::new_id()?));
std::fs::rename(rendered.path(), views.join(&target))
.with_context(|| format!("moving view {name} in place"))?;
rendered.keep();
replace_link(&link, &target)?;
}
None => {
if old.is_some() {
std::fs::remove_file(&link)?;
}
}
}
if let Some(old) = old {
std::fs::remove_dir_all(views.join(old))?;
}
Ok(())
}
}
fn create_dir(path: &Path, mode: u32) -> Result<()> {
std::fs::DirBuilder::new()
.recursive(true)
.mode(mode)
.create(path)
.with_context(|| format!("creating {}", path.display()))
}
/// Points the symbolic link `link` at `target`, atomically.
fn replace_link(link: &Path, target: &Path) -> Result<()> {
let name = link.file_name().unwrap_or_default().to_string_lossy();
let new = link.with_file_name(format!(".{name}.new-link"));
let _ = std::fs::remove_file(&new);
std::os::unix::fs::symlink(target, &new)?;
std::fs::rename(&new, link).with_context(|| format!("replacing {}", link.display()))
}
/// Copies the tree `from` to `to`: directories, regular files and symbolic links. A
/// missing `from` copies nothing.
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
let entries = match std::fs::read_dir(from) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("reading {}", from.display())),
};
create_dir(to, 0o700)?;
for entry in entries {
let entry = entry?;
let (source, target) = (entry.path(), to.join(entry.file_name()));
let kind = entry.file_type()?;
if kind.is_symlink() {
std::os::unix::fs::symlink(std::fs::read_link(&source)?, &target)?;
} else if kind.is_dir() {
copy_tree(&source, &target)?;
} else {
std::fs::copy(&source, &target)
.with_context(|| format!("copying {}", source.display()))?;
}
}
Ok(())
}
|