16 from Gaudi
import Configuration
18 log = logging.getLogger(__name__)
29 __nonzero__ = __bool__
40 class Property(object):
46 return bytes(self.
value).decode(
"utf-8")
58 self.
lib.py_bootstrap_fsm_configure(self.
ptr)
63 self.
lib.py_bootstrap_fsm_initialize(self.
ptr)
79 self.
lib.py_bootstrap_fsm_finalize(self.
ptr)
84 self.
lib.py_bootstrap_fsm_terminate(self.
ptr)
88 return self.
lib.py_bootstrap_getService(self.
ptr, name.encode(
"ascii"))
92 self.
lib.py_bootstrap_setProperty(
93 self.
ptr, name.encode(
"ascii"), value.encode(
"ascii")
99 self.
lib.py_bootstrap_getProperty(self.
ptr, name.encode(
"ascii"))
106 self.
lib.py_bootstrap_setOption(
107 self.
ptr, key.encode(
"ascii"), value.encode(
"ascii")
111 from ctypes
import RTLD_GLOBAL, PyDLL, c_bool, c_char_p, c_int, c_void_p, util
116 class IInterface_p(c_void_p):
118 return "IInterface_p(0x%x)" % (0
if self.value
is None else self.value)
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)
153 f = getattr(gkl,
"py_bootstrap_fsm_%s" % name)
154 f.restype, f.argtypes = c_bool, [IInterface_p]
155 gkl.py_bootstrap_app_run.restype = c_bool
156 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
158 gkl.py_helper_printAlgsSequences.restype =
None
159 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
162 ptr = self.
lib.py_bootstrap_createApplicationMgr()
167 return self.
lib.py_bootstrap_ROOT_VERSION_CODE()
172 a = root_version_code >> 16 & 0xFF
173 b = root_version_code >> 8 & 0xFF
174 c = root_version_code & 0xFF
180 Return all options from the old configuration system as a dictionary.
182 If explicit_defaults is true, include default values of unset properties in the dictionary.
184 from itertools
import chain
186 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
196 while count != new_count:
199 new_count = len(needed_conf)
200 for n
in needed_conf:
201 c = Configurable.allConfigurables[n]
202 if hasattr(c,
"getValuedProperties"):
203 c.getValuedProperties()
205 for n
in needed_conf:
206 c = Configurable.allConfigurables[n]
208 chain(c.getDefaultProperties().items(), c.getValuedProperties().items())
210 else c.getValuedProperties().items()
214 if hasattr(Configurable,
"PropertyReference")
and isinstance(
215 v, Configurable.PropertyReference
220 if isinstance(v, str):
222 v =
'"%s"' % v.replace(
'"',
'\\"')
223 elif hasattr(v,
"__opt_value__"):
224 v = v.__opt_value__()
225 old_opts[
".".join((n, p))] = str(v)
232 Return all options from the old and new configuration system as a dictionary.
234 If explicit_defaults is true, include default values of unset properties in the dictionary.
241 opts = GaudiConfig2.all_options(
False)
243 conflicts = [n
for n
in set(opts).intersection(old_opts)
if opts[n] != old_opts[n]]
246 log.error(
"Some properties are set in old and new style configuration")
247 log.warning(
"name: old -> new")
249 log.warning(
"%s: %s -> %s", n, old_opts[n], opts[n])
252 opts.update(old_opts)
254 if explicit_defaults:
258 all_opts.update(GaudiConfig2.all_options(
True))
262 all_opts.update(opts)
270 Helper to convert values to old .opts format.
272 >>> print(toOpt('some "text"'))
274 >>> print(toOpt('first\\nsecond'))
277 >>> print(toOpt({'a': [1, 2, '3']}))
280 if isinstance(value, str):
281 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
282 elif isinstance(value, dict):
286 elif hasattr(value,
"__iter__"):
287 return "[{0}]".
format(
", ".join(
map(toOpt, value)))
294 Helper to parse option strings to Python values.
296 Ideally it should just be "eval", but the string parser of Gaudi
297 is different from the Python one, so we get string options that
298 cannot be just evaluated.
300 >>> print(parseOpt('123'))
302 >>> print(parseOpt('"some\\n\\\\"text\\\\""'))
305 >>> print(parseOpt(''))
312 quoted_string = re.compile(
r'^"(.*)"$', re.DOTALL)
317 m = quoted_string.match(s)
319 return m.group(1).replace(
'\\"',
'"')
325 from Configurables
import ApplicationMgr
328 if os.environ.get(
"GAUDIAPPNAME"):
329 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
330 if os.environ.get(
"GAUDIAPPVERSION"):
331 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
332 self.
log = logging.getLogger(__name__)
341 import multiprocessing
344 from time
import ctime
347 datetime = datetime.replace(
" ",
"_")
348 outfile = open(
"gaudirun-%s.log" % (datetime),
"w")
350 streamhandler = logging.StreamHandler(stream=outfile)
351 console = logging.StreamHandler()
353 formatter = logging.Formatter(
354 "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
357 streamhandler.setFormatter(formatter)
358 console.setFormatter(formatter)
362 self.
log = multiprocessing.log_to_stderr()
363 self.
log.setLevel(logging.INFO)
364 self.
log.name =
"Gaudi/Main.py Logger"
365 self.
log.handlers = []
367 self.
log.addHandler(streamhandler)
368 self.
log.addHandler(console)
369 self.
log.removeHandler(console)
371 self.
log.setLevel = logging.INFO
376 from collections
import defaultdict
377 from pprint
import pformat
379 optDict = defaultdict(dict)
382 c, p = key.rsplit(
".", 1)
383 optDict[c][p] =
parseOpt(allOpts[key])
384 formatted = pformat(dict(optDict))
387 return re.sub(
r'"\n +"',
"", formatted, flags=re.MULTILINE)
400 output = open(filename,
"wb")
402 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
406 to_dump[n] = Configuration.allConfigurables[n]
407 pickle.dump(to_dump, output, -1)
411 msg =
"Dumping all configurables and properties"
413 msg +=
" (different from default)"
425 ".pkl":
lambda filename, all: self.
_writepickle(filename),
426 ".py":
lambda filename, all: open(filename,
"w").write(
429 ".opts":
lambda filename, all: open(filename,
"w").write(
432 ".json":
lambda filename, all: json.dump(
433 getAllOpts(all), open(filename,
"w"), indent=2, sort_keys=
True
439 write[
".yaml"] =
lambda filename, all: yaml.safe_dump(
442 write[
".yml"] = write[
".yaml"]
446 from os.path
import splitext
448 ext = splitext(filename)[1]
450 write[ext](filename, all)
453 "Unknown file type '%s'. Must be any of %r.", ext, sorted(write.keys())
459 def run(self, attach_debugger, ncpus=None):
471 self.
log.info(
"attaching debugger to PID " + str(os.getpid()))
473 os.P_NOWAIT, debugger, [debugger,
"-q",
"python", str(os.getpid())]
482 os.waitpid(pid, os.WNOHANG)
488 from GaudiKernel.Proxy.Configurable
import expandvars
494 from GaudiKernel.Proxy.Configurable
import Configurable
496 self.
log.debug(
"runSerial: apply options")
498 conf_dict[
"ApplicationMgr.JobOptionsType"] =
'"NONE"'
501 conf_dict[
"ApplicationMgr.PrintAlgsSequence"] =
"true"
503 if hasattr(Configurable,
"_configurationLocked"):
504 Configurable._configurationLocked =
True
509 self.
log.debug(
"-" * 80)
510 self.
log.debug(
"%s: running in serial mode", __name__)
511 self.
log.debug(
"-" * 80)
519 sysTime =
time() - sysStart
520 self.
log.debug(
"-" * 80)
522 "%s: serial system finished, time taken: %5.4fs", __name__, sysTime
524 self.
log.debug(
"-" * 80)
533 c = Configurable.allConfigurables
534 self.
log.info(
"-" * 80)
535 self.
log.info(
"%s: Parallel Mode : %i ", __name__, ncpus)
537 (
"platform",
" ".join(os.uname())),
538 (
"config", os.environ.get(
"BINARY_TAG")
or os.environ.get(
"CMTCONFIG")),
539 (
"app. name", os.environ.get(
"GAUDIAPPNAME")),
540 (
"app. version", os.environ.get(
"GAUDIAPPVERSION")),
542 self.
log.info(
"%s: %30s : %s ", __name__, name, value
or "Undefined")
544 events = str(c[
"ApplicationMgr"].EvtMax)
546 events =
"Undetermined"
547 self.
log.info(
"%s: Events Specified : %s ", __name__, events)
548 self.
log.info(
"-" * 80)
550 Parall = gpp.Coord(ncpus, c, self.
log)
553 self.
log.info(
"MAIN.PY : received %s from Coordinator" % (sc))
556 sysTime =
time() - sysStart
557 self.
log.name =
"Gaudi/Main.py Logger"
558 self.
log.info(
"-" * 80)
560 "%s: parallel system finished, time taken: %5.4fs", __name__, sysTime
562 self.
log.info(
"-" * 80)