feat: add process monitoring to Monitor panel
User asked for process monitoring. Added:
1. core/monitor.py:
- Extended _LINUX_METRICS_SCRIPT with ===PROC=== section
- ps -e -o stat= | awk counts total/running/sleep/disk-sleep/zombie
- ps -eo pid,user,pcpu,pmem,vsz,rss,stat,etimes,times,args
Uses etimes/times (numeric) instead of start/time (string with
spaces) to avoid column-shift bugs. awk joins 10th col onwards
with spaces so comm retains its full command line.
- New empty-dict fields: proc_total, proc_running, proc_sleep,
proc_disk, proc_zombie, processes
- New processes[] array with full per-process fields
2. ui/widgets.py MonitorPanel:
- New _build_proc_summary() - 4-stat overview card (total/running/
sleep/zombie, color-coded)
- New _build_proc_table() - 9-column process list with:
* Search box (multi-keyword AND match across pid/user/stat/comm)
* Sort dropdown (CPU / MEM / PID / start time / user)
* Color-coded CPU% (red >=50%, orange >=20%)
* Color-coded MEM% (red >=10%, orange >=5%)
* Color-coded STAT (red for zombie)
* RSS formatted with format_bytes
* ETIME / TIME formatted as 5d3h / 2h15m / 45s
- _apply_proc_filter() - filter + sort + render in one pass
- _proc_context_menu() - right-click menu:
* kill (SIGTERM) | kill -9 (SIGKILL) | copy PID | copy cmd |
filter by this command
- _proc_kill_selected() / _proc_kill() - sends kill over SSH
with confirmation dialog, shows remote exit code in result
- Splitter: 4 metric cards + proc summary + disk + net on top,
process list on bottom. User-draggable.
3. New test_process_monitor.py (5 tests, all pass):
- Real SSH connection, collects process data
- Renders MonitorPanel with 200 rows
- Tests search filter / sort change / clear
- Tests killing a real sleep process: starts sleep 60, finds it
in the table, calls _proc_kill (with QMessageBox monkey-patched
to auto-yes), verifies remote kill -0 returns 'No such process'
- Also fixed passwords in test_e2e.py + test_terminal.py to match
the working local sshd credentials
All tests pass: core 6/6 + UI 3/3 + E2E 6/6 + terminal 5/5 + proc 5/5
Build: 57 MB single-file exe.
This commit is contained in:
+309
-10
@@ -10,15 +10,15 @@ from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
from PyQt5.QtCore import Qt, pyqtSignal, QSize
|
||||
from PyQt5.QtGui import QFont, QColor, QIcon, QPixmap, QPainter, QBrush
|
||||
from PyQt5.QtCore import Qt, pyqtSignal, QSize, QTimer
|
||||
from PyQt5.QtGui import QFont, QColor, QIcon, QPixmap, QPainter, QBrush, QKeySequence
|
||||
from PyQt5.QtWidgets import (
|
||||
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QLineEdit,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView,
|
||||
QFileDialog, QMessageBox, QProgressBar, QTreeWidget, QTreeWidgetItem,
|
||||
QTextEdit, QSplitter, QFrame, QSizePolicy, QGroupBox, QFormLayout,
|
||||
QComboBox, QToolButton, QStyle, QApplication, QInputDialog,
|
||||
QListWidget, QListWidgetItem, QTabWidget,
|
||||
QListWidget, QListWidgetItem, QTabWidget, QMenu, QShortcut,
|
||||
)
|
||||
|
||||
from core.ssh_client import SSHConnection
|
||||
@@ -394,25 +394,45 @@ class MonitorPanel(QWidget):
|
||||
self.info_label.setStyleSheet("color: #666;")
|
||||
layout.addWidget(self.info_label)
|
||||
|
||||
# 用 Splitter 把 4 行指标卡 + 磁盘网络 放上半,进程表放下半
|
||||
splitter = QSplitter(Qt.Vertical)
|
||||
layout.addWidget(splitter, 1)
|
||||
|
||||
# ---- 上半:指标卡 + 磁盘 + 网络 ----
|
||||
upper = QWidget()
|
||||
uv = QVBoxLayout(upper)
|
||||
uv.setContentsMargins(0, 0, 0, 0)
|
||||
uv.setSpacing(10)
|
||||
|
||||
# CPU + 内存行
|
||||
grid = QHBoxLayout()
|
||||
grid.addWidget(self._build_card("CPU 使用率", "cpu_card"))
|
||||
grid.addWidget(self._build_card("内存", "mem_card"))
|
||||
layout.addLayout(grid)
|
||||
uv.addLayout(grid)
|
||||
|
||||
# 负载 + 启动时间
|
||||
grid2 = QHBoxLayout()
|
||||
grid2.addWidget(self._build_card("系统负载", "load_card"))
|
||||
grid2.addWidget(self._build_card("启动时间", "uptime_card"))
|
||||
layout.addLayout(grid2)
|
||||
uv.addLayout(grid2)
|
||||
|
||||
# 磁盘 + 网络
|
||||
grid3 = QHBoxLayout()
|
||||
# 进程统计 + 磁盘
|
||||
grid_proc_disk = QHBoxLayout()
|
||||
grid_proc_disk.addWidget(self._build_proc_summary())
|
||||
self.disk_group = self._build_table_card("磁盘", ["挂载点", "已用/总大小", "使用率", "进度"])
|
||||
grid_proc_disk.addWidget(self.disk_group, 2)
|
||||
uv.addLayout(grid_proc_disk)
|
||||
|
||||
# 网络
|
||||
self.net_group = self._build_table_card("网络", ["网卡", "↓ 接收", "↑ 发送", "速率"])
|
||||
grid3.addWidget(self.disk_group)
|
||||
grid3.addWidget(self.net_group)
|
||||
layout.addLayout(grid3, 1)
|
||||
uv.addWidget(self.net_group)
|
||||
|
||||
splitter.addWidget(upper)
|
||||
|
||||
# ---- 下半:进程表 ----
|
||||
self.proc_group = self._build_proc_table()
|
||||
splitter.addWidget(self.proc_group)
|
||||
splitter.setSizes([400, 350])
|
||||
|
||||
def _build_card(self, title: str, name: str) -> QGroupBox:
|
||||
box = QGroupBox(title)
|
||||
@@ -440,6 +460,99 @@ class MonitorPanel(QWidget):
|
||||
v.addWidget(table)
|
||||
return box
|
||||
|
||||
def _build_proc_summary(self) -> QGroupBox:
|
||||
"""进程总数 / 运行中 / 睡眠 / 僵尸 概览卡"""
|
||||
box = QGroupBox("进程概览")
|
||||
v = QVBoxLayout(box)
|
||||
# 4 个数字一行
|
||||
row1 = QHBoxLayout()
|
||||
self.proc_total_value = QLabel("0")
|
||||
self.proc_total_value.setStyleSheet("font-size: 18pt; font-weight: bold; color: #42a5f5;")
|
||||
self.proc_total_value.setAlignment(Qt.AlignCenter)
|
||||
row1.addWidget(self._wrap_with_caption(self.proc_total_value, "总数"))
|
||||
self.proc_running_value = QLabel("0")
|
||||
self.proc_running_value.setStyleSheet("font-size: 18pt; font-weight: bold; color: #66bb6a;")
|
||||
self.proc_running_value.setAlignment(Qt.AlignCenter)
|
||||
row1.addWidget(self._wrap_with_caption(self.proc_running_value, "运行"))
|
||||
self.proc_sleep_value = QLabel("0")
|
||||
self.proc_sleep_value.setStyleSheet("font-size: 18pt; font-weight: bold; color: #b0bec5;")
|
||||
self.proc_sleep_value.setAlignment(Qt.AlignCenter)
|
||||
row1.addWidget(self._wrap_with_caption(self.proc_sleep_value, "睡眠"))
|
||||
self.proc_zombie_value = QLabel("0")
|
||||
self.proc_zombie_value.setStyleSheet("font-size: 18pt; font-weight: bold; color: #ef5350;")
|
||||
self.proc_zombie_value.setAlignment(Qt.AlignCenter)
|
||||
row1.addWidget(self._wrap_with_caption(self.proc_zombie_value, "僵尸"))
|
||||
v.addLayout(row1)
|
||||
box.setMaximumWidth(380)
|
||||
return box
|
||||
|
||||
def _wrap_with_caption(self, value_label: QLabel, caption: str) -> QWidget:
|
||||
w = QWidget()
|
||||
v = QVBoxLayout(w)
|
||||
v.setContentsMargins(0, 0, 0, 0)
|
||||
v.setSpacing(2)
|
||||
v.addWidget(value_label)
|
||||
cap = QLabel(caption)
|
||||
cap.setAlignment(Qt.AlignCenter)
|
||||
cap.setStyleSheet("color: #888; font-size: 9pt;")
|
||||
v.addWidget(cap)
|
||||
return w
|
||||
|
||||
def _build_proc_table(self) -> QGroupBox:
|
||||
"""进程列表(搜索 + 排序 + 右键杀进程)"""
|
||||
box = QGroupBox("进程列表(前 200,按 CPU 降序,双击/右键杀进程)")
|
||||
v = QVBoxLayout(box)
|
||||
|
||||
# 工具栏
|
||||
toolbar = QHBoxLayout()
|
||||
self.proc_search = QLineEdit()
|
||||
self.proc_search.setPlaceholderText("🔍 过滤(PID/用户/命令行,含空格时拆分多关键字)...")
|
||||
self.proc_search.textChanged.connect(self._apply_proc_filter)
|
||||
toolbar.addWidget(self.proc_search, 1)
|
||||
self.proc_sort_combo = QComboBox()
|
||||
self.proc_sort_combo.addItems([
|
||||
"按 CPU 降序", "按内存降序", "按 PID 升序", "按启动时间降序", "按用户",
|
||||
])
|
||||
self.proc_sort_combo.currentIndexChanged.connect(self._apply_proc_filter)
|
||||
toolbar.addWidget(QLabel("排序:"))
|
||||
toolbar.addWidget(self.proc_sort_combo)
|
||||
v.addLayout(toolbar)
|
||||
|
||||
# 表格
|
||||
headers = ["PID", "用户", "CPU%", "MEM%", "RSS", "STAT", "启动", "CPU时间", "命令"]
|
||||
self.proc_table = QTableWidget(0, len(headers))
|
||||
self.proc_table.setHorizontalHeaderLabels(headers)
|
||||
self.proc_table.verticalHeader().setVisible(False)
|
||||
self.proc_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
|
||||
self.proc_table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
||||
self.proc_table.setAlternatingRowColors(True)
|
||||
# 列宽策略
|
||||
h = self.proc_table.horizontalHeader()
|
||||
h.setSectionResizeMode(0, QHeaderView.ResizeToContents) # PID
|
||||
h.setSectionResizeMode(1, QHeaderView.ResizeToContents) # USER
|
||||
h.setSectionResizeMode(2, QHeaderView.ResizeToContents) # CPU%
|
||||
h.setSectionResizeMode(3, QHeaderView.ResizeToContents) # MEM%
|
||||
h.setSectionResizeMode(4, QHeaderView.ResizeToContents) # RSS
|
||||
h.setSectionResizeMode(5, QHeaderView.ResizeToContents) # STAT
|
||||
h.setSectionResizeMode(6, QHeaderView.ResizeToContents) # ETIME
|
||||
h.setSectionResizeMode(7, QHeaderView.ResizeToContents) # TIME
|
||||
h.setSectionResizeMode(8, QHeaderView.Stretch) # COMMAND
|
||||
# 右键菜单
|
||||
self.proc_table.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||
self.proc_table.customContextMenuRequested.connect(self._proc_context_menu)
|
||||
# 双击行 -> 杀进程
|
||||
self.proc_table.doubleClicked.connect(self._proc_kill_selected)
|
||||
v.addWidget(self.proc_table, 1)
|
||||
|
||||
# 提示
|
||||
hint = QLabel("提示: 右键/双击进程可执行 kill / kill -9。危险操作,请确认 PID。")
|
||||
hint.setStyleSheet("color: #888; font-size: 9pt;")
|
||||
v.addWidget(hint)
|
||||
|
||||
# 当前缓存的进程数据(worker 回调里更新)
|
||||
self._proc_data: List[dict] = []
|
||||
return box
|
||||
|
||||
def _value_label(self, name: str) -> QLabel:
|
||||
return self.findChild(QLabel, f"{name}_value")
|
||||
|
||||
@@ -528,6 +641,16 @@ class MonitorPanel(QWidget):
|
||||
f"启动于: {time.strftime('%Y-%m-%d %H:%M', time.localtime(boot_ts))}"
|
||||
)
|
||||
|
||||
# 进程概览
|
||||
self.proc_total_value.setText(str(m.get("proc_total", 0)))
|
||||
self.proc_running_value.setText(str(m.get("proc_running", 0)))
|
||||
self.proc_sleep_value.setText(str(m.get("proc_sleep", 0)))
|
||||
self.proc_zombie_value.setText(str(m.get("proc_zombie", 0)))
|
||||
|
||||
# 进程列表
|
||||
self._proc_data = m.get("processes", [])
|
||||
self._apply_proc_filter()
|
||||
|
||||
# 磁盘表
|
||||
disks = m.get("disks", [])
|
||||
disk_table: QTableWidget = self.disk_group.findChild(QTableWidget)
|
||||
@@ -576,6 +699,182 @@ class MonitorPanel(QWidget):
|
||||
else:
|
||||
net_table.setItem(i, 3, QTableWidgetItem("采样中..."))
|
||||
|
||||
# ============================================================
|
||||
# 进程表:过滤 / 排序 / 杀进程
|
||||
# ============================================================
|
||||
def _apply_proc_filter(self):
|
||||
"""根据搜索框 + 排序下拉,过滤并刷新进程表"""
|
||||
if not hasattr(self, "proc_table"):
|
||||
return
|
||||
query = self.proc_search.text().strip().lower() if hasattr(self, "proc_search") else ""
|
||||
terms = [t for t in query.split() if t]
|
||||
sort_idx = self.proc_sort_combo.currentIndex() if hasattr(self, "proc_sort_combo") else 0
|
||||
|
||||
data = list(self._proc_data)
|
||||
# 过滤
|
||||
if terms:
|
||||
def match(p):
|
||||
hay = f"{p.get('pid','')} {p.get('user','')} {p.get('stat','')} {p.get('comm','')}".lower()
|
||||
return all(t in hay for t in terms)
|
||||
data = [p for p in data if match(p)]
|
||||
# 排序
|
||||
if sort_idx == 0: # CPU 降序
|
||||
data.sort(key=lambda p: p.get("pcpu", 0), reverse=True)
|
||||
elif sort_idx == 1: # MEM 降序
|
||||
data.sort(key=lambda p: p.get("pmem", 0), reverse=True)
|
||||
elif sort_idx == 2: # PID 升序
|
||||
data.sort(key=lambda p: p.get("pid", 0))
|
||||
elif sort_idx == 3: # 启动时间降序(etime 大 = 新)
|
||||
data.sort(key=lambda p: p.get("etime", 0), reverse=True)
|
||||
elif sort_idx == 4: # 按用户,再 CPU
|
||||
data.sort(key=lambda p: (p.get("user", ""), -p.get("pcpu", 0)))
|
||||
|
||||
self.proc_table.setRowCount(len(data))
|
||||
for row, p in enumerate(data):
|
||||
pid = p.get("pid", 0)
|
||||
user = p.get("user", "")
|
||||
pcpu = p.get("pcpu", 0.0)
|
||||
pmem = p.get("pmem", 0.0)
|
||||
rss = p.get("rss", 0)
|
||||
stat = p.get("stat", "")
|
||||
etime = p.get("etime", 0)
|
||||
ptime = p.get("time", 0)
|
||||
comm = p.get("comm", "")
|
||||
# PID 列把 pid 存到 UserRole,方便右键菜单拿到
|
||||
pid_item = QTableWidgetItem(str(pid))
|
||||
pid_item.setData(Qt.UserRole, pid)
|
||||
pid_item.setData(Qt.UserRole + 1, comm)
|
||||
pid_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
|
||||
self.proc_table.setItem(row, 0, pid_item)
|
||||
self.proc_table.setItem(row, 1, QTableWidgetItem(user))
|
||||
cpu_item = QTableWidgetItem(f"{pcpu:.1f}")
|
||||
cpu_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
|
||||
# 高的 CPU/MEM 标色
|
||||
if pcpu >= 50:
|
||||
cpu_item.setForeground(QColor("#ef5350"))
|
||||
elif pcpu >= 20:
|
||||
cpu_item.setForeground(QColor("#ffa726"))
|
||||
self.proc_table.setItem(row, 2, cpu_item)
|
||||
mem_item = QTableWidgetItem(f"{pmem:.1f}")
|
||||
mem_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
|
||||
if pmem >= 10:
|
||||
mem_item.setForeground(QColor("#ef5350"))
|
||||
elif pmem >= 5:
|
||||
mem_item.setForeground(QColor("#ffa726"))
|
||||
self.proc_table.setItem(row, 3, mem_item)
|
||||
rss_item = QTableWidgetItem(SystemMonitor.format_bytes(rss * 1024))
|
||||
rss_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
|
||||
self.proc_table.setItem(row, 4, rss_item)
|
||||
# STAT 含 Z 用红色
|
||||
stat_item = QTableWidgetItem(stat)
|
||||
if stat.startswith("Z"):
|
||||
stat_item.setForeground(QColor("#ef5350"))
|
||||
self.proc_table.setItem(row, 5, stat_item)
|
||||
self.proc_table.setItem(row, 6, QTableWidgetItem(self._fmt_duration(etime)))
|
||||
self.proc_table.setItem(row, 7, QTableWidgetItem(self._fmt_duration(ptime)))
|
||||
comm_item = QTableWidgetItem(comm)
|
||||
comm_item.setToolTip(comm)
|
||||
self.proc_table.setItem(row, 8, comm_item)
|
||||
# 更新标题栏显示当前过滤后条数
|
||||
total = len(self._proc_data)
|
||||
shown = len(data)
|
||||
title = "进程列表"
|
||||
if terms or sort_idx != 0:
|
||||
title += f" (显示 {shown}/{total})"
|
||||
else:
|
||||
title += f" (前 {total})"
|
||||
self.proc_group.setTitle(title)
|
||||
|
||||
@staticmethod
|
||||
def _fmt_duration(seconds: int) -> str:
|
||||
"""把秒数格式化成 5d3h / 2h15m / 45s"""
|
||||
s = int(seconds)
|
||||
if s < 0:
|
||||
s = 0
|
||||
days, rem = divmod(s, 86400)
|
||||
hours, rem = divmod(rem, 3600)
|
||||
mins, secs = divmod(rem, 60)
|
||||
if days:
|
||||
return f"{days}d{hours}h"
|
||||
if hours:
|
||||
return f"{hours}h{mins}m"
|
||||
if mins:
|
||||
return f"{mins}m{secs}s"
|
||||
return f"{secs}s"
|
||||
|
||||
def _proc_context_menu(self, pos):
|
||||
idx = self.proc_table.indexAt(pos)
|
||||
if not idx.isValid():
|
||||
return
|
||||
row = idx.row()
|
||||
pid_item = self.proc_table.item(row, 0)
|
||||
if not pid_item:
|
||||
return
|
||||
pid = pid_item.data(Qt.UserRole)
|
||||
comm = pid_item.data(Qt.UserRole + 1) or ""
|
||||
menu = QMenu(self.proc_table)
|
||||
a_soft = menu.addAction(f"🔪 kill {pid} (SIGTERM)")
|
||||
a_hard = menu.addAction(f"☠ kill -9 {pid} (SIGKILL)")
|
||||
menu.addSeparator()
|
||||
a_copy = menu.addAction("复制 PID")
|
||||
a_copy_comm = menu.addAction("复制命令行")
|
||||
a_filter = menu.addAction("按此命令过滤")
|
||||
chosen = menu.exec_(self.proc_table.viewport().mapToGlobal(pos))
|
||||
if chosen == a_soft:
|
||||
self._proc_kill(pid, comm, force=False)
|
||||
elif chosen == a_hard:
|
||||
self._proc_kill(pid, comm, force=True)
|
||||
elif chosen == a_copy:
|
||||
QApplication.clipboard().setText(str(pid))
|
||||
elif chosen == a_copy_comm:
|
||||
QApplication.clipboard().setText(comm)
|
||||
elif chosen == a_filter:
|
||||
# 取 comm 的第一段(命令名)
|
||||
base = comm.split()[0] if comm else ""
|
||||
if base:
|
||||
self.proc_search.setText(base)
|
||||
|
||||
def _proc_kill_selected(self):
|
||||
"""双击行:杀进程(弹确认)"""
|
||||
rows = self.proc_table.selectionModel().selectedRows()
|
||||
if not rows:
|
||||
return
|
||||
row = rows[0].row()
|
||||
pid_item = self.proc_table.item(row, 0)
|
||||
if not pid_item:
|
||||
return
|
||||
pid = pid_item.data(Qt.UserRole)
|
||||
comm = pid_item.data(Qt.UserRole + 1) or ""
|
||||
self._proc_kill(pid, comm, force=False)
|
||||
|
||||
def _proc_kill(self, pid: int, comm: str, force: bool = False):
|
||||
"""在远程主机上执行 kill [pid]"""
|
||||
if not self.current_host_id:
|
||||
return
|
||||
conn = self.manager.get_connection(self.current_host_id)
|
||||
if not conn or not conn.connected:
|
||||
QMessageBox.warning(self, "未连接", "主机未连接")
|
||||
return
|
||||
sig = "SIGKILL" if force else "SIGTERM"
|
||||
flag = "-9" if force else ""
|
||||
short_comm = (comm[:60] + "…") if len(comm) > 60 else comm
|
||||
reply = QMessageBox.question(
|
||||
self, f"杀进程 {pid}",
|
||||
f"确定要 {sig} 进程 {pid} 吗?\n\n"
|
||||
f"命令: {short_comm}\n\n"
|
||||
f"建议: 先 SIGTERM 让进程清理;不响应再 SIGKILL。",
|
||||
QMessageBox.Yes | QMessageBox.No,
|
||||
)
|
||||
if reply != QMessageBox.Yes:
|
||||
return
|
||||
code, out, err = conn.exec_command(f"kill {flag} {pid} 2>&1; echo \"exit=$?\"", timeout=10)
|
||||
if code == 0:
|
||||
QMessageBox.information(self, "完成",
|
||||
f"已对 PID {pid} 发送 {sig}\n远程返回:\n{out.strip()}")
|
||||
else:
|
||||
QMessageBox.critical(self, "失败",
|
||||
f"kill {pid} 失败\n退出码: {code}\nstderr: {err.strip()}\nstdout: {out.strip()}")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# AI Agent 对话面板
|
||||
|
||||
Reference in New Issue
Block a user