xbp 0.9.4

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
use anyhow::Result;
use colored::Colorize;
use serde::{Deserialize, Serialize};
use sysinfo::{System, Disks, Networks};
use tokio::process::Command;
use crate::logging::log_info;
use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize)]
pub struct SystemMetrics {
    pub cpu_usage: f32,
    pub memory_total: u64,
    pub memory_used: u64,
    pub memory_percent: f32,
    pub disk_total: u64,
    pub disk_used: u64,
    pub disk_percent: f32,
    pub network_rx: u64,
    pub network_tx: u64,
    pub uptime: u64,
    pub process_count: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PortCheck {
    pub port: u16,
    pub is_open: bool,
    pub is_blocked: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct InternetSpeed {
    pub download_mbps: f64,
    pub upload_mbps: f64,
    pub ping_ms: f64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DiagnosticReport {
    pub system_metrics: SystemMetrics,
    pub nginx_status: Option<NginxStatus>,
    pub port_checks: Vec<PortCheck>,
    pub internet_speed: Option<InternetSpeed>,
    pub connectivity: bool,
    pub installed_programs: HashMap<String, bool>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct NginxStatus {
    pub is_running: bool,
    pub is_enabled: bool,
    pub config_valid: bool,
    pub error: Option<String>,
}

pub async fn get_system_metrics() -> Result<SystemMetrics> {
    let mut sys = System::new_all();
    sys.refresh_all();

    let cpu_usage = sys.cpus().iter().map(|cpu| cpu.cpu_usage()).sum::<f32>() / sys.cpus().len() as f32;
    let memory_total = sys.total_memory();
    let memory_used = sys.used_memory();
    let memory_percent = (memory_used as f32 / memory_total as f32) * 100.0;

    let mut disk_total = 0;
    let mut disk_used = 0;
    for disk in Disks::new_with_refreshed_list().iter() {
        disk_total += disk.total_space();
        disk_used += disk.total_space() - disk.available_space();
    }
    let disk_percent = if disk_total > 0 {
        (disk_used as f32 / disk_total as f32) * 100.0
    } else {
        0.0
    };

    let networks = Networks::new_with_refreshed_list();
    let mut network_rx = 0;
    let mut network_tx = 0;
    for (_interface_name, network) in &networks {
        network_rx += network.total_received();
        network_tx += network.total_transmitted();
    }

    let uptime = System::uptime();
    let process_count = sys.processes().len();

    Ok(SystemMetrics {
        cpu_usage,
        memory_total,
        memory_used,
        memory_percent,
        disk_total,
        disk_used,
        disk_percent,
        network_rx,
        network_tx,
        uptime,
        process_count,
    })
}

pub async fn check_nginx_status() -> Result<NginxStatus> {
    let is_running = check_systemctl_status("nginx").await?;
    let is_enabled = check_systemctl_enabled("nginx").await?;
    
    let config_valid = if is_running {
        match Command::new("nginx").arg("-t").output().await {
            Ok(output) => output.status.success(),
            Err(_) => false,
        }
    } else {
        false
    };

    Ok(NginxStatus {
        is_running,
        is_enabled,
        config_valid,
        error: None,
    })
}

async fn check_systemctl_status(service: &str) -> Result<bool> {
    let output = Command::new("systemctl")
        .arg("is-active")
        .arg(service)
        .output()
        .await?;
    
    Ok(output.status.success())
}

async fn check_systemctl_enabled(service: &str) -> Result<bool> {
    let output = Command::new("systemctl")
        .arg("is-enabled")
        .arg(service)
        .output()
        .await?;
    
    Ok(output.status.success())
}

pub async fn check_port_availability(port: u16) -> Result<PortCheck> {
    use std::net::TcpListener;
    
    let is_open = TcpListener::bind(format!("127.0.0.1:{}", port)).is_ok();
    
    let is_blocked = if cfg!(target_os = "linux") {
        check_firewall_blocked(port).await.unwrap_or(false)
    } else {
        false
    };

    Ok(PortCheck {
        port,
        is_open,
        is_blocked,
    })
}

async fn check_firewall_blocked(port: u16) -> Result<bool> {
    let output = Command::new("iptables")
        .arg("-L")
        .arg("-n")
        .output()
        .await?;
    
    if !output.status.success() {
        return Ok(false);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let port_str = port.to_string();
    Ok(stdout.contains(&format!("dpt:{}", port_str)) && stdout.contains("DROP"))
}

pub async fn check_internet_connectivity() -> Result<bool> {
    let result = if cfg!(target_os = "windows") {
        Command::new("ping")
            .arg("-n")
            .arg("1")
            .arg("-w")
            .arg("2000")
            .arg("8.8.8.8")
            .output()
            .await?
    } else {
        Command::new("ping")
            .arg("-c")
            .arg("1")
            .arg("-W")
            .arg("2")
            .arg("8.8.8.8")
            .output()
            .await?
    };
    
    Ok(result.status.success())
}

pub async fn measure_internet_speed() -> Result<InternetSpeed> {
    if let Ok(speed) = measure_speed_with_speedtest_cli().await {
        return Ok(speed);
    }
    
    let ping = measure_ping().await?;
    let download_mbps = measure_download_speed().await.unwrap_or(0.0);
    let upload_mbps = 0.0;

    Ok(InternetSpeed {
        download_mbps,
        upload_mbps,
        ping_ms: ping,
    })
}

async fn measure_speed_with_speedtest_cli() -> Result<InternetSpeed> {
    let output = Command::new("speedtest-cli")
        .arg("--simple")
        .output()
        .await?;
    
    if !output.status.success() {
        return Err(anyhow::anyhow!("speedtest-cli failed"));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut ping_ms = 0.0;
    let mut download_mbps = 0.0;
    let mut upload_mbps = 0.0;

    for line in stdout.lines() {
        if line.starts_with("Ping:") {
            if let Some(val) = line.split_whitespace().nth(1) {
                ping_ms = val.parse().unwrap_or(0.0);
            }
        } else if line.starts_with("Download:") {
            if let Some(val) = line.split_whitespace().nth(1) {
                download_mbps = val.parse().unwrap_or(0.0);
            }
        } else if line.starts_with("Upload:") {
            if let Some(val) = line.split_whitespace().nth(1) {
                upload_mbps = val.parse().unwrap_or(0.0);
            }
        }
    }

    Ok(InternetSpeed {
        download_mbps,
        upload_mbps,
        ping_ms,
    })
}

async fn measure_ping() -> Result<f64> {
    let output = if cfg!(target_os = "windows") {
        Command::new("ping")
            .arg("-n")
            .arg("4")
            .arg("8.8.8.8")
            .output()
            .await?
    } else {
        Command::new("ping")
            .arg("-c")
            .arg("4")
            .arg("8.8.8.8")
            .output()
            .await?
    };
    
    if !output.status.success() {
        return Ok(0.0);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    
    if cfg!(target_os = "windows") {
        for line in stdout.lines() {
            if line.contains("Average") {
                if let Some(avg_part) = line.split('=').last() {
                    let avg_str = avg_part.trim().trim_end_matches("ms");
                    if let Ok(avg) = avg_str.parse::<f64>() {
                        return Ok(avg);
                    }
                }
            }
        }
    } else {
        for line in stdout.lines() {
            if line.contains("avg") || line.contains("rtt") {
                if let Some(avg_str) = line.split('/').nth(4) {
                    if let Ok(avg) = avg_str.trim().parse::<f64>() {
                        return Ok(avg);
                    }
                }
            }
        }
    }
    
    Ok(0.0)
}

async fn measure_download_speed() -> Result<f64> {
    use std::time::Instant;
    
    let start = Instant::now();
    let client = reqwest::Client::new();
    
    let response = client
        .get("http://speedtest.ftp.otenet.gr/files/test1Mb.db")
        .send()
        .await?;
    
    let bytes = response.bytes().await?;
    let duration = start.elapsed().as_secs_f64();
    
    let megabits = (bytes.len() as f64 * 8.0) / 1_000_000.0;
    let mbps = megabits / duration;
    
    Ok(mbps)
}

pub async fn check_installed_programs() -> HashMap<String, bool> {
    let programs = vec![
        "jq", "curl", "nginx", "git", "docker", "node", "npm", 
        "python3", "pip3", "cargo", "rustc", "pm2", "speedtest-cli"
    ];
    
    let mut results = HashMap::new();
    
    for program in programs {
        let is_installed = check_program_installed(program).await;
        results.insert(program.to_string(), is_installed);
    }
    
    results
}

async fn check_program_installed(program: &str) -> bool {
    let cmd = if cfg!(target_os = "windows") {
        Command::new("where")
            .arg(program)
            .output()
            .await
    } else {
        Command::new("which")
            .arg(program)
            .output()
            .await
    };
    
    match cmd {
        Ok(output) => output.status.success(),
        Err(_) => false,
    }
}

pub async fn print_diagnostic_report(report: &DiagnosticReport) {
    println!("\n{}", "═══════════════════════════════════════════════════".bright_cyan());
    println!("{}", "           XBP SYSTEM DIAGNOSTICS REPORT".bright_cyan().bold());
    println!("{}", "═══════════════════════════════════════════════════".bright_cyan());
    
    println!("\n{}", "📊 SYSTEM METRICS".bright_yellow().bold());
    println!("{}", "─────────────────────────────────────────────────".bright_black());
    
    let metrics = &report.system_metrics;
    
    let cpu_color = if metrics.cpu_usage > 80.0 { "red" } else if metrics.cpu_usage > 50.0 { "yellow" } else { "green" };
    println!("  {} {:.1}%", "CPU Usage:".bright_white(), format!("{}", metrics.cpu_usage).color(cpu_color));
    
    let mem_color = if metrics.memory_percent > 80.0 { "red" } else if metrics.memory_percent > 50.0 { "yellow" } else { "green" };
    println!("  {} {:.1}% ({} MB / {} MB)", 
        "Memory:".bright_white(),
        format!("{}", metrics.memory_percent).color(mem_color),
        metrics.memory_used / 1024 / 1024,
        metrics.memory_total / 1024 / 1024
    );
    
    let disk_color = if metrics.disk_percent > 80.0 { "red" } else if metrics.disk_percent > 50.0 { "yellow" } else { "green" };
    println!("  {} {:.1}% ({} GB / {} GB)", 
        "Disk:".bright_white(),
        format!("{}", metrics.disk_percent).color(disk_color),
        metrics.disk_used / 1024 / 1024 / 1024,
        metrics.disk_total / 1024 / 1024 / 1024
    );
    
    println!("  {} {} MB ↓ / {} MB ↑", 
        "Network:".bright_white(),
        metrics.network_rx / 1024 / 1024,
        metrics.network_tx / 1024 / 1024
    );
    
    let uptime_hours = metrics.uptime / 3600;
    let uptime_minutes = (metrics.uptime % 3600) / 60;
    println!("  {} {}h {}m", "Uptime:".bright_white(), uptime_hours, uptime_minutes);
    println!("  {} {}", "Processes:".bright_white(), metrics.process_count);
    
    println!("\n{}", "🔧 INSTALLED PROGRAMS".bright_yellow().bold());
    println!("{}", "─────────────────────────────────────────────────".bright_black());
    
    let mut programs: Vec<_> = report.installed_programs.iter().collect();
    programs.sort_by_key(|(name, _)| *name);
    
    for (program, installed) in programs {
        let status_icon = if *installed { "".green() } else { "".red() };
        let status_text = if *installed { "Installed".green() } else { "Not Found".red() };
        println!("  {} {:15} {}", status_icon, program, status_text);
    }
    
    if let Some(nginx) = &report.nginx_status {
        println!("\n{}", "🔧 NGINX STATUS".bright_yellow().bold());
        println!("{}", "─────────────────────────────────────────────────".bright_black());
        
        let status_icon = if nginx.is_running { "".green() } else { "".red() };
        println!("  {} {}", status_icon, if nginx.is_running { "Running".green() } else { "Stopped".red() });
        
        let enabled_icon = if nginx.is_enabled { "".green() } else { "".red() };
        println!("  {} {}", enabled_icon, if nginx.is_enabled { "Enabled".green() } else { "Disabled".red() });
        
        let config_icon = if nginx.config_valid { "".green() } else { "".red() };
        println!("  {} {}", config_icon, if nginx.config_valid { "Config Valid".green() } else { "Config Invalid".red() });
    }
    
    if !report.port_checks.is_empty() {
        println!("\n{}", "🔌 PORT STATUS".bright_yellow().bold());
        println!("{}", "─────────────────────────────────────────────────".bright_black());
        
        for port_check in &report.port_checks {
            let status_icon = if port_check.is_open { "".green() } else { "".red() };
            let blocked_text = if port_check.is_blocked { " (BLOCKED)".red() } else { "".normal() };
            println!("  {} Port {}: {}{}", 
                status_icon, 
                port_check.port, 
                if port_check.is_open { "Available".green() } else { "In Use".red() },
                blocked_text
            );
        }
    }
    
    println!("\n{}", "🌐 CONNECTIVITY".bright_yellow().bold());
    println!("{}", "─────────────────────────────────────────────────".bright_black());
    
    let conn_icon = if report.connectivity { "".green() } else { "".red() };
    println!("  {} {}", conn_icon, if report.connectivity { "Internet Connected".green() } else { "No Internet".red() });
    
    if let Some(speed) = &report.internet_speed {
        println!("  {} {:.2} ms", "Ping:".bright_white(), speed.ping_ms);
        println!("  {} {:.2} Mbps", "Download:".bright_white(), speed.download_mbps);
        if speed.upload_mbps > 0.0 {
            println!("  {} {:.2} Mbps", "Upload:".bright_white(), speed.upload_mbps);
        }
    }
    
    println!("\n{}", "═══════════════════════════════════════════════════".bright_cyan());
}

pub async fn run_full_diagnostics(ports: Vec<u16>) -> Result<DiagnosticReport> {
    let _ = log_info("diag", "Running system diagnostics...", None).await;
    
    let system_metrics = get_system_metrics().await?;
    let nginx_status = check_nginx_status().await.ok();
    let connectivity = check_internet_connectivity().await.unwrap_or(false);
    let installed_programs = check_installed_programs().await;
    
    let mut port_checks = Vec::new();
    for port in ports {
        if let Ok(check) = check_port_availability(port).await {
            port_checks.push(check);
        }
    }
    
    let internet_speed = if connectivity {
        measure_internet_speed().await.ok()
    } else {
        None
    };
    
    Ok(DiagnosticReport {
        system_metrics,
        nginx_status,
        port_checks,
        internet_speed,
        connectivity,
        installed_programs,
    })
}