3 from Gaudi
import Configuration
6 log = logging.getLogger(__name__)
14 __nonzero__ = __bool__
21 class Property(object):
25 return str(self.
value)
47 return self.lib.py_bootstrap_getService(self.
ptr, name)
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()
104 return self.lib.py_bootstrap_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)))
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__)
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
188 from pprint
import pformat
189 conf_dict = Configuration.configurationDict(all)
190 return pformat(conf_dict)
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)
208 output = open(filename,
'wb')
210 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
213 to_dump[n] = Configuration.allConfigurables[n]
214 pickle.dump(to_dump, output, -1)
218 msg =
'Dumping all configurables and properties' 220 msg +=
' (different from default)' 222 conf_dict = Configuration.configurationDict(all)
229 write = {
".pkl" :
lambda filename, all: self.
_writepickle(filename),
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):
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. 272 from GaudiKernel.Proxy.Configurable
import expandvars
275 expandvars =
lambda data : data
277 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
280 if _bootstrap
is None:
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')
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')
356 os.environ.get(
'GAUDIRUN_USE_GAUDIPYTHON')):
361 self.log.debug(
'-'*80)
362 self.log.debug(
'%s: running in serial mode', __name__)
363 self.log.debug(
'-'*80)
369 def runner(app, nevt):
370 self.log.debug(
'initialize')
371 sc = app.initialize()
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')
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())
423 self.log.fatal(
"Cannot use custom main loop in multi-process mode, check your options")
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)
def printAlgsSequences(self)
def run(self, attach_debugger, ncpus=None)
Instantiate and run the application.
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)
std::string toString(const TYPE &obj)
the generic implementation of the type conversion to the string
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)
def setProperty(self, name, value)
def runSerial(self, attach_debugger)