11 from __future__
import print_function
15 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))
64 self.
lib.py_bootstrap_fsm_initialize(self.
ptr))
68 self.
lib.py_bootstrap_fsm_start(self.
ptr))
72 self.
lib.py_bootstrap_app_run(self.
ptr, nevt))
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 from ctypes
import (PyDLL, util, c_void_p, c_bool, c_char_p, c_int,
111 class IInterface_p(c_void_p):
113 return "IInterface_p(0x%x)" % (0
if self.value
is None else 116 self.
log = logging.getLogger(
'BootstrapHelper')
117 libname = util.find_library(
'GaudiKernel')
or 'libGaudiKernel.so' 118 self.
log.debug(
'loading GaudiKernel (%s)', libname)
122 self.
lib = gkl = PyDLL(libname, mode=RTLD_GLOBAL)
125 (
'createApplicationMgr', IInterface_p, []),
126 (
'getService', IInterface_p, [IInterface_p, c_char_p]),
127 (
'setProperty', c_bool, [IInterface_p, c_char_p, c_char_p]),
128 (
'getProperty', c_char_p, [IInterface_p, c_char_p]),
129 (
'addPropertyToCatalogue', c_bool,
130 [IInterface_p, c_char_p, c_char_p, c_char_p]),
131 (
'ROOT_VERSION_CODE', c_int, []),
134 for name, restype, argtypes
in functions:
135 f = getattr(gkl,
'py_bootstrap_%s' % name)
136 f.restype, f.argtypes = restype, argtypes
139 if name
not in self.__class__.__dict__:
140 setattr(self, name, f)
142 for name
in (
'configure',
'initialize',
'start',
'stop',
'finalize',
144 f = getattr(gkl,
'py_bootstrap_fsm_%s' % name)
145 f.restype, f.argtypes = c_bool, [IInterface_p]
146 gkl.py_bootstrap_app_run.restype = c_bool
147 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
149 gkl.py_helper_printAlgsSequences.restype =
None 150 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
153 ptr = self.
lib.py_bootstrap_createApplicationMgr()
158 return self.
lib.py_bootstrap_ROOT_VERSION_CODE()
163 a = root_version_code >> 16 & 0xff
164 b = root_version_code >> 8 & 0xff
165 c = root_version_code & 0xff
170 from itertools
import chain
172 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
181 while count != new_count:
184 new_count = len(needed_conf)
185 for n
in needed_conf:
186 c = Configurable.allConfigurables[n]
187 if hasattr(c,
'getValuedProperties'):
188 c.getValuedProperties()
190 for n
in needed_conf:
191 c = Configurable.allConfigurables[n]
192 items = (chain(c.getDefaultProperties().
items(),
193 c.getValuedProperties().
items())
194 if explicit_defaults
else c.getValuedProperties().
items())
197 if hasattr(Configurable,
"PropertyReference")
and type(
198 v) == Configurable.PropertyReference:
202 if isinstance(v, str):
204 v =
'"%s"' % v.replace(
'"',
'\\"')
205 elif sys.version_info < (3, )
and isinstance(v, long):
207 elif hasattr(v,
'__opt_value__'):
208 v = v.__opt_value__()
209 old_opts[
'.'.join((n, p))] = str(v)
212 opts = GaudiConfig2.all_options(explicit_defaults)
215 n
for n
in set(opts).intersection(old_opts)
if opts[n] != old_opts[n]
219 log.error(
'Some properties are set in old and new style configuration')
220 log.warning(
'name: old -> new')
222 log.warning(
'%s: %s -> %s', n, old_opts[n], opts[n])
225 opts.update(old_opts)
231 Helper to convert values to old .opts format. 233 >>> print(toOpt('some "text"')) 235 >>> print(toOpt('first\\nsecond')) 238 >>> print(toOpt({'a': [1, 2, '3']})) 241 if isinstance(value, six.string_types):
242 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
243 elif isinstance(value, dict):
244 return '{{{0}}}'.
format(
', '.join(
246 elif hasattr(value,
'__iter__'):
247 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
254 Helper to parse option strings to Python values. 256 Ideally it should just be "eval", but the string parser of Gaudi 257 is different from the Python one, so we get string options that 258 cannot be just evaluated. 260 >>> print(parseOpt('123')) 262 >>> print(parseOpt('"some\\n\\\\"text\\\\""')) 265 >>> print(parseOpt('')) 271 quoted_string = re.compile(
r'^"(.*)"$', re.DOTALL)
276 m = quoted_string.match(s)
278 return m.group(1).replace(
'\\"',
'"')
284 from Configurables
import ApplicationMgr
286 if "GAUDIAPPNAME" in os.environ:
287 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
288 if "GAUDIAPPVERSION" in os.environ:
289 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
290 self.
log = logging.getLogger(__name__)
299 import multiprocessing
301 from time
import ctime
303 datetime = datetime.replace(
' ',
'_')
304 outfile = open(
'gaudirun-%s.log' % (datetime),
'w')
306 streamhandler = logging.StreamHandler(stream=outfile)
307 console = logging.StreamHandler()
309 formatter = logging.Formatter(
310 "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
312 streamhandler.setFormatter(formatter)
313 console.setFormatter(formatter)
317 self.
log = multiprocessing.log_to_stderr()
318 self.
log.setLevel(logging.INFO)
319 self.
log.name =
'Gaudi/Main.py Logger' 320 self.
log.handlers = []
322 self.
log.addHandler(streamhandler)
323 self.
log.addHandler(console)
324 self.
log.removeHandler(console)
326 self.
log.setLevel = logging.INFO
330 from pprint
import pformat
331 from collections
import defaultdict
332 optDict = defaultdict(dict)
335 c, p = key.rsplit(
'.', 1)
336 optDict[c][p] =
parseOpt(allOpts[key])
337 formatted = pformat(dict(optDict))
344 return re.sub(
r'"\n +"',
'', formatted, flags=re.MULTILINE)
355 output = open(filename,
'wb')
357 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
360 to_dump[n] = Configuration.allConfigurables[n]
361 pickle.dump(to_dump, output, -1)
365 msg =
'Dumping all configurables and properties' 367 msg +=
' (different from default)' 376 write = {
".pkl":
lambda filename, all: self.
_writepickle(filename),
377 ".py":
lambda filename, all: open(filename,
"w").write(self.
generatePyOutput(all) +
"\n"),
378 ".opts":
lambda filename, all: open(filename,
"w").write(self.
generateOptsOutput(all) +
"\n"),
380 from os.path
import splitext
381 ext = splitext(filename)[1]
383 write[ext](filename, all)
385 log.error(
"Unknown file type '%s'. Must be any of %r.", ext,
391 def run(self, attach_debugger, ncpus=None):
402 self.
log.info(
'attaching debugger to PID ' + str(os.getpid()))
403 pid = os.spawnvp(os.P_NOWAIT, debugger,
404 [debugger,
'-q',
'python',
412 os.waitpid(pid, os.WNOHANG)
418 from GaudiKernel.Proxy.Configurable
import expandvars
424 from GaudiKernel.Proxy.Configurable
import Configurable
426 self.
log.debug(
'runSerial: apply options')
428 conf_dict[
'ApplicationMgr.JobOptionsType'] =
'"NONE"' 431 conf_dict[
'ApplicationMgr.PrintAlgsSequence'] =
'true' 433 if hasattr(Configurable,
"_configurationLocked"):
434 Configurable._configurationLocked =
True 439 self.
log.debug(
'-' * 80)
440 self.
log.debug(
'%s: running in serial mode', __name__)
441 self.
log.debug(
'-' * 80)
448 sysTime =
time() - sysStart
449 self.
log.debug(
'-' * 80)
450 self.
log.debug(
'%s: serial system finished, time taken: %5.4fs',
452 self.
log.debug(
'-' * 80)
460 c = Configurable.allConfigurables
461 self.
log.info(
'-' * 80)
462 self.
log.info(
'%s: Parallel Mode : %i ', __name__, ncpus)
464 (
'platrofm',
' '.join(os.uname())),
465 (
'config', os.environ.get(
'BINARY_TAG')
466 or os.environ.get(
'CMTCONFIG')),
467 (
'app. name', os.environ.get(
'GAUDIAPPNAME')),
468 (
'app. version', os.environ.get(
'GAUDIAPPVERSION')),
470 self.
log.info(
'%s: %30s : %s ', __name__, name, value
473 events = str(c[
'ApplicationMgr'].EvtMax)
475 events =
"Undetermined" 476 self.
log.info(
'%s: Events Specified : %s ', __name__, events)
477 self.
log.info(
'-' * 80)
479 Parall = gpp.Coord(ncpus, c, self.
log)
482 self.
log.info(
'MAIN.PY : received %s from Coordinator' % (sc))
485 sysTime =
time() - sysStart
486 self.
log.name =
'Gaudi/Main.py Logger' 487 self.
log.info(
'-' * 80)
488 self.
log.info(
'%s: parallel system finished, time taken: %5.4fs',
490 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 getAllOpts(explicit_defaults=False)
def setProperty(self, name, value)
def runSerial(self, attach_debugger)