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
|
//! 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
//! 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;
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,
/// 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>,
}
/// 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()))?;
Ok(Some(Snapshot {
id: file.id,
base: file.base,
content: content::read_dir(&dir.join("entries"))?,
schema,
}))
}
/// Makes `content` 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,
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),
};
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)?;
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)
}
/// 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()))
}
|