forjar 1.4.2

Rust-native Infrastructure as Code — bare-metal first, BLAKE3 state, provenance tracing
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
//! Fleet operations.

use super::apply::*;
use super::helpers::*;
use crate::core::types;
use crate::tripwire::eventlog;
use std::path::Path;

/// FJ-327: Re-run only previously failed resources.
pub(crate) fn cmd_retry_failed(
    file: &Path,
    state_dir: &Path,
    param_overrides: &[String],
    timeout: Option<u64>,
) -> Result<(), String> {
    let config = parse_and_validate(file)?;

    // Scan event logs for the most recent ResourceFailed events per machine
    let mut failed_resources: Vec<(String, String)> = Vec::new(); // (machine, resource)

    for (name, _machine) in &config.machines {
        let log_path = eventlog::event_log_path(state_dir, name);
        if !log_path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&log_path)
            .map_err(|e| format!("cannot read {}: {}", log_path.display(), e))?;

        // Find the last ApplyCompleted to mark the boundary, then collect
        // ResourceFailed events after the last ApplyCompleted
        let mut last_apply_line = 0usize;
        let lines: Vec<&str> = content.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.contains("ApplyCompleted") {
                last_apply_line = i;
            }
        }

        // Collect ResourceFailed events from the last apply run
        // We scan backwards from the last ApplyCompleted to find ResourceFailed in that run
        for line in &lines[..=last_apply_line] {
            if let Ok(event) = serde_json::from_str::<types::TimestampedEvent>(line) {
                if let types::ProvenanceEvent::ResourceFailed {
                    ref machine,
                    ref resource,
                    ..
                } = event.event
                {
                    // Check if this is from the most recent run (same machine)
                    if machine == name {
                        failed_resources.push((name.clone(), resource.clone()));
                    }
                }
            }
        }
    }

    if failed_resources.is_empty() {
        println!("No failed resources found in event logs. Nothing to retry.");
        return Ok(());
    }

    println!("Retrying {} failed resource(s):", failed_resources.len());
    for (machine, resource) in &failed_resources {
        println!("  {machine}{resource}");
    }
    println!();

    // Apply each failed resource individually
    for (machine, resource) in &failed_resources {
        println!("Retrying {resource} on {machine}...");
        cmd_apply(
            file,
            state_dir,
            Some(machine),
            Some(resource),
            None,  // tag_filter
            None,  // group_filter
            true,  // force — re-apply regardless of hash
            false, // dry_run
            false, // no_tripwire
            param_overrides,
            false, // auto_commit
            timeout,
            false, // json
            false, // verbose
            None,  // env_file
            None,  // workspace
            false, // report
            false, // force_unlock
            None,  // output_mode
            false, // progress
            false, // timing
            0,     // retry
            true,  // yes — no confirmation
            false, // parallel
            None,  // resource_timeout
            false, // rollback_on_failure
            None,  // max_parallel
            None,  // notify,
            None,  // subset
            false, // confirm_destructive
            None,  // exclude
            false, // sequential
            None,  // telemetry_endpoint
            false, // refresh
            None,  // force_tag
        )?;
    }

    println!(
        "\n{} Retried {} resource(s) successfully.",
        green(""),
        failed_resources.len()
    );
    Ok(())
}

/// FJ-324: Rolling deployment — apply N machines at a time, stop on failure.
pub(crate) fn cmd_rolling(
    file: &Path,
    state_dir: &Path,
    batch_size: usize,
    param_overrides: &[String],
    timeout: Option<u64>,
) -> Result<(), String> {
    let config = parse_and_validate(file)?;
    let machine_names: Vec<String> = config.machines.keys().cloned().collect();

    if machine_names.is_empty() {
        return Err("no machines defined in config".to_string());
    }

    let batches: Vec<Vec<String>> = machine_names
        .chunks(batch_size)
        .map(|chunk| chunk.to_vec())
        .collect();

    println!(
        "Rolling deploy: {} machines in {} batch(es) of {}",
        machine_names.len(),
        batches.len(),
        batch_size,
    );

    for (i, batch) in batches.iter().enumerate() {
        println!(
            "\n--- Batch {}/{}: {} ---",
            i + 1,
            batches.len(),
            batch.join(", ")
        );

        for machine in batch {
            cmd_apply(
                file,
                state_dir,
                Some(machine),
                None,  // resource_filter
                None,  // tag_filter
                None,  // group_filter
                false, // force
                false, // dry_run
                false, // no_tripwire
                param_overrides,
                false, // auto_commit
                timeout,
                false, // json
                false, // verbose
                None,  // env_file
                None,  // workspace
                false, // report
                false, // force_unlock
                None,  // output_mode
                false, // progress
                false, // timing
                0,     // retry
                true,  // yes
                false, // parallel
                None,  // resource_timeout
                false, // rollback_on_failure
                None,  // max_parallel
                None,  // notify,
                None,  // subset
                false, // confirm_destructive
                None,  // exclude
                false, // sequential
                None,  // telemetry_endpoint
                false, // refresh
                None,  // force_tag
            )?;
        }

        println!("Batch {}/{} complete.", i + 1, batches.len());
    }

    println!(
        "\n{} Rolling deploy complete: {} machines converged.",
        green(""),
        machine_names.len()
    );
    Ok(())
}

/// FJ-325: Canary deployment — apply to one machine first, then rest.
pub(crate) fn cmd_canary(
    file: &Path,
    state_dir: &Path,
    canary_machine: &str,
    auto_proceed: bool,
    param_overrides: &[String],
    timeout: Option<u64>,
) -> Result<(), String> {
    let config = parse_and_validate(file)?;

    if !config.machines.contains_key(canary_machine) {
        return Err(format!(
            "canary machine '{}' not found in config (available: {})",
            canary_machine,
            config
                .machines
                .keys()
                .cloned()
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }

    // Phase 1: Apply to canary
    println!("=== Canary Phase: applying to '{canary_machine}' ===\n");

    cmd_apply(
        file,
        state_dir,
        Some(canary_machine),
        None,
        None,
        None,
        false,
        false,
        false,
        param_overrides,
        false,
        timeout,
        false,
        false,
        None,
        None,
        false,
        false,
        None,
        false,
        false,
        0,
        true,
        false,
        None,
        false,
        None,
        None,
        None,  // subset
        false, // confirm_destructive
        None,  // exclude
        false, // sequential
        None,  // telemetry_endpoint
        false, // refresh
        None,  // force_tag
    )?;

    println!("\n{} Canary '{}' succeeded.", green(""), canary_machine);

    // Phase 2: Apply to remaining machines
    let remaining: Vec<String> = config
        .machines
        .keys()
        .filter(|k| *k != canary_machine)
        .cloned()
        .collect();

    if remaining.is_empty() {
        println!("No remaining machines. Canary deploy complete.");
        return Ok(());
    }

    if !auto_proceed {
        println!(
            "\nCanary succeeded. Remaining machines: {}",
            remaining.join(", ")
        );
        println!("Use --auto-proceed to skip this confirmation in CI.");
        println!("Proceeding to remaining machines...");
    }

    println!(
        "\n=== Fleet Phase: applying to {} remaining machine(s) ===\n",
        remaining.len()
    );

    for machine in &remaining {
        cmd_apply(
            file,
            state_dir,
            Some(machine),
            None,
            None,
            None,
            false,
            false,
            false,
            param_overrides,
            false,
            timeout,
            false,
            false,
            None,
            None,
            false,
            false,
            None,
            false,
            false,
            0,
            true,
            false,
            None,
            false,
            None,
            None,
            None,  // subset
            false, // confirm_destructive
            None,  // exclude
            false, // sequential
            None,  // telemetry_endpoint
            false, // refresh
            None,  // force_tag
        )?;
    }

    println!(
        "\n{} Canary deploy complete: canary + {} machine(s) converged.",
        green(""),
        remaining.len()
    );
    Ok(())
}

/// FJ-326: List all machines with connection status.
pub(crate) fn cmd_inventory(file: &Path, json: bool) -> Result<(), String> {
    let config = parse_and_validate(file)?;

    let mut results: Vec<serde_json::Value> = Vec::new();

    for (name, machine) in &config.machines {
        let is_local = machine.addr == "127.0.0.1" || machine.addr == "localhost";
        let is_container =
            machine.addr == "container" || machine.transport.as_deref() == Some("container");

        let (status, transport_type) = if is_local {
            ("reachable".to_string(), "local")
        } else if is_container {
            ("container".to_string(), "container")
        } else {
            // Try SSH connection test: ssh -o BatchMode=yes -o ConnectTimeout=5
            let user_host = format!("{}@{}", machine.user, machine.addr);
            let mut ssh_args = vec!["-o", "BatchMode=yes", "-o", "ConnectTimeout=5"];
            if let Some(ref key) = machine.ssh_key {
                ssh_args.push("-i");
                ssh_args.push(key);
            }
            ssh_args.push(&user_host);
            ssh_args.push("echo");
            ssh_args.push("ok");
            let result = std::process::Command::new("ssh")
                .args(&ssh_args)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status();
            match result {
                Ok(s) if s.success() => ("reachable".to_string(), "ssh"),
                _ => ("unreachable".to_string(), "ssh"),
            }
        };

        let resource_count = config
            .resources
            .values()
            .filter(|r| match &r.machine {
                types::MachineTarget::Single(m) => m == name,
                types::MachineTarget::Multiple(ms) => ms.contains(&name.to_string()),
            })
            .count();

        if json {
            results.push(serde_json::json!({
                "name": name,
                "hostname": machine.hostname,
                "addr": machine.addr,
                "user": machine.user,
                "arch": machine.arch,
                "transport": transport_type,
                "status": status,
                "roles": machine.roles,
                "resources": resource_count,
            }));
        } else {
            let status_icon = match status.as_str() {
                "reachable" => green(""),
                "container" => dim(""),
                _ => red(""),
            };
            println!(
                "  {} {} ({}) [{}] — {} via {} ({} resources)",
                status_icon,
                name,
                machine.hostname,
                machine.addr,
                status,
                transport_type,
                resource_count,
            );
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&results).unwrap_or_default()
        );
    } else {
        println!("\n{} machines in inventory", config.machines.len());
    }

    Ok(())
}