18 from Gaudi
import Configuration
20 log = logging.getLogger(__name__)
31 __nonzero__ = __bool__
42 class Property(object):
48 return bytes(self.
value).decode(
"utf-8")
60 self.
lib.py_bootstrap_fsm_configure(self.
ptr)
65 self.
lib.py_bootstrap_fsm_initialize(self.
ptr)
81 self.
lib.py_bootstrap_fsm_finalize(self.
ptr)
86 self.
lib.py_bootstrap_fsm_terminate(self.
ptr)
90 return self.
lib.py_bootstrap_getService(self.
ptr, name.encode(
"ascii"))
94 self.
lib.py_bootstrap_setProperty(
95 self.
ptr, name.encode(
"ascii"), value.encode(
"ascii")
101 self.
lib.py_bootstrap_getProperty(self.
ptr, name.encode(
"ascii"))
108 self.
lib.py_bootstrap_setOption(
109 self.
ptr, key.encode(
"ascii"), value.encode(
"ascii")
113 from ctypes
import RTLD_GLOBAL, PyDLL, c_bool, c_char_p, c_int, c_void_p, util
118 class IInterface_p(c_void_p):
120 return "IInterface_p(0x%x)" % (0
if self.value
is None else self.value)
122 self.
log = logging.getLogger(
"BootstrapHelper")
123 libname = util.find_library(
"GaudiKernel")
or "libGaudiKernel.so"
124 self.
log.debug(
"loading GaudiKernel (%s)", libname)
128 self.
lib = gkl = PyDLL(libname, mode=RTLD_GLOBAL)
131 (
"createApplicationMgr", IInterface_p, []),
132 (
"getService", IInterface_p, [IInterface_p, c_char_p]),
133 (
"setProperty", c_bool, [IInterface_p, c_char_p, c_char_p]),
134 (
"getProperty", c_char_p, [IInterface_p, c_char_p]),
135 (
"setOption",
None, [IInterface_p, c_char_p, c_char_p]),
136 (
"ROOT_VERSION_CODE", c_int, []),
139 for name, restype, argtypes
in functions:
140 f = getattr(gkl,
"py_bootstrap_%s" % name)
141 f.restype, f.argtypes = restype, argtypes
144 if name
not in self.__class__.__dict__:
145 setattr(self, name, f)
155 f = getattr(gkl,
"py_bootstrap_fsm_%s" % name)
156 f.restype, f.argtypes = c_bool, [IInterface_p]
157 gkl.py_bootstrap_app_run.restype = c_bool
158 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
160 gkl.py_helper_printAlgsSequences.restype =
None
161 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
164 ptr = self.
lib.py_bootstrap_createApplicationMgr()
169 return self.
lib.py_bootstrap_ROOT_VERSION_CODE()
174 a = root_version_code >> 16 & 0xFF
175 b = root_version_code >> 8 & 0xFF
176 c = root_version_code & 0xFF
182 Return all options from the old configuration system as a dictionary.
184 If explicit_defaults is true, include default values of unset properties in the dictionary.
186 from itertools
import chain
188 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
198 while count != new_count:
201 new_count = len(needed_conf)
202 for n
in needed_conf:
203 c = Configurable.allConfigurables[n]
204 if hasattr(c,
"getValuedProperties"):
205 c.getValuedProperties()
207 for n
in needed_conf:
208 c = Configurable.allConfigurables[n]
210 chain(c.getDefaultProperties().
items(), c.getValuedProperties().
items())
212 else c.getValuedProperties().
items()
216 if hasattr(Configurable,
"PropertyReference")
and isinstance(
217 v, Configurable.PropertyReference
222 if isinstance(v, str):
224 v =
'"%s"' % v.replace(
'"',
'\\"')
225 elif hasattr(v,
"__opt_value__"):
226 v = v.__opt_value__()
227 old_opts[
".".join((n, p))] = str(v)
234 Return all options from the old and new configuration system as a dictionary.
236 If explicit_defaults is true, include default values of unset properties in the dictionary.
243 opts = GaudiConfig2.all_options(
False)
245 conflicts = [n
for n
in set(opts).intersection(old_opts)
if opts[n] != old_opts[n]]
248 log.error(
"Some properties are set in old and new style configuration")
249 log.warning(
"name: old -> new")
251 log.warning(
"%s: %s -> %s", n, old_opts[n], opts[n])
254 opts.update(old_opts)
256 if explicit_defaults:
260 all_opts.update(GaudiConfig2.all_options(
True))
264 all_opts.update(opts)
272 Helper to convert values to old .opts format.
274 >>> print(toOpt('some "text"'))
276 >>> print(toOpt('first\\nsecond'))
279 >>> print(toOpt({'a': [1, 2, '3']}))
282 if isinstance(value, six.string_types):
283 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
284 elif isinstance(value, dict):
288 elif hasattr(value,
"__iter__"):
289 return "[{0}]".
format(
", ".join(
map(toOpt, value)))
296 Helper to parse option strings to Python values.
298 Ideally it should just be "eval", but the string parser of Gaudi
299 is different from the Python one, so we get string options that
300 cannot be just evaluated.
302 >>> print(parseOpt('123'))
304 >>> print(parseOpt('"some\\n\\\\"text\\\\""'))
307 >>> print(parseOpt(''))
314 quoted_string = re.compile(
r'^"(.*)"$', re.DOTALL)
319 m = quoted_string.match(s)
321 return m.group(1).replace(
'\\"',
'"')
327 from Configurables
import ApplicationMgr
330 if os.environ.get(
"GAUDIAPPNAME"):
331 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
332 if os.environ.get(
"GAUDIAPPVERSION"):
333 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
334 self.
log = logging.getLogger(__name__)
343 import multiprocessing
346 from time
import ctime
349 datetime = datetime.replace(
" ",
"_")
350 outfile = open(
"gaudirun-%s.log" % (datetime),
"w")
352 streamhandler = logging.StreamHandler(stream=outfile)
353 console = logging.StreamHandler()
355 formatter = logging.Formatter(
356 "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
359 streamhandler.setFormatter(formatter)
360 console.setFormatter(formatter)
364 self.
log = multiprocessing.log_to_stderr()
365 self.
log.setLevel(logging.INFO)
366 self.
log.name =
"Gaudi/Main.py Logger"
367 self.
log.handlers = []
369 self.
log.addHandler(streamhandler)
370 self.
log.addHandler(console)
371 self.
log.removeHandler(console)
373 self.
log.setLevel = logging.INFO
377 from collections
import defaultdict
378 from pprint
import pformat
380 optDict = defaultdict(dict)
383 c, p = key.rsplit(
".", 1)
384 optDict[c][p] =
parseOpt(allOpts[key])
385 formatted = pformat(dict(optDict))
393 return re.sub(
r'"\n +"',
"", formatted, flags=re.MULTILINE)
406 output = open(filename,
"wb")
408 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
412 to_dump[n] = Configuration.allConfigurables[n]
413 pickle.dump(to_dump, output, -1)
417 msg =
"Dumping all configurables and properties"
419 msg +=
" (different from default)"
431 ".pkl":
lambda filename, all: self.
_writepickle(filename),
432 ".py":
lambda filename, all: open(filename,
"w").write(
435 ".opts":
lambda filename, all: open(filename,
"w").write(
438 ".json":
lambda filename, all: json.dump(
439 getAllOpts(all), open(filename,
"w"), indent=2, sort_keys=
True
445 write[
".yaml"] =
lambda filename, all: yaml.safe_dump(
448 write[
".yml"] = write[
".yaml"]
452 from os.path
import splitext
454 ext = splitext(filename)[1]
456 write[ext](filename, all)
459 "Unknown file type '%s'. Must be any of %r.", ext, sorted(write.keys())
465 def run(self, attach_debugger, ncpus=None):
477 self.
log.info(
"attaching debugger to PID " + str(os.getpid()))
479 os.P_NOWAIT, debugger, [debugger,
"-q",
"python", str(os.getpid())]
488 os.waitpid(pid, os.WNOHANG)
494 from GaudiKernel.Proxy.Configurable
import expandvars
500 from GaudiKernel.Proxy.Configurable
import Configurable
502 self.
log.debug(
"runSerial: apply options")
504 conf_dict[
"ApplicationMgr.JobOptionsType"] =
'"NONE"'
507 conf_dict[
"ApplicationMgr.PrintAlgsSequence"] =
"true"
509 if hasattr(Configurable,
"_configurationLocked"):
510 Configurable._configurationLocked =
True
515 self.
log.debug(
"-" * 80)
516 self.
log.debug(
"%s: running in serial mode", __name__)
517 self.
log.debug(
"-" * 80)
525 sysTime =
time() - sysStart
526 self.
log.debug(
"-" * 80)
528 "%s: serial system finished, time taken: %5.4fs", __name__, sysTime
530 self.
log.debug(
"-" * 80)
539 c = Configurable.allConfigurables
540 self.
log.info(
"-" * 80)
541 self.
log.info(
"%s: Parallel Mode : %i ", __name__, ncpus)
543 (
"platform",
" ".join(os.uname())),
544 (
"config", os.environ.get(
"BINARY_TAG")
or os.environ.get(
"CMTCONFIG")),
545 (
"app. name", os.environ.get(
"GAUDIAPPNAME")),
546 (
"app. version", os.environ.get(
"GAUDIAPPVERSION")),
548 self.
log.info(
"%s: %30s : %s ", __name__, name, value
or "Undefined")
550 events = str(c[
"ApplicationMgr"].EvtMax)
552 events =
"Undetermined"
553 self.
log.info(
"%s: Events Specified : %s ", __name__, events)
554 self.
log.info(
"-" * 80)
556 Parall = gpp.Coord(ncpus, c, self.
log)
559 self.
log.info(
"MAIN.PY : received %s from Coordinator" % (sc))
562 sysTime =
time() - sysStart
563 self.
log.name =
"Gaudi/Main.py Logger"
564 self.
log.info(
"-" * 80)
566 "%s: parallel system finished, time taken: %5.4fs", __name__, sysTime
568 self.
log.info(
"-" * 80)