xbp 10.17.2

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
use colored::Colorize;
use tokio::process::Command;

use crate::cli::commands;
use crate::cli::error::{CliResult, ErrorFactory};
use crate::cli::ui;
use crate::commands::kafka_logs::LogConfig;
#[cfg(feature = "docker")]
use crate::commands::print_docker_ps;
use crate::commands::service::load_xbp_config;
use crate::commands::{
    pm2_env, pm2_flush, pm2_list, pm2_logs, pm2_monitor, pm2_resurrect, pm2_save, pm2_snapshot,
    pm2_start_wrapper, run_ports, start_log_shipping, tail_kafka_topic,
};
use crate::logging::{get_log_directory, log_error, log_info, log_warn};
use crate::strategies::get_all_services;
use crate::utils::command_exists;

pub async fn handle_start(args: Vec<String>, debug: bool) -> CliResult<()> {
    if let Err(e) =
        ui::with_loader("Starting process with PM2", pm2_start_wrapper(args, debug)).await
    {
        let _ = log_error("start", "Failed to start process", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "start",
            "start process via PM2",
            e,
            Some("Pass a valid start command, e.g. `xbp start \"./binary --port 3000\"`."),
        ));
    }
    if let Err(e) = ui::with_loader("Saving PM2 process table", pm2_save(debug)).await {
        let _ = log_error("start", "pm2 save failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "start",
            "persist PM2 process list",
            e,
            Some("Ensure PM2 has permission to write its dump file."),
        ));
    }
    if let Err(e) = ui::with_loader("Refreshing PM2 process list", pm2_list(debug)).await {
        let _ = log_error("start", "pm2 list failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "start",
            "list PM2 processes",
            e,
            None,
        ));
    }
    Ok(())
}

pub async fn handle_logs_flag() -> CliResult<()> {
    let log_dir = get_log_directory().await.map_err(|e| {
        ErrorFactory::operation("logs", "resolve log directory", e.to_string(), None)
    })?;

    ui::section("Logs");
    ui::divider(56);
    println!(
        "  {} {}",
        "Path:".bright_white(),
        log_dir.display().to_string().cyan()
    );

    if cfg!(target_os = "windows") {
        println!("  {}", "Opening in Explorer...".dimmed());
        let _ = Command::new("explorer").arg(log_dir).spawn();
    } else {
        println!("  {}", "Quick view:".bright_blue());
        println!("    cd {}", log_dir.display().to_string().cyan());
        println!("    tail -f xbp-*.log");
    }

    Ok(())
}

pub async fn handle_ports(
    cmd: commands::PortsCmd,
    global_port: Option<u16>,
    debug: bool,
) -> CliResult<()> {
    let mut args: Vec<String> = Vec::new();
    let port: Option<u16> = global_port.or(cmd.port);
    if let Some(p) = port {
        args.push("-p".to_string());
        args.push(p.to_string());
    }
    if cmd.kill {
        args.push("--kill".to_string());
        args.push("-k".to_string());
    }
    if cmd.nginx {
        args.push("-n".to_string());
        args.push("--nginx".to_string());
    }
    if cmd.full {
        args.push("--full".to_string());
    }
    if cmd.no_local {
        args.push("--no-local".to_string());
    }
    if cmd.exposure {
        args.push("--exposure".to_string());
    }
    if let Err(e) = ui::with_loader("Scanning host ports", run_ports(&args, debug)).await {
        let _ = log_error("ports", "Error running ports", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "ports",
            "inspect ports",
            e,
            Some("Use `xbp ports -h` to verify valid flags and arguments."),
        ));
    }
    Ok(())
}

pub async fn handle_logs(cmd: commands::LogsCmd, debug: bool) -> CliResult<()> {
    let commands::LogsCmd {
        project,
        ssh_host,
        ssh_username,
        ssh_password,
    } = cmd;

    let remote_requested = ssh_host.is_some() || ssh_username.is_some() || ssh_password.is_some();
    if remote_requested {
        if let Err(e) = ui::with_loader(
            "Opening remote log stream",
            crate::commands::ssh_logs::run_remote_logs(
                project.clone(),
                ssh_host,
                ssh_username,
                ssh_password,
                debug,
            ),
        )
        .await
        {
            let _ = log_error("logs", "Remote logs failed", Some(&e)).await;
            return Err(ErrorFactory::operation(
                "logs",
                "stream remote logs",
                e,
                Some("Verify SSH host, username, and password parameters."),
            ));
        }
        return Ok(());
    }

    #[cfg(feature = "docker")]
    {
        if let Some(ref target) = project {
            match crate::commands::try_stream_docker_logs(target, debug).await {
                Ok(Some(())) => return Ok(()),
                Ok(None) => {}
                Err(e) => {
                    let _ = log_error("docker", "docker logs failed", Some(&e)).await;
                    return Err(ErrorFactory::operation(
                        "docker",
                        "stream docker logs",
                        e,
                        Some("Check Docker daemon health and container identifiers."),
                    ));
                }
            }
        }
    }

    if let Err(e) = ui::with_loader("Opening PM2 log stream", pm2_logs(project, debug)).await {
        let _ = log_error("pm2", "pm2 logs failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "pm2",
            "stream PM2 logs",
            e,
            Some("Run `xbp list` to inspect available PM2 process names."),
        ));
    }
    Ok(())
}

pub async fn handle_list(debug: bool) -> CliResult<()> {
    // Show PM2 processes
    if let Err(e) = ui::with_loader("Loading PM2 processes", pm2_list(debug)).await {
        let _ = log_error("pm2", "pm2 list failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "pm2",
            "list PM2 processes",
            e,
            Some("Ensure PM2 is installed and running."),
        ));
    }

    // Show docker ps snapshot when available
    #[cfg(feature = "docker")]
    {
        if let Err(e) = print_docker_ps(debug).await {
            let _ = log_warn("docker", "docker ps snapshot failed", Some(&e)).await;
        }
    }

    // Show systemd service status if configured
    if let Err(e) = show_systemd_status(debug).await {
        if debug {
            let _ = log_warn(
                "systemd",
                "Could not check systemd status",
                Some(&e.to_string()),
            )
            .await;
        }
    }

    Ok(())
}

pub async fn handle_snapshot(debug: bool) -> CliResult<()> {
    match ui::with_loader("Creating PM2 snapshot", pm2_snapshot(debug)).await {
        Ok(path) => {
            let _ = log_info(
                "snapshot",
                "Saved PM2 snapshot",
                Some(&path.display().to_string()),
            )
            .await;
            println!("Saved PM2 snapshot to {}", path.display());
            Ok(())
        }
        Err(e) => {
            let _ = log_error("snapshot", "PM2 snapshot failed", Some(&e)).await;
            Err(ErrorFactory::operation(
                "snapshot",
                "create PM2 snapshot",
                e,
                Some("Verify PM2_HOME is writable."),
            ))
        }
    }
}

pub async fn handle_resurrect(debug: bool) -> CliResult<()> {
    if let Err(e) = ui::with_loader("Restoring PM2 snapshot", pm2_resurrect(debug)).await {
        let _ = log_error("pm2", "pm2 resurrect failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "pm2",
            "resurrect PM2 processes",
            e,
            Some("Create a snapshot first with `xbp snapshot`."),
        ));
    }
    Ok(())
}

pub async fn handle_stop(target: Option<String>, debug: bool) -> CliResult<()> {
    let target = target.unwrap_or_else(|| "all".to_string());
    if let Err(e) = ui::with_loader(
        &format!("Stopping PM2 target `{}`", target),
        crate::commands::pm2_stop(&target, debug),
    )
    .await
    {
        let _ = log_error("pm2", "pm2 stop failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "pm2",
            &format!("stop `{}`", target),
            e,
            Some("Use `xbp list` to confirm process names/ids."),
        ));
    }
    Ok(())
}

pub async fn handle_flush(target: Option<String>, debug: bool) -> CliResult<()> {
    if let Err(e) = ui::with_loader("Flushing PM2 logs", pm2_flush(target.as_deref(), debug)).await
    {
        let _ = log_error("pm2", "pm2 flush failed", Some(&e)).await;
        return Err(ErrorFactory::operation("pm2", "flush PM2 logs", e, None));
    }
    Ok(())
}

pub async fn handle_env(target: String, debug: bool) -> CliResult<()> {
    if let Err(e) = ui::with_loader(
        &format!("Inspecting PM2 env for `{}`", target),
        pm2_env(&target, debug),
    )
    .await
    {
        let _ = log_error("pm2", "pm2 env failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "pm2",
            &format!("inspect env for `{}`", target),
            e,
            Some("Use PM2 process name or numeric id."),
        ));
    }
    Ok(())
}

pub async fn handle_monitor(cmd: commands::MonitorCmd, debug: bool) -> CliResult<()> {
    match cmd.command {
        Some(commands::MonitorSubCommand::Check) => {
            if !crate::commands::service::is_xbp_project().await {
                return crate::cli::handlers::project::handle_project_selection().await;
            }
            if let Err(e) = ui::with_loader(
                "Running monitor check",
                crate::commands::monitor::run_single_check(),
            )
            .await
            {
                let _ = log_error("monitor", "Monitor check failed", Some(&e.to_string())).await;
                return Err(ErrorFactory::operation(
                    "monitor",
                    "run monitor check",
                    e.to_string(),
                    Some("Confirm monitoring config fields are present."),
                ));
            }
        }
        Some(commands::MonitorSubCommand::Start) => {
            if !crate::commands::service::is_xbp_project().await {
                return crate::cli::handlers::project::handle_project_selection().await;
            }
            if let Err(e) = ui::with_loader(
                "Starting monitor daemon",
                crate::commands::monitor::start_monitor_daemon(),
            )
            .await
            {
                let _ = log_error("monitor", "Monitor daemon failed", Some(&e.to_string())).await;
                return Err(ErrorFactory::operation(
                    "monitor",
                    "start monitor daemon",
                    e.to_string(),
                    Some("Validate monitor config and process permissions."),
                ));
            }
        }
        None => {
            if let Err(e) = ui::with_loader("Opening PM2 monitor UI", pm2_monitor(debug)).await {
                let _ = log_error("monitor", "PM2 monitor failed", Some(&e)).await;
                return Err(ErrorFactory::operation(
                    "monitor",
                    "open PM2 monitor",
                    e,
                    Some("Ensure PM2 daemon is available."),
                ));
            }
        }
    }
    Ok(())
}

pub async fn handle_tail(cmd: commands::TailCmd, _debug: bool) -> CliResult<()> {
    if cmd.kafka {
        match LogConfig::from_xbp_config().await {
            Ok(Some(config)) => {
                if let Err(e) =
                    ui::with_loader("Tailing Kafka topic", tail_kafka_topic(&config)).await
                {
                    let _ =
                        log_error("tail", "Failed to tail Kafka topic", Some(&e.to_string())).await;
                    return Err(ErrorFactory::operation(
                        "tail",
                        "tail Kafka topic",
                        e.to_string(),
                        Some("Check Kafka broker/topic values in config."),
                    ));
                }
            }
            Ok(None) => {
                let _ = log_error("tail", "No log configuration found in xbp.json", None).await;
                return Err(ErrorFactory::config(
                    "tail",
                    "No log configuration found in xbp.json",
                    Some("Configure kafka logging fields or run `xbp tail` without `--kafka`."),
                ));
            }
            Err(e) => {
                let _ =
                    log_error("tail", "Failed to load configuration", Some(&e.to_string())).await;
                return Err(ErrorFactory::operation(
                    "tail",
                    "load log configuration",
                    e.to_string(),
                    Some("Fix xbp config syntax/path issues and retry."),
                ));
            }
        }
    } else if cmd.ship {
        if let Err(e) = ui::with_loader("Shipping logs to Kafka", start_log_shipping()).await {
            let _ = log_error("tail", "Failed to ship logs", Some(&e.to_string())).await;
            return Err(ErrorFactory::operation(
                "tail",
                "ship logs",
                e.to_string(),
                Some("Ensure log shipping backend is configured correctly."),
            ));
        }
    } else if let Err(e) = ui::with_loader("Starting live log tail", start_log_shipping()).await {
        let _ = log_error("tail", "Failed to tail logs", Some(&e.to_string())).await;
        return Err(ErrorFactory::operation(
            "tail",
            "tail logs",
            e.to_string(),
            Some("Ensure runtime log shipping prerequisites are met."),
        ));
    }
    Ok(())
}

pub async fn show_systemd_status(debug: bool) -> CliResult<()> {
    if !cfg!(target_os = "linux") || !command_exists("systemctl") {
        return Ok(());
    }

    // Try to load the config - if not in an xbp project, skip silently
    let config = match load_xbp_config().await {
        Ok(cfg) => cfg,
        Err(_) => return Ok(()), // Not in an xbp project, skip
    };

    // Collect all systemd service names from config
    let mut systemd_services = Vec::new();

    // Check project-level systemd_service_name
    if let Some(ref name) = config.systemd_service_name {
        systemd_services.push(name.clone());
    }

    // Check service-level systemd_service_name
    let services = get_all_services(&config);
    for service in services {
        if let Some(ref name) = service.systemd_service_name {
            if !systemd_services.contains(name) {
                systemd_services.push(name.clone());
            }
        }
    }

    if systemd_services.is_empty() {
        return Ok(()); // No systemd services configured
    }

    ui::section("Systemd Services");
    ui::divider(60);

    for service_name in systemd_services {
        check_systemd_service_status(&service_name, debug).await;
    }

    Ok(())
}

async fn check_systemd_service_status(service_name: &str, debug: bool) {
    // Try to check service status without sudo first
    let output = Command::new("systemctl")
        .arg("status")
        .arg(service_name)
        .arg("--no-pager")
        .output()
        .await;

    match output {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);

            // Check if service exists
            if stderr.contains("could not be found") || stderr.contains("not loaded") {
                ui::status_line(service_name, "Not Found", false);
                if debug {
                    println!("    Service unit not found in systemd");
                }
                return;
            }

            // Check if we have permission issues
            if stderr.contains("Permission denied") || stderr.contains("Failed to get properties") {
                ui::status_line(service_name, "Permission Denied", false);
                if debug {
                    println!("    Run with sudo to see full status");
                }
                return;
            }

            // Parse status from output
            let status = if stdout.contains("Active: active (running)") {
                "Running".green()
            } else if stdout.contains("Active: inactive (dead)") {
                "Stopped".dimmed()
            } else if stdout.contains("Active: failed") {
                "Failed".red()
            } else if stdout.contains("Active: activating") {
                "Starting".yellow()
            } else if stdout.contains("Active: deactivating") {
                "Stopping".yellow()
            } else {
                "Unknown".yellow()
            };

            let ok = stdout.contains("Active: active (running)");
            println!(
                "  {} {} {}",
                if ok {
                    "".bright_green().bold()
                } else {
                    "".bright_yellow().bold()
                },
                service_name.bright_white(),
                status
            );

            if debug {
                // Show first few lines of status
                let lines: Vec<&str> = stdout.lines().take(3).collect();
                for line in lines {
                    println!("    {}", line.trim());
                }
            }
        }
        Err(e) => {
            ui::status_line(service_name, "Error", false);
            if debug {
                println!("    Failed to check status: {}", e);
            }
        }
    }
}