1 from __future__
import print_function
5 from Gaudi
import Configuration
10 log = logging.getLogger(__name__)
21 __nonzero__ = __bool__
32 class Property(object):
38 return bytes(self.
value).decode(
'utf-8')
50 self.
lib.py_bootstrap_fsm_configure(self.
ptr))
54 self.
lib.py_bootstrap_fsm_initialize(self.
ptr))
58 self.
lib.py_bootstrap_fsm_start(self.
ptr))
62 self.
lib.py_bootstrap_app_run(self.
ptr, nevt))
66 self.
lib.py_bootstrap_fsm_stop(self.
ptr))
70 self.
lib.py_bootstrap_fsm_finalize(self.
ptr))
74 self.
lib.py_bootstrap_fsm_terminate(self.
ptr))
77 return self.
lib.py_bootstrap_getService(self.
ptr,
82 self.
lib.py_bootstrap_setProperty(self.
ptr,
84 value.encode(
'ascii')))
88 self.
lib.py_bootstrap_getProperty(self.
ptr,
89 name.encode(
'ascii')))
95 from ctypes
import (PyDLL, util, c_void_p, c_bool, c_char_p, c_int,
101 class IInterface_p(c_void_p):
103 return "IInterface_p(0x%x)" % (0
if self.value
is None else 106 self.
log = logging.getLogger(
'BootstrapHelper')
107 libname = util.find_library(
'GaudiKernel')
or 'libGaudiKernel.so' 108 self.
log.debug(
'loading GaudiKernel (%s)', libname)
112 self.
lib = gkl = PyDLL(libname, mode=RTLD_GLOBAL)
115 (
'createApplicationMgr', IInterface_p, []),
116 (
'getService', IInterface_p, [IInterface_p, c_char_p]),
117 (
'setProperty', c_bool, [IInterface_p, c_char_p, c_char_p]),
118 (
'getProperty', c_char_p, [IInterface_p, c_char_p]),
119 (
'addPropertyToCatalogue', c_bool,
120 [IInterface_p, c_char_p, c_char_p, c_char_p]),
121 (
'ROOT_VERSION_CODE', c_int, []),
124 for name, restype, argtypes
in functions:
125 f = getattr(gkl,
'py_bootstrap_%s' % name)
126 f.restype, f.argtypes = restype, argtypes
129 if name
not in self.__class__.__dict__:
130 setattr(self, name, f)
132 for name
in (
'configure',
'initialize',
'start',
'stop',
'finalize',
134 f = getattr(gkl,
'py_bootstrap_fsm_%s' % name)
135 f.restype, f.argtypes = c_bool, [IInterface_p]
136 gkl.py_bootstrap_app_run.restype = c_bool
137 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
139 gkl.py_helper_printAlgsSequences.restype =
None 140 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
143 ptr = self.
lib.py_bootstrap_createApplicationMgr()
148 return self.
lib.py_bootstrap_ROOT_VERSION_CODE()
153 a = root_version_code >> 16 & 0xff
154 b = root_version_code >> 8 & 0xff
155 c = root_version_code & 0xff
164 Helper to convert values to old .opts format. 166 >>> print(toOpt('some "text"')) 168 >>> print(toOpt('first\\nsecond')) 171 >>> print(toOpt({'a': [1, 2, '3']})) 174 if isinstance(value, six.string_types):
175 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
176 elif isinstance(value, dict):
177 return '{{{0}}}'.
format(
', '.join(
179 elif hasattr(value,
'__iter__'):
180 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
187 from Configurables
import ApplicationMgr
189 if "GAUDIAPPNAME" in os.environ:
190 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
191 if "GAUDIAPPVERSION" in os.environ:
192 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
193 self.
log = logging.getLogger(__name__)
202 import multiprocessing
204 from time
import ctime
206 datetime = datetime.replace(
' ',
'_')
207 outfile = open(
'gaudirun-%s.log' % (datetime),
'w')
209 streamhandler = logging.StreamHandler(stream=outfile)
210 console = logging.StreamHandler()
212 formatter = logging.Formatter(
213 "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
215 streamhandler.setFormatter(formatter)
216 console.setFormatter(formatter)
220 self.
log = multiprocessing.log_to_stderr()
221 self.
log.setLevel(logging.INFO)
222 self.
log.name =
'Gaudi/Main.py Logger' 223 self.
log.handlers = []
225 self.
log.addHandler(streamhandler)
226 self.
log.addHandler(console)
227 self.
log.removeHandler(console)
229 self.
log.setLevel = logging.INFO
233 from pprint
import pformat
234 conf_dict = Configuration.configurationDict(all)
235 formatted = pformat(conf_dict)
242 return re.sub(
r'"\n +"',
'', formatted, flags=re.MULTILINE)
245 conf_dict = Configuration.configurationDict(all)
247 names = list(conf_dict.keys())
250 props = list(conf_dict[n].keys())
253 out.append(
'%s.%s = %s;' % (n, p,
toOpt(conf_dict[n][p])))
254 return "\n".join(out)
259 output = open(filename,
'wb')
261 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
264 to_dump[n] = Configuration.allConfigurables[n]
265 pickle.dump(to_dump, output, -1)
269 msg =
'Dumping all configurables and properties' 271 msg +=
' (different from default)' 273 conf_dict = Configuration.configurationDict(all)
281 write = {
".pkl":
lambda filename, all: self.
_writepickle(filename),
282 ".py":
lambda filename, all: open(filename,
"w").write(self.
generatePyOutput(all) +
"\n"),
283 ".opts":
lambda filename, all: open(filename,
"w").write(self.
generateOptsOutput(all) +
"\n"),
285 from os.path
import splitext
286 ext = splitext(filename)[1]
288 write[ext](filename, all)
290 log.error(
"Unknown file type '%s'. Must be any of %r.", ext,
296 def run(self, attach_debugger, ncpus=None):
307 self.
log.info(
'attaching debugger to PID ' + str(os.getpid()))
308 pid = os.spawnvp(os.P_NOWAIT, debugger,
309 [debugger,
'-q',
'python',
317 os.waitpid(pid, os.WNOHANG)
323 from GaudiKernel.Proxy.Configurable
import expandvars
329 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
331 self.
log.debug(
'runSerial: apply options')
332 conf_dict = {
'ApplicationMgr.JobOptionsType':
'"NONE"'}
336 for c
in list(Configurable.allConfigurables.values()):
337 if hasattr(c,
'getValuedProperties'):
338 c.getValuedProperties()
341 c = Configurable.allConfigurables[n]
342 for p, v
in c.getValuedProperties().
items():
345 if hasattr(Configurable,
"PropertyReference")
and type(
346 v) == Configurable.PropertyReference:
352 v =
'"%s"' % v.replace(
'"',
'\\"')
353 elif sys.version_info < (
354 3, )
and type(v) == long:
356 conf_dict[
'{}.{}'.
format(n, p)] = str(v)
359 conf_dict[
'ApplicationMgr.PrintAlgsSequence'] =
'true' 361 if hasattr(Configurable,
"_configurationLocked"):
362 Configurable._configurationLocked =
True 367 self.
log.debug(
'-' * 80)
368 self.
log.debug(
'%s: running in serial mode', __name__)
369 self.
log.debug(
'-' * 80)
376 sysTime =
time() - sysStart
377 self.
log.debug(
'-' * 80)
378 self.
log.debug(
'%s: serial system finished, time taken: %5.4fs',
380 self.
log.debug(
'-' * 80)
388 c = Configurable.allConfigurables
389 self.
log.info(
'-' * 80)
390 self.
log.info(
'%s: Parallel Mode : %i ', __name__, ncpus)
392 (
'platrofm',
' '.join(os.uname())),
393 (
'config', os.environ.get(
'BINARY_TAG')
394 or os.environ.get(
'CMTCONFIG')),
395 (
'app. name', os.environ.get(
'GAUDIAPPNAME')),
396 (
'app. version', os.environ.get(
'GAUDIAPPVERSION')),
398 self.
log.info(
'%s: %30s : %s ', __name__, name, value
401 events = str(c[
'ApplicationMgr'].EvtMax)
403 events =
"Undetermined" 404 self.
log.info(
'%s: Events Specified : %s ', __name__, events)
405 self.
log.info(
'-' * 80)
407 Parall = gpp.Coord(ncpus, c, self.
log)
410 self.
log.info(
'MAIN.PY : received %s from Coordinator' % (sc))
413 sysTime =
time() - sysStart
414 self.
log.name =
'Gaudi/Main.py Logger' 415 self.
log.info(
'-' * 80)
416 self.
log.info(
'%s: parallel system finished, time taken: %5.4fs',
418 self.
log.info(
'-' * 80)
def printAlgsSequences(self)
def run(self, attach_debugger, ncpus=None)
def setupParallelLogging(self)
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
def _writepickle(self, filename)
def generateOptsOutput(self, all=False)
def runParallel(self, ncpus)
def hookDebugger(self, debugger='gdb')
def generatePyOutput(self, all=False)
def __init__(self, ptr, lib)
void py_helper_printAlgsSequences(IInterface *app)
Helper to call printAlgsSequences from Pyhton ctypes.
struct GAUDI_API map
Parametrisation class for map-like implementation.
def getProperty(self, name)
def getService(self, name)
def createApplicationMgr(self)
def create(cls, appType, opts)
def __init__(self, value)
The Application Manager class.
def ROOT_VERSION_CODE(self)
def __init__(self, value)
def printconfig(self, old_format=False, all=False)
def writeconfig(self, filename, all=False)
def setProperty(self, name, value)
def runSerial(self, attach_debugger)