3 from Gaudi
import Configuration
6 log = logging.getLogger(__name__)
8 class BootstrapHelper(object):
14 __nonzero__ = __bool__
25 return str(self.value)
31 self._as_parameter_ = ptr
33 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_fsm_configure(self.ptr))
35 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_fsm_initialize(self.ptr))
37 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_fsm_start(self.ptr))
39 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_app_run(self.ptr, nevt))
41 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_fsm_stop(self.ptr))
43 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_fsm_finalize(self.ptr))
45 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_fsm_terminate(self.ptr))
47 return self.lib.py_bootstrap_getService(self.ptr, name)
49 return BootstrapHelper.StatusCode(self.lib.py_bootstrap_setProperty(self.ptr, name, value))
51 return BootstrapHelper.Property(self.lib.py_bootstrap_getProperty(self.ptr, name))
52 def printAlgsSequences(self):
53 return self.lib.py_helper_printAlgsSequences(self.ptr)
56 from ctypes
import PyDLL, c_void_p, c_bool, c_char_p, c_int
59 class IInterface_p(c_void_p):
61 return "IInterface_p(0x%x)" % (0
if self.value
is None
63 self.log = logging.getLogger(
'BootstrapHelper')
65 libname =
'libGaudiKernel.so'
66 self.log.debug(
'loading GaudiKernel (%s)', libname)
70 self.lib = gkl = PyDLL(libname)
72 functions = [(
'createApplicationMgr', IInterface_p, []),
73 (
'getService', IInterface_p, [IInterface_p, c_char_p]),
74 (
'setProperty', c_bool, [IInterface_p, c_char_p, c_char_p]),
75 (
'getProperty', c_char_p, [IInterface_p, c_char_p]),
76 (
'addPropertyToCatalogue', c_bool, [IInterface_p, c_char_p, c_char_p, c_char_p]),
77 (
'ROOT_VERSION_CODE', c_int, []),
80 for name, restype, argtypes
in functions:
81 f = getattr(gkl,
'py_bootstrap_%s' % name)
82 f.restype, f.argtypes = restype, argtypes
85 if name
not in self.__class__.__dict__:
86 setattr(self, name, f)
88 for name
in (
'configure',
'initialize',
'start',
89 'stop',
'finalize',
'terminate'):
90 f = getattr(gkl,
'py_bootstrap_fsm_%s' % name)
91 f.restype, f.argtypes = c_bool, [IInterface_p]
92 gkl.py_bootstrap_app_run.restype = c_bool
93 gkl.py_bootstrap_app_run.argtypes = [IInterface_p, c_int]
95 gkl.py_helper_printAlgsSequences.restype =
None
96 gkl.py_helper_printAlgsSequences.argtypes = [IInterface_p]
99 ptr = self.lib.py_bootstrap_createApplicationMgr()
100 return self.AppMgr(ptr, self.lib)
104 return self.lib.py_bootstrap_ROOT_VERSION_CODE()
107 def ROOT_VERSION(self):
108 root_version_code = self.ROOT_VERSION_CODE
109 a = root_version_code >> 16 & 0xff
110 b = root_version_code >> 8 & 0xff
111 c = root_version_code & 0xff
119 Helper to convert values to old .opts format.
121 >>> print toOpt('some "text"')
123 >>> print toOpt('first\\nsecond')
126 >>> print toOpt({'a': [1, 2, '3']})
129 if isinstance(value, basestring):
130 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
131 elif isinstance(value, dict):
133 for k, v
in value.iteritems()))
134 elif hasattr(value,
'__iter__'):
135 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
139 class gaudimain(object) :
144 from Configurables
import ApplicationMgr
146 if "GAUDIAPPNAME" in os.environ:
147 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
148 if "GAUDIAPPVERSION" in os.environ:
149 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
150 self.log = logging.getLogger(__name__)
151 self.printsequence =
False
153 def setupParallelLogging( self ) :
158 import multiprocessing
160 from time
import ctime
162 datetime = datetime.replace(
' ',
'_')
163 outfile = open(
'gaudirun-%s.log'%(datetime),
'w' )
165 streamhandler = logging.StreamHandler(stream=outfile)
166 console = logging.StreamHandler()
168 formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s" )
170 streamhandler.setFormatter(formatter)
171 console.setFormatter(formatter)
175 self.log = multiprocessing.log_to_stderr()
176 self.log.setLevel( logging.INFO )
177 self.log.name =
'Gaudi/Main.py Logger'
178 self.log.handlers = []
180 self.log.addHandler(streamhandler)
181 self.log.addHandler(console)
182 self.log.removeHandler(console)
184 self.log.setLevel = logging.INFO
187 def generatePyOutput(self, all = False):
188 from pprint
import pformat
189 conf_dict = Configuration.configurationDict(all)
190 return pformat(conf_dict)
192 def generateOptsOutput(self, all = False):
193 from pprint
import pformat
194 conf_dict = Configuration.configurationDict(all)
196 names = conf_dict.keys()
199 props = conf_dict[n].keys()
202 out.append(
'%s.%s = %s;' % (n,p,
toOpt(conf_dict[n][p])))
203 return "\n".join(out)
205 def _writepickle(self, filename) :
208 output = open(filename,
'wb')
213 to_dump[n] = Configuration.allConfigurables[n]
214 pickle.dump(to_dump, output, -1)
217 def printconfig(self, old_format = False, all = False) :
218 msg =
'Dumping all configurables and properties'
220 msg +=
' (different from default)'
222 conf_dict = Configuration.configurationDict(all)
224 print self.generateOptsOutput(all)
226 print self.generatePyOutput(all)
228 def writeconfig(self, filename, all = False):
229 write = {
".pkl" :
lambda filename, all: self._writepickle(filename),
230 ".py" :
lambda filename, all: open(filename,
"w").write(self.generatePyOutput(all) +
"\n"),
231 ".opts":
lambda filename, all: open(filename,
"w").write(self.generateOptsOutput(all) +
"\n"),
233 from os.path
import splitext
234 ext = splitext(filename)[1]
236 write[ext](filename, all)
238 log.error(
"Unknown file type '%s'. Must be any of %r.", ext, write.keys())
243 def run(self, attach_debugger, ncpus = None):
246 result = self.runSerial(attach_debugger)
249 result = self.runParallel(ncpus)
252 def hookDebugger(self,debugger='gdb'):
254 self.log.info(
'attaching debugger to PID ' + str(os.getpid()))
255 pid = os.spawnvp(os.P_NOWAIT,
256 debugger, [debugger,
'-q',
'python', str(os.getpid())])
263 os.waitpid( pid, os.WNOHANG )
269 Bootstrap the application with minimal use of Python bindings.
275 expandvars =
lambda data : data
280 if _bootstrap
is None:
281 _bootstrap = BootstrapHelper()
283 self.log.debug(
'basicInit: instantiate ApplicationMgr')
284 self.ip = self.g = _bootstrap.createApplicationMgr()
286 self.log.debug(
'basicInit: apply options')
289 comp =
'ApplicationMgr'
290 props = Configurable.allConfigurables.get(comp, {})
292 props =
expandvars(props.getValuedProperties())
293 for p, v
in props.items() + [(
'JobOptionsType',
'NONE')]:
294 if not self.g.setProperty(p, str(v)):
295 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
298 if _bootstrap.ROOT_VERSION < (6, 2, 7):
306 msp = self.g.getService(comp)
308 self.log.error(
'Cannot get service %s', comp)
310 props = Configurable.allConfigurables.get(comp, {})
312 props =
expandvars(props.getValuedProperties())
313 for p, v
in props.items():
314 if not _bootstrap.setProperty(msp, p, str(v)):
315 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
319 comp =
'JobOptionsSvc'
320 jos = self.g.getService(comp)
322 self.log.error(
'Cannot get service %s', comp)
325 c = Configurable.allConfigurables[n]
326 if n
in [
'ApplicationMgr',
'MessageSvc']:
328 for p, v
in c.getValuedProperties().items() :
331 if hasattr(Configurable,
"PropertyReference")
and type(v) == Configurable.PropertyReference:
335 if type(v) == str : v =
'"%s"' % v
336 elif type(v) == long: v =
'%d' % v
337 _bootstrap.addPropertyToCatalogue(jos, n, p, str(v))
338 if hasattr(Configurable,
"_configurationLocked"):
339 Configurable._configurationLocked =
True
340 self.log.debug(
'basicInit: done')
342 def gaudiPythonInit(self):
344 Initialize the application with full Python bindings.
346 self.log.debug(
'gaudiPythonInit: import GaudiPython')
348 self.log.debug(
'gaudiPythonInit: instantiate ApplicationMgr')
351 self.log.debug(
'gaudiPythonInit: done')
353 def runSerial(self,attach_debugger) :
356 os.environ.get(
'GAUDIRUN_USE_GAUDIPYTHON')):
357 self.gaudiPythonInit()
361 self.log.debug(
'-'*80)
362 self.log.debug(
'%s: running in serial mode', __name__)
363 self.log.debug(
'-'*80)
367 runner = self.mainLoop
369 def runner(app, nevt):
370 self.log.debug(
'initialize')
371 sc = app.initialize()
373 if self.printsequence:
374 app.printAlgsSequences()
375 self.log.debug(
'start')
378 self.log.debug(
'run(%d)', nevt)
380 self.log.debug(
'stop')
382 self.log.debug(
'finalize')
383 app.finalize().ignore()
384 self.log.debug(
'terminate')
385 sc1 = app.terminate()
390 self.log.debug(
'status code: %s',
391 'SUCCESS' if sc.isSuccess()
else 'FAILURE')
394 if (attach_debugger ==
True) : self.hookDebugger()
397 statuscode = runner(self.g, int(self.ip.getProperty(
'EvtMax').
toString()))
400 self.ip.setProperty(
'ReturnCode', str(128 + 11))
403 print 'Exception:', x
405 self.ip.setProperty(
'ReturnCode',
'1')
407 if hasattr(statuscode,
"isSuccess"):
408 success = statuscode.isSuccess()
412 if not success
and self.ip.getProperty(
'ReturnCode').
toString() ==
'0':
414 self.ip.setProperty(
'ReturnCode',
'1')
415 sysTime =
time()-sysStart
416 self.log.debug(
'-'*80)
417 self.log.debug(
'%s: serial system finished, time taken: %5.4fs', __name__, sysTime)
418 self.log.debug(
'-'*80)
419 return int(self.ip.getProperty(
'ReturnCode').
toString())
421 def runParallel(self, ncpus) :
423 self.log.fatal(
"Cannot use custom main loop in multi-process mode, check your options")
425 self.setupParallelLogging( )
428 c = Configurable.allConfigurables
429 self.log.info(
'-'*80)
430 self.log.info(
'%s: Parallel Mode : %i ', __name__, ncpus)
431 for name, value
in [(
'platrofm',
' '.join(os.uname())),
432 (
'config', os.environ.get(
'BINARY_TAG')
or
433 os.environ.get(
'CMTCONFIG')),
434 (
'app. name', os.environ.get(
'GAUDIAPPNAME')),
435 (
'app. version', os.environ.get(
'GAUDIAPPVERSION')),
437 self.log.info(
'%s: %30s : %s ', __name__, name, value
or 'Undefined')
439 events = str(c[
'ApplicationMgr'].EvtMax)
441 events =
"Undetermined"
442 self.log.info(
'%s: Events Specified : %s ', __name__, events)
443 self.log.info(
'-'*80)
445 Parall = gpp.Coord( ncpus, c, self.log )
448 self.log.info(
'MAIN.PY : received %s from Coordinator'%(sc))
451 sysTime =
time()-sysStart
452 self.log.name =
'Gaudi/Main.py Logger'
453 self.log.info(
'-'*80)
454 self.log.info(
'%s: parallel system finished, time taken: %5.4fs', __name__, sysTime)
455 self.log.info(
'-'*80)
int PyHelper() ROOT_VERSION_CODE()
def __init__(self, name=Configurable.DefaultName, _enabled=True, kwargs)
std::string toString(const TYPE &obj)
the generic implementation of the type conversion to the string
const char *PyHelper() getProperty(IInterface *p, char *name)
struct GAUDI_API map
Parametrisation class for map-like implementation.
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
This class is used for returning status codes from appropriate routines.
bool PyHelper() setProperty(IInterface *p, char *name, char *value)
The Application Manager class.
Property base class allowing Property* collections to be "homogeneous".
def getNeededConfigurables()
IInterface *PyHelper() getService(IInterface *app, char *name)
GAUDI_API IAppMgrUI * createApplicationMgr(const std::string &dllname, const std::string &factname)