Add ollama-plagin-swap remote swap control plugin
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
|
||||
import ollama_swap_agent as a
|
||||
import ollama_swap_common as c
|
||||
|
||||
|
||||
def make_config(tmp_path):
|
||||
return c.merge_config(
|
||||
{
|
||||
"bind_host": "127.0.0.1",
|
||||
"port": 0,
|
||||
"token": "secret",
|
||||
"state_file": str(tmp_path / "state.json"),
|
||||
"launch_agent_plist": str(tmp_path / "com.ollama.serve.plist"),
|
||||
"poll_interval_seconds": 60,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_check_once_restarts_when_threshold_exceeded(tmp_path):
|
||||
config = make_config(tmp_path)
|
||||
runtime = a.Runtime(config)
|
||||
fake_stats = c.SwapStats(100, 40, 60)
|
||||
with mock.patch.object(runtime.sampler, "sample", return_value=fake_stats), \
|
||||
mock.patch.object(runtime, "_running_models", return_value=[]), \
|
||||
mock.patch.object(a.RemoteOllama, "is_busy", return_value=False), \
|
||||
mock.patch.object(runtime.controller, "restart", return_value={"restarted": True}):
|
||||
result = runtime.check_once()
|
||||
assert result["restarted"] is True
|
||||
|
||||
|
||||
def test_check_once_defers_when_busy(tmp_path):
|
||||
config = make_config(tmp_path)
|
||||
runtime = a.Runtime(config)
|
||||
fake_stats = c.SwapStats(100, 40, 60)
|
||||
with mock.patch.object(runtime.sampler, "sample", return_value=fake_stats), \
|
||||
mock.patch.object(a.RemoteOllama, "is_busy", return_value=True):
|
||||
result = runtime.check_once()
|
||||
assert result["restarted"] is False
|
||||
assert result["deferred"] is True
|
||||
|
||||
|
||||
def test_restart_rejects_busy_without_force(tmp_path):
|
||||
config = make_config(tmp_path)
|
||||
runtime = a.Runtime(config)
|
||||
fake_stats = c.SwapStats(100, 40, 60)
|
||||
with mock.patch.object(runtime.sampler, "sample", return_value=fake_stats), \
|
||||
mock.patch.object(a.RemoteOllama, "is_busy", return_value=True):
|
||||
try:
|
||||
runtime.restart(force=False)
|
||||
except a.BusyError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("expected BusyError")
|
||||
|
||||
|
||||
def test_http_status_and_restart(tmp_path):
|
||||
config = make_config(tmp_path)
|
||||
runtime = a.Runtime(config)
|
||||
a.JsonHandler.runtime = runtime
|
||||
httpd = a.ReusableServer(("127.0.0.1", 0), a.JsonHandler)
|
||||
port = httpd.server_address[1]
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
# unauthorized
|
||||
req = __import__("urllib.request", fromlist=["urlopen"]).urlopen(
|
||||
"http://127.0.0.1:%d/status" % port, timeout=2
|
||||
)
|
||||
raise AssertionError("expected HTTPError")
|
||||
except Exception as exc:
|
||||
assert "401" in str(exc)
|
||||
fake_stats = c.SwapStats(100, 40, 60)
|
||||
with mock.patch.object(runtime.sampler, "sample", return_value=fake_stats), \
|
||||
mock.patch.object(a.RemoteOllama, "is_busy", return_value=False), \
|
||||
mock.patch.object(runtime.controller, "restart", return_value={"restarted": True}):
|
||||
import urllib.request
|
||||
|
||||
req = urllib.request.Request(
|
||||
"http://127.0.0.1:%d/status" % port,
|
||||
headers={"Authorization": "Bearer secret"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=2) as response:
|
||||
data = json.loads(response.read().decode())
|
||||
assert data["recommendation"] in {"restart", "none", "defer"}
|
||||
|
||||
body = json.dumps({"reason": "test", "force": True}).encode()
|
||||
req = urllib.request.Request(
|
||||
"http://127.0.0.1:%d/restart" % port,
|
||||
data=body,
|
||||
headers={"Authorization": "Bearer secret", "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=2) as response:
|
||||
data = json.loads(response.read().decode())
|
||||
assert data["ok"] is True
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
@@ -0,0 +1,70 @@
|
||||
import json
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
|
||||
import ollama_swap_common as c
|
||||
|
||||
|
||||
def test_parse_sysctl_swap():
|
||||
output = "total = 2048.00M used = 512.00M free = 1536.00M (encrypted)"
|
||||
stats = c.parse_sysctl_swap(output)
|
||||
assert round(stats.total_mb, 2) == 2048.0
|
||||
assert round(stats.used_mb, 2) == 512.0
|
||||
assert round(stats.percent, 2) == 25.0
|
||||
|
||||
|
||||
def test_parse_proc_meminfo():
|
||||
text = "SwapTotal: 2097148 kB\nSwapFree: 1048572 kB\n"
|
||||
stats = c.parse_proc_meminfo(text)
|
||||
assert round(stats.total_mb, 2) == 2048.0
|
||||
assert round(stats.used_mb, 2) == 1024.0
|
||||
|
||||
|
||||
def test_parse_free_output():
|
||||
output = " total used free\nSwap: 2147483648 536870912 1610612736\n"
|
||||
stats = c.parse_free_output(output)
|
||||
assert round(stats.total_mb, 2) == 2048.0
|
||||
assert round(stats.used_mb, 2) == 512.0
|
||||
|
||||
|
||||
def test_threshold_percent():
|
||||
config = c.merge_config({"swap_threshold_percent": 25, "swap_threshold_mb": None})
|
||||
stats = c.SwapStats(1000, 200, 800)
|
||||
assert c.threshold_exceeded(config, stats) is False
|
||||
stats2 = c.SwapStats(1000, 300, 700)
|
||||
assert c.threshold_exceeded(config, stats2) is True
|
||||
|
||||
|
||||
def test_threshold_combined():
|
||||
config = c.merge_config({"swap_threshold_percent": 25, "swap_threshold_mb": 200})
|
||||
assert c.threshold_exceeded(config, c.SwapStats(1000, 100, 900)) is False
|
||||
assert c.threshold_exceeded(config, c.SwapStats(1000, 300, 700)) is True
|
||||
|
||||
|
||||
def test_validate_config_requires_token_for_remote():
|
||||
config = c.merge_config({"bind_host": "0.0.0.0", "token": None, "allow_insecure": False})
|
||||
try:
|
||||
c.validate_config(config)
|
||||
except ValueError as exc:
|
||||
assert "token" in str(exc)
|
||||
else:
|
||||
raise AssertionError("expected ValueError")
|
||||
|
||||
|
||||
def test_count_recent():
|
||||
now = c.now_utc()
|
||||
import datetime as dt
|
||||
times = [c.format_iso(now)]
|
||||
|
||||
recent = c.format_iso(now - dt.timedelta(minutes=10))
|
||||
old = c.format_iso(now - dt.timedelta(hours=2))
|
||||
assert c.count_recent([recent, old], now - dt.timedelta(hours=1)) == 1
|
||||
|
||||
|
||||
def test_load_config_missing_file(tmp_path):
|
||||
config = c.load_config(str(tmp_path / "config.json"))
|
||||
assert config["port"] == 8731
|
||||
assert config["swap_threshold_percent"] == 25
|
||||
Reference in New Issue
Block a user