Skip to content

Commit 2e0a7c6

Browse files
committed
zndraw: proper startup routine, so we don't just hope that zndraw is ready
1 parent 6ede307 commit 2e0a7c6

File tree

1 file changed

+29
-14
lines changed
  • src/python/espressomd

1 file changed

+29
-14
lines changed

src/python/espressomd/zn.py

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import urllib.parse
3030
import typing
3131
import scipy.spatial.transform
32+
import httpx
3233

3334
from espressomd.plugins import ase
3435

@@ -241,12 +242,28 @@ def __init__(self,
241242
# A server is started in a subprocess, and we have to wait for it
242243
if self.SERVER_PORT is None:
243244
print("Starting ZnDraw server, this may take a few seconds")
244-
self.port = port
245-
self._start_server()
246-
time.sleep(10)
245+
Visualizer.SERVER_PORT = port
246+
self.server = subprocess.Popen(
247+
["zndraw", "--no-browser", f"--port={self.SERVER_PORT}"],
248+
stdout=subprocess.DEVNULL,
249+
stderr=subprocess.DEVNULL)
250+
251+
# Check that the server is up
252+
max_wait_iterations = 60
253+
while True:
254+
try:
255+
r = httpx.get(f"{self.url}:{self.SERVER_PORT}/health")
256+
if r.status_code == 200:
257+
break
258+
except httpx.RequestError:
259+
pass
260+
time.sleep(0.5)
261+
max_wait_iterations -= 1
262+
if max_wait_iterations == 0:
263+
raise RuntimeError(
264+
"ZnDraw server did not start within the expected time")
247265

248266
self._start_zndraw()
249-
time.sleep(2)
250267

251268
if vector_field is not None:
252269
self.arrow_config = {'colormap': [[0.5, 0.9, 0.5], [0.0, 0.9, 0.5]],
@@ -265,16 +282,14 @@ def __init__(self,
265282
raise NotImplementedError(
266283
"Only Jupyter notebook is supported at the moment")
267284

268-
def _start_server(self):
269-
"""
270-
Start the ZnDraw server through a subprocess
271-
"""
272-
Visualizer.SERVER_PORT = self.port
273-
274-
self.server = subprocess.Popen(["zndraw", "--no-browser", f"--port={self.port}"],
275-
stdout=subprocess.DEVNULL,
276-
stderr=subprocess.DEVNULL
277-
)
285+
# Wait until the session is ready
286+
max_wait_iterations = 60
287+
while len(self.zndraw.sessions) == 0:
288+
time.sleep(0.5)
289+
max_wait_iterations -= 1
290+
if max_wait_iterations == 0:
291+
raise RuntimeError(
292+
"ZnDraw session did not start within the expected time")
278293

279294
def _start_zndraw(self):
280295
"""

0 commit comments

Comments
 (0)