dance-ops 0.1.0

Deploy NixOS hosts safely from a local inventory
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
//! Concurrent review and deployment coordination.

mod host;
mod operations;
mod review;
mod rollback;

use std::{
    fmt::{self, Display, Formatter},
    io::{self, IsTerminal},
    num::NonZeroU32,
};

use dialoguer::{Confirm, console::style, theme::ColorfulTheme};
use futures::future::join_all;
use tabled::Table;

use self::{
    host::Outcome as HostOutcome,
    review::{HostRow, ReviewOutcome, ReviewedHost, Validity},
};
use crate::{
    error::Error,
    git::PendingUpdates,
    inventory::{Host, Inventory},
    process::ProcessContext,
    status::{self, ProgressDisplay},
    update::{self, UpdateOutcome},
    verification::ConfiguredOutcome,
};

/// Configures review, approval, and cleanup for a deployment.
#[derive(Clone, Copy)]
pub(crate) struct DeployOptions {
    /// Selects whether flake inputs are updated during review.
    pub(crate) update_flakes: bool,
    /// Selects whether changed flake locks are committed after deployment.
    pub(crate) commit_flakes: bool,
    /// Selects whether interactive approval has been bypassed.
    pub(crate) approved: bool,
    /// Configures work performed after approval.
    pub(crate) host: HostOptions,
}

/// Configures activation, verification, rollback, and cleanup.
#[derive(Clone, Copy)]
pub(crate) struct HostOptions {
    /// Selects whether a configured verifier is included.
    pub(crate) include_verifier: bool,
    /// Selects whether failed deployments restore their reviewed systems.
    pub(crate) rollback: bool,
    /// Selects post-deployment cleanup and generation retention.
    pub(crate) keep_generations: Option<NonZeroU32>,
}

/// Contains the actionable hosts and any failure found during review.
struct ReviewResult {
    /// Contains hosts whose desired systems differ from their active systems.
    outdated: Vec<ReviewedHost>,
    /// Contains the first failure encountered while collecting information.
    first_error: Option<Error>,
    /// Contains updated locks awaiting successful deployment.
    pending_updates: PendingUpdates,
}

/// Aggregates deployment outcomes for terminal output and exit status.
#[derive(Default)]
struct DeploymentSummary {
    /// Counts successful activations.
    activated: usize,
    /// Identifies deployment failures left in place.
    failed: Vec<String>,
    /// Identifies failures followed by successful restoration.
    rolled_back: Vec<String>,
    /// Identifies hosts that need operator recovery.
    recovery_required: Vec<String>,
    /// Identifies successful activations whose cleanup failed.
    cleanup_failed: Vec<String>,
    /// Retains the first deployment error.
    first_error: Option<Error>,
}

impl DeploymentSummary {
    /// Adds one host outcome.
    fn record(&mut self, host: String, outcome: HostOutcome) {
        let error = match outcome {
            HostOutcome::Activated => {
                self.activated += 1;
                return;
            }
            HostOutcome::Failed(error) => {
                self.failed.push(host);
                error
            }
            HostOutcome::RolledBack(error) => {
                self.rolled_back.push(host);
                error
            }
            HostOutcome::RecoveryRequired(error) => {
                self.recovery_required.push(host);
                error
            }
            HostOutcome::CleanupFailed(error) => {
                self.activated += 1;
                self.cleanup_failed.push(host);
                error
            }
        };
        self.first_error.get_or_insert(error);
    }

    /// Returns the first deployment failure when present.
    fn result(self) -> Result<(), Error> {
        self.first_error.map_or(Ok(()), Err)
    }
}

impl Display for DeploymentSummary {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "deployment: {} activated, {} failed",
            self.activated,
            self.failed.len()
        )?;
        for (count, label) in [
            (self.rolled_back.len(), "rolled back"),
            (self.recovery_required.len(), "recovery required"),
            (self.cleanup_failed.len(), "cleanup failed"),
        ] {
            if count != 0 {
                write!(formatter, ", {count} {label}")?;
            }
        }
        for (hosts, label) in [
            (&self.failed, "failed"),
            (&self.rolled_back, "rolled back"),
            (&self.recovery_required, "recovery required"),
            (&self.cleanup_failed, "cleanup failed"),
        ] {
            if !hosts.is_empty() {
                write!(formatter, "\n{label}: {}", hosts.join(", "))?;
            }
        }
        Ok(())
    }
}

/// Reports the selected hosts without activating them.
pub(crate) async fn status(
    inventory: Inventory,
    update_flakes: bool,
    processes: &ProcessContext<'_>,
) -> Result<(), Error> {
    let result = collect(inventory, update_flakes, false, true, processes).await?;
    result.first_error.map_or(Ok(()), Err)
}

/// Reviews and deploys the selected hosts.
pub(crate) async fn deploy(
    inventory: Inventory,
    options: DeployOptions,
    processes: &ProcessContext<'_>,
) -> Result<(), Error> {
    let ReviewResult {
        outdated,
        first_error,
        pending_updates,
    } = collect(
        inventory,
        options.update_flakes,
        options.commit_flakes,
        false,
        processes,
    )
    .await?;
    if outdated.is_empty() {
        return match first_error {
            Some(error) => Err(error),
            None => pending_updates.commit(processes).await,
        };
    }

    if !options.approved && !confirm()? {
        return first_error.map_or(Ok(()), Err);
    }

    let deployment = deploy_hosts(outdated, options.host, processes).await;
    if let Some(error) = first_error {
        return Err(error);
    }
    deployment?;
    pending_updates.commit(processes).await
}

/// Collects and displays the active and desired state of selected hosts.
async fn collect(
    inventory: Inventory,
    update_flakes: bool,
    commit_flakes: bool,
    validate_current: bool,
    processes: &ProcessContext<'_>,
) -> Result<ReviewResult, Error> {
    let flakes = inventory.flake_groups();
    let hosts = inventory.into_iter().collect::<Vec<_>>();
    let display = ProgressDisplay::new()?;
    let progresses = display.hosts(hosts.iter().map(Host::id));
    let initial_phase = if update_flakes {
        status::DeploymentPhase::UpdatingInputs
    } else {
        status::DeploymentPhase::CheckingStatus
    };
    for (host, progress) in hosts.iter().zip(&progresses) {
        status::set_phase(progress, host.id(), initial_phase);
    }
    let flakes = flakes
        .into_iter()
        .map(|(path, _)| {
            let dependent = hosts
                .iter()
                .zip(&progresses)
                .filter(|(host, _)| host.flake_path() == path.as_path())
                .map(|(_, progress)| progress.clone())
                .collect();
            (path, dependent)
        })
        .collect();

    let deployed = join_all(
        hosts
            .iter()
            .zip(&progresses)
            .map(|(host, progress)| review::deployed(host, processes, progress)),
    );
    let local = async {
        let updates = if update_flakes {
            update::flakes(flakes, commit_flakes, processes).await
        } else {
            UpdateOutcome::default()
        };
        let expected = join_all(hosts.iter().zip(&progresses).map(|(host, progress)| async {
            if updates.failed(host.flake_path()) {
                review::skip_expected(progress);
                None
            } else {
                status::set_phase(progress, host.id(), status::DeploymentPhase::CheckingStatus);
                Some(review::expected(host, processes, progress).await)
            }
        }));
        let validity = async {
            if validate_current {
                join_all(hosts.iter().zip(&progresses).map(|(host, progress)| async {
                    if updates.failed(host.flake_path()) {
                        review::skip_validity(progress);
                        None
                    } else {
                        Some(review::validity(host, processes, progress).await)
                    }
                }))
                .await
            } else {
                std::iter::repeat_with(|| None).take(hosts.len()).collect()
            }
        };
        let (expected, validity) = tokio::join!(expected, validity);
        (updates, expected, validity)
    };
    let (deployed, (updates, expected, validity)) = tokio::join!(deployed, local);
    let (update_error, pending_updates) = updates.into_parts();

    let mut rows = Vec::with_capacity(hosts.len());
    let mut outdated = Vec::new();
    let mut up_to_date = 0;
    let mut failed = 0;
    let mut validation_failed = 0;
    let mut first_error = update_error;
    for (((host, deployed), expected), validity) in
        hosts.into_iter().zip(deployed).zip(expected).zip(validity)
    {
        let valid = match validity {
            Some(Ok(ConfiguredOutcome::Verified)) => Validity::Valid,
            Some(Ok(ConfiguredOutcome::Missing)) => Validity::Missing,
            Some(Err(error)) => {
                validation_failed += 1;
                first_error.get_or_insert(error);
                Validity::Failed
            }
            None => Validity::Unchecked,
        };
        match (deployed, expected) {
            (Ok(deployed), Some(Ok(expected))) => {
                match review::review(host, deployed, &expected, valid) {
                    ReviewOutcome::UpToDate(row) => {
                        rows.push(row);
                        up_to_date += 1;
                    }
                    ReviewOutcome::OutOfDate(row, host) => {
                        rows.push(row);
                        outdated.push(host);
                    }
                }
            }
            (Err(error), _) | (_, Some(Err(error))) => {
                rows.push(HostRow::failed(&host, valid));
                failed += 1;
                first_error.get_or_insert(error);
            }
            (_, None) => {
                rows.push(HostRow::failed(&host, valid));
                failed += 1;
            }
        }
    }

    for progress in progresses {
        progress.finish_and_clear();
    }
    rows.sort_by_key(HostRow::needs_activation);
    if io::stdout().is_terminal() {
        println!("{}", Table::new(rows));
    } else {
        print!(
            "status: {up_to_date} up to date, {} out of date, {failed} failed",
            outdated.len()
        );
        if validate_current {
            print!(", {validation_failed} validation failed");
        }
        println!();
    }

    Ok(ReviewResult {
        outdated,
        first_error,
        pending_updates,
    })
}

/// Requests approval for an interactive deployment.
fn confirm() -> Result<bool, Error> {
    if !(io::stdin().is_terminal() && io::stderr().is_terminal()) {
        return Err(Error::ConfirmationRequired);
    }

    let theme = ColorfulTheme {
        success_prefix: style(">".to_owned()).for_stderr().green(),
        ..ColorfulTheme::default()
    };
    Confirm::with_theme(&theme)
        .with_prompt("Deploy the outdated systems?")
        .default(false)
        .interact()
        .map_err(|source| Error::Confirmation { source })
}

/// Deploys all reviewed hosts independently and concurrently.
async fn deploy_hosts(
    reviewed: Vec<ReviewedHost>,
    options: HostOptions,
    processes: &ProcessContext<'_>,
) -> Result<(), Error> {
    let display = ProgressDisplay::new()?;
    let progresses = display.hosts(reviewed.iter().map(ReviewedHost::id));
    let hosts = reviewed
        .iter()
        .map(|host| host.id().to_owned())
        .collect::<Vec<_>>();
    let outcomes = join_all(
        reviewed
            .into_iter()
            .zip(&progresses)
            .map(|(host, progress)| host::deploy(host, options, processes, progress)),
    )
    .await;

    let mut summary = DeploymentSummary::default();
    for ((host, outcome), progress) in hosts.into_iter().zip(outcomes).zip(progresses) {
        outcome.finish_progress(&host, &progress);
        summary.record(host, outcome);
    }
    println!("{summary}");
    summary.result()
}

#[cfg(test)]
mod tests {
    use super::{DeploymentSummary, HostOutcome};
    use crate::error::Error;

    /// Checks that successful restoration remains visible and fails the workflow.
    #[test]
    fn rolled_back_hosts_are_reported_as_failures() {
        let mut summary = DeploymentSummary::default();
        summary.record(
            "www".to_owned(),
            HostOutcome::RolledBack(Error::ConfirmationRequired),
        );

        assert_eq!(
            summary.to_string(),
            "deployment: 0 activated, 0 failed, 1 rolled back\nrolled back: www"
        );
        assert!(summary.result().is_err());
    }
}