sd-switch 0.6.4

A systemd unit reload/restart utility for Home Manager
Documentation
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
use crate::systemd::JobSet;
use crate::systemd::UnitManager;
mod error;
mod i18n_lib;
pub mod systemd;
mod unit_file;

use i18n_lib::MSG;
use std::collections::BTreeMap;
use std::{
    collections::HashSet,
    path::{Path, PathBuf},
    rc::Rc,
    time::Duration,
};
use systemd::UnitStatus;
use unit_file::UnitFile;

use anyhow::{Context, Result};

fn pretty_unit_names<I>(unit_names: I) -> String
where
    I: IntoIterator,
    I::Item: AsRef<str>,
{
    let mut str_vec = unit_names
        .into_iter()
        .map(|s| String::from(s.as_ref()))
        .collect::<Vec<_>>();
    str_vec.sort();
    str_vec.join(", ")
}

fn is_unit_available(unit_path: &Path) -> bool {
    unit_path.exists()
        && !unit_path
            .canonicalize()
            .map(|p| p == Path::new("/dev/null"))
            .unwrap_or(true)
}

/// Given an active unit name this returns the actual unit file name. In the
/// case of a parameterized unit, e.g., `foo@bar.service` this function returns
/// `foo@.service`. For nonparameterized unit names it returns none.
fn parameterized_base_name(unit_name: &str) -> Option<String> {
    let res = unit_name.splitn(2, '@').collect::<Vec<_>>();
    match res[..] {
        [base_name, arg_and_suffix] => {
            let res = arg_and_suffix.rsplitn(2, '.').collect::<Vec<_>>();
            match res[..] {
                [suffix, arg] if !arg.is_empty() => Some(format!("{base_name}@.{suffix}")),
                _ => None,
            }
        }
        _ => None,
    }
}

/// Returns the file path of the given unit name within the given directory.
///
/// If no matching file is found then `None` is returned.
///
/// If the given unit name is a parameterized named then an exactly matching
/// file is returned, if it exists, otherwise the template file path is
/// returned.
fn find_unit_file_path(unit_directory: &Path, unit_name: &str) -> Option<PathBuf> {
    Some(unit_directory.join(unit_name))
        .filter(|e| is_unit_available(e))
        .or_else(|| {
            parameterized_base_name(unit_name)
                .map(|n| unit_directory.join(n))
                .filter(|e| is_unit_available(e))
        })
}

/// A plan of unit actions needed to accomplish the switch.
struct SwitchPlan {
    unit_plan: BTreeMap<Rc<str>, UnitPlan>,
}

impl SwitchPlan {
    fn build_unit_plan(
        &'_ mut self,
        name: Rc<str>,
        populate_decisions: bool,
    ) -> UnitPlanBuilder<'_> {
        UnitPlanBuilder {
            switch_plan: self,
            populate_decisions,
            name,
            decisions: Vec::new(),
        }
    }

    fn stop_units(&self) -> BTreeMap<&str, &UnitPlan> {
        self.units_with_action(|a| *a == UnitAction::Stop || *a == UnitAction::StopStart)
    }

    fn start_units(&self) -> BTreeMap<&str, &UnitPlan> {
        self.units_with_action(|a| *a == UnitAction::Start || *a == UnitAction::StopStart)
    }

    fn reload_units(&self) -> BTreeMap<&str, &UnitPlan> {
        self.units_with_action(|a| *a == UnitAction::Reload)
    }

    fn restart_units(&self) -> BTreeMap<&str, &UnitPlan> {
        self.units_with_action(|a| *a == UnitAction::Restart)
    }

    fn keep_old_units(&self) -> BTreeMap<&str, &UnitPlan> {
        self.units_with_action(|a| *a == UnitAction::KeepOld)
    }

    fn unchanged_units(&self) -> BTreeMap<&str, &UnitPlan> {
        self.units_with_action(|a| *a == UnitAction::NoAction)
    }

    fn units_with_action(
        &self,
        predicate: impl Fn(&UnitAction) -> bool,
    ) -> BTreeMap<&str, &UnitPlan> {
        self.unit_plan
            .iter()
            .filter(|(_, v)| predicate(&v.action))
            .map(|(k, v)| (k.as_ref(), v))
            .collect()
    }
}

/// The plan for a given unit. The plan consists of the action to perform plus a
/// chain of decisions why that action was chosen. Since populating the the
/// decision chain is pretty expensive, it is only actually populated when
/// specifically needed such as when verbose output is desired.
struct UnitPlan {
    action: UnitAction,
    /// The decision trace showing the decision taken to arrive at the given
    /// action.
    decisions: Vec<UnitDecision>,
}

struct UnitPlanBuilder<'a> {
    switch_plan: &'a mut SwitchPlan,
    populate_decisions: bool,
    name: Rc<str>,
    decisions: Vec<UnitDecision>,
}

impl<'a> UnitPlanBuilder<'a> {
    fn push_decision(mut self, decision: UnitDecision) -> Self {
        if self.populate_decisions {
            self.decisions.push(decision);
        }
        self
    }

    fn action(self, action: UnitAction) {
        self.switch_plan.unit_plan.insert(
            self.name,
            UnitPlan {
                action,
                decisions: self.decisions,
            },
        );
    }
}

/// The available actions for a given unit.
#[derive(Debug, PartialEq, Eq)]
enum UnitAction {
    NoAction,
    StopStart,
    Start,
    Stop,
    Restart,
    Reload,
    KeepOld,
}

/// A description of why a given action was chosen for a unit.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum UnitDecision {
    /// Whether the new unit exists.
    NewExists,
    /// Whether the old unit exists.
    OldExists,
    /// There is no old unit but there is an active unit with the same name does.
    OldNotExists,
    /// New and old units are equal using restart semantics.
    RestartEq,
    /// New and old units are equal using reload semantics.
    ReloadEq,
    /// The new unit is having a special target unit.
    UnitType(unit_file::UnitType),
    /// The new unit has a special switch method.
    SwitchMethod(unit_file::UnitSwitchMethod),
    /// The active unit refuse manual stop.
    ActiveRefuseManualStop,
    /// Wanted by active target.
    WantedByActiveTarget,
}

struct UnitWithTarget {
    unit_path: PathBuf,
    unit_name: Rc<str>,
    target_name: Rc<str>,
}

fn build_switch_plan(
    old_dir: Option<&Path>,
    new_dir: &Path,
    populate_decisions: bool,
    service_manager: &impl systemd::ServiceManager,
) -> Result<SwitchPlan> {
    let mut switch_plan = SwitchPlan {
        unit_plan: BTreeMap::new(),
    };

    let mut active_unit_names = HashSet::new();

    let active_units = service_manager
        .list_units_by_states(&["active", "activating"])
        .with_context(|| MSG.err_listing_active_units())?;

    // Handle units that are currently active, typically this implies restarting
    // the unit in some way.
    for active_unit in active_units {
        let new_unit_path_opt = find_unit_file_path(new_dir, active_unit.name());
        let old_unit_path_opt = old_dir
            .as_ref()
            .and_then(|d| find_unit_file_path(d, active_unit.name()));

        let active_unit_name: Rc<str> = active_unit.name().into();
        active_unit_names.insert(active_unit_name.clone());

        let mut upb = switch_plan.build_unit_plan(active_unit_name, populate_decisions);

        if let Some(new_unit_path) = new_unit_path_opt {
            let new_unit_file = UnitFile::load(&new_unit_path)
                .with_context(|| MSG.err_read_unit_file(&new_unit_path))?;

            upb = upb.push_decision(UnitDecision::NewExists);

            if let Some(old_unit_path) = old_unit_path_opt {
                let old_unit_file = UnitFile::load(&old_unit_path)
                    .with_context(|| MSG.err_read_unit_file(&old_unit_path))?;

                upb = upb.push_decision(UnitDecision::OldExists);

                if old_unit_file.restart_eq(&new_unit_file) {
                    upb.push_decision(UnitDecision::RestartEq)
                        .action(UnitAction::NoAction);
                } else if old_unit_file.reload_eq(&new_unit_file) {
                    upb.push_decision(UnitDecision::ReloadEq)
                        .action(UnitAction::Reload);
                } else if new_unit_file.unit_type() == unit_file::UnitType::Target {
                    upb = upb.push_decision(UnitDecision::UnitType(new_unit_file.unit_type()));

                    if new_unit_file.switch_method() == unit_file::UnitSwitchMethod::StopOnly {
                        upb.push_decision(UnitDecision::SwitchMethod(
                            new_unit_file.switch_method(),
                        ))
                        .action(UnitAction::KeepOld);
                    } else {
                        upb.action(UnitAction::Start);
                    }
                } else {
                    upb = upb
                        .push_decision(UnitDecision::SwitchMethod(new_unit_file.switch_method()));

                    match new_unit_file.switch_method() {
                        unit_file::UnitSwitchMethod::Reload => {
                            upb.action(UnitAction::Reload);
                        }
                        unit_file::UnitSwitchMethod::Restart => {
                            upb.action(UnitAction::Restart);
                        }
                        unit_file::UnitSwitchMethod::StopStart => {
                            if service_manager
                                .unit_manager(&active_unit)?
                                .refuse_manual_stop()?
                            {
                                upb.push_decision(UnitDecision::ActiveRefuseManualStop)
                                    .action(UnitAction::NoAction);
                            } else {
                                upb.action(UnitAction::StopStart);
                            }
                        }
                        unit_file::UnitSwitchMethod::StopOnly => {
                            if service_manager
                                .unit_manager(&active_unit)?
                                .refuse_manual_stop()?
                            {
                                upb.push_decision(UnitDecision::ActiveRefuseManualStop)
                                    .action(UnitAction::NoAction);
                            } else {
                                upb.action(UnitAction::Stop);
                            }
                        }
                        unit_file::UnitSwitchMethod::KeepOld => {
                            upb.action(UnitAction::KeepOld);
                        }
                    }
                }
            } else {
                upb = upb.push_decision(UnitDecision::OldNotExists);

                if service_manager
                    .unit_manager(&active_unit)?
                    .refuse_manual_stop()?
                {
                    upb.push_decision(UnitDecision::ActiveRefuseManualStop)
                        .action(UnitAction::KeepOld);
                } else if new_unit_file.switch_method() == unit_file::UnitSwitchMethod::StopOnly {
                    upb.push_decision(UnitDecision::SwitchMethod(new_unit_file.switch_method()))
                        .action(UnitAction::KeepOld);
                } else {
                    upb.action(UnitAction::StopStart);
                }
            }
        } else if old_unit_path_opt.is_some() {
            upb = upb.push_decision(UnitDecision::OldExists);

            if service_manager
                .unit_manager(&active_unit)?
                .refuse_manual_stop()?
            {
                upb.push_decision(UnitDecision::ActiveRefuseManualStop)
                    .action(UnitAction::KeepOld);
            } else {
                upb.action(UnitAction::Stop);
            }
        }
    }

    // Handle units that are not currently active but are wanted by an active
    // target. Typically this is simply a matter of starting the new unit.
    for wanted_unit in find_wanted_units(new_dir)? {
        // Skip if the unit is not wanted by an active target.
        if !active_unit_names.contains(&wanted_unit.target_name) {
            continue;
        }

        // Skip if the unit is actually active.
        if active_unit_names.contains(&wanted_unit.unit_name) {
            continue;
        }

        let new_unit_file = UnitFile::load(&wanted_unit.unit_path)
            .with_context(|| MSG.err_read_unit_file(&wanted_unit.unit_path))?;

        let mut upb = switch_plan.build_unit_plan(wanted_unit.unit_name, populate_decisions);

        upb = upb
            .push_decision(UnitDecision::NewExists)
            .push_decision(UnitDecision::WantedByActiveTarget);

        if new_unit_file.switch_method() == unit_file::UnitSwitchMethod::StopOnly {
            upb.push_decision(UnitDecision::SwitchMethod(new_unit_file.switch_method()))
                .action(UnitAction::NoAction);
        } else {
            upb.action(UnitAction::Start);
        }
    }

    Ok(switch_plan)
}

fn find_wanted_units(new_dir: &Path) -> Result<Vec<UnitWithTarget>> {
    let mut result = Vec::new();

    for dir_entry in std::fs::read_dir(new_dir)? {
        let dir_entry = dir_entry.with_context(|| MSG.err_read_dir_entry(new_dir))?;

        // Get the file name as a string. Ignore the string if we cannot parse it.
        let entry_file_name = dir_entry
            .file_name()
            .into_string()
            .expect("unit with valid Unicode file name");

        if dir_entry.metadata()?.is_dir() && entry_file_name.ends_with(".target.wants") {
            let dir_name = entry_file_name;
            let target_name: Rc<str> = dir_name
                .strip_suffix(".wants")
                .expect("directory name should end in .wants")
                .into();
            for wants_entry in std::fs::read_dir(dir_entry.path())? {
                let wants_entry = wants_entry
                    .with_context(|| MSG.err_read_dir_entry(dir_entry.path().as_path()))?;

                let unit_name = wants_entry
                    .file_name()
                    .into_string()
                    .expect("unit with valid Unicode file name")
                    .into();
                result.push(UnitWithTarget {
                    unit_path: wants_entry.path(),
                    unit_name,
                    target_name: target_name.clone(),
                });
            }
        }
    }

    Ok(result)
}

fn exec_pre_reload<F>(
    plan: &SwitchPlan,
    service_manager: &impl systemd::ServiceManager,
    job_handler: F,
    dry_run: bool,
    timeout: Duration,
) -> Result<()>
where
    F: Fn(&str, &str) + Send + 'static,
{
    let stop_units = plan.stop_units();

    if stop_units.is_empty() {
        return Ok(());
    }

    println!(
        "{}",
        MSG.stopping_units(&pretty_unit_names(stop_units.keys()))
    );

    if !dry_run {
        let mut job_set = service_manager.new_job_set()?;

        for uf in stop_units.keys() {
            job_set
                .stop_unit(uf)
                .with_context(|| MSG.err_unit_action_failed(uf, UnitAction::Stop))?;
        }

        job_set.wait_for_all(job_handler, timeout)?;
    }

    Ok(())
}

fn exec_reload(
    service_manager: &impl systemd::ServiceManager,
    dry_run: bool,
    verbose: bool,
) -> Result<()> {
    if !dry_run {
        if verbose {
            println!("{}", MSG.resetting_failed_units());
        }
        service_manager
            .reset_failed()
            .with_context(|| MSG.err_resetting_failed_units())?;

        if verbose {
            println!("{}", MSG.reloading_systemd());
        }
        service_manager
            .daemon_reload()
            .with_context(|| MSG.err_reloading_systemd())?;
    }

    Ok(())
}

fn exec_post_reload<F>(
    plan: &SwitchPlan,
    service_manager: &impl systemd::ServiceManager,
    job_handler: F,
    dry_run: bool,
    verbose: bool,
    timeout: Duration,
) -> Result<()>
where
    F: Fn(&str, &str) + Send + 'static,
{
    let mut job_set = service_manager.new_job_set()?;

    {
        let units = plan.reload_units();
        if !units.is_empty() {
            println!("{}", MSG.reloading_units(&pretty_unit_names(units.keys())));

            if !dry_run {
                for uf in units.keys() {
                    job_set
                        .reload_unit(uf)
                        .with_context(|| MSG.err_unit_action_failed(uf, UnitAction::Reload))?;
                }
            }
        }
    }

    {
        let units = plan.restart_units();
        if !units.is_empty() {
            println!("{}", MSG.restarting_units(&pretty_unit_names(units.keys())));

            if !dry_run {
                for uf in units.keys() {
                    job_set
                        .restart_unit(uf)
                        .with_context(|| MSG.err_unit_action_failed(uf, UnitAction::Restart))?;
                }
            }
        }
    }

    {
        let units = plan.keep_old_units();
        if !units.is_empty() {
            println!(
                "{}",
                MSG.keeping_old_units(&pretty_unit_names(units.keys()))
            );
        }
    }

    if verbose {
        let units = plan.unchanged_units();
        if !units.is_empty() {
            println!("{}", MSG.unchanged_units(&pretty_unit_names(units.keys())));
        }
    }

    {
        let units = plan.start_units();
        if !units.is_empty() {
            println!("{}", MSG.starting_units(&pretty_unit_names(units.keys())));

            if !dry_run {
                for uf in units.keys() {
                    job_set
                        .start_unit(uf)
                        .with_context(|| MSG.err_unit_action_failed(uf, UnitAction::Start))?;
                }
            }
        }
    }

    job_set.wait_for_all(job_handler, timeout)?;

    Ok(())
}

fn print_plan(plan: &SwitchPlan) {
    if plan.unit_plan.is_empty() {
        println!("The calculated switch plan is empty.");
        return;
    }

    println!("Unit switch plan:");

    for (unit_file, unit_plan) in &plan.unit_plan {
        let action = match unit_plan.action {
            UnitAction::NoAction => "No action",
            UnitAction::StopStart => "Stop/Start",
            UnitAction::Start => "Start",
            UnitAction::Stop => "Stop",
            UnitAction::Restart => "Restart",
            UnitAction::Reload => "Reload",
            UnitAction::KeepOld => "Keep active",
        };
        let decisions = pretty_unit_names(unit_plan.decisions.iter().map(|v| format!("{:?}", v)));
        println!("  {action} {unit_file} ({decisions})");
    }
}

/// Performs a systemd unit "switch".
pub fn switch(
    service_manager: &impl systemd::ServiceManager,
    old_dir: Option<&Path>,
    new_dir: &Path,
    dry_run: bool,
    verbose: bool,
    timeout: Duration,
) -> Result<()> {
    let system_status = service_manager.system_status()?;

    // If the systemd manager status is degraded then inform the user about the
    // failed units. We will still attempt to perform the switch, though.
    if matches!(system_status, systemd::SystemStatus::Degraded) {
        let units_by_states = service_manager.list_units_by_states(&["failed"])?;
        let failed: Vec<&str> = units_by_states.iter().map(|status| status.name()).collect();
        let failed = failed.join(", ");
        eprintln!(
            "The service manager is degraded.\n\
             Failed services: {failed}\n\
             Attempting to continue anyway..."
        );
    }

    let do_switch = {
        use systemd::SystemStatus::{
            Degraded, Initializing, Maintenance, Running, Starting, Stopping,
        };
        match system_status {
            Initializing | Starting | Running | Degraded => true,
            Maintenance | Stopping => false,
        }
    };

    if !do_switch {
        if verbose {
            println!("Skipping switch since systemd has {system_status} status");
        }
        return Ok(());
    }

    let plan = build_switch_plan(old_dir, new_dir, verbose, service_manager)
        .context("Failed to build switch plan")?;

    if verbose {
        print_plan(&plan);
    }

    let job_handler = move |name: &str, state: &str| {
        if verbose || state != "done" {
            println!("{name} {state}");
        }
    };

    exec_pre_reload(&plan, service_manager, job_handler, dry_run, timeout)
        .context("Failed to perform pre-reload tasks")?;

    exec_reload(service_manager, dry_run, verbose)?;

    exec_post_reload(
        &plan,
        service_manager,
        job_handler,
        dry_run,
        verbose,
        timeout,
    )
    .context("Failed to perform post-reload tasks")?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_get_base_name_for_parameterized_unit() {
        assert_eq!(
            parameterized_base_name("foo@bar.service"),
            Some(String::from("foo@.service"))
        );
        assert_eq!(
            parameterized_base_name("foo@bar.baz.service"),
            Some(String::from("foo@.service"))
        );
    }

    #[test]
    fn no_base_name_for_nonparameterized_units() {
        assert_eq!(parameterized_base_name("foo@.service"), None);
        assert_eq!(parameterized_base_name("foo.service"), None);
        assert_eq!(parameterized_base_name("foo@barservice"), None);
    }
}