Coverage for trlcdoc/plantuml.py: 96%

167 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 14:00 +0000

1"""Provide the PlantUML jar, replacing the get_plantuml.sh/.bat scripts.""" 

2 

3# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents. 

4# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de 

5# 

6# This file is part of trlcdoc program. 

7# 

8# The trlcdoc program is free software: you can redistribute it and/or modify it under 

9# the terms of the GNU General Public License as published by the Free Software Foundation, 

10# either version 3 of the License, or (at your option) any later version. 

11# 

12# The trlcdoc program is distributed in the hope that it will be useful, but 

13# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 

14# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 

15# 

16# You should have received a copy of the GNU General Public License along with pyTRLCConverter. 

17# If not, see <https://www.gnu.org/licenses/>. 

18 

19# Imports ********************************************************************** 

20 

21import atexit 

22import logging 

23import os 

24import signal 

25import socket 

26import subprocess 

27import sys 

28import threading 

29import time 

30import urllib.request 

31from dataclasses import dataclass, field 

32from pathlib import Path 

33from typing import Any 

34from urllib.parse import urlparse 

35 

36from .config import Config 

37from .log import command_line, redact_url 

38from .plantuml_client import encode_diagram 

39from .util import TrlcdocError, find_graphviz, find_tool, prepare_output 

40 

41# Variables ******************************************************************** 

42 

43LOG = logging.getLogger(__name__) 

44 

45DEFAULT_VERSION = "1.2024.8" 

46DOWNLOAD_URL = "https://github.com/plantuml/plantuml/releases/download/v{version}/plantuml-{version}.jar" 

47 

48# Java option that keeps PlantUML from starting the graphical user interface support of the system. 

49JAVA_HEADLESS = "-Djava.awt.headless=true" 

50 

51# The picoweb server listens on this address only, so it cannot be reached from the network. 

52PICOWEB_HOST = "127.0.0.1" 

53# Seconds until the picoweb server must render its first diagram: Java start and PlantUML initialization. 

54PICOWEB_START_TIMEOUT = 30.0 

55# Seconds between two checks whether the picoweb server answers. 

56PICOWEB_POLL_INTERVAL = 0.1 

57# Seconds the picoweb server gets to stop before it is killed. 

58PICOWEB_STOP_TIMEOUT = 5.0 

59# Diagram that checks that the picoweb server renders. A sequence diagram doesn't need Graphviz. 

60PICOWEB_PROBE_DIAGRAM = "@startuml\nA -> B\n@enduml\n" 

61 

62# Proxy exceptions, which keep requests to the local server away from a proxy configured for the internet. 

63# Both spellings are in use. Environment variable names on Windows ignore the case, there they are one variable. 

64NO_PROXY_NAMES = ("NO_PROXY",) if sys.platform == "win32" else ("NO_PROXY", "no_proxy") 

65# Environment variables set while the picoweb server runs. 

66PICOWEB_ENV_NAMES = ("PLANTUML", *NO_PROXY_NAMES) 

67 

68# Classes ********************************************************************** 

69 

70 

71@dataclass 

72class PicowebServer: 

73 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

74 """The running PlantUML picoweb server and what to restore when it stops.""" 

75 

76 process: subprocess.Popen 

77 """The Java process of the server.""" 

78 url: str 

79 """Server URL for the PLANTUML environment variable.""" 

80 saved_env: dict[str, str | None] = field(default_factory=dict) 

81 """Values of PICOWEB_ENV_NAMES before the server started, None if unset.""" 

82 saved_sigterm: Any = None 

83 """The SIGTERM handler before the server started, None if it was not replaced.""" 

84 

85 

86# The picoweb server of this trlcdoc run: empty if none runs, never more than one entry. 

87_running_picoweb: list[PicowebServer] = [] 

88 

89# Functions ******************************************************************** 

90 

91 

92def provide_plantuml(cfg: Config) -> Path | str: 

93 # lobster-trace: SwRequirements.sw_req_plantuml 

94 # lobster-trace: SwRequirements.sw_req_external_tools 

95 """Locate or download plantuml.jar and export it in the PLANTUML environment variable. 

96 

97 The PLANTUML environment variable, a jar or a PlantUML server URL, has precedence 

98 over the configured jar, which has precedence over a download of the configured version. 

99 A jar needs Java and Graphviz, which are checked before anything is downloaded. 

100 

101 With plantuml.picoweb (default), a jar is started once as local picoweb server, and its URL 

102 is exported instead of the jar. If the server doesn't start, the jar is exported. 

103 

104 Args: 

105 cfg (Config): Project configuration. 

106 

107 Returns: 

108 Path | str: The plantuml.jar file, or the PlantUML server URL. 

109 

110 Raises: 

111 TrlcdocError: If the jar is missing and cannot be downloaded, or Java or Graphviz is missing. 

112 """ 

113 env_jar = os.environ.get("PLANTUML", "") 

114 cfg_jar = cfg.plantuml.get("jar") 

115 version = cfg.plantuml.get("version", DEFAULT_VERSION) 

116 

117 server = urlparse(env_jar).scheme in ("http", "https") 

118 if not server: 

119 find_tool("java", "A Java runtime is needed to run the PlantUML jar, or set PLANTUML to a PlantUML server URL.") 

120 find_graphviz("by PlantUML for all diagrams except sequence diagrams") 

121 

122 if server: 

123 LOG.debug("PlantUML server from the PLANTUML environment variable") 

124 jar = env_jar 

125 elif env_jar and Path(env_jar).is_file(): 

126 LOG.debug("PlantUML jar from the PLANTUML environment variable") 

127 jar = Path(env_jar).resolve() 

128 elif cfg_jar: 

129 LOG.debug("PlantUML jar from plantuml.jar of the configuration") 

130 jar = cfg.path(cfg_jar) 

131 else: 

132 jar = cfg.plantuml_dir / f"plantuml-{version}.jar" 

133 if jar.is_file(): 

134 LOG.debug("PlantUML jar %s downloaded before", version) 

135 else: 

136 prepare_output(cfg.output) 

137 _download(DOWNLOAD_URL.format(version=version), jar) 

138 

139 if isinstance(jar, Path) and not jar.is_file(): 

140 raise TrlcdocError(f"PlantUML jar {jar} not found.") 

141 

142 os.environ["PLANTUML"] = str(jar) 

143 LOG.info("PlantUML: %s", redact_url(str(jar))) 

144 LOG.debug("env: PLANTUML=%s", redact_url(str(jar))) 

145 if isinstance(jar, Path): 

146 if cfg.plantuml.get("picoweb", True): 

147 url = start_picoweb(cfg, jar) 

148 if url is not None: 

149 return url 

150 else: 

151 LOG.debug("No picoweb server: plantuml.picoweb is false, every diagram starts the jar.") 

152 return jar 

153 

154 

155def start_picoweb(cfg: Config, jar: Path) -> str | None: 

156 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

157 """Start the PlantUML jar as local picoweb server and export its URL in the PLANTUML environment variable. 

158 

159 The server runs until stop_picoweb(), which trlcdoc calls when it finishes, and at the latest 

160 when Python exits. If the server doesn't render a diagram within PICOWEB_START_TIMEOUT seconds, 

161 it is stopped and a warning is printed: the jar renders each diagram instead. 

162 

163 Args: 

164 cfg (Config): Project configuration. 

165 jar (Path): The plantuml.jar file. 

166 

167 Returns: 

168 str | None: The server URL, or None if the server is not available. 

169 """ 

170 stop_picoweb() 

171 

172 port = _free_port() 

173 url = f"http://{PICOWEB_HOST}:{port}/plantuml" 

174 cmd = [find_tool("java"), JAVA_HEADLESS, "-jar", str(jar), f"-picoweb:{port}:{PICOWEB_HOST}"] 

175 log_file = cfg.plantuml_dir / "picoweb.log" 

176 prepare_output(cfg.output) 

177 cfg.plantuml_dir.mkdir(parents=True, exist_ok=True) 

178 

179 LOG.info("Starting PlantUML picoweb server %s", url) 

180 LOG.debug(" $ %s (cwd %s, log %s)", command_line(cmd), cfg.root, log_file) 

181 with log_file.open("w", encoding="utf-8") as log: 

182 try: 

183 # The project root is the folder of relative !include paths, as the server gets no file name. 

184 process = subprocess.Popen( 

185 cmd, cwd=cfg.root, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT 

186 ) 

187 except OSError as err: 

188 _warn_no_picoweb(str(err)) 

189 return None 

190 

191 server = PicowebServer(process, url, {name: os.environ.get(name) for name in PICOWEB_ENV_NAMES}) 

192 _running_picoweb.append(server) 

193 atexit.register(stop_picoweb) 

194 server.saved_sigterm = _exit_on_sigterm() 

195 

196 if not _wait_for_picoweb(process, url): 

197 stop_picoweb() 

198 output = log_file.read_text(encoding="utf-8", errors="replace").strip() 

199 _warn_no_picoweb(f"no diagram rendered within {PICOWEB_START_TIMEOUT:g} s. {output}".strip()) 

200 return None 

201 

202 os.environ["PLANTUML"] = url 

203 LOG.debug("env: PLANTUML=%s", url) 

204 for name in NO_PROXY_NAMES: 

205 _add_no_proxy_host(name, PICOWEB_HOST) 

206 LOG.debug("env: %s=%s", name, os.environ[name]) 

207 return url 

208 

209 

210def stop_picoweb() -> None: 

211 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

212 """Stop the picoweb server, if one runs, and restore the environment from before its start. 

213 

214 The server gets PICOWEB_STOP_TIMEOUT seconds to stop, then it is killed. 

215 """ 

216 if not _running_picoweb: 

217 return 

218 server = _running_picoweb.pop() 

219 atexit.unregister(stop_picoweb) 

220 LOG.debug("Stopping PlantUML picoweb server %s", server.url) 

221 

222 if server.process.poll() is None: 

223 server.process.terminate() 

224 try: 

225 server.process.wait(PICOWEB_STOP_TIMEOUT) 

226 except subprocess.TimeoutExpired: 

227 server.process.kill() 

228 server.process.wait() 

229 

230 for name, value in server.saved_env.items(): 

231 if value is None: 

232 os.environ.pop(name, None) 

233 else: 

234 os.environ[name] = value 

235 if server.saved_sigterm is not None: 

236 signal.signal(signal.SIGTERM, server.saved_sigterm) 

237 

238 

239def _add_no_proxy_host(name: str, host: str) -> None: 

240 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

241 """Add a host to a comma separated proxy exception variable, unless it is listed already. 

242 

243 Args: 

244 name (str): Name of the environment variable, e.g. NO_PROXY. 

245 host (str): Host that is reached without proxy. 

246 """ 

247 hosts = [entry.strip() for entry in os.environ.get(name, "").split(",") if entry.strip()] 

248 if host not in hosts: 

249 hosts.append(host) 

250 os.environ[name] = ",".join(hosts) 

251 

252 

253def _free_port() -> int: 

254 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

255 """Get a TCP port on PICOWEB_HOST that is free at the moment. 

256 

257 Returns: 

258 int: The port number chosen by the system. 

259 """ 

260 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: 

261 sock.bind((PICOWEB_HOST, 0)) 

262 return sock.getsockname()[1] 

263 

264 

265def _wait_for_picoweb(process: subprocess.Popen, url: str) -> bool: 

266 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

267 """Wait until the picoweb server renders a diagram. 

268 

269 Args: 

270 process (subprocess.Popen): The Java process of the server. 

271 url (str): Server URL. 

272 

273 Returns: 

274 bool: True if the server rendered the probe diagram, False if it ended or the time is up. 

275 """ 

276 probe_url = f"{url}/svg/{encode_diagram(PICOWEB_PROBE_DIAGRAM)}" 

277 # The probe goes directly to the local server, even if a proxy is configured. 

278 opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) 

279 deadline = time.monotonic() + PICOWEB_START_TIMEOUT 

280 while time.monotonic() < deadline and process.poll() is None: 

281 try: 

282 with opener.open(probe_url, timeout=max(deadline - time.monotonic(), PICOWEB_POLL_INTERVAL)) as response: 

283 return response.status == 200 

284 except OSError: 

285 # Not listening yet. 

286 time.sleep(PICOWEB_POLL_INTERVAL) 

287 return False 

288 

289 

290def _exit_on_sigterm() -> Any: 

291 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

292 """Let SIGTERM end trlcdoc like sys.exit(), so the picoweb server is stopped. 

293 

294 By default, SIGTERM ends Python without running finally blocks and atexit functions, 

295 which would leave the server running. Signal handlers can only be set in the main thread. 

296 

297 Returns: 

298 Any: The previous SIGTERM handler, None if the handler was not replaced. 

299 """ 

300 if threading.current_thread() is not threading.main_thread(): 

301 return None 

302 # Exit code 128 + signal number, as the shell reports a terminated process. 

303 return signal.signal(signal.SIGTERM, lambda signum, _frame: sys.exit(128 + signum)) 

304 

305 

306def _warn_no_picoweb(reason: str) -> None: 

307 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

308 """Warn that the picoweb server is not available and the jar renders each diagram. 

309 

310 Args: 

311 reason (str): Why the server is not available. 

312 """ 

313 LOG.warning( 

314 "Warning: The PlantUML picoweb server is not available, every diagram starts the jar instead. " 

315 "Set plantuml.picoweb to false to skip the server.\n %s", 

316 reason, 

317 ) 

318 

319 

320def java_headless_env() -> dict[str, str]: 

321 # lobster-trace: SwRequirements.sw_req_plantuml 

322 """Get the environment that makes Java run PlantUML headless in the converters. 

323 

324 pyTRLCConverter starts PlantUML with the headless option only on Linux. Windows needs none, 

325 but on macOS each diagram would start the graphical user interface support of Java (Dock icon). 

326 Java reads additional options from JAVA_TOOL_OPTIONS. It reports them on stderr, which 

327 pyTRLCConverter logs as error, so they are only set on macOS. 

328 

329 see also: https://github.com/NewTec-GmbH/pyTRLCConverter/issues/180 

330 

331 Returns: 

332 dict[str, str]: Additional environment variables for the converters, empty except on macOS. 

333 """ 

334 env: dict[str, str] = {} 

335 options = os.environ.get("JAVA_TOOL_OPTIONS", "") 

336 if sys.platform == "darwin" and JAVA_HEADLESS not in options.split(): 

337 env["JAVA_TOOL_OPTIONS"] = f"{options} {JAVA_HEADLESS}".strip() 

338 return env 

339 

340 

341def _download(url: str, target: Path) -> Path: 

342 # lobster-trace: SwRequirements.sw_req_plantuml 

343 """Download a file. 

344 

345 Args: 

346 url (str): Source URL. 

347 target (Path): Destination file. 

348 

349 Returns: 

350 Path: The downloaded file. 

351 

352 Raises: 

353 TrlcdocError: If the download fails. 

354 """ 

355 LOG.info("Downloading %s", url) 

356 target.parent.mkdir(parents=True, exist_ok=True) 

357 partial = target.with_suffix(".part") 

358 try: 

359 urllib.request.urlretrieve(url, partial) 

360 partial.replace(target) 

361 except OSError as err: 

362 partial.unlink(missing_ok=True) 

363 raise TrlcdocError(f"Download of {url} failed: {err}") from err 

364 return target 

365 

366 

367# Main *************************************************************************