11 from __future__
import print_function
15 from Gaudi
import Configuration
20 log = logging.getLogger(__name__)
31 __nonzero__ = __bool__
48 return bytes(self.
value).decode(
'utf-8')
60 self.
lib.py_bootstrap_fsm_configure(self.
ptr))
64 self.
lib.py_bootstrap_fsm_initialize(self.
ptr))
68 self.
lib.py_bootstrap_fsm_start(self.
ptr))
76 self.
lib.py_bootstrap_fsm_stop(self.
ptr))
80 self.
lib.py_bootstrap_fsm_finalize(self.
ptr))
84 self.
lib.py_bootstrap_fsm_terminate(self.
ptr))
87 return self.
lib.py_bootstrap_getService(self.
ptr,
92 self.
lib.py_bootstrap_setProperty(self.
ptr,
94 value.encode(
'ascii')))
98 self.
lib.py_bootstrap_getProperty(self.
ptr,
99 name.encode(
'ascii')))
105 self.
lib.py_bootstrap_setOption(self.
ptr, key.encode(
'ascii'),
106 value.encode(
'ascii'))
109 from ctypes
import (PyDLL, util, c_void_p, c_bool, c_char_p, c_int,
115 class IInterface_p(c_void_p):
117 return "IInterface_p(0x%x)" % (0
if self.value
is None else
120 self.
log = logging.getLogger(
'BootstrapHelper')
121 libname = util.find_library(
'GaudiKernel')
or 'libGaudiKernel.so'
122 self.
log.debug(
'loading GaudiKernel (%s)', libname)
126 self.
lib = gkl = PyDLL(libname, mode=RTLD_GLOBAL)
129 (
'createApplicationMgr', IInterface_p, []),
130 (
'getService', IInterface_p, [IInterface_p, c_char_p]),
131 (
'setProperty', c_bool, [IInterface_p, c_char_p, c_char_p]),
132 (
'getProperty', c_char_p, [IInterface_p, c_char_p]),
133 (
'setOption',
None, [IInterface_p, c_char_p, c_char_p]),
134 (
'ROOT_VERSION_CODE', c_int, []),
137 for name, restype, argtypes
in functions:
138 f = getattr(gkl,
'py_bootstrap_%s' % name)
139 f.restype, f.argtypes = restype, argtypes
142 if name
not in self.__class__.__dict__:
143 setattr(self, name, f)
145 for name
in (
'configure',
'initialize',
'start',
'stop',
'finalize',
147 f = getattr(gkl,
'py_bootstrap_fsm_%s' % name)
148 f.restype, f.argtypes = c_bool, [IInterface_p]
149 gkl.py_bootstrap_app_run.restype = c_bool
150 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
152 gkl.py_helper_printAlgsSequences.restype =
None
153 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
156 ptr = self.
lib.py_bootstrap_createApplicationMgr()
161 return self.
lib.py_bootstrap_ROOT_VERSION_CODE()
166 a = root_version_code >> 16 & 0xff
167 b = root_version_code >> 8 & 0xff
168 c = root_version_code & 0xff
174 Return all options from the old configuration system as a dictionary.
176 If explicit_defaults is true, include default values of unset properties in the dictionary.
178 from itertools
import chain
179 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
189 while count != new_count:
192 new_count = len(needed_conf)
193 for n
in needed_conf:
194 c = Configurable.allConfigurables[n]
195 if hasattr(c,
'getValuedProperties'):
196 c.getValuedProperties()
198 for n
in needed_conf:
199 c = Configurable.allConfigurables[n]
200 items = (chain(c.getDefaultProperties().
items(),
201 c.getValuedProperties().
items())
202 if explicit_defaults
else c.getValuedProperties().
items())
205 if hasattr(Configurable,
"PropertyReference")
and type(
206 v) == Configurable.PropertyReference:
210 if isinstance(v, str):
212 v =
'"%s"' % v.replace(
'"',
'\\"')
213 elif sys.version_info < (3, )
and isinstance(v, long):
215 elif hasattr(v,
'__opt_value__'):
216 v = v.__opt_value__()
217 old_opts[
'.'.join((n, p))] = str(v)
224 Return all options from the old and configuration system as a dictionary.
226 If explicit_defaults is true, include default values of unset properties in the dictionary.
232 opts = GaudiConfig2.all_options(
False)
235 n
for n
in set(opts).intersection(old_opts)
if opts[n] != old_opts[n]
239 log.error(
'Some properties are set in old and new style configuration')
240 log.warning(
'name: old -> new')
242 log.warning(
'%s: %s -> %s', n, old_opts[n], opts[n])
245 opts.update(old_opts)
247 if explicit_defaults:
251 all_opts.update(GaudiConfig2.all_options(
True))
255 all_opts.update(opts)
263 Helper to convert values to old .opts format.
265 >>> print(toOpt('some "text"'))
267 >>> print(toOpt('first\\nsecond'))
270 >>> print(toOpt({'a': [1, 2, '3']}))
273 if isinstance(value, six.string_types):
274 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
275 elif isinstance(value, dict):
276 return '{{{0}}}'.
format(
', '.join(
278 elif hasattr(value,
'__iter__'):
279 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
286 Helper to parse option strings to Python values.
288 Ideally it should just be "eval", but the string parser of Gaudi
289 is different from the Python one, so we get string options that
290 cannot be just evaluated.
292 >>> print(parseOpt('123'))
294 >>> print(parseOpt('"some\\n\\\\"text\\\\""'))
297 >>> print(parseOpt(''))
303 quoted_string = re.compile(
r'^"(.*)"$', re.DOTALL)
308 m = quoted_string.match(s)
310 return m.group(1).replace(
'\\"',
'"')
316 from Configurables
import ApplicationMgr
318 if "GAUDIAPPNAME" in os.environ:
319 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
320 if "GAUDIAPPVERSION" in os.environ:
321 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
322 self.
log = logging.getLogger(__name__)
331 import multiprocessing
333 from time
import ctime
335 datetime = datetime.replace(
' ',
'_')
336 outfile = open(
'gaudirun-%s.log' % (datetime),
'w')
338 streamhandler = logging.StreamHandler(stream=outfile)
339 console = logging.StreamHandler()
341 formatter = logging.Formatter(
342 "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
344 streamhandler.setFormatter(formatter)
345 console.setFormatter(formatter)
349 self.
log = multiprocessing.log_to_stderr()
350 self.
log.setLevel(logging.INFO)
351 self.
log.name =
'Gaudi/Main.py Logger'
352 self.
log.handlers = []
354 self.
log.addHandler(streamhandler)
355 self.
log.addHandler(console)
356 self.
log.removeHandler(console)
358 self.
log.setLevel = logging.INFO
362 from pprint
import pformat
363 from collections
import defaultdict
364 optDict = defaultdict(dict)
367 c, p = key.rsplit(
'.', 1)
368 optDict[c][p] =
parseOpt(allOpts[key])
369 formatted = pformat(dict(optDict))
376 return re.sub(
r'"\n +"',
'', formatted, flags=re.MULTILINE)
387 output = open(filename,
'wb')
389 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
392 to_dump[n] = Configuration.allConfigurables[n]
393 pickle.dump(to_dump, output, -1)
397 msg =
'Dumping all configurables and properties'
399 msg +=
' (different from default)'
408 write = {
".pkl":
lambda filename, all: self.
_writepickle(filename),
409 ".py":
lambda filename, all: open(filename,
"w").write(self.
generatePyOutput(all) +
"\n"),
410 ".opts":
lambda filename, all: open(filename,
"w").write(self.
generateOptsOutput(all) +
"\n"),
412 from os.path
import splitext
413 ext = splitext(filename)[1]
415 write[ext](filename, all)
417 log.error(
"Unknown file type '%s'. Must be any of %r.", ext,
423 def run(self, attach_debugger, ncpus=None):
434 self.
log.info(
'attaching debugger to PID ' + str(os.getpid()))
435 pid = os.spawnvp(os.P_NOWAIT, debugger,
436 [debugger,
'-q',
'python',
444 os.waitpid(pid, os.WNOHANG)
450 from GaudiKernel.Proxy.Configurable
import expandvars
456 from GaudiKernel.Proxy.Configurable
import Configurable
458 self.
log.debug(
'runSerial: apply options')
460 conf_dict[
'ApplicationMgr.JobOptionsType'] =
'"NONE"'
463 conf_dict[
'ApplicationMgr.PrintAlgsSequence'] =
'true'
465 if hasattr(Configurable,
"_configurationLocked"):
466 Configurable._configurationLocked =
True
471 self.
log.debug(
'-' * 80)
472 self.
log.debug(
'%s: running in serial mode', __name__)
473 self.
log.debug(
'-' * 80)
480 sysTime =
time() - sysStart
481 self.
log.debug(
'-' * 80)
482 self.
log.debug(
'%s: serial system finished, time taken: %5.4fs',
484 self.
log.debug(
'-' * 80)
492 c = Configurable.allConfigurables
493 self.
log.info(
'-' * 80)
494 self.
log.info(
'%s: Parallel Mode : %i ', __name__, ncpus)
496 (
'platform',
' '.join(os.uname())),
497 (
'config', os.environ.get(
'BINARY_TAG')
498 or os.environ.get(
'CMTCONFIG')),
499 (
'app. name', os.environ.get(
'GAUDIAPPNAME')),
500 (
'app. version', os.environ.get(
'GAUDIAPPVERSION')),
502 self.
log.info(
'%s: %30s : %s ', __name__, name, value
505 events = str(c[
'ApplicationMgr'].EvtMax)
507 events =
"Undetermined"
508 self.
log.info(
'%s: Events Specified : %s ', __name__, events)
509 self.
log.info(
'-' * 80)
511 Parall = gpp.Coord(ncpus, c, self.
log)
514 self.
log.info(
'MAIN.PY : received %s from Coordinator' % (sc))
517 sysTime =
time() - sysStart
518 self.
log.name =
'Gaudi/Main.py Logger'
519 self.
log.info(
'-' * 80)
520 self.
log.info(
'%s: parallel system finished, time taken: %5.4fs',
522 self.
log.info(
'-' * 80)