4 from Gaudi
import Configuration
7 log = logging.getLogger(__name__)
17 __nonzero__ = __bool__
28 class Property(object):
33 return str(self.
value)
64 return self.lib.py_bootstrap_getService(self.
ptr, name)
73 return self.lib.py_helper_printAlgsSequences(self.
ptr)
76 from ctypes
import (PyDLL, util, c_void_p, c_bool, c_char_p, c_int,
81 class IInterface_p(c_void_p):
83 return "IInterface_p(0x%x)" % (0
if self.value
is None 85 self.
log = logging.getLogger(
'BootstrapHelper')
86 libname = util.find_library(
'GaudiKernel')
or 'libGaudiKernel.so' 87 self.log.debug(
'loading GaudiKernel (%s)', libname)
91 self.
lib = gkl = PyDLL(libname, mode=RTLD_GLOBAL)
93 functions = [(
'createApplicationMgr', IInterface_p, []),
94 (
'getService', IInterface_p, [IInterface_p, c_char_p]),
95 (
'setProperty', c_bool, [
96 IInterface_p, c_char_p, c_char_p]),
97 (
'getProperty', c_char_p, [IInterface_p, c_char_p]),
98 (
'addPropertyToCatalogue', c_bool, [
99 IInterface_p, c_char_p, c_char_p, c_char_p]),
100 (
'ROOT_VERSION_CODE', c_int, []),
103 for name, restype, argtypes
in functions:
104 f = getattr(gkl,
'py_bootstrap_%s' % name)
105 f.restype, f.argtypes = restype, argtypes
108 if name
not in self.__class__.__dict__:
109 setattr(self, name, f)
111 for name
in (
'configure',
'initialize',
'start',
112 'stop',
'finalize',
'terminate'):
113 f = getattr(gkl,
'py_bootstrap_fsm_%s' % name)
114 f.restype, f.argtypes = c_bool, [IInterface_p]
115 gkl.py_bootstrap_app_run.restype = c_bool
116 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
118 gkl.py_helper_printAlgsSequences.restype =
None 119 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
122 ptr = self.lib.py_bootstrap_createApplicationMgr()
127 return self.lib.py_bootstrap_ROOT_VERSION_CODE()
132 a = root_version_code >> 16 & 0xff
133 b = root_version_code >> 8 & 0xff
134 c = root_version_code & 0xff
143 Helper to convert values to old .opts format. 145 >>> print toOpt('some "text"') 147 >>> print toOpt('first\\nsecond') 150 >>> print toOpt({'a': [1, 2, '3']}) 153 if isinstance(value, basestring):
154 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
155 elif isinstance(value, dict):
157 for k, v
in value.iteritems()))
158 elif hasattr(value,
'__iter__'):
159 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
169 from Configurables
import ApplicationMgr
171 if "GAUDIAPPNAME" in os.environ:
172 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
173 if "GAUDIAPPVERSION" in os.environ:
174 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
175 self.
log = logging.getLogger(__name__)
183 import multiprocessing
185 from time
import ctime
187 datetime = datetime.replace(
' ',
'_')
188 outfile = open(
'gaudirun-%s.log' % (datetime),
'w')
190 streamhandler = logging.StreamHandler(stream=outfile)
191 console = logging.StreamHandler()
193 formatter = logging.Formatter(
194 "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
196 streamhandler.setFormatter(formatter)
197 console.setFormatter(formatter)
201 self.
log = multiprocessing.log_to_stderr()
202 self.log.setLevel(logging.INFO)
203 self.log.name =
'Gaudi/Main.py Logger' 204 self.log.handlers = []
206 self.log.addHandler(streamhandler)
207 self.log.addHandler(console)
208 self.log.removeHandler(console)
210 self.log.setLevel = logging.INFO
214 from pprint
import pformat
215 conf_dict = Configuration.configurationDict(all)
216 return pformat(conf_dict)
219 from pprint
import pformat
220 conf_dict = Configuration.configurationDict(all)
222 names = conf_dict.keys()
225 props = conf_dict[n].keys()
228 out.append(
'%s.%s = %s;' % (n, p,
toOpt(conf_dict[n][p])))
229 return "\n".join(out)
234 output = open(filename,
'wb')
239 to_dump[n] = Configuration.allConfigurables[n]
240 pickle.dump(to_dump, output, -1)
244 msg =
'Dumping all configurables and properties' 246 msg +=
' (different from default)' 248 conf_dict = Configuration.configurationDict(all)
255 write = {
".pkl":
lambda filename, all: self.
_writepickle(filename),
259 from os.path
import splitext
260 ext = splitext(filename)[1]
262 write[ext](filename, all)
264 log.error(
"Unknown file type '%s'. Must be any of %r.",
270 def run(self, attach_debugger, ncpus=None):
281 self.log.info(
'attaching debugger to PID ' + str(os.getpid()))
282 pid = os.spawnvp(os.P_NOWAIT,
283 debugger, [debugger,
'-q',
'python', str(os.getpid())])
290 os.waitpid(pid, os.WNOHANG)
296 Bootstrap the application with minimal use of Python bindings. 304 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
307 if _bootstrap
is None:
310 self.log.debug(
'basicInit: instantiate ApplicationMgr')
311 self.
ip = self.
g = _bootstrap.createApplicationMgr()
313 self.log.debug(
'basicInit: apply options')
316 comp =
'ApplicationMgr' 317 props = Configurable.allConfigurables.get(comp, {})
319 props =
expandvars(props.getValuedProperties())
320 for p, v
in props.items() + [(
'JobOptionsType',
'NONE')]:
321 if not self.g.setProperty(p, str(v)):
322 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
325 if _bootstrap.ROOT_VERSION < (6, 2, 7):
333 msp = self.g.getService(comp)
335 self.log.error(
'Cannot get service %s', comp)
337 props = Configurable.allConfigurables.get(comp, {})
339 props =
expandvars(props.getValuedProperties())
340 for p, v
in props.items():
341 if not _bootstrap.setProperty(msp, p, str(v)):
342 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
346 comp =
'JobOptionsSvc' 347 jos = self.g.getService(comp)
349 self.log.error(
'Cannot get service %s', comp)
352 c = Configurable.allConfigurables[n]
353 if n
in [
'ApplicationMgr',
'MessageSvc']:
355 for p, v
in c.getValuedProperties().items():
358 if hasattr(Configurable,
"PropertyReference")
and type(v) == Configurable.PropertyReference:
364 elif type(v) == long:
366 _bootstrap.addPropertyToCatalogue(jos, n, p, str(v))
367 if hasattr(Configurable,
"_configurationLocked"):
368 Configurable._configurationLocked =
True 369 self.log.debug(
'basicInit: done')
373 Initialize the application with full Python bindings. 375 self.log.debug(
'gaudiPythonInit: import GaudiPython')
377 self.log.debug(
'gaudiPythonInit: instantiate ApplicationMgr')
380 self.log.debug(
'gaudiPythonInit: done')
385 os.environ.get(
'GAUDIRUN_USE_GAUDIPYTHON')):
390 self.log.debug(
'-' * 80)
391 self.log.debug(
'%s: running in serial mode', __name__)
392 self.log.debug(
'-' * 80)
398 def runner(app, nevt):
399 self.log.debug(
'initialize')
400 sc = app.initialize()
403 app.printAlgsSequences()
404 self.log.debug(
'start')
407 self.log.debug(
'run(%d)', nevt)
409 self.log.debug(
'stop')
411 self.log.debug(
'finalize')
412 app.finalize().ignore()
413 self.log.debug(
'terminate')
414 sc1 = app.terminate()
419 self.log.debug(
'status code: %s',
420 'SUCCESS' if sc.isSuccess()
else 'FAILURE')
423 if (attach_debugger ==
True):
427 statuscode = runner(self.
g, int(
428 self.ip.getProperty(
'EvtMax').
toString()))
431 self.ip.setProperty(
'ReturnCode', str(128 + 11))
434 print 'Exception:', x
436 self.ip.setProperty(
'ReturnCode',
'1')
438 if hasattr(statuscode,
"isSuccess"):
439 success = statuscode.isSuccess()
443 if not success
and self.ip.getProperty(
'ReturnCode').
toString() ==
'0':
445 self.ip.setProperty(
'ReturnCode',
'1')
446 sysTime =
time() - sysStart
447 self.log.debug(
'-' * 80)
449 '%s: serial system finished, time taken: %5.4fs', __name__, sysTime)
450 self.log.debug(
'-' * 80)
451 return int(self.ip.getProperty(
'ReturnCode').
toString())
456 "Cannot use custom main loop in multi-process mode, check your options")
461 c = Configurable.allConfigurables
462 self.log.info(
'-' * 80)
463 self.log.info(
'%s: Parallel Mode : %i ', __name__, ncpus)
464 for name, value
in [(
'platrofm',
' '.join(os.uname())),
465 (
'config', os.environ.get(
'BINARY_TAG')
or 466 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__,
471 name, value
or 'Undefined')
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)
489 '%s: parallel system finished, time taken: %5.4fs', __name__, sysTime)
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 gaudiPythonInit(self)
def runParallel(self, ncpus)
def hookDebugger(self, debugger='gdb')
def generatePyOutput(self, all=False)
def __init__(self, ptr, lib)
struct GAUDI_API map
Parametrisation class for map-like implementation.
def getProperty(self, name)
def getService(self, name)
def createApplicationMgr(self)
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)
std::string toString(const Type &)
def setProperty(self, name, value)
def runSerial(self, attach_debugger)