cluster4npu/gentle_cleanup.py

121 lines
3.8 KiB
Python

"""
Gentle cleanup of app data (safer approach)
"""
import psutil
import os
import sys
import time
def find_and_kill_app_processes():
"""Find and kill only the Cluster4NPU app processes"""
killed_processes = []
for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'cwd']):
try:
if 'python' in proc.info['name'].lower():
cmdline = proc.info['cmdline']
cwd = proc.info['cwd']
# Check if this is our app
if (cmdline and
(any('main.py' in arg for arg in cmdline) or
any('cluster4npu' in arg.lower() for arg in cmdline) or
(cwd and 'cluster4npu' in cwd.lower()))):
print(f"Found app process: {proc.info['pid']}")
print(f" Command: {' '.join(cmdline) if cmdline else 'N/A'}")
print(f" Working dir: {cwd}")
# Try gentle termination first
proc.terminate()
time.sleep(2)
# If still running, force kill
if proc.is_running():
proc.kill()
print(f" Force killed: {proc.info['pid']}")
else:
print(f" Gently terminated: {proc.info['pid']}")
killed_processes.append(proc.info['pid'])
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
if killed_processes:
print(f"\nKilled {len(killed_processes)} app processes")
time.sleep(2)
else:
print("No app processes found")
def clear_app_locks():
"""Remove only app-specific lock files"""
app_specific_locks = [
'cluster4npu.lock',
'.cluster4npu.lock',
'Cluster4NPU.lock',
'main.lock',
'.main.lock'
]
locations = [
os.getcwd(), # Current directory
os.path.expanduser('~'), # User home
os.path.join(os.path.expanduser('~'), '.cluster4npu'), # App data dir
'C:\\temp' if os.name == 'nt' else '/tmp', # System temp
]
removed_files = []
for location in locations:
if not os.path.exists(location):
continue
for lock_name in app_specific_locks:
lock_path = os.path.join(location, lock_name)
if os.path.exists(lock_path):
try:
os.remove(lock_path)
removed_files.append(lock_path)
print(f"Removed lock: {lock_path}")
except Exception as e:
print(f"Could not remove {lock_path}: {e}")
if not removed_files:
print("No lock files found")
def reset_shared_memory():
"""Reset Qt shared memory for the app"""
try:
from PyQt5.QtCore import QSharedMemory
shared_mem = QSharedMemory("Cluster4NPU")
if shared_mem.attach():
print("Found shared memory, detaching...")
shared_mem.detach()
# Try to create and destroy to fully reset
if shared_mem.create(1):
shared_mem.detach()
print("Reset shared memory")
except Exception as e:
print(f"Could not reset shared memory: {e}")
if __name__ == '__main__':
print("Gentle App Cleanup")
print("=" * 30)
print("\n1. Looking for app processes...")
find_and_kill_app_processes()
print("\n2. Clearing app locks...")
clear_app_locks()
print("\n3. Resetting shared memory...")
reset_shared_memory()
print("\n" + "=" * 30)
print("Cleanup complete!")
print("You can now start the app with 'python main.py'")