vpstream 0.2.1__tar.gz → 0.3.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 (43) hide show
  1. {vpstream-0.2.1 → vpstream-0.3.0}/CHANGELOG.md +8 -0
  2. {vpstream-0.2.1 → vpstream-0.3.0}/PKG-INFO +21 -1
  3. {vpstream-0.2.1 → vpstream-0.3.0}/README.md +20 -0
  4. {vpstream-0.2.1 → vpstream-0.3.0}/pyproject.toml +1 -1
  5. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/cli.py +12 -0
  6. vpstream-0.3.0/src/vpstream/config.py +113 -0
  7. vpstream-0.3.0/src/vpstream/doctor.py +242 -0
  8. vpstream-0.3.0/src/vpstream/tailscale.py +27 -0
  9. vpstream-0.3.0/src/vpstream/tests/test_config.py +58 -0
  10. vpstream-0.3.0/src/vpstream/tests/test_doctor.py +208 -0
  11. {vpstream-0.2.1 → vpstream-0.3.0}/.gitignore +0 -0
  12. {vpstream-0.2.1 → vpstream-0.3.0}/LICENSE +0 -0
  13. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/__init__.py +0 -0
  14. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/__main__.py +0 -0
  15. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/assets/__init__.py +0 -0
  16. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/assets/caps.html +0 -0
  17. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/assets/caps.js +0 -0
  18. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/assets/hls.js.LICENSE +0 -0
  19. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/assets/hls.js.version +0 -0
  20. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/assets/hls.min.js +0 -0
  21. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/bench.py +0 -0
  22. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/caps/__init__.py +0 -0
  23. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/caps/clips.py +0 -0
  24. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/caps/server.py +0 -0
  25. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/ffargs.py +0 -0
  26. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/ffmpeg_install.py +0 -0
  27. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/probe.py +0 -0
  28. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/selftest.py +0 -0
  29. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/subtitles.py +0 -0
  30. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/__init__.py +0 -0
  31. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/conftest.py +0 -0
  32. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/data/three-cues.sup +0 -0
  33. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/fakes.py +0 -0
  34. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_assets.py +0 -0
  35. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_bench.py +0 -0
  36. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_caps.py +0 -0
  37. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_cli.py +0 -0
  38. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_ffargs.py +0 -0
  39. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_ffmpeg_install.py +0 -0
  40. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_integration.py +0 -0
  41. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_probe.py +0 -0
  42. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tests/test_subtitles.py +0 -0
  43. {vpstream-0.2.1 → vpstream-0.3.0}/src/vpstream/tools.py +0 -0
@@ -2,6 +2,14 @@
2
2
 
3
3
  <!-- version list -->
4
4
 
5
+ ## v0.3.0 (2026-11-10)
6
+
7
+ ### Features
8
+
9
+ - Add vpstream doctor and the configuration file ([#5](https://github.com/skj-skj/vpstream/pull/5),
10
+ [`364af62`](https://github.com/skj-skj/vpstream/commit/364af6266dbaee33c960a6cc0a856c28e33d40a8))
11
+
12
+
5
13
  ## v0.2.1 (2026-11-10)
6
14
 
7
15
  ### Bug Fixes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: vpstream
3
- Version: 0.2.1
3
+ Version: 0.3.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
@@ -48,6 +48,26 @@ vpstream --version
48
48
  vpstream selftest --integration
49
49
  ```
50
50
 
51
+ ## `vpstream doctor`
52
+
53
+ Checks this host for everything vpstream needs and lists all of it in one report: the Python
54
+ version, ffmpeg, ffprobe, Caddy, ufw, Tailscale, systemd and sudo, whether ufw is enabled and
55
+ Tailscale is connected, the fonts burned-in subtitles fall back to, the configuration file,
56
+ and where vpstream itself is installed. Each problem comes with the command that fixes it.
57
+ The exit code is 1 when something required is missing. Nothing is changed and no root is
58
+ needed.
59
+
60
+ The service runs as its own user, with a small root helper for the firewall, so it needs a
61
+ system-wide install that root owns. A per-user `pipx install` is reported as a problem:
62
+
63
+ ```text
64
+ sudo PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install "vpstream[dev]"
65
+ pipx uninstall vpstream # the per-user copy, if there is one
66
+ ```
67
+
68
+ Settings are read from `/etc/vpstream/config.toml` when it exists: `port` under `[stream]`
69
+ (default 1337) and `port` under `[dashboard]` (default 1338).
70
+
51
71
  ## `vpstream install ffmpeg` and `vpstream update ffmpeg`
52
72
 
53
73
  Distribution packages of ffmpeg are often several versions old. `vpstream install ffmpeg`
@@ -29,6 +29,26 @@ 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
+
32
52
  ## `vpstream install ffmpeg` and `vpstream update ffmpeg`
33
53
 
34
54
  Distribution packages of ffmpeg are often several versions old. `vpstream install ffmpeg`
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "vpstream"
7
- version = "0.2.1"
7
+ version = "0.3.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"
@@ -134,6 +134,15 @@ def cmd_caps(args: argparse.Namespace) -> int:
134
134
  return 0
135
135
 
136
136
 
137
+ def cmd_doctor(args: argparse.Namespace) -> int:
138
+ from vpstream import doctor
139
+ from vpstream.tools import SystemRunner
140
+
141
+ checks = doctor.run_checks(SystemRunner())
142
+ print(doctor.format_report(checks))
143
+ return doctor.exit_code(checks)
144
+
145
+
137
146
  def _ask(question: str) -> bool:
138
147
  try:
139
148
  answer = input(f"{question} [y/N] ")
@@ -194,6 +203,9 @@ def build_parser() -> argparse.ArgumentParser:
194
203
  )
195
204
  st.set_defaults(func=cmd_selftest)
196
205
 
206
+ d = sub.add_parser("doctor", help="check this host for the programs vpstream needs")
207
+ d.set_defaults(func=cmd_doctor)
208
+
197
209
  b = sub.add_parser("bench", help="measure how fast this host prepares a file")
198
210
  b.add_argument("file")
199
211
  b.add_argument(
@@ -0,0 +1,113 @@
1
+ """The configuration file, and the fixed places vpstream uses on a host."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ MIN_PORT = 1024 # the daemon runs as an unprivileged user, which cannot bind lower ports
11
+
12
+
13
+ class ConfigError(ValueError):
14
+ """The configuration file cannot be used; the message lists every problem."""
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Paths:
19
+ """Where things live. Tests move everything under a temporary folder with `under`."""
20
+
21
+ config_file: Path = Path("/etc/vpstream/config.toml")
22
+ state_dir: Path = Path("/var/lib/vpstream")
23
+ cache_dir: Path = Path("/var/cache/vpstream")
24
+ run_dir: Path = Path("/run/vpstream")
25
+
26
+ @property
27
+ def socket(self) -> Path:
28
+ return self.run_dir / "daemon.sock"
29
+
30
+ @classmethod
31
+ def under(cls, root: Path) -> Paths:
32
+ default = cls()
33
+ return cls(
34
+ config_file=root / default.config_file.relative_to("/"),
35
+ state_dir=root / default.state_dir.relative_to("/"),
36
+ cache_dir=root / default.cache_dir.relative_to("/"),
37
+ run_dir=root / default.run_dir.relative_to("/"),
38
+ )
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Config:
43
+ stream_port: int = 1337
44
+ dashboard_port: int = 1338
45
+
46
+
47
+ # Section and key in the file -> field of Config.
48
+ _KEYS = {("stream", "port"): "stream_port", ("dashboard", "port"): "dashboard_port"}
49
+
50
+ DEFAULT_TEXT = """\
51
+ # vpstream configuration. Restart the service after a change:
52
+ # sudo systemctl restart vpstream
53
+
54
+ [stream]
55
+ # The public port viewers connect to. It is open in the firewall only while a stream runs.
56
+ port = 1337
57
+
58
+ [dashboard]
59
+ # The dashboard port. It listens on the Tailscale address only.
60
+ port = 1338
61
+ """
62
+
63
+
64
+ def _port_problem(name: str, value: Any) -> str | None:
65
+ # bool is an int in Python, and `port = true` is a mistake, not port 1.
66
+ if isinstance(value, bool) or not isinstance(value, int):
67
+ return f"{name} must be a whole number, not {value!r}"
68
+ if not MIN_PORT <= value <= 65535:
69
+ return f"{name} must be from {MIN_PORT} to 65535, not {value}"
70
+ return None
71
+
72
+
73
+ def parse(text: str) -> Config:
74
+ """Read configuration text. Missing keys take their defaults; unknown keys are errors."""
75
+ try:
76
+ data = tomllib.loads(text)
77
+ except tomllib.TOMLDecodeError as exc:
78
+ raise ConfigError(f"not valid TOML: {exc}") from exc
79
+ problems: list[str] = []
80
+ values: dict[str, int] = {}
81
+ for section, body in data.items():
82
+ if not isinstance(body, dict):
83
+ problems.append(f"unknown setting {section!r}")
84
+ continue
85
+ for key, value in body.items():
86
+ field = _KEYS.get((section, key))
87
+ name = f"{section}.{key}"
88
+ if field is None:
89
+ problems.append(f"unknown setting {name!r}")
90
+ elif problem := _port_problem(name, value):
91
+ problems.append(problem)
92
+ else:
93
+ values[field] = value
94
+ config = Config(**values)
95
+ if not problems and config.stream_port == config.dashboard_port:
96
+ problems.append(f"stream.port and dashboard.port are both {config.stream_port}")
97
+ if problems:
98
+ raise ConfigError("; ".join(problems))
99
+ return config
100
+
101
+
102
+ def load(path: Path) -> Config:
103
+ """Read the configuration file. A missing file means the defaults."""
104
+ try:
105
+ text = path.read_text(encoding="utf-8")
106
+ except FileNotFoundError:
107
+ return Config()
108
+ except (OSError, UnicodeDecodeError) as exc:
109
+ raise ConfigError(f"cannot read {path}: {exc}") from exc
110
+ try:
111
+ return parse(text)
112
+ except ConfigError as exc:
113
+ raise ConfigError(f"{path}: {exc}") from exc
@@ -0,0 +1,242 @@
1
+ """`vpstream doctor`: check this host for everything vpstream needs, and say what is missing.
2
+
3
+ Every check runs, so one report lists all the problems at once.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import stat
10
+ import sys
11
+ from collections.abc import Sequence
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ from vpstream import config, tailscale
17
+ from vpstream.tools import PACKAGES, Runner
18
+
19
+ Status = Literal["ok", "problem", "warning"]
20
+
21
+ MIN_PYTHON = (3, 12)
22
+ SYSTEM_INSTALL = 'sudo PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install "vpstream[dev]"'
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Check:
27
+ name: str
28
+ status: Status
29
+ detail: str = ""
30
+ fix: str = ""
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Tool:
35
+ name: str
36
+ needed_for: str
37
+ fix: str
38
+ required: bool = True
39
+
40
+
41
+ TOOLS = (
42
+ Tool("ffmpeg", "preparing videos for the browser", "vpstream install ffmpeg"),
43
+ Tool("ffprobe", "reading the tracks of a video", "vpstream install ffmpeg"),
44
+ Tool("caddy", "serving streams", "sudo apt install caddy"),
45
+ Tool("ufw", "opening the stream port only while a stream runs", "sudo apt install ufw"),
46
+ Tool("tailscale", "the private dashboard", "see https://tailscale.com/download/linux"),
47
+ Tool("systemctl", "running the service", "vpstream needs a host that runs systemd"),
48
+ Tool("sudo", "the firewall helper", "as root: apt install sudo"),
49
+ Tool("mkvextract", "WebVTT subtitles stored by mkvmerge", "", required=False),
50
+ Tool("mkvmerge", "WebVTT subtitles stored by mkvmerge", "", required=False),
51
+ )
52
+
53
+ # Burned-in subtitles fall back to these when a file does not carry its font.
54
+ FONTS = (("Noto Sans CJK", "fonts-noto-cjk"), ("Liberation Sans", "fonts-liberation"))
55
+
56
+
57
+ def check_python(version: Sequence[int]) -> Check:
58
+ shown = ".".join(str(n) for n in version[:3])
59
+ if tuple(version[:2]) >= MIN_PYTHON:
60
+ return Check("python", "ok", shown)
61
+ need = ".".join(str(n) for n in MIN_PYTHON)
62
+ return Check("python", "problem", f"{shown}; vpstream needs {need} or newer")
63
+
64
+
65
+ def check_tool(runner: Runner, tool: Tool) -> Check:
66
+ path = runner.which(tool.name)
67
+ if path:
68
+ return Check(tool.name, "ok", path)
69
+ fix = tool.fix or f"sudo apt install {PACKAGES.get(tool.name, tool.name)}"
70
+ status: Status = "problem" if tool.required else "warning"
71
+ return Check(tool.name, status, f"not found; needed for {tool.needed_for}", fix)
72
+
73
+
74
+ def check_systemd(marker: Path) -> Check:
75
+ """systemd is the running init system when it has made its runtime folder."""
76
+ if marker.is_dir():
77
+ return Check("systemd", "ok", "running")
78
+ return Check("systemd", "problem", f"not running this host ({marker} is missing)")
79
+
80
+
81
+ def ufw_enabled(conf_text: str) -> bool:
82
+ """Whether ufw.conf says the firewall starts on boot: a line `ENABLED=yes`."""
83
+ for line in conf_text.splitlines():
84
+ key, _, value = line.partition("=")
85
+ if key.strip() == "ENABLED":
86
+ return value.strip().strip("\"'").lower() == "yes"
87
+ return False
88
+
89
+
90
+ def check_ufw_enabled(conf: Path) -> Check:
91
+ try:
92
+ text = conf.read_text(encoding="utf-8", errors="replace")
93
+ except OSError as exc:
94
+ return Check("ufw enabled", "warning", f"cannot read {conf}: {exc.strerror}")
95
+ if ufw_enabled(text):
96
+ return Check("ufw enabled", "ok", "yes")
97
+ return Check(
98
+ "ufw enabled",
99
+ "problem",
100
+ "ufw is not enabled, so no port is closed by it",
101
+ "enable ufw yourself, after allowing your SSH access; vpstream never enables it",
102
+ )
103
+
104
+
105
+ def check_tailscale(runner: Runner) -> Check:
106
+ try:
107
+ return Check("tailscale up", "ok", tailscale.ipv4(runner))
108
+ except tailscale.TailscaleDown as exc:
109
+ return Check("tailscale up", "problem", str(exc), "sudo tailscale up")
110
+
111
+
112
+ def check_fonts(runner: Runner) -> list[Check]:
113
+ if not runner.which("fc-list"):
114
+ return [
115
+ Check("fonts", "warning", "fc-list not found", "sudo apt install fontconfig"),
116
+ ]
117
+ families = runner.run(["fc-list", ":", "family"], timeout=30).stdout.lower()
118
+ checks = []
119
+ for family, package in FONTS:
120
+ if family.lower() in families:
121
+ checks.append(Check(f"font {family}", "ok", "installed"))
122
+ else:
123
+ checks.append(
124
+ Check(
125
+ f"font {family}",
126
+ "warning",
127
+ "not installed; burned-in subtitles may show boxes or another font",
128
+ f"sudo apt install {package}",
129
+ )
130
+ )
131
+ return checks
132
+
133
+
134
+ def check_config(path: Path) -> Check:
135
+ if not path.exists():
136
+ return Check("config", "ok", f"no {path}; the defaults are used")
137
+ try:
138
+ cfg = config.load(path)
139
+ except config.ConfigError as exc:
140
+ return Check("config", "problem", str(exc), f"edit {path}")
141
+ return Check(
142
+ "config", "ok", f"{path} (stream port {cfg.stream_port}, dashboard {cfg.dashboard_port})"
143
+ )
144
+
145
+
146
+ def folder_problem(folder: Path, st: os.stat_result, owner_uid: int = 0) -> str | None:
147
+ """Why one folder on the way to the package is not safe for the service, or None."""
148
+ if not st.st_mode & stat.S_IXOTH:
149
+ return f"other users cannot enter {folder}"
150
+ if st.st_uid != owner_uid:
151
+ return f"{folder} is not owned by root"
152
+ if st.st_mode & stat.S_ISVTX:
153
+ return None # sticky, like /tmp: others cannot replace what root put there
154
+ if st.st_mode & stat.S_IWOTH:
155
+ return f"{folder} is writable by every user"
156
+ if st.st_mode & stat.S_IWGRP and st.st_gid != 0:
157
+ return f"{folder} is writable by a group other than root"
158
+ return None
159
+
160
+
161
+ def install_problem(package_dir: Path, owner_uid: int = 0) -> str | None:
162
+ """Why the service cannot safely run the package from `package_dir`, or None.
163
+
164
+ The service runs as its own user and its firewall helper runs as root, so every folder
165
+ down to the package must be open to other users, owned by root and writable by nobody else.
166
+ """
167
+ try:
168
+ package_dir = package_dir.resolve()
169
+ for folder in (package_dir, *package_dir.parents):
170
+ if problem := folder_problem(folder, folder.stat(), owner_uid):
171
+ return problem
172
+ if not package_dir.stat().st_mode & stat.S_IROTH:
173
+ return f"other users cannot read {package_dir}"
174
+ except OSError as exc:
175
+ return f"cannot check {package_dir}: {exc.strerror}"
176
+ return None
177
+
178
+
179
+ def check_install(package_dir: Path, owner_uid: int = 0) -> Check:
180
+ problem = install_problem(package_dir, owner_uid)
181
+ if problem is None:
182
+ return Check("install", "ok", str(package_dir))
183
+ return Check(
184
+ "install",
185
+ "problem",
186
+ f"{problem}; the service cannot run from a per-user install",
187
+ f"{SYSTEM_INSTALL} (then remove the per-user copy: pipx uninstall vpstream)",
188
+ )
189
+
190
+
191
+ def run_checks(
192
+ runner: Runner,
193
+ *,
194
+ python_version: Sequence[int] | None = None,
195
+ package_dir: Path | None = None,
196
+ paths: config.Paths | None = None,
197
+ systemd_marker: Path = Path("/run/systemd/system"),
198
+ ufw_conf: Path = Path("/etc/ufw/ufw.conf"),
199
+ ) -> list[Check]:
200
+ """Run every check. Nothing here changes the host or needs root."""
201
+ paths = paths or config.Paths()
202
+ checks = [check_python(python_version or tuple(sys.version_info[:3]))]
203
+ checks += [check_tool(runner, tool) for tool in TOOLS]
204
+ found = {c.name for c in checks if c.status == "ok"}
205
+ if "systemctl" in found:
206
+ checks.append(check_systemd(systemd_marker))
207
+ if "ufw" in found:
208
+ checks.append(check_ufw_enabled(ufw_conf))
209
+ if "tailscale" in found:
210
+ checks.append(check_tailscale(runner))
211
+ checks += check_fonts(runner)
212
+ checks.append(check_install(package_dir or Path(__file__).parent))
213
+ checks.append(check_config(paths.config_file))
214
+ return checks
215
+
216
+
217
+ _LABELS = {"ok": "ok", "problem": "PROBLEM", "warning": "warning"}
218
+
219
+
220
+ def format_report(checks: Sequence[Check]) -> str:
221
+ width = max(len(c.name) for c in checks)
222
+ lines = []
223
+ for c in checks:
224
+ lines.append(f"{_LABELS[c.status]:<8} {c.name:<{width}} {c.detail}".rstrip())
225
+ if c.fix and c.status != "ok":
226
+ lines.append(f"{'':<8} {'':<{width}} fix: {c.fix}")
227
+ problems = sum(c.status == "problem" for c in checks)
228
+ warnings = sum(c.status == "warning" for c in checks)
229
+ summary = (
230
+ "Everything vpstream needs is here." if not problems else f"{_count(problems, 'problem')}."
231
+ )
232
+ if warnings:
233
+ summary += f" {_count(warnings, 'warning')}."
234
+ return "\n".join([*lines, "", summary])
235
+
236
+
237
+ def _count(n: int, word: str) -> str:
238
+ return f"{n} {word}" if n == 1 else f"{n} {word}s"
239
+
240
+
241
+ def exit_code(checks: Sequence[Check]) -> int:
242
+ return 1 if any(c.status == "problem" for c in checks) else 0
@@ -0,0 +1,27 @@
1
+ """What vpstream needs to know from Tailscale: this host's tailnet address."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+
7
+ from vpstream.tools import Runner, tail
8
+
9
+ INTERFACE = "tailscale0"
10
+
11
+
12
+ class TailscaleDown(RuntimeError):
13
+ """Tailscale is missing, stopped or logged out, so there is no tailnet address."""
14
+
15
+
16
+ def ipv4(runner: Runner) -> str:
17
+ """This host's Tailscale IPv4 address, from `tailscale ip -4`."""
18
+ if not runner.which("tailscale"):
19
+ raise TailscaleDown("tailscale was not found on PATH")
20
+ res = runner.run(["tailscale", "ip", "-4"], timeout=15)
21
+ if res.returncode != 0:
22
+ raise TailscaleDown(f"tailscale ip -4 failed: {tail(res, stdout=True)}")
23
+ lines = res.stdout.split()
24
+ try:
25
+ return str(ipaddress.IPv4Address(lines[0]))
26
+ except (IndexError, ValueError):
27
+ raise TailscaleDown(f"tailscale ip -4 printed no address: {res.stdout.strip()!r}") from None
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from vpstream import config
8
+
9
+
10
+ def test_defaults_and_default_text_agree() -> None:
11
+ assert config.parse("") == config.Config()
12
+ assert config.parse(config.DEFAULT_TEXT) == config.Config(stream_port=1337, dashboard_port=1338)
13
+
14
+
15
+ def test_values_are_read() -> None:
16
+ cfg = config.parse("[stream]\nport = 2000\n[dashboard]\nport = 2001\n")
17
+ assert (cfg.stream_port, cfg.dashboard_port) == (2000, 2001)
18
+
19
+
20
+ @pytest.mark.parametrize(
21
+ ("text", "message"),
22
+ [
23
+ ("[stream]\nport = 80\n", "from 1024 to 65535"),
24
+ ("[stream]\nport = 70000\n", "from 1024 to 65535"),
25
+ ('[stream]\nport = "1337"\n', "whole number"),
26
+ ("[stream]\nport = true\n", "whole number"),
27
+ ("[stream]\nprot = 1337\n", "unknown setting 'stream.prot'"),
28
+ ("port = 1337\n", "unknown setting 'port'"),
29
+ ("[stream]\nport = 1338\n", "both 1338"),
30
+ ("[stream\n", "not valid TOML"),
31
+ ],
32
+ )
33
+ def test_bad_values_are_refused(text: str, message: str) -> None:
34
+ with pytest.raises(config.ConfigError, match=message):
35
+ config.parse(text)
36
+
37
+
38
+ def test_every_problem_is_listed() -> None:
39
+ with pytest.raises(config.ConfigError) as exc:
40
+ config.parse("[stream]\nport = 1\n[dashboard]\nport = 2\nx = 1\n")
41
+ assert str(exc.value).count(";") == 2
42
+
43
+
44
+ def test_load(tmp_path: Path) -> None:
45
+ path = tmp_path / "config.toml"
46
+ assert config.load(path) == config.Config()
47
+ path.write_text("[dashboard]\nport = 4000\n")
48
+ assert config.load(path).dashboard_port == 4000
49
+ path.write_text("[dashboard]\nport = 1\n")
50
+ with pytest.raises(config.ConfigError, match=str(path)):
51
+ config.load(path)
52
+
53
+
54
+ def test_paths_under_a_root(tmp_path: Path) -> None:
55
+ paths = config.Paths.under(tmp_path)
56
+ assert paths.config_file == tmp_path / "etc/vpstream/config.toml"
57
+ assert paths.socket == tmp_path / "run/vpstream/daemon.sock"
58
+ assert config.Paths().socket == Path("/run/vpstream/daemon.sock")
@@ -0,0 +1,208 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from vpstream import cli, config, doctor, tailscale
9
+ from vpstream.tests.fakes import FakeRunner
10
+
11
+ ALL_TOOLS = (*(t.name for t in doctor.TOOLS), "fc-list")
12
+ FAMILIES = "Noto Sans CJK JP\nLiberation Sans\nDejaVu Sans\n"
13
+
14
+
15
+ def _host(tmp_path: Path, available: tuple[str, ...] = ALL_TOOLS) -> tuple[FakeRunner, dict]:
16
+ """A fake host where everything is fine."""
17
+ runner = FakeRunner(available)
18
+ runner.on("tailscale", "ip", "-4", stdout="100.64.0.7\n")
19
+ runner.on("fc-list", stdout=FAMILIES)
20
+ marker = tmp_path / "systemd"
21
+ marker.mkdir()
22
+ ufw_conf = tmp_path / "ufw.conf"
23
+ ufw_conf.write_text("# comment\nENABLED=yes\nLOGLEVEL=low\n")
24
+ package = tmp_path / "pkg"
25
+ package.mkdir(mode=0o755)
26
+ kwargs = {
27
+ "python_version": (3, 12, 3),
28
+ "package_dir": package,
29
+ "paths": config.Paths.under(tmp_path),
30
+ "systemd_marker": marker,
31
+ "ufw_conf": ufw_conf,
32
+ }
33
+ return runner, kwargs
34
+
35
+
36
+ def _by_name(checks: list[doctor.Check]) -> dict[str, doctor.Check]:
37
+ return {c.name: c for c in checks}
38
+
39
+
40
+ def test_every_missing_tool_is_reported(tmp_path: Path) -> None:
41
+ runner, kwargs = _host(tmp_path, available=())
42
+ checks = _by_name(doctor.run_checks(runner, **kwargs))
43
+ for tool in doctor.TOOLS:
44
+ assert checks[tool.name].status == ("problem" if tool.required else "warning")
45
+ assert checks[tool.name].fix
46
+ assert checks["ffprobe"].fix == "vpstream install ffmpeg"
47
+ assert checks["mkvmerge"].fix == "sudo apt install mkvtoolnix"
48
+ # Checks that need a missing tool are left out instead of failing a second time.
49
+ assert not {"systemd", "ufw enabled", "tailscale up"} & set(checks)
50
+ assert doctor.exit_code(list(checks.values())) == 1
51
+
52
+
53
+ def test_a_missing_optional_tool_is_only_a_warning(tmp_path: Path) -> None:
54
+ tools = tuple(t for t in ALL_TOOLS if not t.startswith("mkv"))
55
+ runner, kwargs = _host(tmp_path, available=tools)
56
+ checks = doctor.run_checks(runner, **kwargs)
57
+ # The install check needs root-owned folders, which a test cannot make.
58
+ checks = [c for c in checks if c.name != "install"]
59
+ assert {c.name for c in checks if c.status == "warning"} == {"mkvextract", "mkvmerge"}
60
+ assert doctor.exit_code(checks) == 0
61
+ report = doctor.format_report(checks)
62
+ assert "Everything vpstream needs is here. 2 warnings." in report
63
+ assert "fix: sudo apt install mkvtoolnix" in report
64
+
65
+
66
+ def test_python_version() -> None:
67
+ assert doctor.check_python((3, 12, 0)).status == "ok"
68
+ assert doctor.check_python((3, 14, 8)).detail == "3.14.8"
69
+ old = doctor.check_python((3, 11, 9))
70
+ assert old.status == "problem" and "3.12 or newer" in old.detail
71
+
72
+
73
+ def test_systemd_must_be_running(tmp_path: Path) -> None:
74
+ assert doctor.check_systemd(tmp_path).status == "ok"
75
+ assert doctor.check_systemd(tmp_path / "nope").status == "problem"
76
+
77
+
78
+ @pytest.mark.parametrize(
79
+ ("text", "enabled"),
80
+ [
81
+ ("ENABLED=yes\n", True),
82
+ ('ENABLED="yes"\n', True),
83
+ ("ENABLED=no\n", False),
84
+ ("# ENABLED=yes\n", False),
85
+ ("LOGLEVEL=low\n", False),
86
+ ],
87
+ )
88
+ def test_ufw_enabled(text: str, enabled: bool) -> None:
89
+ assert doctor.ufw_enabled(text) is enabled
90
+
91
+
92
+ def test_ufw_not_enabled_is_a_problem_vpstream_does_not_fix(tmp_path: Path) -> None:
93
+ conf = tmp_path / "ufw.conf"
94
+ conf.write_text("ENABLED=no\n")
95
+ check = doctor.check_ufw_enabled(conf)
96
+ assert check.status == "problem" and "never enables" in check.fix
97
+ assert doctor.check_ufw_enabled(tmp_path / "nope").status == "warning"
98
+
99
+
100
+ def test_tailscale_address() -> None:
101
+ runner = FakeRunner(("tailscale",))
102
+ runner.on("tailscale", "ip", "-4", stdout="100.64.0.7\n")
103
+ assert tailscale.ipv4(runner) == "100.64.0.7"
104
+ assert doctor.check_tailscale(runner).detail == "100.64.0.7"
105
+
106
+
107
+ @pytest.mark.parametrize(
108
+ ("returncode", "stdout", "message"),
109
+ [
110
+ (1, "Tailscale is stopped.\n", "Tailscale is stopped"),
111
+ (0, "", "printed no address"),
112
+ (0, "fd7a:115c:a1e0::1\n", "printed no address"),
113
+ ],
114
+ )
115
+ def test_tailscale_down(returncode: int, stdout: str, message: str) -> None:
116
+ runner = FakeRunner(("tailscale",))
117
+ runner.on("tailscale", "ip", "-4", returncode=returncode, stdout=stdout)
118
+ with pytest.raises(tailscale.TailscaleDown, match=message):
119
+ tailscale.ipv4(runner)
120
+ check = doctor.check_tailscale(runner)
121
+ assert check.status == "problem" and check.fix == "sudo tailscale up"
122
+
123
+
124
+ def test_tailscale_not_installed() -> None:
125
+ with pytest.raises(tailscale.TailscaleDown, match="not found"):
126
+ tailscale.ipv4(FakeRunner(()))
127
+
128
+
129
+ def test_missing_fonts_are_warnings() -> None:
130
+ runner = FakeRunner(("fc-list",))
131
+ runner.on("fc-list", stdout="DejaVu Sans\nLiberation Sans\n")
132
+ checks = _by_name(doctor.check_fonts(runner))
133
+ assert checks["font Liberation Sans"].status == "ok"
134
+ assert checks["font Noto Sans CJK"].status == "warning"
135
+ assert checks["font Noto Sans CJK"].fix == "sudo apt install fonts-noto-cjk"
136
+ assert doctor.check_fonts(FakeRunner(()))[0].fix == "sudo apt install fontconfig"
137
+
138
+
139
+ def test_config_check(tmp_path: Path) -> None:
140
+ path = tmp_path / "config.toml"
141
+ assert "defaults" in doctor.check_config(path).detail
142
+ path.write_text("[stream]\nport = 2000\n")
143
+ assert "stream port 2000" in doctor.check_config(path).detail
144
+ path.write_text("[stream]\nport = 1\n")
145
+ assert doctor.check_config(path).status == "problem"
146
+
147
+
148
+ def test_each_folder_must_be_safe_for_the_service(tmp_path: Path) -> None:
149
+ me = os.getuid()
150
+ folder = tmp_path / "home"
151
+ folder.mkdir()
152
+
153
+ def problem(mode: int, owner: int = me) -> str | None:
154
+ folder.chmod(mode)
155
+ return doctor.folder_problem(folder, folder.stat(), owner)
156
+
157
+ assert problem(0o755) is None
158
+ assert problem(0o711) is None
159
+ assert problem(0o750) == f"other users cannot enter {folder}"
160
+ assert problem(0o757) == f"{folder} is writable by every user"
161
+ assert problem(0o1777) is None # sticky, like /tmp
162
+ assert problem(0o755, owner=me + 1) == f"{folder} is not owned by root"
163
+ if folder.stat().st_gid != 0:
164
+ assert problem(0o775) == f"{folder} is writable by a group other than root"
165
+
166
+
167
+ def test_install_is_checked_up_to_the_root(tmp_path: Path) -> None:
168
+ package = tmp_path / "closed" / "vpstream"
169
+ package.mkdir(parents=True)
170
+ package.chmod(0o755)
171
+ (tmp_path / "closed").chmod(0o700)
172
+ problem = doctor.install_problem(package, owner_uid=os.getuid())
173
+ assert problem == f"other users cannot enter {tmp_path / 'closed'}"
174
+
175
+
176
+ def test_install_must_be_owned_by_root(tmp_path: Path) -> None:
177
+ package = tmp_path / "vpstream"
178
+ package.mkdir(mode=0o755)
179
+ if os.getuid() == 0:
180
+ pytest.skip("root owns the test folder")
181
+ check = doctor.check_install(package)
182
+ assert check.status == "problem"
183
+ assert "PIPX_HOME=/opt/pipx" in check.fix
184
+ assert doctor.install_problem(tmp_path / "nope") == f"cannot check {tmp_path / 'nope'}: " + (
185
+ "No such file or directory"
186
+ )
187
+
188
+
189
+ def test_report_and_exit_code() -> None:
190
+ checks = [
191
+ doctor.Check("python", "ok", "3.12.3"),
192
+ doctor.Check("caddy", "problem", "not found", "sudo apt install caddy"),
193
+ doctor.Check("mkvmerge", "warning", "not found", "sudo apt install mkvtoolnix"),
194
+ ]
195
+ lines = doctor.format_report(checks).splitlines()
196
+ assert lines[0] == "ok python 3.12.3"
197
+ assert lines[1] == "PROBLEM caddy not found"
198
+ assert lines[2].strip() == "fix: sudo apt install caddy"
199
+ assert lines[-1] == "1 problem. 1 warning."
200
+ assert doctor.exit_code(checks) == 1
201
+ assert doctor.exit_code(checks[:1]) == 0
202
+
203
+
204
+ def test_cli_doctor_prints_a_report(capsys: pytest.CaptureFixture[str]) -> None:
205
+ code = cli.main(["doctor"])
206
+ out = capsys.readouterr().out
207
+ assert code in (0, 1)
208
+ assert "python" in out and "install" in out
File without changes
File without changes
File without changes
File without changes
File without changes