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
80 class IInterface_p(c_void_p):
82 return "IInterface_p(0x%x)" % (0
if self.value
is None 84 self.
log = logging.getLogger(
'BootstrapHelper')
85 libname = util.find_library(
'GaudiKernel')
or 'libGaudiKernel.so' 86 self.log.debug(
'loading GaudiKernel (%s)', libname)
90 self.
lib = gkl = PyDLL(libname)
92 functions = [(
'createApplicationMgr', IInterface_p, []),
93 (
'getService', IInterface_p, [IInterface_p, c_char_p]),
94 (
'setProperty', c_bool, [
95 IInterface_p, c_char_p, c_char_p]),
96 (
'getProperty', c_char_p, [IInterface_p, c_char_p]),
97 (
'addPropertyToCatalogue', c_bool, [
98 IInterface_p, c_char_p, c_char_p, c_char_p]),
99 (
'ROOT_VERSION_CODE', c_int, []),
102 for name, restype, argtypes
in functions:
103 f = getattr(gkl,
'py_bootstrap_%s' % name)
104 f.restype, f.argtypes = restype, argtypes
107 if name
not in self.__class__.__dict__:
108 setattr(self, name, f)
110 for name
in (
'configure',
'initialize',
'start',
111 'stop',
'finalize',
'terminate'):
112 f = getattr(gkl,
'py_bootstrap_fsm_%s' % name)
113 f.restype, f.argtypes = c_bool, [IInterface_p]
114 gkl.py_bootstrap_app_run.restype = c_bool
115 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
117 gkl.py_helper_printAlgsSequences.restype =
None 118 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
121 ptr = self.lib.py_bootstrap_createApplicationMgr()
126 return self.lib.py_bootstrap_ROOT_VERSION_CODE()
131 a = root_version_code >> 16 & 0xff
132 b = root_version_code >> 8 & 0xff
133 c = root_version_code & 0xff
142 Helper to convert values to old .opts format. 144 >>> print toOpt('some "text"') 146 >>> print toOpt('first\\nsecond') 149 >>> print toOpt({'a': [1, 2, '3']}) 152 if isinstance(value, basestring):
153 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
154 elif isinstance(value, dict):
156 for k, v
in value.iteritems()))
157 elif hasattr(value,
'__iter__'):
158 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
168 from Configurables
import ApplicationMgr
170 if "GAUDIAPPNAME" in os.environ:
171 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
172 if "GAUDIAPPVERSION" in os.environ:
173 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
174 self.
log = logging.getLogger(__name__)
182 import multiprocessing
184 from time
import ctime
186 datetime = datetime.replace(
' ',
'_')
187 outfile = open(
'gaudirun-%s.log' % (datetime),
'w')
189 streamhandler = logging.StreamHandler(stream=outfile)
190 console = logging.StreamHandler()
192 formatter = logging.Formatter(
193 "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
195 streamhandler.setFormatter(formatter)
196 console.setFormatter(formatter)
200 self.
log = multiprocessing.log_to_stderr()
201 self.log.setLevel(logging.INFO)
202 self.log.name =
'Gaudi/Main.py Logger' 203 self.log.handlers = []
205 self.log.addHandler(streamhandler)
206 self.log.addHandler(console)
207 self.log.removeHandler(console)
209 self.log.setLevel = logging.INFO
213 from pprint
import pformat
214 conf_dict = Configuration.configurationDict(all)
215 return pformat(conf_dict)
218 from pprint
import pformat
219 conf_dict = Configuration.configurationDict(all)
221 names = conf_dict.keys()
224 props = conf_dict[n].keys()
227 out.append(
'%s.%s = %s;' % (n, p,
toOpt(conf_dict[n][p])))
228 return "\n".join(out)
233 output = open(filename,
'wb')
235 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
238 to_dump[n] = Configuration.allConfigurables[n]
239 pickle.dump(to_dump, output, -1)
243 msg =
'Dumping all configurables and properties' 245 msg +=
' (different from default)' 247 conf_dict = Configuration.configurationDict(all)
254 write = {
".pkl":
lambda filename, all: self.
_writepickle(filename),
258 from os.path
import splitext
259 ext = splitext(filename)[1]
261 write[ext](filename, all)
263 log.error(
"Unknown file type '%s'. Must be any of %r.",
269 def run(self, attach_debugger, ncpus=None):
280 self.log.info(
'attaching debugger to PID ' + str(os.getpid()))
281 pid = os.spawnvp(os.P_NOWAIT,
282 debugger, [debugger,
'-q',
'python', str(os.getpid())])
289 os.waitpid(pid, os.WNOHANG)
295 Bootstrap the application with minimal use of Python bindings. 298 from GaudiKernel.Proxy.Configurable
import expandvars
303 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
306 if _bootstrap
is None:
309 self.log.debug(
'basicInit: instantiate ApplicationMgr')
310 self.
ip = self.
g = _bootstrap.createApplicationMgr()
312 self.log.debug(
'basicInit: apply options')
315 comp =
'ApplicationMgr' 316 props = Configurable.allConfigurables.get(comp, {})
318 props =
expandvars(props.getValuedProperties())
319 for p, v
in props.items() + [(
'JobOptionsType',
'NONE')]:
320 if not self.g.setProperty(p, str(v)):
321 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
324 if _bootstrap.ROOT_VERSION < (6, 2, 7):
332 msp = self.g.getService(comp)
334 self.log.error(
'Cannot get service %s', comp)
336 props = Configurable.allConfigurables.get(comp, {})
338 props =
expandvars(props.getValuedProperties())
339 for p, v
in props.items():
340 if not _bootstrap.setProperty(msp, p, str(v)):
341 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
345 comp =
'JobOptionsSvc' 346 jos = self.g.getService(comp)
348 self.log.error(
'Cannot get service %s', comp)
351 c = Configurable.allConfigurables[n]
352 if n
in [
'ApplicationMgr',
'MessageSvc']:
354 for p, v
in c.getValuedProperties().items():
357 if hasattr(Configurable,
"PropertyReference")
and type(v) == Configurable.PropertyReference:
363 elif type(v) == long:
365 _bootstrap.addPropertyToCatalogue(jos, n, p, str(v))
366 if hasattr(Configurable,
"_configurationLocked"):
367 Configurable._configurationLocked =
True 368 self.log.debug(
'basicInit: done')
372 Initialize the application with full Python bindings. 374 self.log.debug(
'gaudiPythonInit: import GaudiPython')
376 self.log.debug(
'gaudiPythonInit: instantiate ApplicationMgr')
379 self.log.debug(
'gaudiPythonInit: done')
384 os.environ.get(
'GAUDIRUN_USE_GAUDIPYTHON')):
389 self.log.debug(
'-' * 80)
390 self.log.debug(
'%s: running in serial mode', __name__)
391 self.log.debug(
'-' * 80)
397 def runner(app, nevt):
398 self.log.debug(
'initialize')
399 sc = app.initialize()
402 app.printAlgsSequences()
403 self.log.debug(
'start')
406 self.log.debug(
'run(%d)', nevt)
408 self.log.debug(
'stop')
410 self.log.debug(
'finalize')
411 app.finalize().ignore()
412 self.log.debug(
'terminate')
413 sc1 = app.terminate()
418 self.log.debug(
'status code: %s',
419 'SUCCESS' if sc.isSuccess()
else 'FAILURE')
422 if (attach_debugger ==
True):
426 statuscode = runner(self.
g, int(
427 self.ip.getProperty(
'EvtMax').
toString()))
430 self.ip.setProperty(
'ReturnCode', str(128 + 11))
433 print 'Exception:', x
435 self.ip.setProperty(
'ReturnCode',
'1')
437 if hasattr(statuscode,
"isSuccess"):
438 success = statuscode.isSuccess()
442 if not success
and self.ip.getProperty(
'ReturnCode').
toString() ==
'0':
444 self.ip.setProperty(
'ReturnCode',
'1')
445 sysTime =
time() - sysStart
446 self.log.debug(
'-' * 80)
448 '%s: serial system finished, time taken: %5.4fs', __name__, sysTime)
449 self.log.debug(
'-' * 80)
450 return int(self.ip.getProperty(
'ReturnCode').
toString())
455 "Cannot use custom main loop in multi-process mode, check your options")
460 c = Configurable.allConfigurables
461 self.log.info(
'-' * 80)
462 self.log.info(
'%s: Parallel Mode : %i ', __name__, ncpus)
463 for name, value
in [(
'platrofm',
' '.join(os.uname())),
464 (
'config', os.environ.get(
'BINARY_TAG')
or 465 os.environ.get(
'CMTCONFIG')),
466 (
'app. name', os.environ.get(
'GAUDIAPPNAME')),
467 (
'app. version', os.environ.get(
'GAUDIAPPVERSION')),
469 self.log.info(
'%s: %30s : %s ', __name__,
470 name, value
or 'Undefined')
472 events = str(c[
'ApplicationMgr'].EvtMax)
474 events =
"Undetermined" 475 self.log.info(
'%s: Events Specified : %s ', __name__, events)
476 self.log.info(
'-' * 80)
478 Parall = gpp.Coord(ncpus, c, self.
log)
481 self.log.info(
'MAIN.PY : received %s from Coordinator' % (sc))
484 sysTime =
time() - sysStart
485 self.log.name =
'Gaudi/Main.py Logger' 486 self.log.info(
'-' * 80)
488 '%s: parallel system finished, time taken: %5.4fs', __name__, sysTime)
489 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)