ollama2cpp 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ollama2cpp/server.py ADDED
@@ -0,0 +1,640 @@
1
+ """``llama-server`` runtime: start, stop, health checks and the pid record.
2
+
3
+ Safety rule: only a process that this module started and recorded (pid **and** creation time) is ever
4
+ terminated. A bare pid is not proof, because operating systems reuse pids.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import codecs
10
+ import http.client
11
+ import json
12
+ import logging
13
+ import socket
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from collections import deque
18
+ from collections.abc import Sequence
19
+ from dataclasses import asdict, dataclass
20
+ from datetime import UTC, datetime
21
+ from pathlib import Path, PureWindowsPath
22
+ from typing import Any
23
+
24
+ import psutil
25
+
26
+ from ollama2cpp import constants, proc, ui
27
+ from ollama2cpp.llamacpp import LlamaCppError
28
+
29
+ __all__ = [
30
+ "LOG_FILENAME",
31
+ "ServerRecord",
32
+ "clear_record",
33
+ "describe_running",
34
+ "health",
35
+ "is_ready",
36
+ "port_in_use",
37
+ "props",
38
+ "read_record",
39
+ "start",
40
+ "stop",
41
+ "write_record",
42
+ ]
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ LOG_FILENAME = "server.log"
47
+ LOG_TAIL_LINES = 20
48
+ CREATE_TIME_TOLERANCE = 1.0
49
+ POLL_INTERVAL = 0.1
50
+ PROBE_TIMEOUT = 0.3 # loopback answers instantly; Windows needs ~1 s to report a refused connection
51
+ KILL_GRACE = 3.0
52
+ HTTP_OK = 200
53
+ MAX_PORT = 65536
54
+ _ANY_V4 = {"", "0.0.0.0"}
55
+ _ANY_V6 = {"::", "[::]"}
56
+
57
+
58
+ @dataclass
59
+ class ServerRecord:
60
+ """The server this tool started, persisted in the pid file.
61
+
62
+ Attributes:
63
+ pid: Process id of ``llama-server``.
64
+ host: Address it listens on.
65
+ port: Port it listens on.
66
+ model: Model alias being served.
67
+ started: ISO-8601 start timestamp.
68
+ create_time: ``psutil`` creation time of the process; ``0.0`` asks ``write_record`` to capture it.
69
+ """
70
+
71
+ pid: int
72
+ host: str
73
+ port: int
74
+ model: str
75
+ started: str
76
+ create_time: float = 0.0
77
+
78
+
79
+ # --- HTTP / socket probes ------------------------------------------------------------------------------------------
80
+
81
+
82
+ def _connect_host(host: str) -> str:
83
+ """Map a bind-all address to one that can be connected to.
84
+
85
+ Args:
86
+ host: Configured listen address.
87
+
88
+ Returns:
89
+ str: Loopback for wildcard addresses and ``localhost``, otherwise ``host`` lower-cased without brackets.
90
+ """
91
+ host = host.strip().lower()
92
+ if host in _ANY_V4 or host == "localhost":
93
+ return "127.0.0.1"
94
+ if host in _ANY_V6:
95
+ return "::1"
96
+ return host.strip("[]")
97
+
98
+
99
+ def _get(host: str, port: int, path: str, timeout: float) -> tuple[int, bytes] | None:
100
+ """GET a path from the local server, bypassing any proxy.
101
+
102
+ Args:
103
+ host: Server address.
104
+ port: Server port.
105
+ path: Request path starting with ``/``.
106
+ timeout: Socket timeout in seconds.
107
+
108
+ Returns:
109
+ tuple[int, bytes] | None: ``(status, body)``, or None when nothing answered (HTTP errors give their status).
110
+ """
111
+ target = _connect_host(host)
112
+ netloc = f"[{target}]" if ":" in target else target
113
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
114
+ try:
115
+ with opener.open(f"http://{netloc}:{port}{path}", timeout=timeout) as resp:
116
+ return resp.status, resp.read()
117
+ except urllib.error.HTTPError as exc:
118
+ return exc.code, b""
119
+ except (urllib.error.URLError, http.client.HTTPException, OSError, ValueError):
120
+ return None
121
+
122
+
123
+ def health(host: str, port: int, timeout: float = 1.0) -> bool:
124
+ """Tell whether a ``llama-server`` is ready (``/health`` returns 200; 503 means still loading).
125
+
126
+ Args:
127
+ host: Server address.
128
+ port: Server port.
129
+ timeout: Socket timeout in seconds.
130
+
131
+ Returns:
132
+ bool: True only for an HTTP 200 answer.
133
+ """
134
+ answer = _get(host, port, "/health", timeout)
135
+ return answer is not None and answer[0] == HTTP_OK
136
+
137
+
138
+ def props(host: str, port: int, timeout: float = 1.0) -> dict[str, Any] | None:
139
+ """Fetch the server's ``/props`` document.
140
+
141
+ Args:
142
+ host: Server address.
143
+ port: Server port.
144
+ timeout: Socket timeout in seconds.
145
+
146
+ Returns:
147
+ dict[str, Any] | None: Parsed JSON object, or None when unavailable or not an object.
148
+ """
149
+ answer = _get(host, port, "/props", timeout)
150
+ if answer is None or answer[0] != HTTP_OK:
151
+ return None
152
+ try:
153
+ data = json.loads(answer[1])
154
+ except ValueError:
155
+ return None
156
+ return data if isinstance(data, dict) else None
157
+
158
+
159
+ def port_in_use(host: str, port: int) -> bool:
160
+ """Tell whether something accepts TCP connections on ``host:port``.
161
+
162
+ Args:
163
+ host: Address to probe.
164
+ port: Port to probe.
165
+
166
+ Returns:
167
+ bool: True when a connection succeeds.
168
+ """
169
+ try:
170
+ with socket.create_connection((_connect_host(host), port), timeout=PROBE_TIMEOUT):
171
+ return True
172
+ except OSError:
173
+ return False
174
+
175
+
176
+ def _model_alias(data: dict[str, Any] | None) -> str | None:
177
+ """Extract a model name from a ``/props`` document, tolerating several layouts.
178
+
179
+ Args:
180
+ data: Parsed ``/props`` JSON, or None.
181
+
182
+ Returns:
183
+ str | None: Alias, model-path basename, or generation-settings model; None if absent.
184
+ """
185
+ if not data:
186
+ return None
187
+ alias = data.get("model_alias")
188
+ if isinstance(alias, str) and alias:
189
+ return alias
190
+ path = data.get("model_path")
191
+ if isinstance(path, str) and path:
192
+ return PureWindowsPath(path).name
193
+ settings = data.get("default_generation_settings")
194
+ if isinstance(settings, dict):
195
+ model = settings.get("model")
196
+ if isinstance(model, str) and model:
197
+ return model
198
+ return None
199
+
200
+
201
+ # --- pid record ----------------------------------------------------------------------------------------------------
202
+
203
+
204
+ def _base(base: Path | None) -> Path:
205
+ """Resolve the storage directory at call time.
206
+
207
+ Args:
208
+ base: Explicit directory, or None for ``constants.home()``.
209
+
210
+ Returns:
211
+ Path: Directory holding the pid file and log.
212
+ """
213
+ return base if base is not None else constants.home()
214
+
215
+
216
+ def _create_time(pid: int) -> float:
217
+ """Return a process creation time, or ``0.0`` when it cannot be read.
218
+
219
+ Args:
220
+ pid: Process id.
221
+
222
+ Returns:
223
+ float: Epoch creation time, ``0.0`` if the process is gone or inaccessible.
224
+ """
225
+ try:
226
+ return psutil.Process(pid).create_time()
227
+ except psutil.Error:
228
+ return 0.0
229
+
230
+
231
+ def _is_ours(rec: ServerRecord) -> bool:
232
+ """Check that the recorded pid is alive and is the very process we started.
233
+
234
+ Args:
235
+ rec: Record to validate.
236
+
237
+ Returns:
238
+ bool: True when the pid exists, is not a zombie and its creation time matches the record.
239
+ """
240
+ try:
241
+ process = psutil.Process(rec.pid)
242
+ if process.status() == psutil.STATUS_ZOMBIE:
243
+ return False
244
+ return abs(process.create_time() - rec.create_time) <= CREATE_TIME_TOLERANCE
245
+ except psutil.Error:
246
+ return False
247
+
248
+
249
+ def write_record(base: Path | None, rec: ServerRecord) -> None:
250
+ """Persist ``rec`` atomically; captures ``create_time`` for ``rec.pid`` when it is ``0.0``.
251
+
252
+ Args:
253
+ base: Storage directory (None for the default).
254
+ rec: Record to write.
255
+ """
256
+ if not rec.create_time:
257
+ rec.create_time = _create_time(rec.pid)
258
+ directory = _base(base)
259
+ directory.mkdir(parents=True, exist_ok=True)
260
+ target = directory / constants.PID_FILENAME
261
+ tmp = target.with_suffix(".tmp")
262
+ tmp.write_text(json.dumps(asdict(rec)), encoding="utf-8")
263
+ tmp.replace(target)
264
+
265
+
266
+ def clear_record(base: Path | None = None) -> None:
267
+ """Remove the pid file if present.
268
+
269
+ Args:
270
+ base: Storage directory (None for the default).
271
+ """
272
+ try:
273
+ (_base(base) / constants.PID_FILENAME).unlink(missing_ok=True)
274
+ except OSError as exc:
275
+ logger.warning("could not remove pid file: %s", exc)
276
+
277
+
278
+ def _parse_record(data: object) -> ServerRecord | None:
279
+ """Build a record from decoded JSON, validating every field's type and range.
280
+
281
+ Args:
282
+ data: Decoded JSON document.
283
+
284
+ Returns:
285
+ ServerRecord | None: The record, or None when ``data`` is not a well-formed record.
286
+ """
287
+ if not isinstance(data, dict):
288
+ return None
289
+ pid, host, port = data.get("pid"), data.get("host"), data.get("port")
290
+ model, started, ctime = data.get("model"), data.get("started"), data.get("create_time")
291
+ if not (isinstance(pid, int) and not isinstance(pid, bool) and pid > 0):
292
+ return None
293
+ if not (isinstance(port, int) and not isinstance(port, bool) and 0 < port < MAX_PORT):
294
+ return None
295
+ if not (isinstance(ctime, int | float) and not isinstance(ctime, bool)):
296
+ return None
297
+ if not (isinstance(host, str) and isinstance(model, str) and isinstance(started, str)):
298
+ return None
299
+ return ServerRecord(pid, host, port, model, started, float(ctime))
300
+
301
+
302
+ def read_record(base: Path | None = None) -> ServerRecord | None:
303
+ """Load the pid record, discarding it when stale, corrupt or pointing at a different process.
304
+
305
+ Args:
306
+ base: Storage directory (None for the default).
307
+
308
+ Returns:
309
+ ServerRecord | None: The record of a live process we started, else None (and the file is removed).
310
+ """
311
+ path = _base(base) / constants.PID_FILENAME
312
+ if not path.is_file():
313
+ return None
314
+ try:
315
+ rec = _parse_record(json.loads(path.read_text(encoding="utf-8")))
316
+ except (OSError, ValueError):
317
+ rec = None
318
+ if rec is None:
319
+ logger.warning("discarding unreadable or invalid pid record %s", path)
320
+ clear_record(base)
321
+ return None
322
+ if not _is_ours(rec):
323
+ clear_record(base)
324
+ return None
325
+ return rec
326
+
327
+
328
+ # --- inspection ----------------------------------------------------------------------------------------------------
329
+
330
+
331
+ def is_ready(host: str, port: int) -> bool:
332
+ """Tell whether the server on ``host:port`` is up and finished loading.
333
+
334
+ Args:
335
+ host: Server address.
336
+ port: Server port.
337
+
338
+ Returns:
339
+ bool: True when ``/health`` returns 200 (readiness only; identity comes from the record).
340
+ """
341
+ return health(host, port)
342
+
343
+
344
+ def _same_host(left: str, right: str) -> bool:
345
+ """Compare two listen addresses, treating wildcard and ``localhost`` spellings as equivalent.
346
+
347
+ Args:
348
+ left: First address.
349
+ right: Second address.
350
+
351
+ Returns:
352
+ bool: True when both resolve to the same connect address.
353
+ """
354
+ return _connect_host(left) == _connect_host(right)
355
+
356
+
357
+ def describe_running(host: str, port: int, base: Path | None = None) -> tuple[str, str | None]:
358
+ """Classify whatever is on ``host:port``.
359
+
360
+ Identity comes from the pid record (valid pid and creation time, same host and port); health only
361
+ describes state, so a server of ours that is still loading is still ``"ours"`` (see ``is_ready``).
362
+
363
+ Args:
364
+ host: Address to inspect.
365
+ port: Port to inspect.
366
+ base: Storage directory (None for the default).
367
+
368
+ Returns:
369
+ tuple[str, str | None]: ``("ours", alias)`` when a valid record matches host and port, where ``alias``
370
+ comes from ``/props`` and falls back to the recorded model; ``("foreign", alias)`` for a listener
371
+ without such a record; ``("none", None)`` when nothing is there.
372
+ """
373
+ rec = read_record(base)
374
+ listening = port_in_use(host, port)
375
+ alias = _model_alias(props(host, port)) if listening else None
376
+ if rec is not None and rec.port == port and _same_host(rec.host, host):
377
+ return "ours", alias or rec.model
378
+ return ("foreign", alias) if listening else ("none", None)
379
+
380
+
381
+ def _refuse_if_occupied(host: str, port: int, base: Path | None) -> None:
382
+ """Raise unless it is safe to start a server on ``host:port``.
383
+
384
+ Args:
385
+ host: Address to listen on.
386
+ port: Port to listen on.
387
+ base: Storage directory (None for the default).
388
+
389
+ Raises:
390
+ LlamaCppError: When our own server is already recorded, or a foreign process holds the port.
391
+ """
392
+ rec = read_record(base)
393
+ if rec is not None:
394
+ raise LlamaCppError(
395
+ f"an ollama2cpp server is already running (pid {rec.pid}, {rec.host}:{rec.port}); stop it first"
396
+ )
397
+ if port_in_use(host, port):
398
+ raise LlamaCppError(f"port {port} on {host} is held by another process (not started by ollama2cpp)")
399
+
400
+
401
+ # --- lifecycle -----------------------------------------------------------------------------------------------------
402
+
403
+
404
+ def _terminate_tree(pid: int, timeout: float) -> None:
405
+ """Terminate a process and its children, escalating to kill after ``timeout``.
406
+
407
+ Args:
408
+ pid: Root process id (must already be verified as ours).
409
+ timeout: Seconds to wait before killing survivors.
410
+ """
411
+ try:
412
+ root = psutil.Process(pid)
413
+ targets = [*root.children(recursive=True), root]
414
+ except psutil.Error:
415
+ return
416
+ for target in targets:
417
+ try:
418
+ target.terminate()
419
+ except psutil.Error:
420
+ logger.debug("terminate failed for pid %s", target.pid)
421
+ _gone, alive = psutil.wait_procs(targets, timeout=timeout)
422
+ for target in alive:
423
+ try:
424
+ target.kill()
425
+ except psutil.Error:
426
+ logger.debug("kill failed for pid %s", target.pid)
427
+ psutil.wait_procs(alive, timeout=KILL_GRACE)
428
+
429
+
430
+ def stop(base: Path | None = None, *, timeout: float = 10.0) -> bool:
431
+ """Stop the server recorded in our pid file (and its children); never touches other processes.
432
+
433
+ Args:
434
+ base: Storage directory (None for the default).
435
+ timeout: Seconds to wait after terminate before killing.
436
+
437
+ Returns:
438
+ bool: True when a recorded, verified process was stopped; False when there was none.
439
+ """
440
+ rec = read_record(base)
441
+ if rec is None:
442
+ return False
443
+ _terminate_tree(rec.pid, timeout)
444
+ clear_record(base)
445
+ return True
446
+
447
+
448
+ def _log_tail(log: Path, offset: int) -> str:
449
+ """Return the last lines the child wrote since ``offset``.
450
+
451
+ Args:
452
+ log: Log file path.
453
+ offset: Byte offset where this run's output begins.
454
+
455
+ Returns:
456
+ str: Up to ``LOG_TAIL_LINES`` lines.
457
+ """
458
+ try:
459
+ with log.open("rb") as handle:
460
+ handle.seek(offset)
461
+ text = handle.read().decode("utf-8", errors="replace")
462
+ except OSError:
463
+ return ""
464
+ return "\n".join(deque(text.splitlines(), maxlen=LOG_TAIL_LINES))
465
+
466
+
467
+ def _failure(message: str, log: Path, offset: int) -> LlamaCppError:
468
+ """Build an error that carries the log tail.
469
+
470
+ Args:
471
+ message: Headline.
472
+ log: Log file path.
473
+ offset: Byte offset where this run's output begins.
474
+
475
+ Returns:
476
+ LlamaCppError: Error with the last log lines appended.
477
+ """
478
+ return LlamaCppError(f"{message}\n--- last {LOG_TAIL_LINES} log lines ---\n{_log_tail(log, offset)}")
479
+
480
+
481
+ class _LogPump:
482
+ """Copies new bytes of a log file to the console, as the child writes them."""
483
+
484
+ def __init__(self, path: Path, offset: int) -> None:
485
+ """Remember where to start reading.
486
+
487
+ Args:
488
+ path: Log file to follow.
489
+ offset: Byte offset to start from.
490
+ """
491
+ self._path = path
492
+ self._offset = offset
493
+ self._decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
494
+
495
+ def pump(self) -> None:
496
+ """Print whatever was appended since the last call."""
497
+ try:
498
+ with self._path.open("rb") as handle:
499
+ handle.seek(self._offset)
500
+ chunk = handle.read()
501
+ except OSError:
502
+ return
503
+ self._offset += len(chunk)
504
+ text = self._decoder.decode(chunk)
505
+ if text:
506
+ ui.console.print(text, markup=False, highlight=False, end="")
507
+
508
+
509
+ def _record_for(pid: int, host: str, port: int, model: str) -> ServerRecord:
510
+ """Build the record for a freshly spawned process.
511
+
512
+ Args:
513
+ pid: Child process id.
514
+ host: Listen address.
515
+ port: Listen port.
516
+ model: Model alias.
517
+
518
+ Returns:
519
+ ServerRecord: Record with the process creation time captured.
520
+ """
521
+ started = datetime.now(UTC).isoformat(timespec="seconds")
522
+ return ServerRecord(pid, host, port, model, started, _create_time(pid))
523
+
524
+
525
+ def _run_foreground(child: proc.Handle, log: Path, offset: int) -> int:
526
+ """Stream the child's output until it exits or the user interrupts.
527
+
528
+ Args:
529
+ child: Running server process.
530
+ log: Log file the child writes to.
531
+ offset: Byte offset where this run's output begins.
532
+
533
+ Returns:
534
+ int: The child's exit code.
535
+ """
536
+ pump = _LogPump(log, offset)
537
+ try:
538
+ while child.poll() is None:
539
+ pump.pump()
540
+ time.sleep(POLL_INTERVAL)
541
+ except KeyboardInterrupt:
542
+ ui.show_notice("info", "Stopping server...")
543
+ _terminate_tree(child.pid, KILL_GRACE)
544
+ code = child.wait()
545
+ pump.pump()
546
+ return code
547
+
548
+
549
+ def _wait_ready(child: proc.Handle, host: str, port: int, ready_timeout: float, log: Path, offset: int) -> None:
550
+ """Block until ``/health`` returns 200, the child dies, or the deadline passes.
551
+
552
+ A child that exits first, or is still not ready at the deadline, raises
553
+ ``LlamaCppError`` with the log tail.
554
+
555
+ Args:
556
+ child: Running server process.
557
+ host: Listen address.
558
+ port: Listen port.
559
+ ready_timeout: Seconds to wait.
560
+ log: Log file the child writes to.
561
+ offset: Byte offset where this run's output begins.
562
+ """
563
+ deadline = time.monotonic() + ready_timeout
564
+ while time.monotonic() < deadline:
565
+ code = child.poll()
566
+ if code is not None:
567
+ raise _failure(f"llama-server exited with code {code} before becoming ready", log, offset)
568
+ if health(host, port, timeout=PROBE_TIMEOUT):
569
+ return
570
+ time.sleep(POLL_INTERVAL)
571
+ raise _failure(f"llama-server was not ready after {ready_timeout:g}s", log, offset)
572
+
573
+
574
+ def _supervise(
575
+ child: proc.Handle, rec: ServerRecord, base: Path | None, log: Path, offset: int, ready_timeout: float | None
576
+ ) -> int:
577
+ """Record the child, then wait for readiness (detach) or stream until it exits (foreground).
578
+
579
+ Args:
580
+ child: Running server process.
581
+ rec: Record to persist for it.
582
+ base: Storage directory (None for the default).
583
+ log: Log file the child writes to.
584
+ offset: Byte offset where this run's output begins.
585
+ ready_timeout: Seconds to wait for readiness, or None for foreground mode.
586
+
587
+ Returns:
588
+ int: 0 once ready (detach) or the child's exit code (foreground).
589
+ """
590
+ write_record(base, rec)
591
+ if ready_timeout is None:
592
+ return _run_foreground(child, log, offset)
593
+ _wait_ready(child, rec.host, rec.port, ready_timeout, log, offset)
594
+ return 0
595
+
596
+
597
+ def start(
598
+ argv: Sequence[str],
599
+ *,
600
+ base: Path | None = None,
601
+ host: str,
602
+ port: int,
603
+ model: str,
604
+ detach: bool,
605
+ ready_timeout: float = 120.0,
606
+ ) -> int:
607
+ """Start ``llama-server`` and record it.
608
+
609
+ Foreground mode streams the server output to the console until it exits or Ctrl-C; detach mode returns
610
+ once ``/health`` answers 200. Output always goes to ``<base>/server.log``. Raises ``LlamaCppError`` when the
611
+ port is occupied or the server fails to become ready. On any failure the child is terminated and the record
612
+ cleared, so no unrecorded server is left running.
613
+
614
+ Args:
615
+ argv: Full ``llama-server`` command line.
616
+ base: Storage directory (None for the default).
617
+ host: Address the server listens on.
618
+ port: Port the server listens on.
619
+ model: Model alias, stored in the record.
620
+ detach: Run in the background and return after it is ready.
621
+ ready_timeout: Seconds to wait for readiness in detach mode.
622
+
623
+ Returns:
624
+ int: Exit code of the server (foreground) or 0 once ready (detach).
625
+ """
626
+ _refuse_if_occupied(host, port, base)
627
+ log = _base(base) / LOG_FILENAME
628
+ offset = log.stat().st_size if log.is_file() else 0
629
+ child = proc.spawn(argv, log_path=log, detach=detach)
630
+ try:
631
+ rec = _record_for(child.pid, host, port, model)
632
+ code = _supervise(child, rec, base, log, offset, ready_timeout if detach else None)
633
+ except BaseException:
634
+ if child.poll() is None:
635
+ _terminate_tree(child.pid, KILL_GRACE)
636
+ clear_record(base)
637
+ raise
638
+ if not detach:
639
+ clear_record(base)
640
+ return code