xbp 0.7.0

XBP is a build pack and deployment management tool to deploy, rust, nextjs etc and manage the NGINX configs below it
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
//! ports command module
//!
//! lists active tcp sockets with optional port filtering killing processes by pid
//! and searching nginx configs for references to a given port
//! when port filter is specified uses netstat -tulpen to get accurate pids
//! contains the high level entrypoint used by the cli and lower level helpers
use netstat2::{get_sockets_info, AddressFamilyFlags, ProtocolFlags, ProtocolSocketInfo};
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::process::Output;
use std::time::{Duration, Instant};
use tokio::process::Command;

use tracing::{debug, error, info, warn};
use crate::logging::{log_info, log_timed, LogLevel};

/// Execute the `ports` command.
///
/// Parses the provided `args` (from clap or manual vector) and executes the
/// sockets listing with optional flags:
/// - `-p <port>`: filter by a specific local port
/// - `--kill`: send `kill -9` to all PIDs bound to the matching sockets
/// - `-n`: search `/etc/nginx/sites-available` for references to the port
///
/// Returns `Ok(())` on success or a descriptive `Err(String)` on failures that
/// prevent execution (e.g., invalid arguments). Non-fatal issues are printed.
pub async fn run_ports(args: &[String], debug: bool) -> Result<(), String> {
    let mut port_filter: Option<String> = None;
    let mut kill: bool = false;
    let mut nginx_search: bool = false;

    let mut i: usize = 0;
    while i < args.len() {
        match args[i].as_str() {
            "-p" => {
                if let Some(p) = args.get(i + 1) {
                    port_filter = Some(p.clone());
                    i += 2;
                } else {
                    return Err("-p requires a port value".to_string());
                }
            }
            "--kill" => {
                kill = true;
                i += 1;
            }
            "-n" => {
                nginx_search = true;
                i += 1;
            }
            _ => {
                i += 1;
            }
        }
    }

    if debug {
        info!("Debug mode enabled");
        debug!("Args: {:?}", args);
    }

    let _ = log_info("ports", "Executing ports command", port_filter.as_deref()).await;

    let start: Instant = Instant::now();
    let command_output: String =
        execute_ports_command_netstat2(port_filter.clone(), debug, kill).await;
    let elapsed: Duration = start.elapsed();

    let _ = log_timed(
        LogLevel::Success,
        "ports",
        "Ports command completed",
        elapsed.as_millis() as u64,
    )
    .await;

    if debug {
        debug!("execute_ports_command took: {:.2?}", elapsed);
    }

    if command_output.trim().is_empty() {
        if let Some(port) = port_filter.clone() {
            info!("No active processes found on port: {}", port);
        }
    } else {
        display_output(command_output);
    }

    if nginx_search {
        if let Some(port) = port_filter {
            info!("Searching NGINX configurations for port: {}", port);
            search_nginx_configs(&port).await;
        } else {
            error!("Error: -n flag requires a port to be specified with -p.");
        }
    }

    Ok(())
}

/// Enumerate TCP sockets and render a table.
///
/// - `port_filter`: when `Some`, only entries matching the given port are shown
/// - `debug`: enables verbose console logs
/// - `kill`: when `true`, attempts to `kill -9` for each associated PID
///
/// Returns a formatted table as a string. Errors reading sockets are rendered
/// into the returned string instead of failing the function.
/// When port_filter is provided, uses netstat to get PIDs for better accuracy.
async fn execute_ports_command_netstat2(
    port_filter: Option<String>,
    debug: bool,
    kill: bool,
) -> String {
    let start: Instant = Instant::now();

    // If port filter is specified, use netstat to get PIDs
    if let Some(ref port) = port_filter {
        return get_port_info_with_netstat(port, debug, kill).await;
    }

    let af_flags: AddressFamilyFlags = AddressFamilyFlags::IPV4 | AddressFamilyFlags::IPV6;
    let proto_flags: ProtocolFlags = ProtocolFlags::TCP;

    let sockets: Vec<netstat2::SocketInfo> = match get_sockets_info(af_flags, proto_flags) {
        Ok(s) => s,
        Err(e) => {
            return format!("Failed to get sockets info: {}", e);
        }
    };

    if debug {
        debug!("Fetched {} TCP sockets", sockets.len());
    }

    let mut table_output: String = String::new();

    let mut port_map: BTreeMap<u16, Vec<(&netstat2::SocketInfo, &netstat2::TcpSocketInfo)>> =
        BTreeMap::new();

    for socket in &sockets {
        if let ProtocolSocketInfo::Tcp(ref tcp_info) = socket.protocol_socket_info {
            port_map
                .entry(tcp_info.local_port)
                .or_default()
                .push((socket, tcp_info));
        }
    }

    for (port, entries) in &port_map {
        table_output.push_str(&format!("Port: {}\n", port));
        table_output.push_str(&format!(
            "{:<10} {:<20} {:<20} {:<10} {:<10}\n",
            "PID", "LocalAddr", "RemoteAddr", "State", "Process"
        ));
        table_output.push_str(&format!("{:-<80}\n", ""));

        // Collect all unique PIDs across all sockets on this port
        let mut pids_to_kill: HashSet<u32> = HashSet::new();

        for (socket, tcp_info) in entries {
            let pids: String = if !socket.associated_pids.is_empty() {
                // Collect PIDs for killing (deduplicated)
                for pid in &socket.associated_pids {
                    pids_to_kill.insert(*pid);
                }
                socket
                    .associated_pids
                    .iter()
                    .map(|pid| pid.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            } else {
                "-".to_string()
            };

            let process_names: String = "-".to_string();

            table_output.push_str(&format!(
                "{:<10} {:<20} {:<20} {:<10} {:<10}\n",
                pids,
                tcp_info.local_addr,
                tcp_info.remote_addr,
                format!("{:?}", tcp_info.state),
                process_names
            ));
        }

        // Kill all unique processes for this port if requested
        if kill && !pids_to_kill.is_empty() {
            if debug {
                debug!(
                    "Found {} unique PID(s) on port {}: {:?}",
                    pids_to_kill.len(),
                    port,
                    pids_to_kill
                );
            }
            for pid in &pids_to_kill {
                let killed: bool = kill_process_with_debug(&pid.to_string(), debug).await;
                if killed {
                    info!("Successfully killed process with PID: {}", pid);
                    table_output.push_str(&format!(
                        "Killed process with PID: {}\n",
                        pid
                    ));
                } else {
                    error!("Failed to kill process with PID: {}", pid);
                }
            }
        }

        table_output.push_str(&format!("{:-<80}\n\n", ""));
    }

    if debug {
        debug!(
            "execute_ports_command_netstat2 took: {:.2?}",
            start.elapsed()
        );
    }

    table_output
}

/// Get port information using netstat command for better PID accuracy.
/// Uses `sudo netstat -tulpen | grep :PORT` to get PIDs for the specified port.
async fn get_port_info_with_netstat(port: &str, debug: bool, kill: bool) -> String {
    if debug {
        debug!("Using netstat to get PIDs for port: {}", port);
    }

    let netstat_cmd = format!("sudo netstat -tulpen | grep :{}", port);

    let output = Command::new("sh")
        .arg("-c")
        .arg(&netstat_cmd)
        .output()
        .await;

    let output = match output {
        Ok(o) => o,
        Err(e) => {
            return format!("Failed to execute netstat: {}", e);
        }
    };

    if !output.status.success() && output.stdout.is_empty() {
        return format!("No processes found on port: {}", port);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);

    if stdout.trim().is_empty() {
        return format!("No processes found on port: {}", port);
    }

    let mut table_output = String::new();
    table_output.push_str(&format!("Port: {}\n", port));
    table_output.push_str(&format!(
        "{:<10} {:<20} {:<20} {:<10} {:<10} {:<10}\n",
        "PID", "Proto", "LocalAddr", "ForeignAddr", "State", "Program"
    ));
    table_output.push_str(&format!("{:-<90}\n", ""));

    // Use HashSet to deduplicate PIDs (same PID might appear for IPv4 and IPv6 sockets)
    let mut pids_to_kill: HashSet<String> = HashSet::new();

    for line in stdout.lines() {
        if line.trim().is_empty() {
            continue;
        }

        // Parse netstat output: Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
        // Example: tcp        0      0 0.0.0.0:3000           0.0.0.0:*               LISTEN      12345/node
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.len() < 7 {
            continue;
        }

        // Extract PID (usually second to last field)
        let pid = if parts.len() >= 7 {
            // PID/Program format
            let pid_program = parts[parts.len() - 1];
            if let Some(slash_pos) = pid_program.find('/') {
                &pid_program[..slash_pos]
            } else {
                pid_program
            }
        } else {
            "-"
        };

        let proto = parts.get(0).unwrap_or(&"-");
        let local_addr = parts.get(3).unwrap_or(&"-");
        let foreign_addr = parts.get(4).unwrap_or(&"-");
        let state = parts.get(parts.len() - 2).unwrap_or(&"-");
        let program = if parts.len() >= 7 {
            let pid_program = parts[parts.len() - 1];
            if let Some(slash_pos) = pid_program.find('/') {
                &pid_program[slash_pos + 1..]
            } else {
                "-"
            }
        } else {
            "-"
        };

        table_output.push_str(&format!(
            "{:<10} {:<20} {:<20} {:<20} {:<10} {:<10}\n",
            pid, proto, local_addr, foreign_addr, state, program
        ));

        // Collect all unique PIDs (deduplicated automatically by HashSet)
        if kill && pid != "-" && pid.parse::<u32>().is_ok() {
            pids_to_kill.insert(pid.to_string());
        }
    }

    table_output.push_str(&format!("{:-<90}\n", ""));

    // Kill all unique processes if requested
    if kill && !pids_to_kill.is_empty() {
        if debug {
            debug!(
                "Found {} unique PID(s) to kill: {:?}",
                pids_to_kill.len(),
                pids_to_kill
            );
        }
        for pid in &pids_to_kill {
            let killed = kill_process_with_debug(pid, debug).await;
            if killed {
                info!("Successfully killed process with PID: {}", pid);
                table_output.push_str(&format!(
                    "Killed process with PID: {}\n",
                    pid
                ));
            } else {
                error!("Failed to kill process with PID: {}", pid);
            }
        }
    }

    table_output
}

/// Attempt to `kill -9 <pid>` and print debug details when enabled.
///
/// Returns `true` when the kill command returns success; `false` otherwise.
async fn kill_process_with_debug(pid: &str, debug: bool) -> bool {
    if debug {
        debug!("Attempting to kill PID: {}", pid);
    }
    let start: Instant = Instant::now();
    let kill_output: Output = Command::new("sh")
        .arg("-c")
        .arg(format!("sudo kill -9 {}", pid))
        .output()
        .await
        .expect("Failed to execute kill command");
    let elapsed = start.elapsed();
    if debug {
        debug!(
            "kill_process output: status={:?}, stdout='{}', stderr='{}', took: {:.2?}",
            kill_output.status,
            String::from_utf8_lossy(&kill_output.stdout),
            String::from_utf8_lossy(&kill_output.stderr),
            elapsed
        );
    }
    kill_output.status.success()
}

/// Print the generated table output to stdout.
fn display_output(output: String) {
    info!("{}", output);
}

/// Search NGINX `sites-available` for references to the provided `port`.
///
/// This is a best-effort scan used for quick diagnostics; it skips unreadable
/// files and reports any I/O errors encountered for the directory.
async fn search_nginx_configs(port: &str) {
    let nginx_sites_available_path = PathBuf::from("/etc/nginx/sites-available");

    if !nginx_sites_available_path.exists() {
        warn!("Warning: /etc/nginx/sites-available/ not found. Skipping NGINX config search.");
        return;
    }

    let mut found_configs = false;

    match fs::read_dir(&nginx_sites_available_path) {
        Ok(entries) => {
            for entry in entries {
                if let Ok(entry) = entry {
                    let path = entry.path();
                    if path.is_file() {
                        let config_content = match fs::read_to_string(&path) {
                            Ok(content) => content,
                            Err(_) => continue,
                        };

                        if config_content.contains(&format!("proxy_pass http://127.0.0.1:{}", port))
                            || config_content.contains(&format!("listen {}", port))
                        {
                            info!(
                                "Found port {} in NGINX config: {}",
                                port,
                                path.display()
                            );
                            found_configs = true;
                        }
                    }
                }
            }
        }
        Err(e) => {
            error!(
                "Error reading NGINX sites-available directory: {}",
                e
            );
            return;
        }
    }

    if !found_configs {
        info!(
            "No NGINX configurations found for port {}.",
            port
        );
    }
}