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
//! Observability exports.

use super::helpers::*;
use crate::core::{state, types};
use std::path::Path;

// FJ-382: Prometheus exposition format
pub(crate) fn cmd_status_prometheus(
    state_dir: &Path,
    machine_filter: Option<&str>,
) -> Result<(), String> {
    let entries =
        std::fs::read_dir(state_dir).map_err(|e| format!("cannot read state dir: {e}"))?;

    let mut converged = 0u64;
    let mut failed = 0u64;
    let mut drifted = 0u64;
    let mut total = 0u64;

    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if let Some(filter) = machine_filter {
            if name != filter {
                continue;
            }
        }
        if !entry.path().is_dir() {
            continue;
        }
        if let Some(lock) = state::load_lock(state_dir, &name)? {
            for (_, rl) in &lock.resources {
                total += 1;
                match rl.status {
                    types::ResourceStatus::Converged => converged += 1,
                    types::ResourceStatus::Failed => failed += 1,
                    types::ResourceStatus::Drifted => drifted += 1,
                    types::ResourceStatus::Unknown => {}
                }
            }
        }
    }

    println!("# HELP forjar_resources_total Total managed resources");
    println!("# TYPE forjar_resources_total gauge");
    println!("forjar_resources_total {total}");
    println!("# HELP forjar_resources_converged Converged resources");
    println!("# TYPE forjar_resources_converged gauge");
    println!("forjar_resources_converged {converged}");
    println!("# HELP forjar_resources_failed Failed resources");
    println!("# TYPE forjar_resources_failed gauge");
    println!("forjar_resources_failed {failed}");
    println!("# HELP forjar_resources_drifted Drifted resources");
    println!("# TYPE forjar_resources_drifted gauge");
    println!("forjar_resources_drifted {drifted}");

    Ok(())
}

// ── FJ-442: status --export ──

fn collect_export_entries(state_dir: &Path, machine: Option<&str>) -> Result<Vec<String>, String> {
    let mut entries = Vec::new();
    if !state_dir.exists() {
        return Ok(entries);
    }
    let dir_entries = std::fs::read_dir(state_dir).map_err(|e| e.to_string())?;
    for entry in dir_entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let m_name = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();
        if m_name.starts_with('.') {
            continue;
        }
        if let Some(filter) = machine {
            if m_name != filter {
                continue;
            }
        }
        if let Ok(Some(lock)) = state::load_lock(state_dir, &m_name) {
            for (rname, rl) in &lock.resources {
                entries.push(format!(
                    "{{\"machine\":\"{}\",\"resource\":\"{}\",\"status\":\"{:?}\",\"hash\":\"{}\"}}",
                    m_name, rname, rl.status, rl.hash
                ));
            }
        }
    }
    Ok(entries)
}

pub(crate) fn cmd_status_export(
    state_dir: &Path,
    machine: Option<&str>,
    output_path: &Path,
    json: bool,
) -> Result<(), String> {
    let entries = collect_export_entries(state_dir, machine)?;

    let content = format!("[{}]", entries.join(",\n"));
    std::fs::write(output_path, &content).map_err(|e| e.to_string())?;

    if json {
        println!(
            "{{\"exported\":true,\"path\":\"{}\",\"entries\":{}}}",
            output_path.display(),
            entries.len()
        );
    } else {
        println!(
            "{} Exported {} entries to {}",
            green(""),
            entries.len(),
            output_path.display()
        );
    }
    Ok(())
}

// ── FJ-402: status --anomalies ──

fn detect_resource_anomalies(
    m_name: &str,
    name: &str,
    rl: &types::ResourceLock,
    anomalies: &mut Vec<(String, String, String)>,
) {
    match rl.status {
        types::ResourceStatus::Failed => {
            anomalies.push((
                m_name.to_string(),
                name.to_string(),
                "status is Failed".to_string(),
            ));
        }
        types::ResourceStatus::Drifted => {
            anomalies.push((
                m_name.to_string(),
                name.to_string(),
                "status is Drifted".to_string(),
            ));
        }
        _ => {}
    }
    if rl.applied_at.is_none() {
        anomalies.push((
            m_name.to_string(),
            name.to_string(),
            "missing applied_at timestamp".to_string(),
        ));
    }
}

fn collect_anomalies(
    state_dir: &Path,
    machine: Option<&str>,
) -> Result<Vec<(String, String, String)>, String> {
    let mut anomalies = Vec::new();
    if !state_dir.exists() {
        return Ok(anomalies);
    }
    let entries = std::fs::read_dir(state_dir).map_err(|e| e.to_string())?;
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let m_name = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();
        if let Some(filter) = machine {
            if m_name != filter {
                continue;
            }
        }
        if let Ok(Some(lock)) = state::load_lock(state_dir, &m_name) {
            for (name, rl) in &lock.resources {
                detect_resource_anomalies(&m_name, name, rl, &mut anomalies);
            }
        }
    }
    Ok(anomalies)
}

pub(crate) fn cmd_status_anomalies(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let anomalies = collect_anomalies(state_dir, machine)?;

    if json {
        let entries: Vec<String> = anomalies
            .iter()
            .map(|(m, r, issue)| {
                format!("{{\"machine\":\"{m}\",\"resource\":\"{r}\",\"issue\":\"{issue}\"}}")
            })
            .collect();
        println!("[{}]", entries.join(","));
    } else if anomalies.is_empty() {
        println!("{} No anomalies detected", green(""));
    } else {
        println!("{} {} anomalie(s) detected:", yellow(""), anomalies.len());
        for (m, r, issue) in &anomalies {
            println!("  {} {}/{}{}", red(""), m, r, issue);
        }
    }
    Ok(())
}

// ── FJ-407: status --diff-from ──

fn diff_both_present(
    m_name: &str,
    cur: &types::StateLock,
    snap: &types::StateLock,
    diffs: &mut Vec<(String, String, String)>,
) {
    for (name, cur_rl) in &cur.resources {
        if let Some(snap_rl) = snap.resources.get(name) {
            if cur_rl.hash != snap_rl.hash {
                diffs.push((m_name.to_string(), name.clone(), "modified".to_string()));
            }
        } else {
            diffs.push((m_name.to_string(), name.clone(), "added".to_string()));
        }
    }
    for name in snap.resources.keys() {
        if !cur.resources.contains_key(name) {
            diffs.push((m_name.to_string(), name.clone(), "removed".to_string()));
        }
    }
}

fn add_all_as(
    m_name: &str,
    lock: &types::StateLock,
    change: &str,
    diffs: &mut Vec<(String, String, String)>,
) {
    for name in lock.resources.keys() {
        diffs.push((m_name.to_string(), name.clone(), change.to_string()));
    }
}

fn diff_machine_resources(
    m_name: &str,
    current: Option<types::StateLock>,
    snapshot: Option<types::StateLock>,
    diffs: &mut Vec<(String, String, String)>,
) {
    match (current, snapshot) {
        (Some(cur), Some(snap)) => diff_both_present(m_name, &cur, &snap, diffs),
        (Some(cur), None) => add_all_as(m_name, &cur, "added", diffs),
        (None, Some(snap)) => add_all_as(m_name, &snap, "removed", diffs),
        (None, None) => {}
    }
}

fn collect_diffs(
    state_dir: &Path,
    snap_dir: &Path,
) -> Result<Vec<(String, String, String)>, String> {
    let mut diffs = Vec::new();
    if !state_dir.exists() {
        return Ok(diffs);
    }
    let entries = std::fs::read_dir(state_dir).map_err(|e| e.to_string())?;
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let m_name = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();
        if m_name.starts_with('.') {
            continue;
        }
        let current = state::load_lock(state_dir, &m_name).ok().flatten();
        let snapshot = state::load_lock(snap_dir, &m_name).ok().flatten();
        diff_machine_resources(&m_name, current, snapshot, &mut diffs);
    }
    Ok(diffs)
}

fn print_diff_output(diffs: &[(String, String, String)], snapshot_name: &str, json: bool) {
    if json {
        let entries: Vec<String> = diffs
            .iter()
            .map(|(m, r, change)| {
                format!("{{\"machine\":\"{m}\",\"resource\":\"{r}\",\"change\":\"{change}\"}}")
            })
            .collect();
        println!("[{}]", entries.join(","));
    } else if diffs.is_empty() {
        println!(
            "{} No changes since snapshot '{}'",
            green(""),
            snapshot_name
        );
    } else {
        println!("Changes since snapshot '{snapshot_name}':");
        for (m, r, change) in diffs {
            let prefix = match change.as_str() {
                "added" => green("+"),
                "removed" => red("-"),
                "modified" => yellow("~"),
                _ => dim("?"),
            };
            println!("  {prefix} {m}/{r}");
        }
    }
}

pub(crate) fn cmd_status_diff_from(
    state_dir: &Path,
    snapshot_name: &str,
    json: bool,
) -> Result<(), String> {
    let snap_dir = state_dir.join(".snapshots").join(snapshot_name);
    if !snap_dir.exists() {
        return Err(format!("snapshot '{snapshot_name}' not found"));
    }

    let diffs = collect_diffs(state_dir, &snap_dir)?;
    print_diff_output(&diffs, snapshot_name, json);
    Ok(())
}

/// FJ-594: Summarize errors across all machines.
fn collect_errors_for_machine(
    state_dir: &Path,
    m: &str,
    errors: &mut Vec<(String, String, String)>,
) {
    let lock_path = state_dir.join(m).join("state.lock.yaml");
    if !lock_path.exists() {
        return;
    }
    let content = std::fs::read_to_string(&lock_path).unwrap_or_default();
    if let Ok(lock) = serde_yaml_ng::from_str::<crate::core::types::StateLock>(&content) {
        for (rname, rlock) in &lock.resources {
            if rlock.status == crate::core::types::ResourceStatus::Failed {
                let detail = if rlock.details.is_empty() {
                    "no details".to_string()
                } else {
                    rlock
                        .details
                        .iter()
                        .map(|(k, v)| format!("{k}={v:?}"))
                        .collect::<Vec<_>>()
                        .join(", ")
                };
                errors.push((m.to_string(), rname.clone(), detail));
            }
        }
    }
}

pub(crate) fn cmd_status_error_summary(
    state_dir: &Path,
    machine: Option<&str>,
    json: bool,
) -> Result<(), String> {
    let machines = discover_machines(state_dir);
    let mut errors: Vec<(String, String, String)> = Vec::new();

    for m in &machines {
        if let Some(filter) = machine {
            if m != filter {
                continue;
            }
        }
        collect_errors_for_machine(state_dir, m, &mut errors);
    }

    if json {
        let items: Vec<String> = errors
            .iter()
            .map(|(m, r, d)| {
                format!(
                    r#"{{"machine":"{}","resource":"{}","error":"{}"}}"#,
                    m,
                    r,
                    d.replace('"', "\\\"")
                )
            })
            .collect();
        println!(
            r#"{{"errors":[{}],"count":{}}}"#,
            items.join(","),
            errors.len()
        );
    } else if errors.is_empty() {
        println!("No errors found across lock files");
    } else {
        println!("Error summary ({} failures):", errors.len());
        for (m, r, d) in &errors {
            println!("  {m}:{r}{d}");
        }
    }
    Ok(())
}