vpstream 0.2.1__tar.gz → 0.4.0__tar.gz

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.
Files changed (47) hide show
  1. {vpstream-0.2.1 → vpstream-0.4.0}/CHANGELOG.md +17 -0
  2. {vpstream-0.2.1 → vpstream-0.4.0}/PKG-INFO +34 -1
  3. {vpstream-0.2.1 → vpstream-0.4.0}/README.md +32 -0
  4. {vpstream-0.2.1 → vpstream-0.4.0}/pyproject.toml +2 -2
  5. vpstream-0.4.0/src/vpstream/api.py +39 -0
  6. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/cli.py +78 -0
  7. vpstream-0.4.0/src/vpstream/client.py +70 -0
  8. vpstream-0.4.0/src/vpstream/config.py +123 -0
  9. vpstream-0.4.0/src/vpstream/daemon.py +157 -0
  10. vpstream-0.4.0/src/vpstream/doctor.py +242 -0
  11. vpstream-0.4.0/src/vpstream/tailscale.py +27 -0
  12. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/conftest.py +11 -0
  13. vpstream-0.4.0/src/vpstream/tests/test_config.py +58 -0
  14. vpstream-0.4.0/src/vpstream/tests/test_daemon.py +263 -0
  15. vpstream-0.4.0/src/vpstream/tests/test_doctor.py +208 -0
  16. {vpstream-0.2.1 → vpstream-0.4.0}/.gitignore +0 -0
  17. {vpstream-0.2.1 → vpstream-0.4.0}/LICENSE +0 -0
  18. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/__init__.py +0 -0
  19. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/__main__.py +0 -0
  20. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/assets/__init__.py +0 -0
  21. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/assets/caps.html +0 -0
  22. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/assets/caps.js +0 -0
  23. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/assets/hls.js.LICENSE +0 -0
  24. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/assets/hls.js.version +0 -0
  25. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/assets/hls.min.js +0 -0
  26. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/bench.py +0 -0
  27. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/caps/__init__.py +0 -0
  28. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/caps/clips.py +0 -0
  29. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/caps/server.py +0 -0
  30. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/ffargs.py +0 -0
  31. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/ffmpeg_install.py +0 -0
  32. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/probe.py +0 -0
  33. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/selftest.py +0 -0
  34. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/subtitles.py +0 -0
  35. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/__init__.py +0 -0
  36. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/data/three-cues.sup +0 -0
  37. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/fakes.py +0 -0
  38. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_assets.py +0 -0
  39. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_bench.py +0 -0
  40. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_caps.py +0 -0
  41. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_cli.py +0 -0
  42. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_ffargs.py +0 -0
  43. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_ffmpeg_install.py +0 -0
  44. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_integration.py +0 -0
  45. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_probe.py +0 -0
  46. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tests/test_subtitles.py +0 -0
  47. {vpstream-0.2.1 → vpstream-0.4.0}/src/vpstream/tools.py +0 -0
@@ -2,6 +2,23 @@
2
2
 
3
3
  <!-- version list -->
4
4
 
5
+ ## v0.4.0 (2026-11-10)
6
+
7
+ ### Features
8
+
9
+ - Add the daemon with its unix-socket CLI and Tailscale-only dashboard port
10
+ ([#6](https://github.com/skj-skj/vpstream/pull/6),
11
+ [`acdef5e`](https://github.com/skj-skj/vpstream/commit/acdef5ec4f27005cf00c419e22040d34b297c2a8))
12
+
13
+
14
+ ## v0.3.0 (2026-11-10)
15
+
16
+ ### Features
17
+
18
+ - Add vpstream doctor and the configuration file ([#5](https://github.com/skj-skj/vpstream/pull/5),
19
+ [`364af62`](https://github.com/skj-skj/vpstream/commit/364af6266dbaee33c960a6cc0a856c28e33d40a8))
20
+
21
+
5
22
  ## v0.2.1 (2026-11-10)
6
23
 
7
24
  ### Bug Fixes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: vpstream
3
- Version: 0.2.1
3
+ Version: 0.4.0
4
4
  Summary: On-demand video streaming from a VPS, controlled over SSH or a private dashboard
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -13,6 +13,7 @@ Classifier: Programming Language :: Python :: 3.13
13
13
  Classifier: Programming Language :: Python :: 3.14
14
14
  Classifier: Topic :: Multimedia :: Video
15
15
  Requires-Python: >=3.12
16
+ Requires-Dist: flask>=3.0
16
17
  Provides-Extra: dev
17
18
  Requires-Dist: pytest>=8; extra == 'dev'
18
19
  Description-Content-Type: text/markdown
@@ -48,6 +49,38 @@ vpstream --version
48
49
  vpstream selftest --integration
49
50
  ```
50
51
 
52
+ ## `vpstream doctor`
53
+
54
+ Checks this host for everything vpstream needs and lists all of it in one report: the Python
55
+ version, ffmpeg, ffprobe, Caddy, ufw, Tailscale, systemd and sudo, whether ufw is enabled and
56
+ Tailscale is connected, the fonts burned-in subtitles fall back to, the configuration file,
57
+ and where vpstream itself is installed. Each problem comes with the command that fixes it.
58
+ The exit code is 1 when something required is missing. Nothing is changed and no root is
59
+ needed.
60
+
61
+ The service runs as its own user, with a small root helper for the firewall, so it needs a
62
+ system-wide install that root owns. A per-user `pipx install` is reported as a problem:
63
+
64
+ ```text
65
+ sudo PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install "vpstream[dev]"
66
+ pipx uninstall vpstream # the per-user copy, if there is one
67
+ ```
68
+
69
+ Settings are read from `/etc/vpstream/config.toml` when it exists: `port` under `[stream]`
70
+ (default 1337) and `port` under `[dashboard]` (default 1338).
71
+
72
+ ## `vpstream daemon` and `vpstream status`
73
+
74
+ One daemon does the work, and the command line and the dashboard both talk to it.
75
+ `vpstream daemon` runs it in the foreground; normally the service does that.
76
+
77
+ - **Command line:** `vpstream status` asks the daemon over a unix socket,
78
+ `/run/vpstream/daemon.sock`, which only the service user and its group can use.
79
+ `--json` prints the raw answer.
80
+ - **Dashboard port:** bound to this host's Tailscale address only (from `tailscale ip -4`),
81
+ never to every interface. While Tailscale has no address the daemon keeps running and tries
82
+ again every 10 seconds; `vpstream status` says why the dashboard is not available.
83
+
51
84
  ## `vpstream install ffmpeg` and `vpstream update ffmpeg`
52
85
 
53
86
  Distribution packages of ffmpeg are often several versions old. `vpstream install ffmpeg`
@@ -29,6 +29,38 @@ vpstream --version
29
29
  vpstream selftest --integration
30
30
  ```
31
31
 
32
+ ## `vpstream doctor`
33
+
34
+ Checks this host for everything vpstream needs and lists all of it in one report: the Python
35
+ version, ffmpeg, ffprobe, Caddy, ufw, Tailscale, systemd and sudo, whether ufw is enabled and
36
+ Tailscale is connected, the fonts burned-in subtitles fall back to, the configuration file,
37
+ and where vpstream itself is installed. Each problem comes with the command that fixes it.
38
+ The exit code is 1 when something required is missing. Nothing is changed and no root is
39
+ needed.
40
+
41
+ The service runs as its own user, with a small root helper for the firewall, so it needs a
42
+ system-wide install that root owns. A per-user `pipx install` is reported as a problem:
43
+
44
+ ```text
45
+ sudo PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install "vpstream[dev]"
46
+ pipx uninstall vpstream # the per-user copy, if there is one
47
+ ```
48
+
49
+ Settings are read from `/etc/vpstream/config.toml` when it exists: `port` under `[stream]`
50
+ (default 1337) and `port` under `[dashboard]` (default 1338).
51
+
52
+ ## `vpstream daemon` and `vpstream status`
53
+
54
+ One daemon does the work, and the command line and the dashboard both talk to it.
55
+ `vpstream daemon` runs it in the foreground; normally the service does that.
56
+
57
+ - **Command line:** `vpstream status` asks the daemon over a unix socket,
58
+ `/run/vpstream/daemon.sock`, which only the service user and its group can use.
59
+ `--json` prints the raw answer.
60
+ - **Dashboard port:** bound to this host's Tailscale address only (from `tailscale ip -4`),
61
+ never to every interface. While Tailscale has no address the daemon keeps running and tries
62
+ again every 10 seconds; `vpstream status` says why the dashboard is not available.
63
+
32
64
  ## `vpstream install ffmpeg` and `vpstream update ffmpeg`
33
65
 
34
66
  Distribution packages of ffmpeg are often several versions old. `vpstream install ffmpeg`
@@ -4,13 +4,13 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "vpstream"
7
- version = "0.2.1"
7
+ version = "0.4.0"
8
8
  description = "On-demand video streaming from a VPS, controlled over SSH or a private dashboard"
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  license-files = ["LICENSE", "src/vpstream/assets/hls.js.LICENSE"]
12
12
  requires-python = ">=3.12"
13
- dependencies = []
13
+ dependencies = ["flask>=3.0"]
14
14
  classifiers = [
15
15
  "Programming Language :: Python :: 3",
16
16
  "Programming Language :: Python :: 3.12",
@@ -0,0 +1,39 @@
1
+ """The daemon's HTTP API: one Flask app, served on the unix socket and on the dashboard port.
2
+
3
+ The CLI and the dashboard call the same routes, so either can act on what the other started.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ from flask import Flask, Response, jsonify
12
+ from markupsafe import escape
13
+ from werkzeug.exceptions import HTTPException
14
+
15
+ API = "/api/v1"
16
+
17
+
18
+ def create_app(status: Callable[[], dict[str, Any]]) -> Flask:
19
+ """Build the app. `status` returns the daemon's current state as plain data."""
20
+ app = Flask("vpstream", static_folder=None, template_folder=None)
21
+
22
+ @app.get(f"{API}/status")
23
+ def api_status() -> Response:
24
+ return jsonify(status())
25
+
26
+ @app.get("/")
27
+ def index() -> str:
28
+ info = status()
29
+ stream = "a stream is running" if info.get("stream") else "no stream is running"
30
+ return (
31
+ "<!doctype html><meta charset=utf-8><title>vpstream</title>"
32
+ f"<h1>vpstream {escape(info.get('version', ''))}</h1><p>The daemon is up; {stream}.</p>"
33
+ )
34
+
35
+ @app.errorhandler(HTTPException)
36
+ def http_error(exc: HTTPException) -> tuple[Response, int]:
37
+ return jsonify(error=exc.description or exc.name), exc.code or 500
38
+
39
+ return app
@@ -9,6 +9,7 @@ import tarfile
9
9
  import time
10
10
  from collections.abc import Sequence
11
11
  from pathlib import Path
12
+ from typing import Any
12
13
 
13
14
  from vpstream import __version__
14
15
 
@@ -134,6 +135,73 @@ def cmd_caps(args: argparse.Namespace) -> int:
134
135
  return 0
135
136
 
136
137
 
138
+ def cmd_doctor(args: argparse.Namespace) -> int:
139
+ from vpstream import doctor
140
+ from vpstream.tools import SystemRunner
141
+
142
+ checks = doctor.run_checks(SystemRunner())
143
+ print(doctor.format_report(checks))
144
+ return doctor.exit_code(checks)
145
+
146
+
147
+ def _duration(seconds: float) -> str:
148
+ """A short human duration: 45s, 3m 12s, 2h 05m, 3d 4h."""
149
+ total = int(seconds)
150
+ days, rest = divmod(total, 86400)
151
+ hours, rest = divmod(rest, 3600)
152
+ minutes, secs = divmod(rest, 60)
153
+ if days:
154
+ return f"{days}d {hours}h"
155
+ if hours:
156
+ return f"{hours}h {minutes:02d}m"
157
+ if minutes:
158
+ return f"{minutes}m {secs:02d}s"
159
+ return f"{secs}s"
160
+
161
+
162
+ def format_status(info: dict[str, Any], cli_version: str) -> str:
163
+ """The daemon's status as text for `vpstream status`."""
164
+ dash = info.get("dashboard") or {}
165
+ lines = [
166
+ f"vpstream daemon {info.get('version')}, "
167
+ f"up {_duration(float(info.get('uptime_seconds') or 0))} (pid {info.get('pid')})",
168
+ f"Stream: {'running' if info.get('stream') else 'none'}",
169
+ f"Stream port: {info.get('stream_port')}",
170
+ "Dashboard: "
171
+ + (f"http://{dash['address']}/" if dash.get("address") else str(dash.get("problem"))),
172
+ ]
173
+ if info.get("version") != cli_version:
174
+ lines.append(
175
+ f"note: the daemon runs {info.get('version')} but this command is {cli_version}; "
176
+ "restart it with: sudo systemctl restart vpstream"
177
+ )
178
+ return "\n".join(lines)
179
+
180
+
181
+ def cmd_status(args: argparse.Namespace) -> int:
182
+ import json
183
+
184
+ from vpstream import client, config
185
+
186
+ try:
187
+ info = client.call(config.default_paths().socket, "GET", "status")
188
+ except (client.DaemonUnavailable, client.DaemonRefused) as exc:
189
+ return _error(str(exc))
190
+ print(json.dumps(info, indent=2) if args.json else format_status(info, __version__))
191
+ return 0
192
+
193
+
194
+ def cmd_daemon(args: argparse.Namespace) -> int:
195
+ from vpstream import config, daemon
196
+ from vpstream.tools import SystemRunner
197
+
198
+ paths = config.default_paths()
199
+ try:
200
+ return daemon.run(config.load(paths.config_file), paths, SystemRunner())
201
+ except (config.ConfigError, daemon.DaemonError) as exc:
202
+ return _error(str(exc))
203
+
204
+
137
205
  def _ask(question: str) -> bool:
138
206
  try:
139
207
  answer = input(f"{question} [y/N] ")
@@ -194,6 +262,16 @@ def build_parser() -> argparse.ArgumentParser:
194
262
  )
195
263
  st.set_defaults(func=cmd_selftest)
196
264
 
265
+ d = sub.add_parser("doctor", help="check this host for the programs vpstream needs")
266
+ d.set_defaults(func=cmd_doctor)
267
+
268
+ s = sub.add_parser("status", help="show what the running daemon is doing")
269
+ s.add_argument("--json", action="store_true", help="print the daemon's answer as JSON")
270
+ s.set_defaults(func=cmd_status)
271
+
272
+ dm = sub.add_parser("daemon", help="run the daemon in the foreground (the service does this)")
273
+ dm.set_defaults(func=cmd_daemon)
274
+
197
275
  b = sub.add_parser("bench", help="measure how fast this host prepares a file")
198
276
  b.add_argument("file")
199
277
  b.add_argument(
@@ -0,0 +1,70 @@
1
+ """Talk to the running daemon over its unix socket."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import socket
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from vpstream import api
12
+
13
+ TIMEOUT = 10.0
14
+
15
+
16
+ class DaemonUnavailable(RuntimeError):
17
+ """The daemon cannot be reached; the message says why and what to do."""
18
+
19
+
20
+ class DaemonRefused(RuntimeError):
21
+ """The daemon answered with an error."""
22
+
23
+
24
+ class _UnixConnection(http.client.HTTPConnection):
25
+ def __init__(self, path: Path, timeout: float) -> None:
26
+ super().__init__("localhost", timeout=timeout)
27
+ self._path = path
28
+
29
+ def connect(self) -> None:
30
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
31
+ sock.settimeout(self.timeout)
32
+ try:
33
+ sock.connect(str(self._path))
34
+ except OSError:
35
+ sock.close()
36
+ raise
37
+ self.sock = sock
38
+
39
+
40
+ def call(socket_path: Path, method: str, route: str, timeout: float = TIMEOUT) -> Any:
41
+ """Send one request to the daemon and return the decoded JSON answer."""
42
+ conn = _UnixConnection(socket_path, timeout)
43
+ try:
44
+ conn.request(method, f"{api.API}/{route}", headers={"Connection": "close"})
45
+ response = conn.getresponse()
46
+ body = response.read()
47
+ except (FileNotFoundError, ConnectionRefusedError) as exc:
48
+ raise DaemonUnavailable(
49
+ f"the vpstream daemon is not running (no answer on {socket_path}). "
50
+ "Start it with: sudo systemctl start vpstream"
51
+ ) from exc
52
+ except PermissionError as exc:
53
+ raise DaemonUnavailable(
54
+ f"no permission to use {socket_path}. Your user must be in the vpstream group: "
55
+ "log out and in again if it was just added, or run the command with sudo"
56
+ ) from exc
57
+ except (OSError, http.client.HTTPException) as exc:
58
+ raise DaemonUnavailable(f"the vpstream daemon did not answer: {exc}") from exc
59
+ finally:
60
+ conn.close()
61
+ try:
62
+ data = json.loads(body)
63
+ except ValueError as exc:
64
+ raise DaemonRefused(
65
+ f"the daemon sent an answer that is not JSON ({response.status})"
66
+ ) from exc
67
+ if response.status >= 400:
68
+ message = data.get("error") if isinstance(data, dict) else None
69
+ raise DaemonRefused(f"the daemon refused: {message or response.status}")
70
+ return data
@@ -0,0 +1,123 @@
1
+ """The configuration file, and the fixed places vpstream uses on a host."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import tomllib
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ MIN_PORT = 1024 # the daemon runs as an unprivileged user, which cannot bind lower ports
12
+
13
+
14
+ class ConfigError(ValueError):
15
+ """The configuration file cannot be used; the message lists every problem."""
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Paths:
20
+ """Where things live. Tests move everything under a temporary folder with `under`."""
21
+
22
+ config_file: Path = Path("/etc/vpstream/config.toml")
23
+ state_dir: Path = Path("/var/lib/vpstream")
24
+ cache_dir: Path = Path("/var/cache/vpstream")
25
+ run_dir: Path = Path("/run/vpstream")
26
+
27
+ @property
28
+ def socket(self) -> Path:
29
+ return self.run_dir / "daemon.sock"
30
+
31
+ @classmethod
32
+ def under(cls, root: Path) -> Paths:
33
+ default = cls()
34
+ return cls(
35
+ config_file=root / default.config_file.relative_to("/"),
36
+ state_dir=root / default.state_dir.relative_to("/"),
37
+ cache_dir=root / default.cache_dir.relative_to("/"),
38
+ run_dir=root / default.run_dir.relative_to("/"),
39
+ )
40
+
41
+
42
+ ROOT_ENV = "VPSTREAM_ROOT"
43
+
44
+
45
+ def default_paths() -> Paths:
46
+ """The real paths, or the same layout under $VPSTREAM_ROOT for trying things out."""
47
+ root = os.environ.get(ROOT_ENV)
48
+ return Paths.under(Path(root)) if root else Paths()
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Config:
53
+ stream_port: int = 1337
54
+ dashboard_port: int = 1338
55
+
56
+
57
+ # Section and key in the file -> field of Config.
58
+ _KEYS = {("stream", "port"): "stream_port", ("dashboard", "port"): "dashboard_port"}
59
+
60
+ DEFAULT_TEXT = """\
61
+ # vpstream configuration. Restart the service after a change:
62
+ # sudo systemctl restart vpstream
63
+
64
+ [stream]
65
+ # The public port viewers connect to. It is open in the firewall only while a stream runs.
66
+ port = 1337
67
+
68
+ [dashboard]
69
+ # The dashboard port. It listens on the Tailscale address only.
70
+ port = 1338
71
+ """
72
+
73
+
74
+ def _port_problem(name: str, value: Any) -> str | None:
75
+ # bool is an int in Python, and `port = true` is a mistake, not port 1.
76
+ if isinstance(value, bool) or not isinstance(value, int):
77
+ return f"{name} must be a whole number, not {value!r}"
78
+ if not MIN_PORT <= value <= 65535:
79
+ return f"{name} must be from {MIN_PORT} to 65535, not {value}"
80
+ return None
81
+
82
+
83
+ def parse(text: str) -> Config:
84
+ """Read configuration text. Missing keys take their defaults; unknown keys are errors."""
85
+ try:
86
+ data = tomllib.loads(text)
87
+ except tomllib.TOMLDecodeError as exc:
88
+ raise ConfigError(f"not valid TOML: {exc}") from exc
89
+ problems: list[str] = []
90
+ values: dict[str, int] = {}
91
+ for section, body in data.items():
92
+ if not isinstance(body, dict):
93
+ problems.append(f"unknown setting {section!r}")
94
+ continue
95
+ for key, value in body.items():
96
+ field = _KEYS.get((section, key))
97
+ name = f"{section}.{key}"
98
+ if field is None:
99
+ problems.append(f"unknown setting {name!r}")
100
+ elif problem := _port_problem(name, value):
101
+ problems.append(problem)
102
+ else:
103
+ values[field] = value
104
+ config = Config(**values)
105
+ if not problems and config.stream_port == config.dashboard_port:
106
+ problems.append(f"stream.port and dashboard.port are both {config.stream_port}")
107
+ if problems:
108
+ raise ConfigError("; ".join(problems))
109
+ return config
110
+
111
+
112
+ def load(path: Path) -> Config:
113
+ """Read the configuration file. A missing file means the defaults."""
114
+ try:
115
+ text = path.read_text(encoding="utf-8")
116
+ except FileNotFoundError:
117
+ return Config()
118
+ except (OSError, UnicodeDecodeError) as exc:
119
+ raise ConfigError(f"cannot read {path}: {exc}") from exc
120
+ try:
121
+ return parse(text)
122
+ except ConfigError as exc:
123
+ raise ConfigError(f"{path}: {exc}") from exc
@@ -0,0 +1,157 @@
1
+ """The always-on daemon: serves the API on a unix socket and on the dashboard port.
2
+
3
+ The dashboard port is bound to the Tailscale address only, never to every interface. While
4
+ Tailscale has no address the daemon keeps running, so the CLI works, and tries again.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import socket
11
+ import threading
12
+ import time
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from vpstream import __version__, api, tailscale
19
+ from vpstream.config import Config, Paths
20
+ from vpstream.tools import Runner
21
+
22
+ SOCKET_MODE = 0o660 # the service user and its group; the folder keeps everyone else out
23
+ RETRY_SECONDS = 10.0
24
+
25
+
26
+ class DaemonError(RuntimeError):
27
+ pass
28
+
29
+
30
+ def bind_unix(path: Path, mode: int = SOCKET_MODE) -> socket.socket:
31
+ """Listen on a unix socket at `path`, replacing a socket file left by an earlier run."""
32
+ try:
33
+ if path.is_socket():
34
+ path.unlink()
35
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
36
+ # The mask applies from the moment the file exists, so it is never open to others.
37
+ old = os.umask(0o777 & ~mode)
38
+ try:
39
+ sock.bind(str(path))
40
+ finally:
41
+ os.umask(old)
42
+ sock.listen(16)
43
+ except OSError as exc:
44
+ raise DaemonError(f"cannot listen on the socket {path}: {exc}") from exc
45
+ return sock
46
+
47
+
48
+ def bind_tcp(host: str, port: int) -> socket.socket:
49
+ """Listen on one address. Raises OSError when the address or port cannot be used."""
50
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
51
+ try:
52
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
53
+ sock.bind((host, port))
54
+ sock.listen(16)
55
+ except OSError:
56
+ sock.close()
57
+ raise
58
+ return sock
59
+
60
+
61
+ @dataclass
62
+ class Daemon:
63
+ config: Config
64
+ paths: Paths
65
+ runner: Runner
66
+ log: Callable[[str], None] = print
67
+ retry_seconds: float = RETRY_SECONDS
68
+ started: float = field(default_factory=time.time)
69
+ dashboard_address: str | None = None
70
+ dashboard_problem: str = "starting"
71
+ ready: threading.Event = field(default_factory=threading.Event)
72
+
73
+ def status(self) -> dict[str, Any]:
74
+ return {
75
+ "version": __version__,
76
+ "pid": os.getpid(),
77
+ "uptime_seconds": round(time.time() - self.started, 1),
78
+ "stream": None,
79
+ "stream_port": self.config.stream_port,
80
+ "dashboard": {
81
+ "port": self.config.dashboard_port,
82
+ "address": self.dashboard_address,
83
+ "problem": None if self.dashboard_address else self.dashboard_problem,
84
+ },
85
+ }
86
+
87
+ def serve(self, stop: threading.Event) -> None:
88
+ """Serve until `stop` is set. The socket file is removed on the way out."""
89
+ from werkzeug.serving import make_server
90
+
91
+ app = api.create_app(self.status)
92
+ self.paths.run_dir.mkdir(parents=True, exist_ok=True)
93
+ listener = bind_unix(self.paths.socket)
94
+ server = make_server(
95
+ f"unix://{self.paths.socket}", 0, app, threaded=True, fd=listener.fileno()
96
+ )
97
+ threads = [
98
+ threading.Thread(target=server.serve_forever, name="socket", daemon=True),
99
+ threading.Thread(target=self._dashboard, args=(app, stop), name="dash", daemon=True),
100
+ ]
101
+ for thread in threads:
102
+ thread.start()
103
+ self.log(f"vpstream {__version__} daemon listening on {self.paths.socket}")
104
+ self.ready.set()
105
+ try:
106
+ stop.wait()
107
+ finally:
108
+ server.shutdown()
109
+ for thread in threads:
110
+ thread.join(timeout=5)
111
+ server.server_close()
112
+ listener.close()
113
+ self.paths.socket.unlink(missing_ok=True)
114
+ self.log("vpstream daemon stopped")
115
+
116
+ def _dashboard(self, app: Any, stop: threading.Event) -> None:
117
+ """Keep the dashboard up on the Tailscale address; wait and retry while it has none."""
118
+ from werkzeug.serving import make_server
119
+
120
+ port = self.config.dashboard_port
121
+ while not stop.is_set():
122
+ try:
123
+ host = tailscale.ipv4(self.runner)
124
+ listener = bind_tcp(host, port)
125
+ except (tailscale.TailscaleDown, OSError) as exc:
126
+ problem = f"the dashboard is not available: {exc}"
127
+ if problem != self.dashboard_problem:
128
+ self.log(f"{problem}; trying again every {self.retry_seconds:g} seconds")
129
+ self.dashboard_problem = problem
130
+ stop.wait(self.retry_seconds)
131
+ continue
132
+ bound_port = listener.getsockname()[1]
133
+ server = make_server(host, bound_port, app, threaded=True, fd=listener.fileno())
134
+ self.dashboard_address = f"{host}:{bound_port}"
135
+ self.log(f"dashboard on http://{self.dashboard_address}/ (Tailscale only)")
136
+ closer = threading.Thread(
137
+ target=lambda s=server: (stop.wait(), s.shutdown()), daemon=True
138
+ )
139
+ closer.start()
140
+ try:
141
+ server.serve_forever()
142
+ finally:
143
+ self.dashboard_address = None
144
+ self.dashboard_problem = "stopped"
145
+ server.server_close()
146
+ listener.close()
147
+
148
+
149
+ def run(config: Config, paths: Paths, runner: Runner) -> int:
150
+ """Run the daemon in the foreground until SIGTERM or Ctrl+C."""
151
+ import signal
152
+
153
+ stop = threading.Event()
154
+ for signum in (signal.SIGTERM, signal.SIGINT):
155
+ signal.signal(signum, lambda *_: stop.set())
156
+ Daemon(config, paths, runner, log=lambda m: print(m, flush=True)).serve(stop)
157
+ return 0