cindy 0.2.1

Managing infrastructure at breakneck speed.
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
use std::str::FromStr;

use zbus_systemd::systemd1::{ManagerProxy, UnitProxy};
use zbus_systemd::zbus;

use crate as cindy;
use crate::Context;

/// Desired **active** (runtime) state of a unit — independent of whether it's
/// enabled at boot. `None` on [`State::runtime`] means "leave the running
/// state alone".
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[crate::wire]
pub enum RuntimeAction {
    Started,
    Stopped,
    Restarted,
    Reloaded,
}

/// Desired **boot** (enablement) state of a unit — independent of whether it's
/// currently running. `None` on [`State::enablement`] means "leave the
/// enablement alone".
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[crate::wire]
pub enum Enablement {
    Masked,
    Disabled,
    Enabled,
}

#[derive(Clone, Default, PartialEq, Eq)]
#[crate::wire]
pub struct State {
    /// Unit name. Bare names (`"nginx"`) get `.service` appended; anything
    /// containing a `.` is passed through unchanged (so `"foo.timer"`,
    /// `"multi-user.target"`, `"docker.socket"` etc. work as-is).
    pub name: String,
    /// Desired boot/enablement state. `None` = don't touch enablement.
    /// The two axes are *mostly* independent — you can enable without
    /// starting, or restart without changing enablement — with one
    /// exception: a masked unit cannot run, so `Some(Enablement::Masked)`
    /// together with a `Some(..)` [`runtime`](Self::runtime) is a
    /// contradiction that [`apply`] rejects. (None of the intent-named
    /// verbs can produce it.)
    pub enablement: Option<Enablement>,
    /// Desired runtime/active state. `None` = don't touch the running state.
    pub runtime: Option<RuntimeAction>,
}

/// Default `Diff` impl renders `State` via `{:#?}` + a unified line diff.
/// No binary payloads here, so no custom rendering is needed.
impl crate::Diff for State {}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum UnitState {
    Enabled,
    EnabledRuntime,
    Linked,
    LinkedRuntime,
    Alias,
    Masked,
    MaskedRuntime,
    Static,
    Disabled,
    Generated,
    Transient,
    Indirect,
    Bad,
}

impl FromStr for UnitState {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "enabled" => Self::Enabled,
            "enabled-runtime" => Self::EnabledRuntime,
            "linked" => Self::Linked,
            "linked-runtime" => Self::LinkedRuntime,
            "alias" => Self::Alias,
            "masked" => Self::Masked,
            "masked-runtime" => Self::MaskedRuntime,
            "static" => Self::Static,
            "disabled" => Self::Disabled,
            "generated" => Self::Generated,
            "transient" => Self::Transient,
            "indirect" => Self::Indirect,
            "bad" | "" => Self::Bad,
            other => return Err(format!("unknown UnitFileState: {other:?}")),
        })
    }
}

impl UnitState {
    fn is_masked(self) -> bool {
        matches!(self, Self::Masked | Self::MaskedRuntime)
    }

    /// `true` when calling `EnableUnitFiles` would actually do something.
    fn needs_enable_call(self) -> bool {
        matches!(self, Self::Disabled)
    }

    /// `true` when calling `DisableUnitFiles` would actively tear down links.
    fn needs_disable_call(self) -> bool {
        matches!(
            self,
            Self::Enabled | Self::EnabledRuntime | Self::Linked | Self::LinkedRuntime | Self::Alias
        )
    }
}

/// Mirror of systemd's `ActiveState` unit property.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ActiveState {
    Active,
    Reloading,
    Inactive,
    Failed,
    Activating,
    Deactivating,
}

impl FromStr for ActiveState {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "active" => Self::Active,
            "reloading" => Self::Reloading,
            "inactive" => Self::Inactive,
            "failed" => Self::Failed,
            "activating" => Self::Activating,
            "deactivating" => Self::Deactivating,
            other => return Err(format!("unknown ActiveState: {other:?}")),
        })
    }
}

impl ActiveState {
    /// `true` if the unit is running or actively transitioning to running.
    /// Matches Ansible's "started" predicate.
    fn is_running(self) -> bool {
        matches!(self, Self::Active | Self::Reloading | Self::Activating)
    }
}

fn is_no_such_unit(err: &zbus::Error) -> bool {
    if let zbus::Error::MethodError(name, _, _) = err {
        let n = name.to_string();
        n.ends_with(".NoSuchUnit") || n.ends_with(".NoSuchUnitFile") || n.ends_with(".LoadFailed")
    } else {
        false
    }
}

async fn read_file_state(
    manager: &ManagerProxy<'_>,
    name: &str,
) -> crate::Result<Option<UnitState>> {
    match manager.get_unit_file_state(name.to_owned()).await {
        Ok(s) => {
            let parsed = s
                .parse::<UnitState>()
                .map_err(anyhow_serde::Error::msg)
                .context("Parsing UnitFileState")?;
            Ok(Some(parsed))
        }
        Err(e) if is_no_such_unit(&e) => Ok(None),
        Err(e) => Err(e).context(format!("GetUnitFileState({name}) failed")),
    }
}

async fn read_active_state(
    manager: &ManagerProxy<'_>,
    conn: &zbus::Connection,
    name: &str,
) -> crate::Result<Option<ActiveState>> {
    let path = match manager.load_unit(name.to_owned()).await {
        Ok(p) => p,
        Err(e) if is_no_such_unit(&e) => return Ok(None),
        Err(e) => return Err(e).context(format!("LoadUnit({name}) failed")),
    };

    let unit = UnitProxy::builder(conn)
        .path(path)
        .context("Invalid unit object path")?
        .build()
        .await
        .context("Couldn't construct Unit proxy")?;

    let raw = unit
        .active_state()
        .await
        .context("Reading ActiveState failed")?;

    let parsed = raw
        .parse::<ActiveState>()
        .map_err(anyhow_serde::Error::msg)
        .context("Parsing ActiveState")?;
    Ok(Some(parsed))
}

/// Run a systemd `daemon-reload` on the remote, making systemd re-read
/// unit files from disk.
///
/// Call this after you've written or removed a unit file yourself
/// (typically with the [`path`](super::path) builtin) and before you
/// drive that unit with [`systemd`]. The [`systemd`] module no longer
/// reloads unconditionally, so a freshly-dropped unit won't be visible
/// until something reloads — this is that something:
///
/// ```rust,ignore
/// if path(unit_file_state).await?.changed() {
///     systemd::daemon_reload().await?;
/// }
/// systemd::systemd(State { name: "myapp".into(), enablement: Some(..), ..Default::default() }).await?;
/// ```
#[crate::remote]
pub async fn daemon_reload() -> crate::Result<()> {
    let conn = zbus::Connection::system()
        .await
        .context("Couldn't connect to the system bus")?;
    let manager = ManagerProxy::new(&conn)
        .await
        .context("Couldn't construct Manager proxy")?;
    manager.reload().await.context("Daemon-reload failed")?;
    Ok(())
}

/// Manage a single systemd unit on the remote machine.
///
/// This is the full-control entry point taking a [`State`], whose two axes —
/// boot ([`State::enablement`]) and runtime ([`State::runtime`]) — are
/// independent. For the common cases, prefer the intent-named helpers below.
#[crate::remote]
pub async fn systemd(state: State) -> crate::Result<super::Return> {
    apply(state).await
}

// Intent-named helpers, each a single `#[crate::action]` fn whose body builds
// a `State` and calls `apply`. The macro generates the concrete `#[remote]`
// wire entry point, the orchestrator shim, and the in-process `::inner`.
//
// The boot and runtime axes are orthogonal: `enable`/`disable`/`mask` touch
// only enablement; `start`/`stop`/`restart`/`reload` touch only the running
// state; and `enable_and_start`/`disable_and_stop` do both for the common
// "make sure it's on and running / off and stopped" case.

// --- boot/enablement only ------------------------------------------------

/// Enable `name` at boot. Does **not** start it now — pair with [`start`], or
/// use [`enable_and_start`]. Orchestrator: `enable(name).await?`.
#[crate::action]
pub async fn enable(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: Some(Enablement::Enabled),
        runtime: None,
    })
    .await
}

/// Disable `name` at boot. Does **not** stop it now — pair with [`stop`], or
/// use [`disable_and_stop`]. Orchestrator: `disable(name).await?`.
#[crate::action]
pub async fn disable(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: Some(Enablement::Disabled),
        runtime: None,
    })
    .await
}

/// Mask `name` (which also stops it — a masked unit can't run). If a real
/// unit file or drop-in is in the way, it is removed to complete the mask.
/// Orchestrator: `mask(name).await?`.
#[crate::action]
pub async fn mask(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: Some(Enablement::Masked),
        // Masked ⇒ stopped, but it lives on the enablement axis; `runtime`
        // stays `None` so we never hit the "masked + runtime" guard.
        runtime: None,
    })
    .await
}

// --- runtime/active only -------------------------------------------------

/// Start `name` now if not already running. Leaves enablement untouched.
/// Orchestrator: `start(name).await?`.
#[crate::action]
pub async fn start(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: None,
        runtime: Some(RuntimeAction::Started),
    })
    .await
}

/// Stop `name` now if running. Leaves enablement untouched.
/// Orchestrator: `stop(name).await?`.
#[crate::action]
pub async fn stop(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: None,
        runtime: Some(RuntimeAction::Stopped),
    })
    .await
}

/// Restart `name` now (unconditionally) — the usual "I changed the config,
/// bounce the service" action. Leaves enablement untouched.
/// Orchestrator: `restart(name).await?`.
#[crate::action]
pub async fn restart(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: None,
        runtime: Some(RuntimeAction::Restarted),
    })
    .await
}

/// Reload `name` now (`systemctl reload`). Leaves enablement untouched.
/// Orchestrator: `reload(name).await?`.
#[crate::action]
pub async fn reload(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: None,
        runtime: Some(RuntimeAction::Reloaded),
    })
    .await
}

// --- both axes (common shortcuts) ----------------------------------------

/// Enable `name` at boot *and* start it now. Orchestrator:
/// `enable_and_start(name).await?`.
#[crate::action]
pub async fn enable_and_start(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: Some(Enablement::Enabled),
        runtime: Some(RuntimeAction::Started),
    })
    .await
}

/// Disable `name` at boot *and* stop it now. Orchestrator:
/// `disable_and_stop(name).await?`.
#[crate::action]
pub async fn disable_and_stop(name: impl Into<String>) -> crate::Result<super::Return> {
    apply(State {
        name,
        enablement: Some(Enablement::Disabled),
        runtime: Some(RuntimeAction::Stopped),
    })
    .await
}

/// Print a one-line note for an *action* that has no state delta to diff.
///
/// `restart`/`reload` leave a running unit running, so the structural
/// `State` diff renders nothing even though work happened. This makes that
/// work visible. Written to stderr — the same stream the diff uses — and
/// honours `NO_COLOR` like [`crate::diff::text_diff`].
fn print_action(unit_name: &str, verb: &str) {
    use std::io::Write as _;
    let (color, reset) = if std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()) {
        ("", "")
    } else {
        ("\x1b[36;1m", "\x1b[0m") // bold cyan, matching diff hunk headers
    };
    let _ = writeln!(
        std::io::stderr().lock(),
        "{color}~ {unit_name} {verb}{reset}",
    );
}

async fn apply(state: State) -> crate::Result<super::Return> {
    let unit_name = {
        let name = &state.name;
        if name.contains('.') {
            name.to_owned()
        } else {
            format!("{name}.service")
        }
    };

    // A masked unit cannot run, so asking to mask *and* drive a runtime
    // action is a contradiction. None of the intent verbs produce this
    // (`mask` leaves `runtime` `None`); reject a hand-built `State` that does,
    // up front, before touching the system.
    if state.enablement == Some(Enablement::Masked)
        && let Some(runtime) = state.runtime
    {
        crate::bail!(
            "invalid systemd request for `{unit_name}`: a unit can't be masked and have a \
             runtime action ({runtime:?}) at once — a masked unit cannot run. Mask it (which \
             stops it), or pick Enabled/Disabled if you need it running.",
        );
    }

    let conn = zbus::Connection::system()
        .await
        .context("Couldn't connect to the system bus")?;
    let manager = ManagerProxy::new(&conn)
        .await
        .context("Couldn't construct Manager proxy")?;

    // No unconditional daemon-reload here: a reload is itself a system
    // action and isn't free on busy hosts, so doing it on every call
    // would make a no-op invocation report work it didn't honestly need
    // to do. We reload *only* after we write/remove unit files below
    // (where systemd genuinely needs to re-read them). If you've just
    // dropped a new unit file via the `path` builtin, call
    // [`daemon_reload`] yourself first, e.g.
    // `if path(...).await?.changed() { daemon_reload().await?; }`.

    let initial_unit_state = read_file_state(&manager, &unit_name).await?;
    let initial_active_state = read_active_state(&manager, &conn, &unit_name).await?;

    // Observe the two axes independently.
    let observed_runtime = if initial_active_state
        .map(ActiveState::is_running)
        .unwrap_or(false)
    {
        RuntimeAction::Started
    } else {
        RuntimeAction::Stopped
    };
    let observed_enablement = initial_unit_state.map(|f| {
        if f.is_masked() {
            Enablement::Masked
        } else if matches!(f, UnitState::Enabled | UnitState::EnabledRuntime) {
            Enablement::Enabled
        } else {
            Enablement::Disabled
        }
    });
    // For each axis, a `None` request leaves that axis at its observed value
    // in the diff.
    let old_view = State {
        name: state.name.clone(),
        enablement: observed_enablement,
        runtime: Some(observed_runtime),
    };
    let new_view = State {
        name: state.name.clone(),
        enablement: state.enablement.or(observed_enablement),
        // `Restarted`/`Reloaded` are unconditional actions, not a steady
        // state — they always leave the unit running, so the *post* state is
        // `Started` for diff purposes.
        runtime: Some(match state.runtime {
            None => observed_runtime,
            Some(RuntimeAction::Stopped) => RuntimeAction::Stopped,
            Some(RuntimeAction::Started | RuntimeAction::Restarted | RuntimeAction::Reloaded) => {
                RuntimeAction::Started
            }
        }),
    };
    if old_view != new_view {
        let _ = <State as crate::Diff>::diff(&old_view, &new_view, &mut std::io::stderr().lock());
    }

    // Nothing requested on either axis ⇒ nothing to do.
    if state.enablement.is_none() && state.runtime.is_none() {
        return Ok(super::Return::Unchanged);
    }

    let mut changed = false;
    let unit_files = vec![unit_name.clone()];
    let is_masked = initial_unit_state
        .map(UnitState::is_masked)
        .unwrap_or(false);

    // Track state mutations across dynamic unmask steps cleanly
    let mut current_file_state = initial_unit_state;

    if let Some(wanted_enablement) = state.enablement {
    match wanted_enablement {
        Enablement::Masked => {
            if !is_masked {
                let unit_path = std::path::Path::new("/etc/systemd/system").join(&unit_name);
                // The mask is a `/dev/null` symlink at this path. Anything
                // already there conflicts: a symlink (a previous mask or an
                // admin link) is replaced safely by `mask_unit_files`, but a
                // *real* file or directory (an admin-authored unit / drop-in)
                // has to be removed first. `mask` is an explicit, unambiguous
                // request to mask the unit, so we remove whatever is in the
                // way rather than refusing.
                let meta = std::fs::symlink_metadata(&unit_path).ok();
                if let Some(meta) = meta.as_ref()
                    && !meta.file_type().is_symlink()
                {
                    if meta.is_dir() {
                        std::fs::remove_dir_all(&unit_path)
                            .context("Failed to clear conflicting directory at mask target")?;
                    } else {
                        std::fs::remove_file(&unit_path)
                            .context("Failed to clear conflicting file at mask target")?;
                    }
                }

                manager
                    .mask_unit_files(unit_files, false, true) // Force point to /dev/null
                    .await
                    .context(format!("MaskUnitFiles({unit_name}) failed"))?;

                manager.reload().await.context("Daemon-reload failed")?;
                changed = true;
            }
        }
        Enablement::Disabled => {
            if is_masked {
                manager
                    .unmask_unit_files(unit_files.clone(), false)
                    .await
                    .context(format!("UnmaskUnitFiles({unit_name}) failed"))?;
                changed = true;
                current_file_state = read_file_state(&manager, &unit_name).await?;
            }
            if current_file_state
                .map(UnitState::needs_disable_call)
                .unwrap_or(false)
            {
                manager
                    .disable_unit_files(unit_files, false)
                    .await
                    .context(format!("DisableUnitFiles({unit_name}) failed"))?;
                changed = true;
            }
        }
        Enablement::Enabled => {
            if is_masked {
                manager
                    .unmask_unit_files(unit_files.clone(), false)
                    .await
                    .context(format!("UnmaskUnitFiles({unit_name}) failed"))?;
                changed = true;
                current_file_state = read_file_state(&manager, &unit_name).await?;
            }
            if current_file_state
                .map(UnitState::needs_enable_call)
                .unwrap_or(true)
            {
                manager
                    .enable_unit_files(unit_files, false, true) // Pass force=true to clear stale overrides
                    .await
                    .context(format!("EnableUnitFiles({unit_name}) failed"))?;
                changed = true;
            }
        }
    }
    } // end `if let Some(wanted_enablement)`

    if let Some(runtime_action) = state.runtime {
        let active = if changed {
            read_active_state(&manager, &conn, &unit_name).await?
        } else {
            initial_active_state
        };
        let is_running = active.map(ActiveState::is_running).unwrap_or(false);

        match runtime_action {
            RuntimeAction::Started => {
                if !is_running {
                    manager
                        .start_unit(unit_name.clone(), "replace".to_owned())
                        .await
                        .context(format!("StartUnit({unit_name}) failed"))?;
                    changed = true;
                }
            }
            RuntimeAction::Stopped => {
                if is_running {
                    manager
                        .stop_unit(unit_name.clone(), "replace".to_owned())
                        .await
                        .context(format!("StopUnit({unit_name}) failed"))?;
                    changed = true;
                }
            }
            RuntimeAction::Restarted => {
                manager
                    .restart_unit(unit_name.clone(), "replace".to_owned())
                    .await
                    .context(format!("RestartUnit({unit_name}) failed"))?;
                print_action(&unit_name, "restarted");
                changed = true;
            }
            RuntimeAction::Reloaded => {
                manager
                    .reload_unit(unit_name.clone(), "replace".to_owned())
                    .await
                    .context(format!("ReloadUnit({unit_name}) failed"))?;
                print_action(&unit_name, "reloaded");
                changed = true;
            }
        }
    }

    Ok(super::Return::from_changed(changed))
}