ryra 0.9.14

A tool to test and deploy self-hosted services on a Linux server using rootless Podman and systemd. Built-in VM testing gives AI agents fast feedback loops for building infrastructure and deploying apps.
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
use anyhow::Result;
use dialoguer::{Confirm, Input};
use ryra_core::Step;
use ryra_core::data::{ServiceData, ServiceStatus};

use super::apply;

pub async fn run(
    services: &[String],
    all: bool,
    orphans: bool,
    yes: bool,
    dry_run: bool,
    purge: bool,
) -> Result<()> {
    let paths = ryra_core::config::ConfigPaths::resolve()?;

    let _lock = super::lock::MutationLock::acquire(dry_run)?;

    // `--orphans` purges every orphan service (leftover data with no
    // config entry). Never touches installed services. `--purge` is
    // implied — orphans have nothing else to preserve.
    // `-a` expands to every installed service. With `--purge` it also
    // sweeps every orphan. `ryra reset` remains distinct — it
    // additionally wipes ryra's own config, CAs, and registry caches.
    //
    // Removing more than one service at once — whether via `-a`,
    // `--orphans`, or an explicit `ryra remove a b c` — goes through the
    // single bulk prompt (`confirm_bulk`): list the services, settle the
    // purge question once, type "remove all" to confirm. The per-service
    // type-the-name confirm is reserved for the single-service case.
    let (targets, effective_purge, skip_prompt) = if orphans {
        let names: Vec<String> = ryra_core::data::enumerate_all()?
            .into_iter()
            .filter(|s| matches!(s.status, ServiceStatus::Orphan))
            .map(|s| s.service)
            .collect();
        if names.is_empty() {
            println!("No orphan data to purge.");
            return Ok(());
        }
        let eff = confirm_bulk(&names, true, yes, dry_run)?;
        (names, eff, true)
    } else if all {
        let mut names: Vec<String> = ryra_core::scan_managed_services()?;
        if purge {
            for svc in ryra_core::data::enumerate_all()? {
                if matches!(svc.status, ServiceStatus::Orphan) && !names.contains(&svc.service) {
                    names.push(svc.service);
                }
            }
        }
        if names.is_empty() {
            println!("Nothing to remove.");
            return Ok(());
        }
        names.sort();
        let eff = confirm_bulk(&names, purge, yes, dry_run)?;
        (names, eff, true)
    } else if services.len() > 1 {
        let eff = confirm_bulk(services, purge, yes, dry_run)?;
        (services.to_vec(), eff, true)
    } else {
        // Single named service: the per-service prompt in `remove_one`
        // handles confirmation. `-y`/`--dry-run` still skip it.
        (services.to_vec(), purge, yes || dry_run)
    };

    // Serialize concurrent removals so two processes don't clobber each
    // other's edits to authelia's configuration.yml when unregistering
    // OIDC clients. Matches the lock acquired in `add.rs::run`.
    let _auth_lock = if !dry_run {
        paths.ensure_dirs()?;
        let lock_path = paths.config_dir.join(".authelia-oidc.lock");
        let file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&lock_path)?;
        file.lock()?;
        Some(file)
    } else {
        None
    };

    for service in &targets {
        remove_one(service, effective_purge, skip_prompt, dry_run).await?;
    }
    Ok(())
}

/// Remove a single service. Handles both the "installed" path (stops +
/// deregisters via `remove_service`) and the "orphan + purge" path
/// (wipes leftover home dir + volumes directly).
async fn remove_one(service: &str, purge: bool, skip_prompt: bool, dry_run: bool) -> Result<()> {
    // Quadlet directory is the source of truth: if the marker'd
    // `.container` is present, the service is installed.
    let is_installed = ryra_core::is_service_installed(service);

    if is_installed {
        // Snapshot what preserve-mode would leave behind BEFORE anything
        // runs. After finalize_remove the service entry is gone and the
        // home dir may be gone too, which breaks volume→service owner
        // inference — enumerate_service would return None even though
        // the volumes still exist on disk.
        let preserved_snapshot = preserved_items(service);

        // Without --purge, if there's actually data on disk and we can
        // prompt, offer to upgrade to purge instead of leaving the user
        // to re-run with --purge.
        let effective_purge = purge
            || (!skip_prompt
                && !preserved_snapshot.is_empty()
                && super::is_interactive()
                && ask_purge_upgrade(service, &preserved_snapshot)?);

        let mode = if effective_purge {
            ryra_core::RemoveMode::Purge
        } else {
            ryra_core::RemoveMode::Preserve
        };
        let result = ryra_core::ops::plan_remove(&ryra_core::ops::RemoveRequest {
            service: service.to_string(),
            mode,
        })?;

        let preserved = if matches!(mode, ryra_core::RemoveMode::Preserve) {
            preserved_snapshot
        } else {
            Vec::new()
        };

        let tailnet_disable = result
            .steps
            .iter()
            .any(|s| matches!(s, Step::TailscaleDisable { .. }));

        if !skip_prompt {
            prompt_installed(service, mode, &preserved, tailnet_disable)?;
        }

        if dry_run {
            super::print_dry_run(&result.steps);
        } else {
            // A `TailscaleDisable` step needs the admin token in
            // preferences.toml. If the install's metadata says
            // tailscale but the token was never saved (e.g. a prior
            // configure ran before the preflight existed), prompt now
            // rather than crashing mid-apply.
            super::add::ensure_tailscale_token_for_steps(&result.steps, super::is_interactive())
                .await?;
            println!("Removing {service}...");
            apply::execute_all(&result.steps).await?;
            ryra_core::finalize_remove(&result.service_name)?;
            super::remove_hosts_entries(service);
            if ryra_core::WellKnownService::Caddy.matches(service) {
                super::remove_caddy_ca();
            }
            print_installed_tail(service, mode, &preserved)?;
        }
        return Ok(());
    }

    // Not installed — orphan path. Without --purge there's nothing to do
    // (the service is already deregistered) but if leftover data exists
    // and we can prompt, offer to wipe it instead of erroring out.
    let svc = ryra_core::data::enumerate_service(service)?;
    if !purge {
        match &svc {
            None => anyhow::bail!("no service named '{service}'"),
            Some(s) => {
                if !super::is_interactive() {
                    anyhow::bail!(
                        "'{service}' is already removed but still has data. Run `ryra remove {service} --purge` to wipe it."
                    );
                }
                // `skip_prompt` here means a bulk prompt already ran (or
                // `-y`): the purge question was settled and the answer
                // was "keep data". Nothing left to do for this orphan.
                if skip_prompt {
                    println!("{service}: already removed; data left in place.");
                    return Ok(());
                }
                if !ask_orphan_purge_upgrade(s)? {
                    return Ok(());
                }
            }
        }
    }

    // Orphan + purge: purge its leftover data.
    let svc = svc.ok_or_else(|| anyhow::anyhow!("no service or leftover data for '{service}'"))?;
    let steps = ryra_core::orphan_purge_steps(&svc);
    if steps.is_empty() {
        println!("{service}: nothing to purge.");
        return Ok(());
    }
    if !skip_prompt {
        prompt_orphan(&svc)?;
    }
    if dry_run {
        super::print_dry_run(&steps);
    } else {
        println!("Purging {service}...");
        apply::execute_all(&steps).await?;
        // A killed `ryra add` can leave a config entry with `installed = false`
        // *and* data on disk. The orphan branch handles the data; this drops
        // the stale entry so `ryra list -a` doesn't keep showing the service.
        // No-op when there's no matching entry (orphan with no stale row).
        ryra_core::finalize_remove(service)?;
        println!("\n{service} purged.");
    }
    Ok(())
}

/// Without `--purge`, ryra preserves data and points users at
/// `--purge` to wipe it later. Surfacing the option here saves a
/// re-run when they wanted it gone in the first place. The
/// type-the-name confirm still gates the destruction.
fn ask_purge_upgrade(service: &str, preserved: &[String]) -> Result<bool> {
    println!("'{service}' has data that would be preserved:");
    for line in preserved {
        println!("  {line}");
    }
    let upgrade = Confirm::new()
        .with_prompt("Also delete this data?")
        .default(false)
        .interact()?;
    println!();
    Ok(upgrade)
}

/// Same idea for orphan data: rather than bail with "re-run with
/// --purge", offer the upgrade in-place. The type-the-name confirm in
/// `prompt_orphan` still gates the destruction.
fn ask_orphan_purge_upgrade(svc: &ServiceData) -> Result<bool> {
    println!("'{}' is already removed but still has data:", svc.service);
    for p in &svc.data_paths {
        println!("  {}", p.display());
    }
    if svc.home_dir.exists() && !svc.data_paths.iter().any(|p| p == &svc.home_dir) {
        println!("  {}", svc.home_dir.display());
    }
    for v in &svc.volumes {
        println!("  volume:{}", v.name);
    }
    let upgrade = Confirm::new()
        .with_prompt("Wipe this data?")
        .default(false)
        .interact()?;
    println!();
    Ok(upgrade)
}

fn prompt_installed(
    service: &str,
    mode: ryra_core::RemoveMode,
    preserved: &[String],
    tailnet_disable: bool,
) -> Result<()> {
    if !super::is_interactive() {
        anyhow::bail!("use --yes (-y) to confirm removal in non-interactive mode");
    }
    let home_dir = ryra_core::service_home(service)?;
    println!("This will:");
    println!("  - Stop and remove {service}");
    if tailnet_disable {
        println!("  - Remove {service} from your tailnet (deregister via Tailscale Admin API)");
    }
    match mode {
        ryra_core::RemoveMode::Purge => {
            println!("  - Delete ALL data and config at {}", home_dir.display());
            println!("  - Remove any podman named volumes for this service");
        }
        ryra_core::RemoveMode::Preserve => {
            println!("  - Delete config + .env at {}", home_dir.display());
            // Services like twenty keep every byte in podman named
            // volumes and leave the home dir empty after preserve-
            // remove — the old copy told users "data preserved at
            // <empty-dir>" and they'd wonder where it went.
            if preserved.is_empty() {
                println!("  - (nothing else to preserve — this service stores no data)");
            } else {
                println!("  - Preserve:");
                for line in preserved {
                    println!("      {line}");
                }
                println!("    (run `ryra remove {service} --purge` later to delete)");
            }
        }
    }
    println!();
    let input: String = Input::new()
        .with_prompt(format!("Type \"{service}\" to confirm"))
        .interact_text()?;
    if input != *service {
        anyhow::bail!("cancelled");
    }
    Ok(())
}

/// Human-readable list of what `preserve`-mode removal will leave
/// behind: classified data paths under the home dir plus any podman
/// named volumes. Returns an empty vec for services that live entirely
/// in their `.env`/config.
fn preserved_items(service: &str) -> Vec<String> {
    let Ok(Some(svc)) = ryra_core::data::enumerate_service(service) else {
        return Vec::new();
    };
    let mut items: Vec<String> = svc
        .data_paths
        .iter()
        .map(|p| p.display().to_string())
        .collect();
    for v in &svc.volumes {
        items.push(format!("volume:{}", v.name));
    }
    items
}

fn prompt_orphan(svc: &ServiceData) -> Result<()> {
    if !super::is_interactive() {
        anyhow::bail!("use --yes (-y) to confirm in non-interactive mode");
    }
    println!("This will purge leftover data for '{}':", svc.service);
    for p in &svc.data_paths {
        println!("  {}", p.display());
    }
    if svc.home_dir.exists() {
        println!("  {}", svc.home_dir.display());
    }
    for v in &svc.volumes {
        println!("  volume:{}", v.name);
    }
    println!();
    let input: String = Input::new()
        .with_prompt(format!("Type \"{}\" to confirm", svc.service))
        .interact_text()?;
    if input != svc.service {
        anyhow::bail!("cancelled");
    }
    Ok(())
}

/// Confirm removal of several services at once. Lists them, settles the
/// purge question once for the whole batch, and gates on the user typing
/// "remove all". Returns the effective purge decision (the `--purge`
/// flag, or the answer to the batch-wide upgrade prompt). With `-y` /
/// `--dry-run` it doesn't prompt and just echoes back `purge`.
fn confirm_bulk(names: &[String], purge: bool, yes: bool, dry_run: bool) -> Result<bool> {
    if yes || dry_run {
        return Ok(purge);
    }
    if !super::is_interactive() {
        anyhow::bail!("use --yes (-y) to confirm in non-interactive mode");
    }
    println!("This will affect {} service(s):", names.len());
    for n in names {
        println!("  {n}");
    }
    println!();
    let installed = ryra_core::list_installed().unwrap_or_default();
    let tailnet_count = names
        .iter()
        .filter(|n| {
            installed.iter().any(|s| {
                &s.name == *n && matches!(s.exposure, ryra_core::Exposure::Tailscale { .. })
            })
        })
        .count();
    if tailnet_count > 0 {
        let plural = if tailnet_count == 1 { "" } else { "s" };
        println!(
            "{tailnet_count} service{plural} on your tailnet — will be deregistered via Tailscale Admin API."
        );
        println!();
    }

    // Settle purge once for the batch. With `--purge` it's already
    // decided. Otherwise, if any listed service has data on disk, offer
    // a single upgrade covering all of them rather than making the user
    // re-run with `--purge`.
    let effective_purge = if purge {
        println!("Mode: --purge — every listed service AND its data/volumes will be wiped.");
        println!();
        true
    } else {
        let with_data: Vec<(&String, Vec<String>)> = names
            .iter()
            .map(|n| (n, preserved_items(n)))
            .filter(|(_, items)| !items.is_empty())
            .collect();
        if with_data.is_empty() {
            println!("Mode: data-preserving (these services store no data, or it's already gone).");
            println!();
            false
        } else {
            println!("These services have data that would be preserved:");
            for (n, items) in &with_data {
                println!("  {n}:");
                for item in items {
                    println!("      {item}");
                }
            }
            let upgrade = Confirm::new()
                .with_prompt("Also delete ALL of this data?")
                .default(false)
                .interact()?;
            println!();
            upgrade
        }
    };

    let input: String = Input::new()
        .with_prompt("Type \"remove all\" to confirm")
        .interact_text()?;
    if input != "remove all" {
        anyhow::bail!("cancelled");
    }
    println!();
    Ok(effective_purge)
}

fn print_installed_tail(
    service: &str,
    mode: ryra_core::RemoveMode,
    preserved: &[String],
) -> Result<()> {
    match mode {
        ryra_core::RemoveMode::Purge => {
            println!("\n{service} removed (purged).");
        }
        ryra_core::RemoveMode::Preserve => {
            println!();
            if preserved.is_empty() {
                println!("{service} removed. No data was preserved.");
            } else {
                println!("{service} removed. Preserved:");
                for line in preserved {
                    println!("  {line}");
                }
                println!("Run `ryra remove {service} --purge` to delete.");
            }
        }
    }
    Ok(())
}