Coverage for downtify/server_port.py: 81%

69 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Which port the server listens on, and changing it from Settings. 

2 

3The port comes from, in order: ``--port`` on the command line, the 

4``DOWNTIFY_PORT`` (or ``PORT``) environment variable, the port saved in 

5Settings > Server (``port`` in ``<data>/server.json``), and ``8000``. The 

6first two can't be changed from Settings - the page says which one set it. 

7 

8A new port applies when the server starts. Settings can also restart it 

9right away (:func:`request_restart`): ``main.py`` stops the server 

10gracefully and starts itself again in the same process, so Docker (tini) 

11and systemd see the same process carry on. 

12 

13In Docker's default *bridge* network the container's port has to match 

14the ``ports:`` mapping: changing it from Settings without changing the 

15mapping (and recreating the container) makes Downtify unreachable. Setting 

16``DOWNTIFY_PORT`` puts things back, since it wins over Settings. 

17""" 

18 

19from __future__ import annotations 

20 

21import os 

22import socket 

23from pathlib import Path 

24from typing import Any, Callable, Optional 

25 

26DEFAULT_PORT = 8000 

27#: Ports Settings accepts. Below 1024 needs root, which the image drops. 

28MIN_PORT = 1024 

29MAX_PORT = 65535 

30#: Where the port the server listens on is written, for healthcheck.sh. 

31RUNTIME_FILE = Path('/tmp/downtify.port') 

32 

33_ENV_VARS = ('DOWNTIFY_PORT', 'PORT') 

34 

35 

36class PortError(ValueError): 

37 """A port Settings can't use; the message says why.""" 

38 

39 

40def clean_port(value: Any) -> int: 

41 """*value* as a port Settings accepts, or :class:`PortError`.""" 

42 

43 try: 

44 port = int(str(value).strip()) 

45 except (TypeError, ValueError) as exc: 

46 raise PortError('The port must be a number') from exc 

47 if not MIN_PORT <= port <= MAX_PORT: 

48 raise PortError(f'Use a port from {MIN_PORT} to {MAX_PORT}') 

49 return port 

50 

51 

52def _env_port(environ: Any) -> tuple[Optional[int], str]: 

53 for name in _ENV_VARS: 

54 raw = str(environ.get(name, '') or '').strip() 

55 if raw: 

56 try: 

57 return int(raw), name 

58 except ValueError: 

59 continue 

60 return None, '' 

61 

62 

63def resolve_port( 

64 cli_port: Optional[int], 

65 saved_port: Optional[int], 

66 environ: Any = None, 

67) -> tuple[int, str]: 

68 """``(port, source)``: the port to listen on and what chose it - 

69 ``--port``, ``DOWNTIFY_PORT``/``PORT``, ``settings`` or ``default``.""" 

70 

71 if cli_port: 

72 return int(cli_port), '--port' 

73 env_port, env_name = _env_port(os.environ if environ is None else environ) 

74 if env_port: 

75 return env_port, env_name 

76 if saved_port: 

77 return int(saved_port), 'settings' 

78 return DEFAULT_PORT, 'default' 

79 

80 

81def locked_by(source: str) -> str: 

82 """What stops Settings from choosing the port (``''`` when nothing).""" 

83 

84 return '' if source in {'settings', 'default'} else source 

85 

86 

87def port_available(host: str, port: int) -> bool: 

88 """Whether *port* can be listened on at *host* right now.""" 

89 

90 family = socket.AF_INET6 if ':' in (host or '') else socket.AF_INET 

91 with socket.socket(family, socket.SOCK_STREAM) as probe: 

92 probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

93 try: 

94 probe.bind((host or '0.0.0.0', port)) 

95 except OSError: 

96 return False 

97 return True 

98 

99 

100def in_docker() -> bool: 

101 return Path('/.dockerenv').exists() 

102 

103 

104def write_runtime_port(port: int, path: Path = RUNTIME_FILE) -> None: 

105 """Note the port the server listens on, for healthcheck.sh.""" 

106 

107 try: 

108 path.write_text(str(port), encoding='utf-8') 

109 except OSError: 

110 pass 

111 

112 

113# ── Restarting ────────────────────────────────────────────────────────── 

114 

115_restart: dict[str, Any] = {'handler': None, 'wanted': False} 

116 

117 

118def set_restart_handler(handler: Optional[Callable[[], None]]) -> None: 

119 """What stops the running server so ``main.py`` can start it again.""" 

120 

121 _restart['handler'] = handler 

122 

123 

124def can_restart() -> bool: 

125 return _restart['handler'] is not None 

126 

127 

128def request_restart() -> bool: 

129 """Ask for a restart; whether one will happen.""" 

130 

131 handler = _restart['handler'] 

132 if handler is None: 

133 return False 

134 _restart['wanted'] = True 

135 handler() 

136 return True 

137 

138 

139def restart_wanted() -> bool: 

140 return bool(_restart['wanted'])