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()
217 hasattr(Configurable,
"PropertyReference")
218 and type(v) == Configurable.PropertyReference
223 if isinstance(v, str):
225 v =
'"%s"' % v.replace(
'"',
'\\"')
226 elif hasattr(v,
"__opt_value__"):
227 v = v.__opt_value__()
228 old_opts[
".".join((n, p))] = str(v)
235 Return all options from the old and new configuration system as a dictionary.
237 If explicit_defaults is true, include default values of unset properties in the dictionary.
244 opts = GaudiConfig2.all_options(
False)
246 conflicts = [n
for n
in set(opts).intersection(old_opts)
if opts[n] != old_opts[n]]
249 log.error(
"Some properties are set in old and new style configuration")
250 log.warning(
"name: old -> new")
252 log.warning(
"%s: %s -> %s", n, old_opts[n], opts[n])
255 opts.update(old_opts)
257 if explicit_defaults:
261 all_opts.update(GaudiConfig2.all_options(
True))
265 all_opts.update(opts)
273 Helper to convert values to old .opts format.
275 >>> print(toOpt('some "text"'))
277 >>> print(toOpt('first\\nsecond'))
280 >>> print(toOpt({'a': [1, 2, '3']}))
283 if isinstance(value, six.string_types):
284 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
285 elif isinstance(value, dict):
289 elif hasattr(value,
"__iter__"):
290 return "[{0}]".
format(
", ".join(
map(toOpt, value)))
297 Helper to parse option strings to Python values.
299 Ideally it should just be "eval", but the string parser of Gaudi
300 is different from the Python one, so we get string options that
301 cannot be just evaluated.
303 >>> print(parseOpt('123'))
305 >>> print(parseOpt('"some\\n\\\\"text\\\\""'))
308 >>> print(parseOpt(''))
315 quoted_string = re.compile(
r'^"(.*)"$', re.DOTALL)
320 m = quoted_string.match(s)
322 return m.group(1).replace(
'\\"',
'"')
328 from Configurables
import ApplicationMgr
331 if os.environ.get(
"GAUDIAPPNAME"):
332 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
333 if os.environ.get(
"GAUDIAPPVERSION"):
334 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
335 self.
log = logging.getLogger(__name__)
344 import multiprocessing
347 from time
import ctime
350 datetime = datetime.replace(
" ",
"_")
351 outfile = open(
"gaudirun-%s.log" % (datetime),
"w")
353 streamhandler = logging.StreamHandler(stream=outfile)
354 console = logging.StreamHandler()
356 formatter = logging.Formatter(
357 "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
360 streamhandler.setFormatter(formatter)
361 console.setFormatter(formatter)
365 self.
log = multiprocessing.log_to_stderr()
366 self.
log.setLevel(logging.INFO)
367 self.
log.name =
"Gaudi/Main.py Logger"
368 self.
log.handlers = []
370 self.
log.addHandler(streamhandler)
371 self.
log.addHandler(console)
372 self.
log.removeHandler(console)
374 self.
log.setLevel = logging.INFO
378 from collections
import defaultdict
379 from pprint
import pformat
381 optDict = defaultdict(dict)
384 c, p = key.rsplit(
".", 1)
385 optDict[c][p] =
parseOpt(allOpts[key])
386 formatted = pformat(dict(optDict))
394 return re.sub(
r'"\n +"',
"", formatted, flags=re.MULTILINE)
407 output = open(filename,
"wb")
409 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
413 to_dump[n] = Configuration.allConfigurables[n]
414 pickle.dump(to_dump, output, -1)
418 msg =
"Dumping all configurables and properties"
420 msg +=
" (different from default)"
432 ".pkl":
lambda filename, all: self.
_writepickle(filename),
433 ".py":
lambda filename, all: open(filename,
"w").write(
436 ".opts":
lambda filename, all: open(filename,
"w").write(
439 ".json":
lambda filename, all: json.dump(
440 getAllOpts(all), open(filename,
"w"), indent=2, sort_keys=
True
446 write[
".yaml"] =
lambda filename, all: yaml.safe_dump(
449 write[
".yml"] = write[
".yaml"]
453 from os.path
import splitext
455 ext = splitext(filename)[1]
457 write[ext](filename, all)
460 "Unknown file type '%s'. Must be any of %r.", ext, sorted(write.keys())
466 def run(self, attach_debugger, ncpus=None):
478 self.
log.info(
"attaching debugger to PID " + str(os.getpid()))
480 os.P_NOWAIT, debugger, [debugger,
"-q",
"python", str(os.getpid())]
489 os.waitpid(pid, os.WNOHANG)
495 from GaudiKernel.Proxy.Configurable
import expandvars
501 from GaudiKernel.Proxy.Configurable
import Configurable
503 self.
log.debug(
"runSerial: apply options")
505 conf_dict[
"ApplicationMgr.JobOptionsType"] =
'"NONE"'
508 conf_dict[
"ApplicationMgr.PrintAlgsSequence"] =
"true"
510 if hasattr(Configurable,
"_configurationLocked"):
511 Configurable._configurationLocked =
True
516 self.
log.debug(
"-" * 80)
517 self.
log.debug(
"%s: running in serial mode", __name__)
518 self.
log.debug(
"-" * 80)
526 sysTime =
time() - sysStart
527 self.
log.debug(
"-" * 80)
529 "%s: serial system finished, time taken: %5.4fs", __name__, sysTime
531 self.
log.debug(
"-" * 80)
540 c = Configurable.allConfigurables
541 self.
log.info(
"-" * 80)
542 self.
log.info(
"%s: Parallel Mode : %i ", __name__, ncpus)
544 (
"platform",
" ".join(os.uname())),
545 (
"config", os.environ.get(
"BINARY_TAG")
or os.environ.get(
"CMTCONFIG")),
546 (
"app. name", os.environ.get(
"GAUDIAPPNAME")),
547 (
"app. version", os.environ.get(
"GAUDIAPPVERSION")),
549 self.
log.info(
"%s: %30s : %s ", __name__, name, value
or "Undefined")
551 events = str(c[
"ApplicationMgr"].EvtMax)
553 events =
"Undetermined"
554 self.
log.info(
"%s: Events Specified : %s ", __name__, events)
555 self.
log.info(
"-" * 80)
557 Parall = gpp.Coord(ncpus, c, self.
log)
560 self.
log.info(
"MAIN.PY : received %s from Coordinator" % (sc))
563 sysTime =
time() - sysStart
564 self.
log.name =
"Gaudi/Main.py Logger"
565 self.
log.info(
"-" * 80)
567 "%s: parallel system finished, time taken: %5.4fs", __name__, sysTime
569 self.
log.info(
"-" * 80)