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
//! Unstick command - Attempt to recover stuck processes
//!
//! Tries gentle recovery signals. Only terminates with --force.
//!
//! Recovery sequence:
//! 1. SIGCONT (wake if stopped)
//! 2. SIGINT (interrupt, like Ctrl+C)
//!
//! With --force:
//! 3. SIGTERM (polite termination request)
//! 4. SIGKILL (force, last resort)
//!
//! Usage:
//! proc unstick # Find and unstick all stuck processes
//! proc unstick :3000 # Unstick process on port 3000
//! proc unstick 1234 # Unstick PID 1234
//! proc unstick node # Unstick stuck node processes
use crate::core::{apply_filters, parse_targets, resolve_targets_excluding_self, Process};
use crate::error::{ProcError, Result};
use crate::ui::{format_duration, plural, Printer};
use clap::Args;
use colored::*;
use dialoguer::Confirm;
use serde::Serialize;
use std::time::Duration;
#[cfg(unix)]
use nix::sys::signal::{kill, Signal};
#[cfg(unix)]
use nix::unistd::Pid;
/// Attempt to recover stuck processes
#[derive(Args, Debug)]
pub struct UnstickCommand {
/// Target: PID, :port, or name (optional - finds all stuck if omitted)
target: Option<String>,
/// Minimum seconds of high CPU before considered stuck (for auto-discovery)
#[arg(long, short, default_value = "300")]
timeout: u64,
/// Force termination if recovery fails
#[arg(long, short = 'f')]
force: bool,
/// Skip confirmation prompt
#[arg(long, short = 'y')]
yes: bool,
/// Show what would be done without doing it
#[arg(long)]
dry_run: bool,
/// Show verbose output
#[arg(long, short = 'v')]
verbose: bool,
/// Output as JSON
#[arg(long, short = 'j')]
json: bool,
/// Filter by directory (defaults to current directory if no path given)
#[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
pub in_dir: Option<String>,
/// Filter by process name
#[arg(long = "by", short = 'b')]
pub by_name: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
enum Outcome {
Recovered, // Process unstuck and still running
Terminated, // Had to kill it (only with --force)
StillStuck, // Could not recover, not terminated (no --force)
NotStuck, // Process wasn't stuck to begin with
Failed(String),
}
impl UnstickCommand {
/// Executes the unstick command, attempting to recover hung processes.
pub fn execute(&self) -> Result<()> {
let printer = Printer::from_flags(self.json, self.verbose);
// Get processes to unstick
let mut stuck = if let Some(ref target) = self.target {
// Specific target
self.resolve_target_processes(target)?
} else {
// Auto-discover stuck processes
let timeout = Duration::from_secs(self.timeout);
Process::find_stuck(timeout)?
};
// Apply --in and --by filters
apply_filters(&mut stuck, &self.in_dir, &self.by_name);
if stuck.is_empty() {
if self.json {
printer.print_json(&UnstickOutput {
action: "unstick",
success: true,
dry_run: self.dry_run,
force: self.force,
found: 0,
recovered: 0,
not_stuck: 0,
still_stuck: 0,
terminated: 0,
failed: 0,
processes: Vec::new(),
});
} else if self.target.is_some() {
printer.warning("Target process not found");
} else {
printer.success("No stuck processes found");
}
return Ok(());
}
// Show stuck processes
if !self.json {
self.show_processes(&stuck);
}
// Dry run
if self.dry_run {
if self.json {
printer.print_json(&UnstickOutput {
action: "unstick",
success: true,
dry_run: true,
force: self.force,
found: stuck.len(),
recovered: 0,
not_stuck: 0,
still_stuck: 0,
terminated: 0,
failed: 0,
processes: stuck
.iter()
.map(|p| ProcessOutcome {
pid: p.pid,
name: p.name.clone(),
outcome: "would_attempt".to_string(),
})
.collect(),
});
} else {
println!(
"\n{} Dry run: Would attempt to unstick {} process{}",
"ℹ".blue().bold(),
stuck.len().to_string().cyan().bold(),
plural(stuck.len())
);
if self.force {
println!(" With --force: will terminate if recovery fails");
} else {
println!(" Without --force: will only attempt recovery");
}
println!();
}
return Ok(());
}
// Confirm
if !self.yes && !self.json {
if self.force {
println!(
"\n{} With --force: processes will be terminated if recovery fails.\n",
"!".yellow().bold()
);
} else {
println!(
"\n{} Will attempt recovery only. Use --force to terminate if needed.\n",
"ℹ".blue().bold()
);
}
let prompt = format!("Unstick {} process{}?", stuck.len(), plural(stuck.len()));
if !Confirm::new()
.with_prompt(prompt)
.default(false)
.interact()?
{
printer.warning("Aborted");
return Ok(());
}
}
// Attempt to unstick each process
let mut outcomes: Vec<(Process, Outcome)> = Vec::new();
for proc in &stuck {
if !self.json {
print!(
" {} {} [PID {}]... ",
"→".bright_black(),
proc.name.white(),
proc.pid.to_string().cyan()
);
}
let outcome = self.attempt_unstick(proc);
if !self.json {
match &outcome {
Outcome::Recovered => println!("{}", "recovered".green()),
Outcome::Terminated => println!("{}", "terminated".yellow()),
Outcome::StillStuck => println!("{}", "still stuck".red()),
Outcome::NotStuck => println!("{}", "not stuck".blue()),
Outcome::Failed(e) => println!("{}: {}", "failed".red(), e),
}
}
outcomes.push((proc.clone(), outcome));
}
// Count outcomes
let recovered = outcomes
.iter()
.filter(|(_, o)| *o == Outcome::Recovered)
.count();
let terminated = outcomes
.iter()
.filter(|(_, o)| *o == Outcome::Terminated)
.count();
let still_stuck = outcomes
.iter()
.filter(|(_, o)| *o == Outcome::StillStuck)
.count();
let not_stuck = outcomes
.iter()
.filter(|(_, o)| *o == Outcome::NotStuck)
.count();
let failed = outcomes
.iter()
.filter(|(_, o)| matches!(o, Outcome::Failed(_)))
.count();
// Output results
if self.json {
printer.print_json(&UnstickOutput {
action: "unstick",
success: failed == 0 && still_stuck == 0,
dry_run: false,
force: self.force,
found: stuck.len(),
recovered,
not_stuck,
still_stuck,
terminated,
failed,
processes: outcomes
.iter()
.map(|(p, o)| ProcessOutcome {
pid: p.pid,
name: p.name.clone(),
outcome: match o {
Outcome::Recovered => "recovered".to_string(),
Outcome::Terminated => "terminated".to_string(),
Outcome::StillStuck => "still_stuck".to_string(),
Outcome::NotStuck => "not_stuck".to_string(),
Outcome::Failed(e) => format!("failed: {}", e),
},
})
.collect(),
});
} else {
println!();
if recovered > 0 {
println!(
"{} {} process{} recovered",
"✓".green().bold(),
recovered.to_string().cyan().bold(),
plural(recovered)
);
}
if not_stuck > 0 {
println!(
"{} {} process{} not stuck",
"ℹ".blue().bold(),
not_stuck.to_string().cyan().bold(),
if not_stuck == 1 { " was" } else { "es were" }
);
}
if terminated > 0 {
println!(
"{} {} process{} terminated",
"!".yellow().bold(),
terminated.to_string().cyan().bold(),
plural(terminated)
);
}
if still_stuck > 0 {
println!(
"{} {} process{} still stuck (use --force to terminate)",
"✗".red().bold(),
still_stuck.to_string().cyan().bold(),
plural(still_stuck)
);
}
if failed > 0 {
println!(
"{} {} process{} failed",
"✗".red().bold(),
failed.to_string().cyan().bold(),
plural(failed)
);
}
}
Ok(())
}
/// Resolve target to processes, excluding self
fn resolve_target_processes(&self, target: &str) -> Result<Vec<Process>> {
let targets = parse_targets(target);
let (processes, _) = resolve_targets_excluding_self(&targets);
if processes.is_empty() {
Err(ProcError::ProcessNotFound(target.to_string()))
} else {
Ok(processes)
}
}
/// Check if a process appears stuck (high CPU)
fn is_stuck(&self, proc: &Process) -> bool {
proc.cpu_percent > 50.0
}
/// Attempt to unstick a process using recovery signals
#[cfg(unix)]
fn attempt_unstick(&self, proc: &Process) -> Outcome {
// For targeted processes, check if actually stuck
if self.target.is_some() && !self.is_stuck(proc) {
return Outcome::NotStuck;
}
let pid = Pid::from_raw(proc.pid as i32);
// Step 1: SIGCONT (wake if stopped)
let _ = kill(pid, Signal::SIGCONT);
std::thread::sleep(Duration::from_secs(1));
if self.check_recovered(proc) {
return Outcome::Recovered;
}
// Step 2: SIGINT (interrupt)
if kill(pid, Signal::SIGINT).is_err() && !proc.is_running() {
return Outcome::Terminated;
}
std::thread::sleep(Duration::from_secs(3));
if !proc.is_running() {
return Outcome::Terminated;
}
if self.check_recovered(proc) {
return Outcome::Recovered;
}
// Without --force, stop here
if !self.force {
return Outcome::StillStuck;
}
// Step 3: SIGTERM (polite termination) - only with --force
if proc.terminate().is_err() && !proc.is_running() {
return Outcome::Terminated;
}
std::thread::sleep(Duration::from_secs(5));
if !proc.is_running() {
return Outcome::Terminated;
}
// Step 4: SIGKILL (force, last resort) - only with --force
match proc.kill() {
Ok(()) => Outcome::Terminated,
Err(e) => {
if !proc.is_running() {
Outcome::Terminated
} else {
Outcome::Failed(e.to_string())
}
}
}
}
#[cfg(not(unix))]
fn attempt_unstick(&self, proc: &Process) -> Outcome {
// For targeted processes, check if actually stuck
if self.target.is_some() && !self.is_stuck(proc) {
return Outcome::NotStuck;
}
// On non-Unix, we can only terminate
if !self.force {
return Outcome::StillStuck;
}
if proc.terminate().is_ok() {
std::thread::sleep(Duration::from_secs(3));
if !proc.is_running() {
return Outcome::Terminated;
}
}
match proc.kill() {
Ok(()) => Outcome::Terminated,
Err(e) => Outcome::Failed(e.to_string()),
}
}
/// Check if process has recovered (no longer stuck)
#[cfg(unix)]
fn check_recovered(&self, proc: &Process) -> bool {
if let Ok(Some(current)) = Process::find_by_pid(proc.pid) {
current.cpu_percent < 10.0
} else {
false
}
}
fn show_processes(&self, processes: &[Process]) {
let label = if self.target.is_some() {
"Target"
} else {
"Found stuck"
};
println!(
"\n{} {} {} process{}:\n",
"!".yellow().bold(),
label,
processes.len().to_string().cyan().bold(),
plural(processes.len())
);
for proc in processes {
let uptime = proc
.start_time
.map(|st| {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs().saturating_sub(st))
.unwrap_or(0);
format_duration(now)
})
.unwrap_or_else(|| "unknown".to_string());
println!(
" {} {} [PID {}] - {:.1}% CPU, running for {}",
"→".bright_black(),
proc.name.white().bold(),
proc.pid.to_string().cyan(),
proc.cpu_percent,
uptime.yellow()
);
}
}
}
#[derive(Serialize)]
struct UnstickOutput {
action: &'static str,
success: bool,
dry_run: bool,
force: bool,
found: usize,
recovered: usize,
not_stuck: usize,
still_stuck: usize,
terminated: usize,
failed: usize,
processes: Vec<ProcessOutcome>,
}
#[derive(Serialize)]
struct ProcessOutcome {
pid: u32,
name: String,
outcome: String,
}