aboutsummaryrefslogtreecommitdiffstats
path: root/src/plan.rs
blob: 9a56505f0cd7929355e7e7099b4e8ceae3fc37ab (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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! What a submission would do, and doing it (docs/design.md, 5.5).
//!
//! The plan: check the channel and the base; apply the items to a copy of the current
//! snapshot; run the validators on it, leaving out optional items an objection names,
//! with their groups, and refusing for a required one or for what is in place; check
//! that every required slot is filled; render the views into scratch and compare.
//! Applying: the same, then the new snapshot becomes current, the views that changed
//! are put in place, and their reactions run, each unit once.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result, anyhow};
use serde::Serialize;

use crate::content::{self, Content};
use crate::media;
use crate::migrate;
use crate::name::Address;
use crate::program::{self, Given, ProgramFailed, Role};
use crate::schema::{Reactions, Schema};
use crate::scratch::Scratch;
use crate::store::{Kept, Lock, Store};
use crate::submission::{Change, Item, Submission};
use crate::view::{self, FileChange};

#[derive(Debug, Clone, Serialize)]
pub struct Plan {
    pub channel: String,
    /// The current snapshot's id.
    pub current: Option<String>,
    /// The snapshot the submission builds on, if it names one.
    pub base: Option<String>,
    pub accepted: bool,
    /// Why not, if not.
    pub refused: Vec<String>,
    pub items: Vec<ItemOutcome>,
    pub warnings: Vec<String>,
    pub views: Vec<ViewOutcome>,
    pub reactions: Reactions,
    /// Whether the snapshot or a view would change.
    pub changes: bool,
    /// The new snapshot's id, once applied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot: Option<String>,
    /// Whether it was staged (`--stage`): its views and reactions come with the
    /// switch to the generation it was planned for.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub staged: bool,
    /// Reactions that failed, once applied.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub failed: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ItemOutcome {
    pub address: Address,
    pub op: &'static str,
    pub required: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    pub goes_in: bool,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub reasons: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ViewOutcome {
    pub name: String,
    pub secret: bool,
    pub change: view::Change,
    pub files: Vec<FileChange>,
}

/// A plan, and what applying it needs.
pub struct Planned {
    pub plan: Plan,
    content: Content,
    kept: Kept,
    content_changes: bool,
    rendered: Vec<(String, Option<Scratch>, bool)>,
}

/// A plan refused: nothing to apply.
fn refused(plan: Plan) -> Result<Planned> {
    Ok(Planned {
        plan,
        content: Content::new(),
        kept: Kept::new(),
        content_changes: false,
        rendered: Vec::new(),
    })
}

/// Plans `submission` against `schema` and what `store` holds.
pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<Planned> {
    let channel = submission.channel.as_str();
    let current = store.current(channel)?;
    let mut plan = Plan {
        channel: channel.to_owned(),
        current: current.as_ref().map(|snapshot| snapshot.id.clone()),
        base: submission.base.clone(),
        accepted: false,
        refused: Vec::new(),
        items: submission
            .items
            .iter()
            .map(|item| ItemOutcome {
                address: item.address.clone(),
                op: match item.change {
                    Change::Remove => "remove",
                    _ => "set",
                },
                required: item.required,
                group: item.group.clone(),
                goes_in: true,
                reasons: Vec::new(),
            })
            .collect(),
        warnings: Vec::new(),
        views: Vec::new(),
        reactions: Reactions::default(),
        changes: false,
        snapshot: None,
        staged: false,
        failed: Vec::new(),
    };
    let Some(channel_spec) = schema.channel(channel) else {
        plan.refused
            .push(format!("the schema has no channel {channel}"));
        return refused(plan);
    };
    if let Some(base) = &submission.base {
        let current_id = current.as_ref().map(|snapshot| snapshot.id.as_str());
        if current_id != Some(base.as_str()) {
            plan.refused.push(format!(
                "the submission builds on {base}, but the current snapshot is {}",
                current_id.unwrap_or("none")
            ));
            return refused(plan);
        }
    }
    let empty = Content::new();
    // What this generation sees of the snapshot, which may have been accepted under
    // another schema.
    let seen = migrate::seen(schema, channel, current.as_ref())?;
    let base_content = match (&current, submission.complete) {
        (Some(_), false) => &seen.content,
        _ => &empty,
    };
    // Other channels, for validators and views given their slots.
    let mut others: BTreeMap<String, Content> = BTreeMap::new();
    let mut other_channels: BTreeSet<&str> = BTreeSet::new();
    for validator in schema.validators_of(channel) {
        for address in validator.slots {
            if address.channel != channel {
                other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0);
            }
        }
    }
    for (_, view) in schema.views_of(Some(channel)) {
        for address in &view.from {
            if address.channel != channel {
                other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0);
            }
        }
    }
    for other in other_channels {
        let content = migrate::seen(schema, other, store.current(other)?.as_ref())?.content;
        others.insert(other.to_owned(), content);
    }

    let items = &submission.items;
    // Items that can't go in, whatever the validators say.
    let mut cannot: BTreeMap<usize, String> = BTreeMap::new();
    for (index, item) in items.iter().enumerate() {
        if let Some(reason) = unfit(schema, item, base_content) {
            cannot.insert(index, reason);
        }
    }
    let mut excluded: BTreeSet<usize> = BTreeSet::new();
    let leave_out =
        |plan: &mut Plan, excluded: &mut BTreeSet<usize>, index: usize, reason: String| -> bool {
            // Whether it may be left out: else the submission is refused.
            let item = &items[index];
            if item.required {
                plan.refused
                    .push(format!("required item {}: {reason}", item.address));
                return false;
            }
            for (other, other_item) in items.iter().enumerate() {
                let together =
                    other == index || (item.group.is_some() && other_item.group == item.group);
                if together && excluded.insert(other) {
                    plan.items[other].goes_in = false;
                    let reason = if other == index {
                        reason.clone()
                    } else {
                        format!(
                            "its group {} can't go in",
                            item.group.as_deref().unwrap_or_default()
                        )
                    };
                    plan.warnings
                        .push(format!("left out: {}: {reason}", other_item.address));
                    plan.items[other].reasons.push(reason);
                }
            }
            true
        };
    for (index, reason) in &cannot {
        if !excluded.contains(index) && !leave_out(&mut plan, &mut excluded, *index, reason.clone())
        {
            return refused(plan);
        }
    }

    let candidate = loop {
        let candidate = apply_items(base_content, items, &excluded);
        let mut blame: Vec<(usize, String)> = Vec::new();
        // Required slots first: validators are given filled slots.
        for (slot, spec) in &channel_spec.slots {
            if !spec.required || candidate.contains_key(slot) {
                continue;
            }
            let address = Address::entry(channel, slot);
            let removals: Vec<usize> = (0..items.len())
                .filter(|index| !excluded.contains(index))
                .filter(|index| {
                    items[*index].address == address && items[*index].change == Change::Remove
                })
                .collect();
            if removals.is_empty() {
                plan.refused
                    .push(format!("required slot {address} is unfilled"));
            }
            blame.extend(
                removals
                    .into_iter()
                    .map(|index| (index, format!("required slot {address} would be unfilled"))),
            );
        }
        if !plan.refused.is_empty() {
            return refused(plan);
        }
        if blame.is_empty() {
            // Validators.
            for validator in schema.validators_of(channel) {
                let entry = |address: &Address| -> Option<&[u8]> {
                    if address.channel == channel {
                        candidate.get(&address.slot).map(Vec::as_slice)
                    } else {
                        others
                            .get(&address.channel)?
                            .get(&address.slot)
                            .map(Vec::as_slice)
                    }
                };
                if validator.of_type && entry(&validator.slots[0]).is_none() {
                    continue;
                }
                let given = Given {
                    slots: validator
                        .slots
                        .iter()
                        .map(|address| {
                            let media_type = schema
                                .slot(address)
                                .map(|slot| slot.media_type.as_str())
                                .unwrap_or_default();
                            (address.clone(), (media_type, entry(address)))
                        })
                        .collect(),
                };
                let outcome = match program::run(
                    &validator.program,
                    Role::Validator,
                    &validator.name,
                    &given,
                    &store.scratch(),
                ) {
                    Ok(outcome) => outcome,
                    Err(error) => match error.downcast::<ProgramFailed>() {
                        Ok(failed) => {
                            plan.refused.push(failed.to_string());
                            return refused(plan);
                        }
                        Err(error) => return Err(error),
                    },
                };
                for objection in outcome.objections {
                    let said = format!(
                        "{}: {} (validator {})",
                        objection.address, objection.message, validator.name
                    );
                    let blamed: Vec<usize> = (0..items.len())
                        .filter(|index| !excluded.contains(index))
                        .filter(|index| items[*index].address.overlaps(&objection.address))
                        .collect();
                    if blamed.is_empty() {
                        plan.refused
                            .push(format!("objection to what is in place: {said}"));
                    }
                    blame.extend(blamed.into_iter().map(|index| (index, said.clone())));
                }
            }
            if !plan.refused.is_empty() {
                return refused(plan);
            }
        }
        if blame.is_empty() {
            break candidate;
        }
        for (index, reason) in blame {
            if !excluded.contains(&index) && !leave_out(&mut plan, &mut excluded, index, reason) {
                return refused(plan);
            }
        }
    };
    // What no slot wants: kept, unless the submission is complete.
    let kept = if submission.complete {
        for slot in seen.kept.keys() {
            plan.warnings.push(format!(
                "goes, as the submission is complete: {channel}/{slot}, which was kept"
            ));
        }
        Kept::new()
    } else {
        let mut kept = seen.kept.clone();
        kept.retain(|slot, (media_type, _)| {
            let superseded = candidate.contains_key(slot);
            if superseded {
                plan.warnings.push(format!(
                    "goes, as {channel}/{slot} is filled anew: the entry of type {media_type} kept from before"
                ));
            }
            !superseded
        });
        for slot in kept.keys() {
            plan.warnings
                .push(format!("kept, in no slot of the schema: {channel}/{slot}"));
        }
        kept
    };

    // Views.
    let mut rendered_views = Vec::new();
    let mut entries: view::Entries = others
        .iter()
        .map(|(name, content)| (name.as_str(), content))
        .collect();
    entries.insert(channel, &candidate);
    for (name, view_spec) in schema.views_of(Some(channel)) {
        let secret = schema.view_is_secret(view_spec);
        let rendered = match view::render(schema, name, view_spec, &entries, &store.scratch()) {
            Ok(rendered) => rendered,
            Err(error) => match error.downcast::<ProgramFailed>() {
                Ok(failed) => {
                    plan.refused.push(failed.to_string());
                    return refused(plan);
                }
                Err(error) => return Err(error),
            },
        };
        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 {
            plan.reactions
                .restart
                .extend(view_spec.reactions.restart.iter().cloned());
            plan.reactions
                .reload
                .extend(view_spec.reactions.reload.iter().cloned());
        }
        plan.views.push(ViewOutcome {
            name: name.clone(),
            secret,
            change,
            files,
        });
        rendered_views.push((name.clone(), rendered, secret));
    }
    let restart: BTreeSet<String> = std::mem::take(&mut plan.reactions.restart)
        .into_iter()
        .collect();
    let reload: BTreeSet<String> = std::mem::take(&mut plan.reactions.reload)
        .into_iter()
        .filter(|unit| !restart.contains(unit))
        .collect();
    plan.reactions = Reactions {
        restart: restart.into_iter().collect(),
        reload: reload.into_iter().collect(),
    };
    let content_changes = current.is_none() || candidate != seen.content || kept != seen.kept;
    plan.changes = content_changes
        || plan
            .views
            .iter()
            .any(|view| view.change != view::Change::Unchanged);
    plan.accepted = true;
    Ok(Planned {
        plan,
        content: candidate,
        kept,
        content_changes,
        rendered: rendered_views,
    })
}

/// Why `item` can't go in, whatever the validators say: no such slot, a record in an
/// entry that holds none.
fn unfit(schema: &Schema, item: &Item, base: &Content) -> Option<String> {
    let Some(slot) = schema.slot(&item.address) else {
        return Some(format!(
            "the schema has no slot {}",
            item.address.of_entry()
        ));
    };
    if item.address.key.is_some() {
        if !media::keyed(&slot.media_type) {
            return Some(format!("type {} holds no records", slot.media_type));
        }
        if let Some(bytes) = base.get(&item.address.slot)
            && let Err(error) = content::records(bytes)
        {
            return Some(format!("the entry in place holds no records: {error}"));
        }
    }
    None
}

/// `base` with the items not `excluded` applied.
fn apply_items(base: &Content, items: &[Item], excluded: &BTreeSet<usize>) -> Content {
    let mut content = base.clone();
    for (index, item) in items.iter().enumerate() {
        if excluded.contains(&index) {
            continue;
        }
        let slot = &item.address.slot;
        match (&item.address.key, &item.change) {
            (None, Change::Entry(bytes)) => {
                content.insert(slot.clone(), bytes.clone());
            }
            (None, Change::Remove) => {
                content.remove(slot);
            }
            (Some(key), change) => {
                // `unfit` made sure an entry in place holds records.
                let mut records = content
                    .get(slot)
                    .and_then(|bytes| content::records(bytes).ok())
                    .unwrap_or_default();
                match change {
                    Change::Record(value) => {
                        records.insert(key.clone(), value.clone());
                    }
                    Change::Remove => {
                        records.remove(key);
                    }
                    Change::Entry(_) => unreachable!("an entry's item has no key"),
                }
                content.insert(slot.clone(), content::from_records(&records));
            }
            (None, Change::Record(_)) => unreachable!("a record's item has a key"),
        }
    }
    content
}

impl Planned {
    /// Applies the plan, if it was accepted: the new snapshot, the views that change,
    /// and, with `lock` released, their reactions.  Units restarted may want the unit
    /// that runs `--migrate`, which waits for the lock: holding it while they restart
    /// would deadlock.
    pub fn apply(
        self,
        store: &Store,
        schema_bytes: &[u8],
        systemctl: &Path,
        lock: Lock,
    ) -> Result<Plan> {
        let mut plan = self.plan;
        if !plan.accepted {
            return Ok(plan);
        }
        if self.content_changes {
            plan.snapshot = Some(store.commit(
                &plan.channel,
                &self.content,
                &self.kept,
                plan.current.as_deref(),
                schema_bytes,
            )?);
        }
        for ((name, rendered, secret), outcome) in self.rendered.into_iter().zip(&plan.views) {
            if outcome.change != view::Change::Unchanged {
                store
                    .install_view(&name, rendered, secret)
                    .with_context(|| format!("view {name}"))?;
            }
        }
        drop(lock);
        plan.failed = react(&plan.reactions, systemctl, Reacting::Apply);
        Ok(plan)
    }

    /// Stages the plan, if it was accepted: only the new snapshot, for the generation
    /// whose schema it was planned against, before switching to it.  No views are put
    /// in place and no reactions run: those of the running generation stay as they
    /// are, and the switch (`--migrate`) brings the new generation's.  The running
    /// generation sees the snapshot as any accepted under another schema: what it has
    /// no slot for is kept.
    pub fn stage(self, store: &Store, schema_bytes: &[u8], lock: Lock) -> Result<Plan> {
        let mut plan = self.plan;
        plan.staged = true;
        if plan.accepted && self.content_changes {
            plan.snapshot = Some(store.commit(
                &plan.channel,
                &self.content,
                &self.kept,
                plan.current.as_deref(),
                schema_bytes,
            )?);
        }
        drop(lock);
        Ok(plan)
    }
}

/// How reactions are run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reacting {
    /// After applying a submission: units are restarted or reloaded, and started if
    /// they aren't running (they may have failed for want of their views).
    Apply,
    /// After a generation change, from the unit that runs `--migrate`, which units
    /// using views are ordered after: only units that are running, without waiting
    /// for them (`--no-block`).  A unit that isn't running starts with the views in
    /// place.
    Migrate,
}

/// Runs `reactions` by `systemctl`, each unit once; returns what failed.
pub fn react(reactions: &Reactions, systemctl: &Path, how: Reacting) -> Vec<String> {
    let mut failed = Vec::new();
    let (options, restart, reload): (&[&str], _, _) = match how {
        Reacting::Apply => (&[], "restart", "reload-or-restart"),
        Reacting::Migrate => (&["--no-block"], "try-restart", "try-reload-or-restart"),
    };
    for (verb, units) in [(restart, &reactions.restart), (reload, &reactions.reload)] {
        if units.is_empty() {
            continue;
        }
        let result = Command::new(systemctl)
            .args(options)
            .arg(verb)
            .args(units)
            .status()
            .map_err(|error| anyhow!("{error}"))
            .and_then(|status| {
                if status.success() {
                    Ok(())
                } else {
                    Err(anyhow!("{status}"))
                }
            });
        if let Err(error) = result {
            failed.push(format!(
                "{} {verb} {}: {error}",
                systemctl.display(),
                units.join(" ")
            ));
        }
    }
    failed
}