├── src └── sysmaid │ ├── action │ ├── __init__.py │ ├── write_file.py │ ├── alarm.py │ ├── stop_service.py │ ├── get_top_processes.py │ ├── kill_process.py │ └── lock_volume.py │ ├── condiction │ ├── __init__.py │ ├── is_exited.py │ ├── is_running.py │ ├── has_no_window.py │ ├── has_windows_look_like.py │ └── is_too_busy.py │ ├── i18n │ ├── zh_cn.py │ ├── en_us.py │ └── __init__.py │ ├── __init__.py │ └── maid.py ├── .gitignore ├── pyproject.toml ├── .github └── workflows │ ├── python-app.yml │ └── python-publish.yml ├── README.md ├── README_en.md ├── tests └── test_stress.py └── LICENSE /src/sysmaid/action/__init__.py: -------------------------------------------------------------------------------- 1 | # nuitka-project: --include-package=sysmaid.action -------------------------------------------------------------------------------- /src/sysmaid/condiction/__init__.py: -------------------------------------------------------------------------------- 1 | # nuitka-project: --include-package=sysmaid.condicion -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.conda/ 2 | /*.build/ 3 | /*.dist/ 4 | __pycache__/ 5 | .vscode/ 6 | SysMaid_Tony.py -------------------------------------------------------------------------------- /src/sysmaid/i18n/zh_cn.py: -------------------------------------------------------------------------------- 1 | # src/sysmaid/i18n/zh_cn.py 2 | translations = { 3 | "init.admin.error.title": "权限错误", 4 | "init.admin.error.message": "SysMaid 需要管理员权限才能正常运行。", 5 | "init.admin.skip.message": "已进入CI模式:UAC检查已被跳过。如果您是普通用户,请立即停止并检查您的环境变量。", 6 | "get_top_processes.result.header": "消耗CPU资源最多的 {count} 个进程:", 7 | "get_top_processes.result.item": " - PID: {pid}, 名称: {name}, CPU: {cpu}%", 8 | "get_top_processes.result.item.error": " - PID: {pid}, 名称: {name}, CPU: N/A (进程已退出)", 9 | "get_top_processes.return.general_error": "错误:无法获取进程信息。{error}", 10 | "alarm.title": "SysMaid 警报" 11 | } -------------------------------------------------------------------------------- /src/sysmaid/condiction/is_exited.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from ..maid import BaseWmiEvent 3 | 4 | logger = logging.getLogger(__name__) 5 | 6 | class ExitedWatchdog(BaseWmiEvent): 7 | def __init__(self, process_name): 8 | super().__init__(name=process_name, event_type='__InstanceDeletionEvent') 9 | 10 | def is_exited(self, func): 11 | self._callbacks['is_exited'] = func 12 | return func 13 | 14 | def handle_event(self, event): 15 | logger.info(f"'{self.name}' has exited. Firing callback.") 16 | if 'is_exited' in self._callbacks: 17 | self._callbacks['is_exited']() -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "sysmaid" 7 | version = "0.7.3" 8 | authors = [ 9 | { name="Tony Zhang", email="zhangtony239@gmail.com" }, 10 | ] 11 | description = "为 Windows 高级用户和开发者打造:一个基于Python的系统管理框架,用于轻松发现并治理那些不守规矩的后台应用和服务。" 12 | readme = "README.md" 13 | requires-python = ">=3.8" 14 | license = { text = "GPL-3.0-only" } 15 | classifiers = [ 16 | "Programming Language :: Python :: 3", 17 | "Operating System :: Microsoft :: Windows", 18 | ] 19 | dependencies = [ 20 | "WMI", 21 | "pywin32", 22 | "psutil", 23 | "mss", 24 | "opencv-python" 25 | ] 26 | 27 | [project.optional-dependencies] 28 | test = [ 29 | "pytest", 30 | ] 31 | -------------------------------------------------------------------------------- /src/sysmaid/i18n/en_us.py: -------------------------------------------------------------------------------- 1 | # src/sysmaid/i18n/en_us.py 2 | translations = { 3 | "init.admin.error.title": "Permission Error", 4 | "init.admin.error.message": "SysMaid requires administrator privileges to run properly.", 5 | "init.admin.skip.message": "CI mode activated: UAC check is bypassed. If you are a regular user, please stop and check your environment variables.", 6 | "get_top_processes.result.header": "Top {count} CPU-consuming processes:", 7 | "get_top_processes.result.item": " - PID: {pid}, Name: {name}, CPU: {cpu}%", 8 | "get_top_processes.result.item.error": " - PID: {pid}, Name: {name}, CPU: N/A (process has exited)", 9 | "get_top_processes.return.general_error": "Error: Could not retrieve top processes. {error}", 10 | "alarm.title": "SysMaid Alarm" 11 | } -------------------------------------------------------------------------------- /src/sysmaid/action/write_file.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | 4 | logger = logging.getLogger(__name__) 5 | 6 | # 避免在SYSTEM账户下运行时,工作目录被强制指向System32的问题 7 | _BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 8 | 9 | def write_file(path: str, content: str, append: bool = False): 10 | """ 11 | 将内容按原样写入指定文件。 12 | 13 | Args: 14 | path (str): 目标文件的路径。 15 | content (str): 要写入的内容。 16 | append (bool, optional): 是否追加到文件末尾。默认为 False,会覆盖整个文件。 17 | """ 18 | try: 19 | # 如果路径是相对路径,则转换为基于项目根目录的绝对路径 20 | if not os.path.isabs(path): 21 | path = os.path.join(_BASE_DIR, path) 22 | 23 | # 确保目录存在 24 | dir_name = os.path.dirname(path) 25 | if dir_name: 26 | os.makedirs(dir_name, exist_ok=True) 27 | 28 | mode = 'a' if append else 'w' 29 | with open(path, mode, encoding='utf-8') as f: 30 | f.write(str(content)) 31 | 32 | logger.info(f"Successfully wrote to file: {path}") 33 | 34 | except Exception as e: 35 | logger.error(f"Failed to write to file {path}: {e}", exc_info=True) -------------------------------------------------------------------------------- /src/sysmaid/action/alarm.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import logging 3 | import threading 4 | from ..i18n import get_text 5 | 6 | logger = logging.getLogger(__name__) 7 | 8 | def _show_messagebox(content: str): 9 | """ 10 | Helper function to display a message box. 11 | This avoids blocking the main thread if the user doesn't close the box immediately. 12 | """ 13 | try: 14 | # MessageBoxW(HWND, text, caption, type) 15 | # HWND = 0 for no owner window 16 | # text = content to display 17 | # caption = window title 18 | # type = 0x40 (MB_ICONINFORMATION) 19 | ctypes.windll.user32.MessageBoxW(0, str(content), get_text("alarm.title"), 0x40) 20 | except Exception as e: 21 | logger.error(f"Failed to show alarm messagebox: {e}", exc_info=True) 22 | 23 | def alarm(content: str): 24 | """ 25 | 在一个独立的线程中安全地弹出一个包含指定内容的系统消息框。 26 | 27 | Args: 28 | content (str): 要显示在消息框中的文本内容。 29 | """ 30 | logger.info(f"Triggering alarm with content: {content}") 31 | # Run the GUI part in a separate thread to avoid blocking the main loop 32 | thread = threading.Thread(target=_show_messagebox, args=(content,)) 33 | thread.daemon = True 34 | thread.start() -------------------------------------------------------------------------------- /.github/workflows/python-app.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Python application 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | permissions: 13 | contents: read 14 | 15 | jobs: 16 | build: 17 | # Use the Windows runner for the build environment 18 | runs-on: windows-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v4 22 | - name: Set up Python 3.10 23 | uses: actions/setup-python@v3 24 | with: 25 | python-version: "3.10" 26 | - name: Install dependencies 27 | run: | 28 | python -m pip install --upgrade pip 29 | # 安装构建和测试所需的工具 30 | pip install flake8 pytest 31 | # 使用pip来安装pyproject.toml中声明的依赖 32 | pip install . 33 | - name: Lint with flake8 34 | run: | 35 | # stop the build if there are Python syntax errors or undefined names 36 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 37 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 38 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 39 | - name: Test with pytest 40 | run: | 41 | pytest 42 | -------------------------------------------------------------------------------- /src/sysmaid/condiction/is_running.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from ..maid import BaseWmiEvent 3 | 4 | logger = logging.getLogger(__name__) 5 | 6 | class RunningWatchdog(BaseWmiEvent): 7 | def __init__(self, process_name): 8 | super().__init__(name=process_name, event_type='__InstanceCreationEvent') 9 | self._initial_check_done = False 10 | 11 | def start(self): 12 | # 在启动事件监听前,先做一次性检查 13 | # 这避免了重写_loop所带来的代码重复 14 | if not self._initial_check_done: 15 | import pythoncom 16 | import wmi 17 | 18 | pythoncom.CoInitialize() 19 | try: 20 | c = wmi.WMI() 21 | existing_processes = c.Win32_Process(Name=self.name) 22 | if existing_processes: 23 | logger.info(f"'{self.name}' is already running. Firing callback on start.") 24 | if 'is_running' in self._callbacks: 25 | self._callbacks['is_running']() 26 | finally: 27 | pythoncom.CoUninitialize() 28 | 29 | self._initial_check_done = True 30 | 31 | # 调用父类的start,启动标准的事件监听循环 32 | super().start() 33 | 34 | def is_running(self, func): 35 | self._callbacks['is_running'] = func 36 | return func 37 | 38 | def handle_event(self, event): 39 | logger.info(f"'{self.name}' has started. Firing callback.") 40 | if 'is_running' in self._callbacks: 41 | self._callbacks['is_running']() -------------------------------------------------------------------------------- /src/sysmaid/action/stop_service.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import wmi 3 | import pythoncom 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | def stop_service(service_name): 8 | """ 9 | Finds and stops a Windows service by its name. 10 | """ 11 | logger.info(f"Executing stop for service '{service_name}'.") 12 | try: 13 | pythoncom.CoInitialize() 14 | c = wmi.WMI() 15 | 16 | # Find the service 17 | services = c.Win32_Service(Name=service_name) 18 | 19 | if not services: 20 | logger.warning(f"Stop command ran, but service '{service_name}' was not found.") 21 | return 22 | 23 | service = services[0] 24 | 25 | # Check if the service is already stopped 26 | if service.State == 'Stopped': 27 | logger.info(f"Service '{service_name}' is already stopped.") 28 | return 29 | 30 | # Stop the service 31 | result, = service.StopService() 32 | 33 | if result == 0: 34 | logger.info(f"Successfully sent stop command to service '{service_name}'.") 35 | elif result == 5: 36 | logger.warning(f"Service '{service_name}' is not running, so it could not be stopped.") 37 | else: 38 | logger.error(f"Failed to stop service '{service_name}'. Error code: {result}") 39 | 40 | except Exception as e: 41 | logger.error(f"A critical error occurred while trying to stop service '{service_name}': {e}", exc_info=True) 42 | finally: 43 | pythoncom.CoUninitialize() -------------------------------------------------------------------------------- /src/sysmaid/i18n/__init__.py: -------------------------------------------------------------------------------- 1 | # nuitka-project: --include-package=sysmaid.i18n 2 | 3 | import importlib 4 | import os 5 | from typing import Dict 6 | 7 | _translations: Dict[str, str] = {} 8 | 9 | 10 | def _load_language(): 11 | """ 12 | Loads the language module based on the system's default locale. 13 | Falls back to en_us if the specific language module is not found. 14 | """ 15 | global _translations 16 | try: 17 | # e.g., 'zh_CN' or 'en_US' 18 | lang_code = str(os.getenv('LANG')).split('.')[0].lower() 19 | if not lang_code: 20 | lang_code = 'en_us' 21 | except (ValueError, TypeError): 22 | lang_code = 'en_us' # Default fallback 23 | 24 | if lang_code is None: 25 | lang_code = 'en_us' 26 | 27 | try: 28 | # Dynamically import the language module 29 | lang_module = importlib.import_module(f'.{lang_code}', __name__) 30 | _translations = lang_module.translations 31 | except (ImportError, AttributeError): 32 | # Fallback to en_us if the specific language module doesn't exist or is invalid 33 | try: 34 | lang_module = importlib.import_module('.en_us', __name__) 35 | _translations = lang_module.translations 36 | except (ImportError, AttributeError): 37 | # If any error occurs, even with the fallback, 38 | # use an empty dict to prevent crashes. 39 | _translations = {} 40 | 41 | 42 | def get_text(key: str) -> str: 43 | """ 44 | Returns the translated text for a given key. 45 | If the key is not found, it returns the key itself as a fallback. 46 | """ 47 | return _translations.get(key, key) 48 | 49 | 50 | # Load the appropriate language when the module is first imported. 51 | _load_language() -------------------------------------------------------------------------------- /src/sysmaid/__init__.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import logging 3 | import os 4 | from .i18n import get_text 5 | from .maid import attend, start 6 | from .action.kill_process import kill_process 7 | from .action.stop_service import stop_service 8 | from .action.lock_volume import lock_volume 9 | from .action.alarm import alarm 10 | from .action.write_file import write_file 11 | from .action.get_top_processes import get_top_processes 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | def set_log_level(level): 16 | """ 17 | Sets the logging level for the SysMaid library. 18 | 19 | Args: 20 | level (str): The desired logging level. Can be one of 'DEBUG', 'INFO', 21 | 'WARNING', 'ERROR', 'CRITICAL'. 22 | """ 23 | # Set up a basic, user-friendly logger for the library. 24 | # The user can override this configuration if they wish. 25 | logging.basicConfig( 26 | level=level, 27 | format='[%(asctime)s] {%(name)-16s} %(message)s', 28 | datefmt='%H:%M:%S' 29 | ) 30 | 31 | def _is_admin(): 32 | try: 33 | return ctypes.windll.shell32.IsUserAnAdmin() 34 | except: # noqa: E722 35 | return False 36 | 37 | # Library requires Admin privileges. 38 | # Skip this check in CI environments where admin rights are not available. 39 | if "CI" in os.environ: 40 | logger.warning(get_text("init.admin.skip.message")) 41 | else: 42 | if not _is_admin(): 43 | ctypes.windll.user32.MessageBoxW(0, get_text("init.admin.error.message"), get_text("init.admin.error.title"), 0x10) 44 | exit(0) 45 | 46 | __all__ = [ 47 | "attend", 48 | "kill_process", 49 | "stop_service", 50 | "lock_volume", 51 | "alarm", 52 | "write_file", 53 | "get_top_processes", 54 | "start", 55 | "set_log_level", 56 | ] -------------------------------------------------------------------------------- /src/sysmaid/condiction/has_no_window.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import wmi 3 | from ..maid import ProcessWatchdog 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | class NoWindowWatchdog(ProcessWatchdog): 8 | def __init__(self, process_name): 9 | super().__init__(process_name) 10 | self._no_window_checks_count = 0 11 | self.GRACE_PERIOD = 3 # 3 seconds 12 | 13 | def has_no_window(self, func): 14 | self._callbacks['has_no_window'] = func 15 | return func 16 | 17 | def check_process_state(self, pids_with_windows): 18 | try: 19 | processes = self.c.Win32_Process(name=self.name) 20 | if not processes: 21 | if self._no_window_checks_count > 0: 22 | logger.debug(f"'{self.name}' is no longer running. Resetting zombie check.") 23 | self._no_window_checks_count = 0 24 | return 25 | 26 | current_pids = {p.ProcessId for p in processes} 27 | 28 | app_has_a_window = any(pid in pids_with_windows for pid in current_pids) 29 | 30 | if app_has_a_window: 31 | if self._no_window_checks_count > 0: 32 | logger.debug(f"'{self.name}' has a visible window. Vindicating.") 33 | self._no_window_checks_count = 0 34 | else: 35 | self._no_window_checks_count += 1 36 | logger.debug(f"'{self.name}' has no visible windows. Zombie check count: {self._no_window_checks_count}/{self.GRACE_PERIOD}") 37 | if self._no_window_checks_count >= self.GRACE_PERIOD: 38 | logger.info(f"ZOMBIE CONFIRMED for app '{self.name}'. All processes lack windows. Firing callback.") 39 | if 'has_no_window' in self._callbacks: 40 | self._callbacks['has_no_window']() 41 | self._no_window_checks_count = 0 42 | 43 | except wmi.x_wmi as e: 44 | logger.error(f"WMI query for '{self.name}' failed: {e}") 45 | -------------------------------------------------------------------------------- /src/sysmaid/action/get_top_processes.py: -------------------------------------------------------------------------------- 1 | import psutil 2 | import logging 3 | from ..i18n import get_text 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | def get_top_processes(count: int) -> str: 8 | """ 9 | 获取CPU占用率最高的N个进程的信息。 10 | 11 | Args: 12 | count (int): 要获取的进程数量。 13 | 14 | Returns: 15 | str: 格式化的进程信息字符串。 16 | """ 17 | try: 18 | processes = [] 19 | for p in psutil.process_iter(['pid', 'name']): 20 | try: 21 | # The pre-warming is now handled by the IsTooBusyWatchdog. 22 | # This call retrieves the CPU usage since the watchdog was initialized. 23 | p.info['cpu_percent'] = p.cpu_percent(interval=None) 24 | processes.append(p) 25 | except (psutil.NoSuchProcess, psutil.AccessDenied): 26 | continue 27 | 28 | # Exclude System Idle Process 29 | processes = [p for p in processes if p.info['name'] != 'System Idle Process'] 30 | 31 | # Sort processes by CPU usage 32 | processes.sort(key=lambda p: p.info['cpu_percent'], reverse=True) 33 | 34 | # Format the output string 35 | top_processes = processes[:count] 36 | result = [get_text("get_top_processes.result.header").format(count=count)] 37 | for p in top_processes: 38 | try: 39 | result.append( 40 | get_text("get_top_processes.result.item").format( 41 | pid=p.info['pid'], 42 | name=p.info['name'], 43 | cpu=f"{p.info['cpu_percent']:.2f}" 44 | ) 45 | ) 46 | except (psutil.NoSuchProcess, psutil.AccessDenied): 47 | result.append( 48 | get_text("get_top_processes.result.item.error").format( 49 | pid=p.info.get('pid', 'N/A'), 50 | name=p.info.get('name', 'N/A') 51 | ) 52 | ) 53 | return "\n".join(result) 54 | 55 | except Exception as e: 56 | logger.error(f"Failed to get top processes: {e}", exc_info=True) 57 | return get_text("get_top_processes.return.general_error").format(error=e) -------------------------------------------------------------------------------- /src/sysmaid/action/kill_process.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import subprocess 3 | 4 | logger = logging.getLogger(__name__) 5 | 6 | def kill_process(process_name): 7 | """ 8 | Forcefully terminates a process and its entire process tree using taskkill. 9 | This requires administrator privileges to kill elevated/protected processes. 10 | """ 11 | logger.info(f"Executing force kill for '{process_name}' using taskkill.") 12 | try: 13 | command = [ 14 | "taskkill", 15 | "/F", # Forcefully terminate 16 | "/T", # Terminate process tree 17 | "/IM", # Specify image name 18 | process_name 19 | ] 20 | 21 | # We use CREATE_NO_WINDOW to prevent the console from flashing. 22 | # capture_output=True pipes stdout/stderr, preventing them from showing up. 23 | result = subprocess.run( 24 | command, 25 | capture_output=True, 26 | text=True, 27 | check=False, # We will check the result manually 28 | creationflags=subprocess.CREATE_NO_WINDOW 29 | ) 30 | 31 | # taskkill exit codes: 32 | # 0: Success, the process was terminated. 33 | # 128: The process was not found. 34 | # 1: Access denied (permission issue). 35 | if result.returncode == 0: 36 | logger.info(f"Successfully sent termination signal to '{process_name}'. Output: {result.stdout.strip()}") 37 | elif result.returncode == 128: 38 | logger.info(f"Kill command ran, but no active '{process_name}' processes were found.") 39 | elif result.returncode == 1: 40 | logger.error(f"Failed to kill '{process_name}': Access Denied. Ensure SysMaid is run with administrator privileges. Details: {result.stderr.strip()}") 41 | else: 42 | logger.error(f"taskkill failed for '{process_name}' with exit code {result.returncode}. Stderr: {result.stderr.strip()}") 43 | 44 | except FileNotFoundError: 45 | logger.critical("`taskkill.exe` not found. This action is only supported on Windows.") 46 | except Exception as e: 47 | logger.error(f"A critical error occurred during taskkill for '{process_name}': {e}", exc_info=True) -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package to PyPI when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | release: 13 | types: [published] 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | release-build: 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v4 24 | 25 | - uses: actions/setup-python@v5 26 | with: 27 | python-version: "3.x" 28 | 29 | - name: Build release distributions 30 | run: | 31 | # NOTE: put your own distribution build steps here. 32 | python -m pip install build 33 | python -m build 34 | 35 | - name: Upload distributions 36 | uses: actions/upload-artifact@v4 37 | with: 38 | name: release-dists 39 | path: dist/ 40 | 41 | pypi-publish: 42 | runs-on: ubuntu-latest 43 | needs: 44 | - release-build 45 | permissions: 46 | # IMPORTANT: this permission is mandatory for trusted publishing 47 | id-token: write 48 | 49 | # Dedicated environments with protections for publishing are strongly recommended. 50 | # For more information, see: https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#deployment-protection-rules 51 | environment: 52 | name: pypi 53 | # OPTIONAL: uncomment and update to include your PyPI project URL in the deployment status: 54 | # url: https://pypi.org/p/YOURPROJECT 55 | # 56 | # ALTERNATIVE: if your GitHub Release name is the PyPI project version string 57 | # ALTERNATIVE: exactly, uncomment the following line instead: 58 | # url: https://pypi.org/project/YOURPROJECT/${{ github.event.release.name }} 59 | 60 | steps: 61 | - name: Retrieve release distributions 62 | uses: actions/download-artifact@v4 63 | with: 64 | name: release-dists 65 | path: dist/ 66 | 67 | - name: Publish release distributions to PyPI 68 | uses: pypa/gh-action-pypi-publish@release/v1 69 | with: 70 | packages-dir: dist/ 71 | -------------------------------------------------------------------------------- /src/sysmaid/condiction/has_windows_look_like.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import mss 3 | import cv2 4 | import numpy as np 5 | import os 6 | from ..maid import HardwareWatchdog 7 | 8 | logger = logging.getLogger(__name__) 9 | 10 | # 避免在SYSTEM账户下运行时,工作目录被强制指向System32的问题 11 | _BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 12 | 13 | class WindowsMatchingWatchdog(HardwareWatchdog): 14 | def __init__(self, hardware_name, template_image_path=None, threshold=0.8, interval=1): 15 | super().__init__(hardware_name) 16 | self.interval = interval # 设置轮询间隔,基类的_loop将会使用它 17 | 18 | if not template_image_path: 19 | raise ValueError("A template image path must be provided for WindowsMatchingWatchdog.") 20 | 21 | # 如果路径是相对路径,则转换为基于项目根目录的绝对路径 22 | if not os.path.isabs(template_image_path): 23 | path = os.path.join(_BASE_DIR, template_image_path) 24 | else: 25 | path = template_image_path 26 | 27 | self.template = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_GRAYSCALE) 28 | self.threshold = threshold 29 | self._callbacks = {} 30 | 31 | if self.template is None: 32 | raise FileNotFoundError(f"Template image not found at path: {path}") 33 | 34 | def check_state(self): 35 | if self.template is None: 36 | # This path should not be reached due to the check in __init__, 37 | # but we add it for type checker robustness and safety. 38 | logger.warning("Template image is not loaded, skipping screen check.") 39 | return 40 | 41 | with mss.mss() as sct: 42 | monitor = sct.monitors[1] # All monitors 43 | sct_img = sct.grab(monitor) 44 | 45 | img = np.array(sct_img) 46 | img_gray = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY) 47 | 48 | res = cv2.matchTemplate(img_gray, self.template, cv2.TM_CCOEFF_NORMED) 49 | loc = np.where(res >= self.threshold) 50 | 51 | if loc[0].size > 0: 52 | logger.info("Found image matching template on screen. Firing callback.") 53 | self.trigger_callback() 54 | 55 | def trigger_callback(self): 56 | if 'is_found' in self._callbacks: 57 | self._callbacks['is_found']() 58 | 59 | @property 60 | def is_found(self): 61 | def decorator(func): 62 | self._callbacks['is_found'] = func 63 | return func 64 | return decorator -------------------------------------------------------------------------------- /src/sysmaid/action/lock_volume.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import wmi 3 | import pythoncom 4 | import time 5 | 6 | logger = logging.getLogger(__name__) 7 | 8 | def lock_volume(drive_letter: str, timeout_seconds=30): 9 | """ 10 | Locks a BitLocker-encrypted volume using WMI, with retries if the volume is in use. 11 | This action requires administrator privileges to run. 12 | """ 13 | logger.info(f"Attempting to lock volume {drive_letter}: via WMI.") 14 | 15 | # Normalize drive letter: accept "D" or "D:" 16 | clean_letter = (drive_letter or "").strip().upper().rstrip(':') 17 | if len(clean_letter) != 1: 18 | logger.error(f"Invalid drive letter provided: '{drive_letter}'. It must be a single character (e.g., 'D').") 19 | return 20 | drive = f"{clean_letter}:" 21 | 22 | try: 23 | pythoncom.CoInitialize() 24 | c = wmi.WMI(namespace="root/cimv2/security/microsoftvolumeencryption") 25 | 26 | # Find the encryptable volume 27 | volumes = c.Win32_EncryptableVolume(DriveLetter=drive) 28 | 29 | if not volumes: 30 | logger.warning(f"Could not find a BitLocker volume for drive '{drive}'. The drive may not exist or is not encryptable.") 31 | return 32 | 33 | volume = volumes[0] 34 | 35 | start_time = time.time() 36 | while True: 37 | result = volume.Lock() 38 | logger.debug(f"Lock command returned: {result}") 39 | return_value = result[0] 40 | 41 | if return_value == 0: 42 | logger.info(f"Successfully sent lock command to volume '{drive}'.") 43 | return 44 | elif return_value == -0x7fcf0000: 45 | logger.info(f"Volume '{drive}' is already locked.") 46 | return 47 | elif return_value == -0x7ff8fffb: 48 | if time.time() - start_time < timeout_seconds: 49 | logger.info(f"Volume '{drive}' is currently in use, retrying in 1 second...") 50 | time.sleep(1) 51 | else: 52 | logger.error(f"Failed to lock volume '{drive}' after {timeout_seconds} seconds as it remains in use. " \ 53 | f"WMI returned error code: {hex(return_value)}") 54 | return 55 | elif return_value == -0x7fceffff: 56 | logger.warning(f"Cannot lock volume {drive} because it is not protected by BitLocker.") 57 | return 58 | else: 59 | logger.error(f"Failed to lock volume '{drive}'. WMI returned error code: {hex(return_value)}") 60 | return # For other errors, no need to retry. 61 | 62 | except Exception as e: 63 | logger.critical(f"An unexpected critical error occurred while trying to lock volume {drive}: {e}", exc_info=True) 64 | finally: 65 | pythoncom.CoUninitialize() -------------------------------------------------------------------------------- /src/sysmaid/condiction/is_too_busy.py: -------------------------------------------------------------------------------- 1 | import time 2 | import psutil 3 | import logging 4 | from ..maid import HardwareWatchdog 5 | 6 | logger = logging.getLogger(__name__) 7 | 8 | class IsTooBusyWatchdog(HardwareWatchdog): 9 | def __init__(self, hardware_name, over, duration): 10 | super().__init__(hardware_name) 11 | if self.name.lower() != 'cpu': 12 | raise ValueError("is_too_busy condition is currently only supported for 'CPU'") 13 | 14 | self.percpu = isinstance(over, list) 15 | if self.percpu: 16 | core_count = psutil.cpu_count() 17 | if len(over) != core_count: 18 | raise ValueError(f"The length of 'over' list ({len(over)}) must match the number of CPU cores ({core_count}).") 19 | if not all(isinstance(x, int) for x in over): 20 | raise ValueError("All elements in the 'over' list must be integers.") 21 | 22 | self.over = over 23 | self.duration = duration 24 | self.busy_start_time = None 25 | self._callbacks = [] 26 | 27 | def check_state(self): 28 | # Currently, only CPU is implemented 29 | if self.name != 'cpu': 30 | return 31 | 32 | is_currently_busy = False 33 | usages = psutil.cpu_percent(interval=self.interval, percpu=self.percpu) 34 | 35 | if self.percpu: 36 | # When percpu is True, usages is a list of floats 37 | if isinstance(usages, list): 38 | for i, (usage, threshold) in enumerate(zip(usages, self.over)): 39 | if threshold != -1 and usage > threshold: 40 | is_currently_busy = True 41 | logger.debug(f"CPU core {i} usage {usage}% exceeded threshold {threshold}%.") 42 | break 43 | else: 44 | # When percpu is False, usages is a single float or int 45 | usage = usages 46 | if isinstance(usage, (float, int)) and usage > self.over: 47 | is_currently_busy = True 48 | logger.debug(f"Overall CPU usage {usage}% exceeded threshold {self.over}.") 49 | 50 | if is_currently_busy: 51 | if self.busy_start_time is None: 52 | self.busy_start_time = time.time() 53 | logger.debug(f"CPU busy condition met. Starting timer for {self.duration} seconds.") 54 | elif time.time() - self.busy_start_time >= self.duration: 55 | logger.info(f"CPU has been too busy for {self.duration} seconds. Triggering action.") 56 | for callback in self._callbacks: 57 | callback() 58 | # Reset after triggering to avoid continuous firing 59 | self.busy_start_time = None 60 | else: 61 | if self.busy_start_time is not None: 62 | logger.debug("CPU usage fell below threshold(s). Resetting timer.") 63 | self.busy_start_time = None 64 | 65 | @property 66 | def is_too_busy(self): 67 | def decorator(func): 68 | self._callbacks.append(func) 69 | return func 70 | return decorator -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SysMaid [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fzhangtony239%2FSysMaid.svg?type=shield&issueType=security)](https://app.fossa.com/projects/git%2Bgithub.com%2Fzhangtony239%2FSysMaid?ref=badge_shield&issueType=security) 2 | [English](https://github.com/zhangtony239/SysMaid/blob/main/README_en.md) 3 | 4 | **SysMaid** 是一个为 Windows 设计的高阶 `win32 api` 抽象层,允许用户通过编写简单的 Python 脚本来发现并优化系统后台环境。它就像一个进程管理界的 uBlock Origin,旨在解决那些“不得不用的软件”所存在的后台滥用问题,并致力于成为 Windows 下最全面的 AutoRun 生态系统。 5 |

6 | 7 | #### 下载的文件不见了? 8 | 9 | 由于 SysMaid 的行为涉及系统级的进程监控和操作,某些杀毒软件(如 Windows Defender)可能会将其误报为潜在威胁。为了确保程序正常运行,强烈建议将您的脚本、打包后的 `.exe` 文件或其所在目录添加到杀毒软件的白名单中。 10 | 11 | ## 核心功能 12 | 13 | * **简洁的规则定义**:通过 Python 装饰器,直观地定义监控规则。 14 | * **进程和服务监控**:轻松监控指定进程的状态,如窗口是否存在、进程是否退出等。 15 | * **自动化操作**:在满足条件时自动执行操作,例如结束进程、停止服务、锁定加密卷等。 16 | * **可扩展性**:可以轻松添加新的条件和操作,以适应更复杂的需求。 17 | 18 | 19 | ## 快速开始 20 | 21 | ### 安装 22 | 23 | ```bash 24 | pip install sysmaid 25 | ``` 26 | 27 | ### 使用 28 | 29 | 创建一个 Python 文件(例如 `my_rules.py`),并添加你的规则: 30 | 31 | ```python 32 | import sysmaid as maid 33 | 34 | if __name__ == "__main__": 35 | # 规则1:当 Canva.exe 进程存在但没有窗口时,结束它 36 | Canva = maid.attend('Canva.exe') 37 | @Canva.has_no_window 38 | def _(): 39 | maid.kill_process('Canva.exe') 40 | 41 | # 规则2:当 GameViewer.exe 进程退出时,停止相关的服务 42 | GameViewer = maid.attend('GameViewer.exe') 43 | @GameViewer.is_exited 44 | def _(): 45 | maid.stop_service('GameViewerService') 46 | 47 | # 规则3:当 CrossDeviceResume.exe 进程运行时,结束它 48 | CrossDeviceResume = maid.attend('CrossDeviceResume.exe') 49 | @CrossDeviceResume.is_running 50 | def _(): 51 | maid.kill_process('CrossDeviceResume.exe') 52 | 53 | # 规则4:当 Macrium Reflect 完成备份或退出时,自动锁定备份盘(D盘)并关闭备份程序 54 | # (需确保 D 盘已启用 BitLocker) 55 | Screen = maid.attend('Screen') 56 | Screen.stop() #截图监听器占用稍大,建议默认关闭 57 | @Screen.has_windows_look_like('samples\\MacriumSuccess.png') 58 | def _(): 59 | maid.kill_process('Reflect.exe') 60 | 61 | Macrium = maid.attend('Reflect.exe') 62 | @Macrium.is_running 63 | def _(): 64 | Screen.start() # maid.attend实例可被规则启停 65 | @Macrium.is_exited 66 | def _(): 67 | maid.lock_volume('D') 68 | Screen.stop() # 硬件监听的Stop权限小于Start,采用引用计数控制,可放心多规则并行 69 | 70 | # 规则5:当 CPU 连续10秒占用率超过 80% 时,举报占用 CPU 最高的5个进程并记入log 71 | Cpu = maid.attend('cpu') 72 | @Cpu.is_too_busy(over=80, duration=10) 73 | # 亦可逐逻辑处理器指定阈值,以解决大小核异构CPU上平均占用计算误差问题 74 | # @Cpu.is_too_busy(over=[40,40,40,40,70,70,70,70], duration=5) 75 | def _(): 76 | TopProcesses = maid.get_top_processes(5) 77 | maid.alarm(TopProcesses) 78 | maid.write_file('logs/TopProcesses.log',TopProcesses) 79 | 80 | # 设置日志级别并启动监控 81 | maid.set_log_level('INFO') 82 | maid.start() 83 | ``` 84 | 85 | 然后运行它: 86 | 87 | ```bash 88 | python my_rules.py 89 | ``` 90 | 91 | ## 部署:打包为后台服务 92 | 93 | 为了实现真正的“后台待命”和开机自启,推荐使用 **Nuitka** 将您的规则脚本打包成一个独立的 `.exe` 可执行文件。Nuitka 会将 Python 脚本编译成 C 代码,生成一个高效、无依赖的程序。 94 | 95 | **安装 Nuitka:** 96 | 97 | ```bash 98 | pip install nuitka 99 | ``` 100 | 101 | **打包指令:** 102 | 103 | ```bash 104 | nuitka --standalone --windows-uac-admin --windows-console-mode=disable your_rules.py 105 | ``` 106 | 107 | * `--standalone`: 创建一个包含所有依赖的独立文件夹。 108 | * `--windows-uac-admin`: 请求管理员权限,这是停止服务等操作所必需的。 109 | * `--windows-console-mode=disable`: 创建一个无窗口的后台应用,运行时不会弹出黑色的控制台窗口。 110 | * `your_rules.py`: 你的规则脚本文件名。 111 | 112 | 打包成功后,你会在 `your_rules.dist` 文件夹中找到生成的 `.exe` 文件。你可以将这个文件或其快捷方式放入系统的“启动”文件夹,即可实现开机自启。 113 | 114 | ## 未来规划 115 | 116 | SysMaid 的目标不止于简单的进程管理。我们希望将其发展成为 Windows 下最全面的 **AutoRun 生态**,包括但不限于: 117 | 118 | * 更丰富的触发条件(如网络活动、CPU/内存占用等)。 119 | * 更多样的响应操作(如修改注册表、文件操作等)。 120 | * 提供图形用户界面,让不熟悉编程的用户也能轻松使用。 121 | * …… 122 | 123 | ## 贡献 124 | 125 | 欢迎任何形式的贡献!如果你有好的想法或发现了 Bug,请随时提交 Issue 或 Pull Request。想要抓取日志,可以使用python状态直接运行,确保日志记录级别在 `INFO` 以上。 126 | 127 | 128 | 129 | 130 | 131 | ## 许可证 132 | 133 | 本项目基于 [GPLv3 License](https://github.com/zhangtony239/SysMaid/blob/main/LICENSE) 开源。 134 | -------------------------------------------------------------------------------- /README_en.md: -------------------------------------------------------------------------------- 1 | # SysMaid [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fzhangtony239%2FSysMaid.svg?type=shield&issueType=security)](https://app.fossa.com/projects/git%2Bgithub.com%2Fzhangtony239%2FSysMaid?ref=badge_shield&issueType=security) 2 | [简体中文](https://github.com/zhangtony239/SysMaid/blob/main/README.md) 3 | 4 | **SysMaid** is a high-level `win32 api` abstraction layer for Windows, allowing users to discover and optimize the system's background environment by writing simple Python scripts. It acts like a uBlock Origin for process management, designed to address the background resource abuse by "must-use software" and aims to become the most comprehensive AutoRun ecosystem on Windows. 5 |

6 | 7 | #### Downloaded file disappeared? 8 | 9 | Due to SysMaid's behavior involving system-level process monitoring and operations, some antivirus software (like Windows Defender) may misreport it as a potential threat. To ensure the program runs correctly, it is strongly recommended to add your script, the packaged `.exe` file, or its directory to your antivirus software's whitelist. 10 | 11 | ## Core Features 12 | 13 | * **Concise Rule Definition**: Intuitively define monitoring rules using Python decorators. 14 | * **Process and Service Monitoring**: Easily monitor the status of specified processes, such as whether a window exists or if a process has exited. 15 | * **Automated Actions**: Automatically execute actions when conditions are met, such as killing a process, stopping a service, or locking an encrypted volume. 16 | * **Extensibility**: Easily add new conditions and actions to meet more complex needs. 17 | 18 | 19 | ## Quick Start 20 | 21 | ### Installation 22 | 23 | ```bash 24 | pip install sysmaid 25 | ``` 26 | 27 | ### Usage 28 | 29 | Create a Python file (e.g., `my_rules.py`) and add your rules: 30 | 31 | ```python 32 | import sysmaid as maid 33 | 34 | if __name__ == "__main__": 35 | # Rule 1: Kill Canva.exe if it's running without a window 36 | Canva = maid.attend('Canva.exe') 37 | @Canva.has_no_window 38 | def _(): 39 | maid.kill_process('Canva.exe') 40 | 41 | # Rule 2: Stop the related service when GameViewer.exe exits 42 | GameViewer = maid.attend('GameViewer.exe') 43 | @GameViewer.is_exited 44 | def _(): 45 | maid.stop_service('GameViewerService') 46 | 47 | # Rule 3: Kill CrossDeviceResume.exe when it is running 48 | CrossDeviceResume = maid.attend('CrossDeviceResume.exe') 49 | @CrossDeviceResume.is_running 50 | def _(): 51 | maid.kill_process('CrossDeviceResume.exe') 52 | 53 | # Rule 4: When Macrium Reflect finishes a backup or exits, automatically lock the backup drive (D:) and close the program 54 | # (Requires BitLocker to be enabled on drive D) 55 | Screen = maid.attend('Screen') 56 | Screen.stop() # The screen listener is resource-intensive, so it's disabled by default 57 | @Screen.has_windows_look_like('samples\\MacriumSuccess.png') 58 | def _(): 59 | maid.kill_process('Reflect.exe') 60 | 61 | Macrium = maid.attend('Reflect.exe') 62 | @Macrium.is_running 63 | def _(): 64 | Screen.start() # maid.attend instances can be started and stopped by rules 65 | @Macrium.is_exited 66 | def _(): 67 | maid.lock_volume('D') 68 | Screen.stop() # Stop has lower priority than Start and is reference-counted, ensuring safe parallel use 69 | 70 | # Rule 5: When CPU usage exceeds 80% for 10 consecutive seconds, report the top 5 CPU-consuming processes and log them. 71 | Cpu = maid.attend('cpu') 72 | @Cpu.is_too_busy(over=80, duration=10) 73 | # You can also specify per-logical-processor thresholds to resolve average utilization calculation errors on heterogeneous CPUs. 74 | # @Cpu.is_too_busy(over=[40,40,40,40,70,70,70,70], duration=5) 75 | def _(): 76 | TopProcesses = maid.get_top_processes(5) 77 | maid.alarm(TopProcesses) 78 | maid.write_file('logs/TopProcesses.log',TopProcesses) 79 | 80 | # Set log level and start monitoring 81 | maid.set_log_level('INFO') 82 | maid.start() 83 | ``` 84 | 85 | Then run it: 86 | 87 | ```bash 88 | python my_rules.py 89 | ``` 90 | 91 | ## Deployment: Packaging as a Background Service 92 | 93 | To achieve true "background standby" and auto-start on boot, it is recommended to use **Nuitka** to package your rule script into a standalone `.exe` executable. Nuitka compiles the Python script into C code, generating an efficient, dependency-free program. 94 | 95 | **Install Nuitka:** 96 | 97 | ```bash 98 | pip install nuitka 99 | ``` 100 | 101 | **Packaging Command:** 102 | 103 | ```bash 104 | nuitka --standalone --windows-uac-admin --windows-console-mode=disable your_rules.py 105 | ``` 106 | 107 | * `--standalone`: Creates a standalone folder with all dependencies included. 108 | * `--windows-uac-admin`: Requests administrator privileges, which are necessary for operations like stopping services. 109 | * `--windows-console-mode=disable`: Creates a windowless background application that won't show a black console window when run. 110 | * `your_rules.py`: Your rule script filename. 111 | 112 | After successful packaging, you will find the generated `.exe` file in the `your_rules.dist` folder. You can place this file or its shortcut into the system's "Startup" folder to have it launch automatically on boot. 113 | 114 | ## Future Plans 115 | 116 | SysMaid's goal extends beyond simple process management. We hope to develop it into the most comprehensive **AutoRun ecosystem** on Windows, including but not limited to: 117 | 118 | * Richer trigger conditions (e.g., network activity, CPU/memory usage). 119 | * More diverse response actions (e.g., modifying the registry, file operations). 120 | * Providing a graphical user interface to make it accessible for users unfamiliar with programming. 121 | * ... 122 | 123 | ## Contributing 124 | 125 | Contributions of any kind are welcome! If you have good ideas or find a bug, please feel free to submit an Issue or Pull Request. To capture logs, you can run the script directly in a Python environment and ensure the logging level is set to `INFO` or higher. 126 | 127 | 128 | 129 | 130 | 131 | ## License 132 | 133 | This project is open-sourced under the [GPLv3 License](https://github.com/zhangtony239/SysMaid/blob/main/LICENSE). 134 | -------------------------------------------------------------------------------- /tests/test_stress.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | # Add the project's 'src' directory to the Python path to allow imports from it. 4 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))) 5 | 6 | import unittest 7 | from unittest.mock import patch, MagicMock, call 8 | 9 | # We need to mock 'sysmaid' and its dependencies BEFORE they are imported by the code under test. 10 | # So, we create fake modules in sys.modules. 11 | import sys 12 | sys.modules['wmi'] = MagicMock() 13 | sys.modules['win32gui'] = MagicMock() 14 | sys.modules['win32process'] = MagicMock() 15 | sys.modules['pythoncom'] = MagicMock() 16 | 17 | # Now we can safely import the package to be tested 18 | import sysmaid as maid 19 | # We also need to import the 'maid' module specifically to access its internal '_watchdogs' list for testing. 20 | from sysmaid import maid as maid_module 21 | 22 | # We will patch the action functions directly on the imported package 23 | maid.kill_process = MagicMock() 24 | maid.stop_service = MagicMock() 25 | 26 | 27 | class StressTest(unittest.TestCase): 28 | 29 | def setUp(self): 30 | """ 31 | This method is called before each test. 32 | It sets up the mock environment. 33 | """ 34 | # Reset mocks and maid's internal state for test isolation 35 | maid.kill_process.reset_mock() 36 | maid.stop_service.reset_mock() 37 | 38 | # VERY IMPORTANT: Clear the global watchdog list in the maid module 39 | maid_module._watchdogs.clear() 40 | 41 | # Shared state for mocks to read from. This simulates the OS state. 42 | self.mock_os_state = { 43 | 'processes': {}, # 'proc_name': {'pid': pid} 44 | 'windows': {} # 'hwnd': pid 45 | } 46 | 47 | # Configure the mocks 48 | self.configure_mocks() 49 | 50 | def tearDown(self): 51 | """ 52 | This method is called after each test. 53 | It stops all watchdog threads to prevent them from running into the next test. 54 | """ 55 | for dog in maid_module._watchdogs: 56 | dog._is_running = False 57 | if dog._thread and dog._thread.is_alive(): 58 | dog._thread.join(timeout=2) # Give threads a moment to die 59 | maid_module._watchdogs.clear() # Final cleanup 60 | 61 | def mock_wmi_constructor(self): 62 | """Mocks `wmi.WMI()`""" 63 | mock_wmi_instance = MagicMock() 64 | 65 | def mock_win32_process(name): 66 | if name in self.mock_os_state['processes']: 67 | pid = self.mock_os_state['processes'][name]['pid'] 68 | mock_process = MagicMock() 69 | mock_process.ProcessId = pid 70 | return [mock_process] 71 | return [] 72 | 73 | mock_wmi_instance.Win32_Process = mock_win32_process 74 | return mock_wmi_instance 75 | 76 | def mock_enum_windows(self, callback, _): 77 | """Mocks `win32gui.EnumWindows`""" 78 | for hwnd, pid in self.mock_os_state['windows'].items(): 79 | # Mock the functions called by the real callback 80 | sys.modules['win32gui'].IsWindowVisible.return_value = True 81 | sys.modules['win32gui'].GetWindowText.return_value = "Mock Window" 82 | sys.modules['win32process'].GetWindowThreadProcessId.return_value = (0, pid) 83 | callback(hwnd, None) 84 | 85 | def configure_mocks(self): 86 | """Apply all mock configurations.""" 87 | sys.modules['wmi'].WMI.side_effect = self.mock_wmi_constructor 88 | sys.modules['win32gui'].EnumWindows.side_effect = self.mock_enum_windows 89 | sys.modules['pythoncom'].CoInitialize.return_value = None 90 | sys.modules['pythoncom'].CoUninitialize.return_value = None 91 | 92 | 93 | @patch('sysmaid.maid.BaseWatchdog.start') 94 | def test_1000_rules_triggered_simultaneously(self, mock_watchdog_start): 95 | """ 96 | Stress test: 1000 has_no_window rules are defined. 97 | The test bypasses threading by patching Watchdog.start and manually 98 | calling check_state to verify the core logic in a fast, deterministic way. 99 | """ 100 | num_rules = 1000 101 | mock_watchdog_start.return_value = None # Ensure start() does nothing 102 | 103 | # 1. Setup the initial state 104 | for i in range(num_rules): 105 | proc_name = f'proc_{i}.exe' 106 | pid = 1000 + i 107 | hwnd = 5000 + i 108 | self.mock_os_state['processes'][proc_name] = {'pid': pid} 109 | self.mock_os_state['windows'][hwnd] = pid 110 | 111 | # 2. Define the 1000 rules 112 | for i in range(num_rules): 113 | proc_name = f'proc_{i}.exe' 114 | action_func = lambda name=proc_name: maid.kill_process(name) 115 | watcher = maid.attend(proc_name) 116 | watcher.has_no_window(action_func) 117 | 118 | # 3. Setup for manual checking 119 | c = self.mock_wmi_constructor() 120 | 121 | # 4. Initial state check: verify no actions are triggered 122 | pids_with_windows = set(self.mock_os_state['windows'].values()) 123 | for dog in maid_module._watchdogs: 124 | dog.c = c # Manually set the mocked WMI connection 125 | dog.check_process_state(pids_with_windows) 126 | maid.kill_process.assert_not_called() 127 | 128 | # 5. The "simultaneous" event: all windows disappear 129 | print("\n--- All windows are disappearing now! ---") 130 | self.mock_os_state['windows'].clear() 131 | pids_with_windows.clear() 132 | 133 | # 6. Manually simulate the 3 checks for the GRACE_PERIOD 134 | print("--- Manually simulating 3 watchdog checks... ---") 135 | for i in range(3): 136 | print(f"Check {i+1}...") 137 | for dog in maid_module._watchdogs: 138 | dog.check_process_state(pids_with_windows) 139 | 140 | # 7. Assert that all 1000 actions have been called 141 | self.assertEqual(maid.kill_process.call_count, num_rules) 142 | expected_calls = [call(f'proc_{i}.exe') for i in range(num_rules)] 143 | maid.kill_process.assert_has_calls(expected_calls, any_order=True) 144 | 145 | print(f"--- Stress test successful! {maid.kill_process.call_count} actions were triggered. ---") 146 | @patch('sysmaid.condiction.is_too_busy.time') 147 | @patch('sysmaid.condiction.is_too_busy.psutil.cpu_percent') 148 | @patch('sysmaid.maid.BaseWatchdog.start') 149 | def test_cpu_is_too_busy_triggers_action(self, mock_start, mock_cpu_percent, mock_time): 150 | """ 151 | Tests that the is_too_busy condition for CPU triggers an action correctly. 152 | """ 153 | mock_start.return_value = None 154 | action_mock = MagicMock() 155 | 156 | # 1. Configure mocks 157 | # Simulate time moving forward 158 | mock_time.time.side_effect = [100, 101, 102, 103, 110, 111] 159 | # Simulate CPU usage 160 | mock_cpu_percent.side_effect = [95, 96, 98, 50] # High, High, High, then Low 161 | 162 | # 2. Define the rule 163 | watcher = maid.attend('cpu') 164 | watcher.is_too_busy(over=90, duration=2)(action_mock) 165 | 166 | # 3. Manually trigger checks 167 | dog = maid_module._watchdogs[-1] # Get the watchdog we just created 168 | 169 | # First check: CPU is busy, timer starts 170 | dog.check_state() 171 | action_mock.assert_not_called() 172 | self.assertIsNotNone(dog.busy_start_time) 173 | 174 | # Second check: Still busy, but duration not met 175 | dog.check_state() 176 | action_mock.assert_not_called() 177 | 178 | # Third check: Still busy, duration is met, action fires 179 | dog.check_state() 180 | action_mock.assert_called_once() 181 | self.assertIsNone(dog.busy_start_time) # Timer should reset after firing 182 | 183 | # Fourth check: CPU usage drops, should not fire again 184 | action_mock.reset_mock() 185 | dog.check_state() 186 | action_mock.assert_not_called() 187 | 188 | 189 | 190 | if __name__ == '__main__': 191 | # Configure logging to see output from maid 192 | import logging 193 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 194 | unittest.main() -------------------------------------------------------------------------------- /src/sysmaid/maid.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import threading 3 | import pythoncom 4 | import wmi 5 | import time 6 | import win32gui 7 | import win32process 8 | from typing import overload, Literal 9 | import pywintypes 10 | 11 | @overload 12 | def attend(name: Literal['cpu', 'ram', 'gpu', 'CPU', 'RAM', 'GPU', 'Screen']) -> 'HardwareWatcher': ... 13 | @overload 14 | def attend(name: str) -> 'ProcessWatcher': ... 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | # 全局的 watchdog 列表,为统一Start做准备 19 | _watchdogs = [] 20 | 21 | HARDWARE_KEYWORDS = ['cpu', 'ram', 'gpu', 'CPU', 'RAM', 'GPU', 'Screen'] 22 | 23 | class BaseWatchdog: 24 | """ 25 | 所有 Watchdog 的基类,处理通用的线程管理和事件循环。 26 | """ 27 | def __init__(self, name): 28 | self.name = name 29 | self.interval = 1 # 默认轮询间隔(秒) 30 | self._callbacks = {} 31 | self._thread = None 32 | self._is_running = False 33 | self._is_paused = False # 新增:员工的暂停状态 34 | _watchdogs.append(self) 35 | 36 | def pause(self): 37 | """暂停工作循环。""" 38 | self._is_paused = True 39 | 40 | def resume(self): 41 | """恢复工作循环。""" 42 | self._is_paused = False 43 | 44 | def _check_and_wait(self): 45 | """封装了暂停检查、任务执行和等待的原子操作。""" 46 | if self._is_paused: 47 | time.sleep(1) # 在暂停时休眠,以降低CPU使用率 48 | return 49 | 50 | self.check_state() 51 | time.sleep(self.interval) 52 | 53 | def _loop(self): 54 | """每个watchdog自己的轮询循环(模板方法)。""" 55 | logger.info(f"Watchdog for '{self.name}' started polling in thread {threading.get_ident()}.") 56 | try: 57 | while self._is_running: 58 | self._check_and_wait() 59 | except Exception as e: 60 | logger.critical(f"Watchdog thread for '{self.name}' has crashed: {e}", exc_info=True) 61 | finally: 62 | logger.info(f"Watchdog thread for '{self.name}' is shutting down.") 63 | 64 | def start(self): 65 | if not self._is_running: 66 | self._is_running = True 67 | self._thread = threading.Thread(target=self._loop) 68 | self._thread.daemon = True 69 | self._thread.start() 70 | 71 | def check_state(self): 72 | raise NotImplementedError 73 | 74 | class ProcessWatchdog(BaseWatchdog): 75 | """专门用于监控进程状态的 Watchdog""" 76 | def __init__(self, process_name): 77 | super().__init__(name=process_name) 78 | 79 | def _loop(self): 80 | """ 81 | 为进程监控定制的循环,在基类循环的基础上增加了WMI初始化和反初始化。 82 | """ 83 | try: 84 | pythoncom.CoInitialize() 85 | self.c = wmi.WMI() 86 | logger.info(f"Process watchdog for '{self.name}' started polling with WMI in thread {threading.get_ident()}.") 87 | 88 | # 调用基类的循环模板 89 | super()._loop() 90 | 91 | except Exception as e: 92 | logger.critical(f"Watchdog thread for '{self.name}' has crashed: {e}", exc_info=True) 93 | finally: 94 | logger.info(f"Watchdog thread for '{self.name}' is shutting down.") 95 | pythoncom.CoUninitialize() 96 | 97 | def check_state(self): 98 | """ 99 | 覆盖基类方法,加入进程特有的窗口信息获取, 100 | 然后调用子类(如NoWindowWatchdog)的最终实现。 101 | """ 102 | pids_with_windows = set() 103 | def enum_windows_callback(hwnd, _): 104 | if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd): 105 | _, found_pid = win32process.GetWindowThreadProcessId(hwnd) 106 | pids_with_windows.add(found_pid) 107 | win32gui.EnumWindows(enum_windows_callback, None) 108 | 109 | # 调用真正的检查逻辑,这个方法将在NoWindowWatchdog等子类中实现 110 | self.check_process_state(pids_with_windows) 111 | 112 | def check_process_state(self, pids_with_windows): 113 | raise NotImplementedError("This method should be implemented by specific process condition subclasses.") 114 | 115 | class BaseWmiEvent: 116 | def __init__(self, name, event_type): 117 | self.name = name 118 | self.event_type = event_type 119 | self._callbacks = {} 120 | self._thread = None 121 | self._is_running = False 122 | self._is_paused = False # 新增:员工的暂停状态 123 | self.query = self._build_query() 124 | _watchdogs.append(self) 125 | 126 | def pause(self): 127 | """暂停工作循环。""" 128 | self._is_paused = True 129 | 130 | def resume(self): 131 | """恢复工作循环。""" 132 | self._is_paused = False 133 | 134 | def _build_query(self): 135 | """构建 WMI 事件查询语句。""" 136 | return (f"SELECT * FROM {self.event_type} " 137 | f"WITHIN 2 WHERE TargetInstance ISA 'Win32_Process' " 138 | f"AND TargetInstance.Name = '{self.name}'") 139 | 140 | def _loop(self): 141 | """WMI事件订阅循环。""" 142 | logger.info(f"WMI event watcher for '{self.name}' ({self.event_type}) started in thread {threading.get_ident()}.") 143 | try: 144 | pythoncom.CoInitialize() 145 | c = wmi.WMI() 146 | watcher = c.ExecNotificationQuery(self.query) 147 | while self._is_running: 148 | if self._is_paused: 149 | time.sleep(1) # 在暂停时休眠 150 | continue 151 | try: 152 | event = watcher.NextEvent(100) 153 | self.handle_event(event) 154 | except pywintypes.com_error as e: 155 | # The HRESULT for WBEM_S_TIMEDOUT is -2147209215. This indicates an expected timeout. 156 | # It's nested deep inside the exception object at e.args[2][5]. 157 | if len(e.args) > 2 and e.args[2] and e.args[2][5] == -2147209215: 158 | continue # This is a timeout, just continue waiting 159 | raise # Re-raise other unexpected COM errors 160 | except Exception as e: 161 | logger.critical(f"WMI event watcher for '{self.name}' has crashed: {e}", exc_info=True) 162 | finally: 163 | logger.info(f"WMI event watcher for '{self.name}' is shutting down.") 164 | pythoncom.CoUninitialize() 165 | 166 | def start(self): 167 | if not self._is_running: 168 | self._is_running = True 169 | self._thread = threading.Thread(target=self._loop) 170 | self._thread.daemon = True 171 | self._thread.start() 172 | 173 | def handle_event(self, event): 174 | raise NotImplementedError("This method should be implemented by subclasses.") 175 | 176 | 177 | class HardwareWatchdog(BaseWatchdog): 178 | """专门用于监控硬件状态的 Watchdog""" 179 | def __init__(self, hardware_name): 180 | super().__init__(name=hardware_name) 181 | 182 | def check_state(self): 183 | raise NotImplementedError("This method should be implemented by subclasses like IsTooBusyWatchdog.") 184 | 185 | class ProcessWatcher: 186 | def __init__(self, process_name): 187 | self.name = process_name 188 | self._watchdogs = {} 189 | self._is_active = True 190 | 191 | def start(self): 192 | """激活此看护实例,并恢复其下所有已创建的规则。""" 193 | logger.info(f"Attendant for '{self.name}' activated.") 194 | self._is_active = True 195 | for dog in self._watchdogs.values(): 196 | dog.resume() 197 | 198 | def stop(self): 199 | """停用此看护实例,并暂停其下所有已创建的规则。""" 200 | logger.info(f"Attendant for '{self.name}' deactivated.") 201 | self._is_active = False 202 | for dog in self._watchdogs.values(): 203 | dog.pause() 204 | 205 | def _get_or_create_watchdog(self, key, factory, *args, **kwargs): 206 | if key not in self._watchdogs: 207 | dog = factory(self.name, *args, **kwargs) 208 | # 在创建时,让所有dog继承当前状态 209 | if not self._is_active: 210 | dog.pause() 211 | self._watchdogs[key] = dog 212 | return self._watchdogs[key] 213 | 214 | @property 215 | def has_no_window(self): 216 | from .condiction.has_no_window import NoWindowWatchdog 217 | dog = self._get_or_create_watchdog('no_window', NoWindowWatchdog) 218 | return dog.has_no_window 219 | 220 | @property 221 | def is_exited(self): 222 | from .condiction.is_exited import ExitedWatchdog 223 | dog = self._get_or_create_watchdog('is_exited', ExitedWatchdog) 224 | return dog.is_exited 225 | 226 | @property 227 | def is_running(self): 228 | from .condiction.is_running import RunningWatchdog 229 | dog = self._get_or_create_watchdog('is_running', RunningWatchdog) 230 | return dog.is_running 231 | 232 | class HardwareWatcher: 233 | def __init__(self, hardware_name): 234 | self.name = hardware_name 235 | self._watchdogs = {} 236 | self._is_active = True 237 | self._start_ref_count = 0 238 | 239 | def start(self): 240 | """激活此看护实例,并恢复其下所有已创建的规则。""" 241 | self._start_ref_count += 1 242 | logger.info(f"Attendant for '{self.name}' start requested. Ref count: {self._start_ref_count}.") 243 | if self._start_ref_count == 1: 244 | logger.info(f"Attendant for '{self.name}' activated.") 245 | self._is_active = True 246 | for dog in self._watchdogs.values(): 247 | dog.resume() 248 | 249 | def stop(self): 250 | """停用此看护实例,并暂停其下所有已创建的规则。""" 251 | if self._start_ref_count > 0: 252 | self._start_ref_count -= 1 253 | logger.info(f"Attendant for '{self.name}' stop requested. Ref count: {self._start_ref_count}.") 254 | if self._start_ref_count == 0: 255 | logger.info(f"Attendant for '{self.name}' deactivated.") 256 | self._is_active = False 257 | for dog in self._watchdogs.values(): 258 | dog.pause() 259 | 260 | def _get_or_create_watchdog(self, key, factory, *args, **kwargs): 261 | if key not in self._watchdogs: 262 | dog = factory(self.name, *args, **kwargs) 263 | # 在创建时,让所有dog继承当前状态 264 | if not self._is_active: 265 | dog.pause() 266 | self._watchdogs[key] = dog 267 | return self._watchdogs[key] 268 | 269 | def is_too_busy(self, over, duration): 270 | from .condiction.is_too_busy import IsTooBusyWatchdog 271 | # 产生一个唯一的key,以便相同的参数得到同一个watchdog 272 | key = f'is_too_busy_{over}_{duration}' 273 | dog = self._get_or_create_watchdog(key, IsTooBusyWatchdog, over=over, duration=duration) 274 | return dog.is_too_busy 275 | 276 | def has_windows_look_like(self, template_image_path: str, threshold: float = 0.8, interval: int = 1): 277 | from .condiction.has_windows_look_like import WindowsMatchingWatchdog 278 | key = f'look_like_{template_image_path}_{threshold}_{interval}' 279 | dog = self._get_or_create_watchdog(key, WindowsMatchingWatchdog, template_image_path=template_image_path, threshold=threshold, interval=interval) 280 | return dog.is_found 281 | 282 | def attend(name: str): 283 | """ 284 | 关注一个进程或硬件,返回一个 Watcher 实例用于设置监控条件。 285 | """ 286 | if name in HARDWARE_KEYWORDS: 287 | return HardwareWatcher(name.lower()) 288 | else: 289 | return ProcessWatcher(name) 290 | 291 | # --- Public Actions --- 292 | def get_top_processes(count: int) -> str: 293 | from .action.get_top_processes import get_top_processes as get_top_processes_func 294 | return get_top_processes_func(count) 295 | 296 | def alarm(content: str): 297 | from .action.alarm import alarm as alarm_func 298 | alarm_func(content) 299 | 300 | def write_file(path: str, content: str, append: bool = False): 301 | from .action.write_file import write_file as write_file_func 302 | write_file_func(path, content, append) 303 | 304 | def start(): 305 | """ 306 | 启动所有已配置的 watchdog 的监控线程,并保持主线程存活直到所有监控结束。 307 | """ 308 | logger.info("SysMaid service starting all watchdogs...") 309 | dogs_to_watch = list(_watchdogs) 310 | if not dogs_to_watch: 311 | logger.warning("No watchdogs configured, SysMaid will exit.") 312 | return 313 | 314 | for dog in dogs_to_watch: 315 | dog.start() 316 | logger.info("All watchdogs have been started.") 317 | 318 | # 只要还有任何一个 watchdog 线程在运行,主线程就保持存活。 319 | # 这是一个容错机制,防止所有监控线程意外崩溃后主进程僵死。 320 | while any(dog._thread and dog._thread.is_alive() for dog in dogs_to_watch): 321 | time.sleep(10) 322 | 323 | logger.warning("All watchdog threads have stopped. SysMaid service is shutting down.") 324 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------