edouard@3501: #!/usr/bin/env python edouard@3501: # -*- coding: utf-8 -*- edouard@3566: edouard@3566: import os edouard@3501: import sys edouard@3501: import tempfile edouard@3501: import random edouard@3501: import shutil edouard@3714: edouard@3501: from util.ProcessLogger import ProcessLogger edouard@3501: from util.paths import Bpath edouard@3501: kinsamanka@3777: _exec = sys.executable if "darwin" not in sys.platform else sys.executable + 'w' kinsamanka@3777: LocalRuntimeInterpreterPath = os.environ.get("BEREMIZPYTHONPATH", _exec) edouard@3566: edouard@3847: LocalHost = os.environ.get("BEREMIZ_LOCAL_HOST", "127.0.0.1") edouard@3721: edouard@3501: class LocalRuntimeMixin(): edouard@3501: edouard@3539: def __init__(self, log, use_gui=True): edouard@3501: self.local_runtime_log = log edouard@3501: self.local_runtime = None edouard@3501: self.runtime_port = None edouard@3501: self.local_runtime_tmpdir = None edouard@3539: self.use_gui = use_gui edouard@3501: edouard@3539: def StartLocalRuntime(self): edouard@3501: if (self.local_runtime is None) or (self.local_runtime.exitcode is not None): edouard@3501: # create temporary directory for runtime working directory edouard@3501: self.local_runtime_tmpdir = tempfile.mkdtemp() edouard@3501: # choose an arbitrary random port for runtime edouard@3501: self.runtime_port = int(random.random() * 1000) + 61131 edouard@3501: self.local_runtime_log.write(_("Starting local runtime...\n")) edouard@3501: # launch local runtime edouard@3501: self.local_runtime = ProcessLogger( edouard@3911: self.local_runtime_log,[ edouard@3566: LocalRuntimeInterpreterPath, edouard@3501: Bpath("Beremiz_service.py"), edouard@3911: "-p", str(self.runtime_port), edouard@3911: "-i", LocalHost, edouard@3539: {False: "-x 0", True: "-x 1"}[self.use_gui], edouard@3911: self.local_runtime_tmpdir], edouard@3501: no_gui=False, edouard@3501: timeout=500, keyword=self.local_runtime_tmpdir, edouard@3501: cwd=self.local_runtime_tmpdir) edouard@3501: self.local_runtime.spin() edouard@3501: return self.runtime_port edouard@3501: edouard@3501: def KillLocalRuntime(self): edouard@3501: if self.local_runtime is not None: edouard@3501: # shutdown local runtime edouard@3501: self.local_runtime.kill(gently=False) edouard@3501: # clear temp dir edouard@3967: try: edouard@3967: shutil.rmtree(self.local_runtime_tmpdir) edouard@3967: except: edouard@3967: pass edouard@3501: edouard@3501: self.local_runtime = None edouard@3501: