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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
|
//! Migrations (docs/design.md, section 6): what a generation sees of the snapshots,
//! which were accepted under other schemas, and putting views in place for it.
//!
//! What a slot of the running schema is filled with, from the stored snapshot and the
//! schema it was accepted under, the first that fits:
//!
//! 1. the entry of the same name, of the same type;
//! 2. the entry of the name the slot says it was `renamedFrom`;
//! 3. the entry of a slot that says, in the stored schema, it was renamed from this
//! one: the way back after a rollback;
//! 4. an entry kept under the same name, of the same type, unless the stored snapshot
//! has an entry of that name: kept entries are older than any stored.
//!
//! Entries no slot takes are kept, with their types. A generation change never
//! rewrites a snapshot: what is seen is computed each time, and stored only when a
//! submission is applied. Not yet: converters, derived slots, steps.
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use anyhow::{Context, Result};
use serde::Serialize;
use crate::content::Content;
use crate::name::Address;
use crate::plan::{self, Plan, Reacting, ViewOutcome, react};
use crate::schema::{Reactions, Schema};
use crate::scratch::Scratch;
use crate::store::{Kept, Snapshot, Store};
use crate::submission::Submission;
use crate::view;
/// What the running generation sees of one channel.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Seen {
#[serde(skip)]
pub content: Content,
#[serde(skip)]
pub kept: Kept,
/// Where entries came from, where that isn't their own slot; what can't be taken.
pub notes: Vec<String>,
/// Required slots nothing fills.
pub unfilled: Vec<String>,
}
impl Seen {
/// The names of the entries kept.
pub fn kept_names(&self) -> Vec<String> {
self.kept.keys().cloned().collect()
}
}
/// What `schema` sees of `channel`, whose current snapshot is `snapshot`.
pub fn seen(schema: &Schema, channel: &str, snapshot: Option<&Snapshot>) -> Result<Seen> {
let mut seen = Seen::default();
let empty_slots = BTreeMap::new();
let slots = schema
.channel(channel)
.map(|spec| &spec.slots)
.unwrap_or(&empty_slots);
let Some(snapshot) = snapshot else {
seen.unfilled = slots
.iter()
.filter(|(_, spec)| spec.required)
.map(|(slot, _)| format!("{channel}/{slot}"))
.collect();
return Ok(seen);
};
let stored = Schema::from_slice(&snapshot.schema)
.with_context(|| format!("the schema channel {channel}'s snapshot was accepted under"))?;
let stored_slots = stored
.channel(channel)
.map(|spec| spec.slots.clone())
.unwrap_or_default();
let stored_type = |slot: &str| {
stored
.slot(&Address::entry(channel, slot))
.map(|spec| spec.media_type.clone())
};
let entries = &snapshot.content;
let mut taken: BTreeSet<&str> = BTreeSet::new();
let mut kept_taken: BTreeSet<&str> = BTreeSet::new();
let mut filled: BTreeSet<&str> = BTreeSet::new();
// 1. Same name, same type.
for (slot, spec) in slots {
let Some(bytes) = entries.get(slot) else {
continue;
};
match stored_type(slot) {
Some(media_type) if media_type == spec.media_type => {
seen.content.insert(slot.clone(), bytes.clone());
taken.insert(slot);
filled.insert(slot);
}
Some(media_type) => seen.notes.push(format!(
"{channel}/{slot}: type {media_type} is now {}, and there is no converter",
spec.media_type
)),
None => {}
}
}
// 2. Renamed from.
for (slot, spec) in slots {
if filled.contains(slot.as_str()) {
continue;
}
let Some(old) = &spec.renamed_from else {
continue;
};
if let Some(bytes) = entries.get(old)
&& !taken.contains(old.as_str())
&& stored_type(old).as_ref() == Some(&spec.media_type)
{
seen.content.insert(slot.clone(), bytes.clone());
seen.notes
.push(format!("{channel}/{slot}: from {channel}/{old}, renamed"));
taken.insert(old);
filled.insert(slot);
}
}
// 3. Renamed, by the stored schema, from this one.
for (slot, spec) in slots {
if filled.contains(slot.as_str()) {
continue;
}
let newer = stored_slots.iter().find(|(newer, newer_spec)| {
newer_spec.renamed_from.as_deref() == Some(slot.as_str())
&& newer_spec.media_type == spec.media_type
&& entries.contains_key(*newer)
&& !taken.contains(newer.as_str())
});
if let Some((newer, _)) = newer {
let (newer, bytes) = entries.get_key_value(newer).unwrap();
seen.content.insert(slot.clone(), bytes.clone());
seen.notes.push(format!(
"{channel}/{slot}: from {channel}/{newer}, which the schema it was accepted under renamed from it"
));
taken.insert(newer);
filled.insert(slot);
}
}
// 4. Kept, under the same name, of the same type, unless there is a newer entry
// of that name: what was kept is never used once its slot was filled anew.
for (slot, spec) in slots {
if filled.contains(slot.as_str()) {
continue;
}
if let Some((media_type, bytes)) = snapshot.kept.get(slot)
&& *media_type == spec.media_type
&& !entries.contains_key(slot)
{
seen.content.insert(slot.clone(), bytes.clone());
seen.notes
.push(format!("{channel}/{slot}: from what was kept"));
kept_taken.insert(slot);
filled.insert(slot);
}
}
for (slot, spec) in slots {
if spec.required && !filled.contains(slot.as_str()) {
seen.unfilled.push(format!("{channel}/{slot}"));
}
}
// What no slot took is kept: the stored entries, then what was kept before.
for (slot, bytes) in entries {
if !taken.contains(slot.as_str()) {
let media_type =
stored_type(slot).unwrap_or_else(|| "application/octet-stream".to_owned());
seen.kept.insert(slot.clone(), (media_type, bytes.clone()));
}
}
for (slot, kept) in &snapshot.kept {
if !kept_taken.contains(slot.as_str()) && !seen.kept.contains_key(slot) {
seen.kept.insert(slot.clone(), kept.clone());
}
}
Ok(seen)
}
/// What every channel of `schema` sees, by channel.
pub fn seen_all(schema: &Schema, store: &Store) -> Result<BTreeMap<String, Seen>> {
let mut all = BTreeMap::new();
let mut channels: BTreeSet<String> = schema.channels.keys().cloned().collect();
channels.extend(store.channels()?);
for channel in channels {
let snapshot = store.current(&channel)?;
all.insert(channel.clone(), seen(schema, &channel, snapshot.as_ref())?);
}
Ok(all)
}
/// Renders every view of `schema` from `seen`, and, unless `dry_run`, puts those that
/// differ from what is in place there, and takes away views the schema doesn't have.
/// Returns how each view changes.
pub fn put_views(
schema: &Schema,
store: &Store,
seen: &BTreeMap<String, Seen>,
dry_run: bool,
) -> Result<Vec<ViewOutcome>> {
let entries: view::Entries = seen
.iter()
.map(|(name, seen)| (name.as_str(), &seen.content))
.collect();
let mut outcomes = Vec::new();
for (name, view_spec) in schema.views_of(None) {
let secret = schema.view_is_secret(view_spec);
let rendered = view::render(schema, name, view_spec, &entries, &store.scratch())
.with_context(|| format!("view {name}"))?;
let installed = store.installed_view(name);
let (change, files) = view::compare(
installed.as_deref(),
rendered.as_ref().map(Scratch::path),
secret,
)?;
if change != view::Change::Unchanged && !dry_run {
store.install_view(name, rendered, secret)?;
}
outcomes.push(ViewOutcome {
name: name.clone(),
secret,
change,
files,
});
}
for name in store.installed_views()? {
if !schema.views.contains_key(&name) {
if !dry_run {
store.install_view(&name, None, false)?;
}
outcomes.push(ViewOutcome {
name,
secret: false,
change: view::Change::Removed,
files: Vec::new(),
});
}
}
Ok(outcomes)
}
/// Puts every view of `schema` in place from the snapshots, and takes away those it
/// doesn't have: at boot. Runs no reactions.
pub fn materialize(schema: &Schema, store: &Store) -> Result<Vec<ViewOutcome>> {
put_views(schema, store, &seen_all(schema, store)?, false)
}
#[derive(Debug, Clone, Serialize)]
pub struct Migration {
/// Whether the state fills every required slot of the schema.
pub accepted: bool,
pub refused: Vec<String>,
pub channels: BTreeMap<String, ChannelMigration>,
pub views: Vec<ViewOutcome>,
pub reactions: Reactions,
pub dry_run: bool,
/// The submissions taken from the incoming directory.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub incoming: Vec<IncomingOutcome>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub failed: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ChannelMigration {
pub snapshot: Option<String>,
#[serde(flatten)]
pub seen: Seen,
pub kept: Vec<String>,
}
/// An incoming submission, and what became of it.
#[derive(Debug, Clone, Serialize)]
pub struct IncomingOutcome {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub plan: Option<Plan>,
/// Why it couldn't even be planned.
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Serves the generation of `schema` (as `schema_bytes`) from the snapshots, after a
/// generation change, or before it (`dry_run`). First the submissions waiting in the
/// incoming directory are planned against `schema`, in order, and stored if accepted
/// (no views, no reactions yet); they are removed, and those refused moved to the
/// refused directory. Then: what each channel sees, which required slots nothing
/// fills, and how the views change. A refused submission, or an unfilled required
/// slot, refuses the switch. Unless `dry_run`, the views are put in place, those of
/// unfilled required slots taken away, and the reactions of those that changed run by
/// `systemctl`. A dry run does all of it on a copy of the snapshots.
pub fn migrate(
schema: &Schema,
schema_bytes: &[u8],
store: &Store,
dry_run: bool,
systemctl: &Path,
) -> Result<Migration> {
let mut refused = Vec::new();
let pending = store.incoming()?;
let scratch = match dry_run && !pending.is_empty() {
true => Some(Scratch::new(&store.scratch(), "state-")?),
false => None,
};
let copy = scratch
.as_ref()
.map(|scratch| store.copy_to(scratch.path()))
.transpose()?;
let work = copy.as_ref().unwrap_or(store);
let mut incoming = Vec::new();
for dir in &pending {
let name = dir
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let planned =
Submission::load(dir).and_then(|submission| plan::plan(schema, work, &submission));
let (outcome, accepted) = match planned {
Err(error) => {
refused.push(format!("incoming {name}: {error:#}"));
let error = Some(format!("{error:#}"));
(
IncomingOutcome {
name: name.clone(),
plan: None,
error,
},
false,
)
}
Ok(planned) => {
let plan = planned.store(work, schema_bytes)?;
if !plan.accepted {
refused.push(format!("incoming {name}: {}", plan.refused.join("; ")));
}
let accepted = plan.accepted;
(
IncomingOutcome {
name: name.clone(),
plan: Some(plan),
error: None,
},
accepted,
)
}
};
incoming.push(outcome);
if !dry_run {
if accepted {
std::fs::remove_dir_all(dir)
.with_context(|| format!("removing {}", dir.display()))?;
} else {
let target = store.refused_dir().join(&name);
std::fs::create_dir_all(store.refused_dir())?;
let _ = std::fs::remove_dir_all(&target);
std::fs::rename(dir, &target)
.with_context(|| format!("moving {} to {}", dir.display(), target.display()))?;
}
}
}
let store = work;
let seen = seen_all(schema, store)?;
let mut channels = BTreeMap::new();
for (channel, channel_seen) in &seen {
for slot in &channel_seen.unfilled {
refused.push(format!("required slot {slot} can't be filled"));
}
channels.insert(
channel.clone(),
ChannelMigration {
snapshot: store.current(channel)?.map(|snapshot| snapshot.id),
seen: channel_seen.clone(),
kept: channel_seen.kept_names(),
},
);
}
let views = put_views(schema, store, &seen, dry_run)?;
let mut restart = BTreeSet::new();
let mut reload = BTreeSet::new();
for outcome in &views {
if outcome.change == view::Change::Unchanged {
continue;
}
if let Some(spec) = schema.views.get(&outcome.name) {
restart.extend(spec.reactions.restart.iter().cloned());
reload.extend(spec.reactions.reload.iter().cloned());
}
}
let reactions = Reactions {
reload: reload.difference(&restart).cloned().collect(),
restart: restart.into_iter().collect(),
};
let failed = if dry_run {
Vec::new()
} else {
match std::fs::remove_file(store.migrate_due()) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
return Err(error)
.with_context(|| format!("removing {}", store.migrate_due().display()));
}
_ => {}
}
react(&reactions, systemctl, Reacting::Migrate)
};
Ok(Migration {
accepted: refused.is_empty(),
refused,
channels,
views,
reactions,
dry_run,
incoming,
failed,
})
}
|