mux: understand process tree, add mux-is-process-stateful event

This commit adds plumbing to support mapping the process tree to
lua objects which in turn allows a new `mux-is-process-stateful`
event to be defined by the user for finer control over closing
prompt behavior.

refs: #1412
This commit is contained in:
Wez Furlong committed 2021-12-18 09:46:00 -07:00
1 parent 2412e663f8
commit ea46967e2d
8 files changed
+256 -44

No files matched your search

+1
View File
@@ -15,6 +15,7 @@
/docs/config/lua/wezterm/index.md
/docs/config/lua/pane/index.md
/docs/config/lua/window/index.md
/docs/config/lua/mux-events/index.md
/docs/config/lua/window-events/index.md
/docs/config/lua/keyassignment/index.md
**/*.rs.bk
Generated
+3 -3
View File
@@ -2287,6 +2287,7 @@ dependencies = [
"log",
"luahelper",
"metrics",
"mlua",
"portable-pty",
"promise",
"rangeset",
@@ -3937,13 +3938,12 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.16.5"
version = "0.22.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567e910ef0207be81a4e1bb0491e9a8d9866cf45b20fe1a52c03d347da9ea51b"
checksum = "7c8591205e26661d45f9b31300599b133328c7e0f57e552a7be8d3b3c5748470"
dependencies = [
"cfg-if 1.0.0",
"core-foundation-sys 0.8.3",
"doc-comment",
"libc",
"ntapi",
"once_cell",
+9
View File
@@ -253,6 +253,15 @@ TermWindow running in the wezterm process.
## Available methods
""",
),
Gen(
"events: Multiplexer",
"config/lua/mux-events",
index="""
# Events emitted by the Multiplexer
The following events can be handled using [wezterm.on](../wezterm/on.md):
""",
),
Gen(
+1
View File
@@ -17,6 +17,7 @@ As features stabilize some brief notes about them will accumulate here.
* [ScrollToTop](config/lua/keyassignment/ScrollToTop.md) and [ScrollToBottom](config/lua/keyassignment/ScrollToBottom.md) key assignments [#1360](https://github.com/wez/wezterm/issues/1360)
* [SSH Domains](config/lua/SshDomain.md) now support specifying `ssh_config` overrides. [#1149](https://github.com/wez/wezterm/issues/1149)
* [default_gui_startup_args](config/lua/config/default_gui_startup_args.md) allows defaulting to starting the ssh client (for example). [#1030](https://github.com/wez/wezterm/issues/1030)
* [mux-is-process-stateful](config/lua/mux-events/mux-is-process-stateful.md) event for finer control over prompting when closing panes. [#1412](https://github.com/wez/wezterm/issues/1412)
#### Changed
@@ -26,8 +26,8 @@ return {
*Since: 20210814-124438-54e29167*:
The default value for this setting now includes some
windows shell processes:
This option now also works on Windows, and the default value for this setting
now includes some windows shell processes:
```
return {
@@ -44,3 +44,9 @@ return {
}
}
```
*Since: nightly builds only*
More advanced control over this behavior can be achieved by defining a
[mux-is-process-stateful](../mux-events/mux-is-process-stateful.md) event handler.
@@ -0,0 +1,72 @@
# `mux-is-process-stateful`
*Since: nightly builds only*
The `mux-is-process-stateful` event is emitted when the multiplexer layer wants
to determine whether a given Pane can be closed without prompting the user.
This event is *synchronous* and must return as quickly as possible in order
to avoid blocking the multiplexer.
The event is passed a `LocalProcessInfo` object representing the process that
corresponds to the pane. `LocalProcessInfo` has the following fields:
* `pid` - the process id
* `ppid` - the parent process id
* `name` - a short name for the process. You probably should prefer to look at the `executable` or `argv` fields instead of this one
* `status` - a string holding the status of the process; it can be `Idle`, `Run`, `Sleep`, `Stop`, `Zombie`, `Tracing`, `Dead`, `Wakekill`, `Waking`, `Parked`, `LockBlocked`, `Unknown`.
* `argv` - a table holding the argument array for the process
* `executable` - the full path to the executable image for the process (may be empty)
* `cwd` - the current working directory for the process (may be empty)
* `children` - a table keyed by child process id and whose values are themselves `LocalProcessInfo` objects that describe the child processes
The hook can return one of the following values:
* `true` - to indicate that this process tree is considered to be stateful and that the user should be prompted before terminating the pane
* `false` - to indicate that the process tree can be terminated *without* prompting the user
* `nil` - to use the default behavior, which is to consider the [skip_close_confirmation_for_processes_named](../config/skip_close_confirmation_for_processes_named.md) configuration option
* any other value, or an error, will be treated as equivalent to returning `nil`
## Example
This example doesn't change any behavior, but demonstrates how to log the various fields of process tree,
indenting the entries for each level of the process hierarchy.
Since it returns `nil`, it uses the default behavior.
```lua
local wezterm = require 'wezterm'
function log_proc(proc, indent)
indent = indent or ""
wezterm.log_info(indent .. "pid=" .. proc.pid .. ", name=" .. proc.name .. ", status=" .. proc.status)
wezterm.log_info(indent .. "argv=" .. table.concat(proc.argv, " "))
wezterm.log_info(indent .. "executable=" .. proc.executable .. ", cwd=" .. proc.cwd)
for pid, child in pairs(proc.children) do
log_proc(child, indent .. " ")
end
end
wezterm.on("mux-is-process-stateful", function(proc)
log_proc(proc)
-- Just use the default behavior
return nil
end)
return {}
```
Produces the following logs for a `zsh` that spawned `bash` that spawned `vim foo`:
```
INFO config::lua > lua: pid=1913470, name=zsh, status=Sleep
INFO config::lua > lua: argv=-zsh
INFO config::lua > lua: executable=/usr/bin/zsh, cwd=/home/wez
INFO config::lua > lua: pid=1913567, name=bash, status=Sleep
INFO config::lua > lua: argv=bash
INFO config::lua > lua: executable=/usr/bin/bash, cwd=/home/wez
INFO config::lua > lua: pid=1913624, name=vim, status=Sleep
INFO config::lua > lua: argv=vim foo
INFO config::lua > lua: executable=/usr/bin/vim, cwd=/home/wez
```
+2 -1
View File
@@ -20,6 +20,7 @@ libc = "0.2"
log = "0.4"
luahelper = { path = "../luahelper" }
metrics = { version="0.17", features=["std"]}
mlua = "0.5"
portable-pty = { path = "../pty", features = ["serde_support"]}
promise = { path = "../promise" }
rangeset = { path = "../rangeset" }
@@ -38,7 +39,7 @@ wezterm-ssh = { path = "../wezterm-ssh" }
wezterm-term = { path = "../term", features=["use_serde"] }
[target.'cfg(any(windows, target_os="linux", target_os="macos"))'.dependencies]
sysinfo = "0.16"
sysinfo = "0.22"
[target."cfg(windows)".dependencies]
winapi = { version = "0.3", features = [
+160 -38
View File
@@ -9,11 +9,13 @@ use config::keyassignment::ScrollbackEraseMode;
use config::{configuration, ExitBehavior};
use portable_pty::{Child, ChildKiller, ExitStatus, MasterPty, PtySize};
use rangeset::RangeSet;
use serde::{Deserialize, Serialize};
use smol::channel::{bounded, Receiver, TryRecvError};
use std::cell::{RefCell, RefMut};
use std::collections::{HashMap, HashSet};
use std::io::Result as IoResult;
use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;
use termwiz::escape::DeviceControlMode;
use termwiz::surface::{Line, SequenceNo, SEQ_ZERO};
@@ -315,23 +317,59 @@ impl Pane for LocalPane {
}
fn can_close_without_prompting(&self) -> bool {
let proc_list = self.divine_process_list();
if !proc_list.is_empty() {
log::trace!("can_close_without_prompting? procs in pane {:?}", proc_list);
if let Some(proc_list) = self.divine_process_list() {
log::trace!(
"can_close_without_prompting? procs in pane {:#?}",
proc_list
);
let skip = configuration()
.skip_close_confirmation_for_processes_named
.iter()
.cloned()
.collect::<HashSet<_>>();
for proc in &proc_list {
if !skip.contains(proc) {
return false;
let hook_result = config::run_immediate_with_lua_config(|lua| {
let lua = match lua {
Some(lua) => lua,
None => return Ok(None),
};
let v = config::lua::emit_sync_callback(
&*lua,
("mux-is-process-stateful".to_string(), (proc_list.clone())),
)?;
match v {
mlua::Value::Nil => Ok(None),
mlua::Value::Boolean(v) => Ok(Some(v)),
_ => Ok(None),
}
});
fn default_stateful_check(proc_list: &LocalProcessInfo) -> bool {
let names = proc_list.flatten_to_exe_names();
let skip = configuration()
.skip_close_confirmation_for_processes_named
.iter()
.cloned()
.collect::<HashSet<_>>();
if !names.is_subset(&skip) {
// There are other processes running than are listed,
// so we consider this to be stateful
return true;
}
false
}
return true;
let is_stateful = match hook_result {
Ok(None) => default_stateful_check(&proc_list),
Ok(Some(s)) => s,
Err(err) => {
log::error!(
"Error while running mux-is-process-stateful \
hook: {:#}, falling back to default behavior",
err
);
default_stateful_check(&proc_list)
}
};
!is_stateful
} else {
#[cfg(unix)]
{
@@ -754,37 +792,121 @@ impl LocalPane {
None
}
fn divine_process_list(&self) -> Vec<String> {
#[allow(unused_mut)]
let mut proc_names = vec![];
fn divine_process_list(&self) -> Option<LocalProcessInfo> {
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
if let ProcessState::Running { pid, .. } = &*self.process.borrow() {
if let Some(pid) = pid {
use sysinfo::{Pid, ProcessExt, RefreshKind, System, SystemExt};
let system = System::new_with_specifics(RefreshKind::new().with_processes());
let procs = system.get_processes();
let mut pids_to_do = vec![*pid as Pid];
if let ProcessState::Running { pid: Some(pid), .. } = &*self.process.borrow() {
return LocalProcessInfo::with_root_pid(*pid);
}
while let Some(pid) = pids_to_do.pop() {
if let Some(proc) = procs.get(&pid) {
if let Some(exe) = proc.exe().file_name() {
proc_names.push(exe.to_string_lossy().into_owned());
}
}
None
}
}
for (child_pid, proc) in procs {
if let Some(parent) = proc.parent() {
if parent == pid {
pids_to_do.push(*child_pid);
}
}
}
}
#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
pub enum LocalProcessStatus {
Idle,
Run,
Sleep,
Stop,
Zombie,
Tracing,
Dead,
Wakekill,
Waking,
Parked,
LockBlocked,
Unknown,
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
impl LocalProcessStatus {
fn from_process_status(status: sysinfo::ProcessStatus) -> Self {
match status {
sysinfo::ProcessStatus::Idle => Self::Idle,
sysinfo::ProcessStatus::Run => Self::Run,
sysinfo::ProcessStatus::Sleep => Self::Sleep,
sysinfo::ProcessStatus::Stop => Self::Stop,
sysinfo::ProcessStatus::Zombie => Self::Zombie,
sysinfo::ProcessStatus::Tracing => Self::Tracing,
sysinfo::ProcessStatus::Dead => Self::Dead,
sysinfo::ProcessStatus::Wakekill => Self::Wakekill,
sysinfo::ProcessStatus::Waking => Self::Waking,
sysinfo::ProcessStatus::Parked => Self::Parked,
sysinfo::ProcessStatus::LockBlocked => Self::LockBlocked,
sysinfo::ProcessStatus::Unknown(_) => Self::Unknown,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LocalProcessInfo {
pub pid: u32,
pub ppid: u32,
pub name: String,
pub executable: PathBuf,
pub argv: Vec<String>,
pub cwd: PathBuf,
pub status: LocalProcessStatus,
pub children: HashMap<u32, LocalProcessInfo>,
}
luahelper::impl_lua_conversion!(LocalProcessInfo);
impl LocalProcessInfo {
fn flatten_to_exe_names(&self) -> HashSet<String> {
let mut names = HashSet::new();
fn flatten(item: &LocalProcessInfo, names: &mut HashSet<String>) {
if let Some(exe) = item.executable.file_name() {
names.insert(exe.to_string_lossy().into_owned());
}
for proc in item.children.values() {
flatten(proc, names);
}
}
proc_names
flatten(self, &mut names);
names
}
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
impl LocalProcessInfo {
fn with_root_pid(pid: u32) -> Option<Self> {
use sysinfo::{
AsU32, Pid, Process, ProcessExt, ProcessRefreshKind, RefreshKind, System, SystemExt,
};
let system = System::new_with_specifics(
RefreshKind::new().with_processes(ProcessRefreshKind::new()),
);
fn build_proc(proc: &Process, processes: &HashMap<Pid, Process>) -> LocalProcessInfo {
// Process has a `tasks` field but it does not correspond to child processes,
// so we need to repeatedly walk the full process list and establish that
// linkage for ourselves here
let mut children = HashMap::new();
let pid = proc.pid();
for (child_pid, child_proc) in processes {
if child_proc.parent() == Some(pid) {
children.insert(child_pid.as_u32(), build_proc(child_proc, processes));
}
}
LocalProcessInfo {
pid: proc.pid().as_u32(),
ppid: proc.parent().map(|pid| pid.as_u32()).unwrap_or(1),
name: proc.name().to_string(),
executable: proc.exe().to_path_buf(),
cwd: proc.cwd().to_path_buf(),
argv: proc.cmd().to_vec(),
status: LocalProcessStatus::from_process_status(proc.status()),
children,
}
}
let proc = system.process(pid as Pid)?;
let procs = system.processes();
Some(build_proc(&proc, &procs))
}
}