From 94765216c8a926b43e655aec320bdb361c7457d8 Mon Sep 17 00:00:00 2001 From: Andrew Emelyaneko Date: Sat, 31 Oct 2026 21:53:48 +0300 Subject: [PATCH] Make agent unload resident Ollama models before threshold restarts --- config.example.json | 2 ++ scripts/install-agent.sh | 4 +++ src/ollama_swap_agent.py | 70 +++++++++++++++++++++++++++++++++++++-- src/ollama_swap_common.py | 5 +++ 4 files changed, 79 insertions(+), 2 deletions(-) diff --git a/config.example.json b/config.example.json index ca9ebf3..a042d6a 100644 --- a/config.example.json +++ b/config.example.json @@ -6,6 +6,8 @@ "poll_interval_seconds": 60, "swap_threshold_percent": null, "swap_threshold_mb": 3048, + "unload_models_before_restart": true, + "unload_wait_seconds": 3, "cooldown_seconds": 600, "max_restarts_per_hour": 2, "restart_force_after_seconds": 300, diff --git a/scripts/install-agent.sh b/scripts/install-agent.sh index 5674fc7..6404936 100755 --- a/scripts/install-agent.sh +++ b/scripts/install-agent.sh @@ -32,6 +32,8 @@ case "${OS}" in "poll_interval_seconds": 60, "swap_threshold_percent": null, "swap_threshold_mb": 3048, + "unload_models_before_restart": true, + "unload_wait_seconds": 3, "cooldown_seconds": 600, "max_restarts_per_hour": 2, "restart_force_after_seconds": 300, @@ -97,6 +99,8 @@ PLIST "poll_interval_seconds": 60, "swap_threshold_percent": null, "swap_threshold_mb": 3048, + "unload_models_before_restart": true, + "unload_wait_seconds": 3, "cooldown_seconds": 600, "max_restarts_per_hour": 2, "restart_force_after_seconds": 300, diff --git a/src/ollama_swap_agent.py b/src/ollama_swap_agent.py index b19a4b9..66384a2 100644 --- a/src/ollama_swap_agent.py +++ b/src/ollama_swap_agent.py @@ -8,6 +8,7 @@ import http.server import json import os import platform +import shutil import socketserver import subprocess import threading @@ -44,6 +45,7 @@ class StateStore: loaded = json.load(handle) if isinstance(loaded, dict): self.data.update(loaded) + self.data["restart_in_progress"] = False except (OSError, json.JSONDecodeError): pass @@ -168,13 +170,71 @@ class RemoteOllama: return data + + +def resolve_ollama_binary(config: Dict[str, Any]) -> Optional[str]: + configured = config.get("ollama_binary") + if isinstance(configured, str) and configured: + if Path(configured).is_file(): + return configured + binary = shutil.which("ollama") + if binary: + return binary + candidates = ( + "/Applications/Ollama.app/Contents/Resources/ollama", + "/usr/local/bin/ollama", + "/opt/ollama/ollama", + "/usr/bin/ollama", + ) + for candidate in candidates: + if Path(candidate).is_file(): + return candidate + return None + + +def stop_ollama_models(config: Dict[str, Any]) -> List[Dict[str, Any]]: + results = [] + if not bool(config.get("unload_models_before_restart", True)): + return results + binary = resolve_ollama_binary(config) + if binary is None: + return [{"model": None, "returncode": -1, "error": "ollama binary not found"}] + try: + models = RemoteOllama(config).running_models() + except Exception as exc: + return [{"model": None, "returncode": -1, "error": "cannot list models: %s" % exc}] + for model in models: + name = model.get("name") or model.get("model") + if not name: + continue + try: + completed = subprocess.run( + [binary, "stop", str(name)], + check=False, + capture_output=True, + text=True, + timeout=30, + ) + results.append({ + "model": name, + "returncode": completed.returncode, + "stdout": completed.stdout.strip(), + "stderr": completed.stderr.strip(), + }) + except (OSError, subprocess.SubprocessError, TimeoutError) as exc: + results.append({"model": name, "returncode": -1, "error": str(exc)}) + wait_seconds = int(config.get("unload_wait_seconds", 0)) + if wait_seconds > 0 and (models or results): + time.sleep(wait_seconds) + return results + + class ServiceController: def __init__(self, config: Dict[str, Any], state: StateStore): self.config = config self.state = state def restart(self, force: bool = False, reason: str = "threshold") -> Dict[str, Any]: - stats_before = None busy = False try: busy = RemoteOllama(self.config).is_busy() @@ -184,6 +244,10 @@ class ServiceController: if busy and not force: raise BusyError("ollama has running models; restart deferred") + # Stop only resident Ollama models before restarting the service. This + # releases loaded resources without broad shell usage. + models_stopped = stop_ollama_models(self.config) + started = common.now_utc() with self.state.lock: if self.state.data.get("restart_in_progress"): @@ -192,6 +256,7 @@ class ServiceController: self.state._save() try: + service_started = common.now_utc() if SYSTEM == "darwin": plist = str(self.config["launch_agent_plist"]) subprocess.run( @@ -236,7 +301,8 @@ class ServiceController: "reason": reason, "busy_before": busy, "health_ok": health_ok, - "duration_seconds": round((finished - started).total_seconds(), 2), + "models_stopped": models_stopped, + "duration_seconds": round((finished - service_started).total_seconds(), 2), } except Exception: self.state.mutate( diff --git a/src/ollama_swap_common.py b/src/ollama_swap_common.py index 2e72da3..65a008b 100644 --- a/src/ollama_swap_common.py +++ b/src/ollama_swap_common.py @@ -23,6 +23,9 @@ DEFAULT_CONFIG = { "cooldown_seconds": 600, "max_restarts_per_hour": 2, "restart_force_after_seconds": 300, + "unload_models_before_restart": True, + "unload_wait_seconds": 3, + "ollama_binary": None, "busy_check_timeout_seconds": 3, "health_timeout_seconds": 5, "restart_health_timeout_seconds": 180, @@ -121,6 +124,8 @@ def validate_config(config: dict[str, Any]) -> None: absolute = config.get("swap_threshold_mb") if absolute is not None and float(absolute) < 0: raise ValueError("swap_threshold_mb must be non-negative") + if config.get("unload_wait_seconds", 0) < 0: + raise ValueError("unload_wait_seconds must be non-negative") def _suffix_to_mb(value: float, suffix: str) -> float: