3 from Gaudi
import Configuration
6 log = logging.getLogger(__name__)
14 __nonzero__ = __bool__
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
57 self.
log = logging.getLogger(
'BootstrapHelper')
59 libname =
'libGaudiKernel.so'
60 self.log.debug(
'loading GaudiKernel (%s)', libname)
64 self.
lib = gkl = PyDLL(libname)
66 functions = [(
'createApplicationMgr', c_void_p, []),
67 (
'getService', c_void_p, [c_void_p, c_char_p]),
68 (
'setProperty', c_bool, [c_void_p, c_char_p, c_char_p]),
69 (
'getProperty', c_char_p, [c_void_p, c_char_p]),
70 (
'addPropertyToCatalogue', c_bool, [c_void_p, c_char_p, c_char_p, c_char_p]),
71 (
'ROOT_VERSION_CODE', c_int, []),
74 for name, restype, args
in functions:
75 f = getattr(gkl,
'py_bootstrap_%s' % name)
76 f.restype, f.args = restype, args
79 if name
not in self.__class__.__dict__:
80 setattr(self, name, f)
82 for name
in (
'configure',
'initialize',
'start',
83 'stop',
'finalize',
'terminate'):
84 f = getattr(gkl,
'py_bootstrap_fsm_%s' % name)
85 f.restype, f.args = c_bool, [c_void_p]
86 gkl.py_bootstrap_app_run.restype = c_bool
87 gkl.py_bootstrap_app_run.args = [c_void_p, c_int]
89 gkl.py_helper_printAlgsSequences.restype =
None
90 gkl.py_helper_printAlgsSequences.args = [c_void_p]
93 ptr = self.lib.py_bootstrap_createApplicationMgr()
98 return self.lib.py_bootstrap_ROOT_VERSION_CODE()
103 a = root_version_code >> 16 & 0xff
104 b = root_version_code >> 8 & 0xff
105 c = root_version_code & 0xff
113 Helper to convert values to old .opts format.
115 >>> print toOpt('some "text"')
117 >>> print toOpt('first\\nsecond')
120 >>> print toOpt({'a': [1, 2, '3']})
123 if isinstance(value, basestring):
124 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
125 elif isinstance(value, dict):
127 for k, v
in value.iteritems()))
128 elif hasattr(value,
'__iter__'):
129 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
138 from Configurables
import ApplicationMgr
140 if "GAUDIAPPNAME" in os.environ:
141 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
142 if "GAUDIAPPVERSION" in os.environ:
143 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
144 self.
log = logging.getLogger(__name__)
152 import multiprocessing
154 from time
import ctime
156 datetime = datetime.replace(
' ',
'_')
157 outfile = open(
'gaudirun-%s.log'%(datetime),
'w' )
159 streamhandler = logging.StreamHandler(strm=outfile)
160 console = logging.StreamHandler()
162 formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s" )
164 streamhandler.setFormatter(formatter)
165 console.setFormatter(formatter)
169 self.
log = multiprocessing.log_to_stderr()
170 self.log.setLevel( logging.INFO )
171 self.log.name =
'Gaudi/Main.py Logger'
172 self.log.handlers = []
174 self.log.addHandler(streamhandler)
175 self.log.addHandler(console)
176 self.log.removeHandler(console)
178 self.log.setLevel = logging.INFO
182 from pprint
import pformat
183 conf_dict = Configuration.configurationDict(all)
184 return pformat(conf_dict)
187 from pprint
import pformat
188 conf_dict = Configuration.configurationDict(all)
190 names = conf_dict.keys()
193 props = conf_dict[n].keys()
196 out.append(
'%s.%s = %s;' % (n,p,
toOpt(conf_dict[n][p])))
197 return "\n".join(out)
202 output = open(filename,
'wb')
204 from GaudiKernel.Proxy.Configurable
import getNeededConfigurables
207 to_dump[n] = Configuration.allConfigurables[n]
208 pickle.dump(to_dump, output, -1)
212 msg =
'Dumping all configurables and properties'
214 msg +=
' (different from default)'
216 conf_dict = Configuration.configurationDict(all)
223 write = {
".pkl" :
lambda filename, all: self.
_writepickle(filename),
224 ".py" :
lambda filename, all: open(filename,
"w").write(self.
generatePyOutput(all) +
"\n"),
225 ".opts":
lambda filename, all: open(filename,
"w").write(self.
generateOptsOutput(all) +
"\n"),
227 from os.path
import splitext
228 ext = splitext(filename)[1]
230 write[ext](filename, all)
232 log.error(
"Unknown file type '%s'. Must be any of %r.", ext, write.keys())
237 def run(self, ncpus = None):
248 Bootstrap the application with minimal use of Python bindings.
251 from GaudiKernel.Proxy.Configurable
import expandvars
254 expandvars =
lambda data : data
256 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
259 if _bootstrap
is None:
262 self.log.debug(
'basicInit: instantiate ApplicationMgr')
263 self.
ip = self.
g = _bootstrap.createApplicationMgr()
265 self.log.debug(
'basicInit: apply options')
268 comp =
'ApplicationMgr'
269 props = Configurable.allConfigurables.get(comp, {})
271 props =
expandvars(props.getValuedProperties())
272 for p, v
in props.items() + [(
'JobOptionsType',
'NONE')]:
273 if not self.g.setProperty(p, str(v)):
274 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
277 if _bootstrap.ROOT_VERSION < (6, 2, 7):
285 msp = self.g.getService(comp)
287 self.log.error(
'Cannot get service %s', comp)
289 props = Configurable.allConfigurables.get(comp, {})
291 props =
expandvars(props.getValuedProperties())
292 for p, v
in props.items():
293 if not _bootstrap.setProperty(msp, p, str(v)):
294 self.log.error(
'Cannot set property %s.%s to %s', comp, p, v)
298 comp =
'JobOptionsSvc'
299 jos = self.g.getService(comp)
301 self.log.error(
'Cannot get service %s', comp)
304 c = Configurable.allConfigurables[n]
305 if n
in [
'ApplicationMgr',
'MessageSvc']:
307 for p, v
in c.getValuedProperties().items() :
310 if hasattr(Configurable,
"PropertyReference")
and type(v) == Configurable.PropertyReference:
314 if type(v) == str : v =
'"%s"' % v
315 elif type(v) == long: v =
'%d' % v
316 _bootstrap.addPropertyToCatalogue(jos, n, p, str(v))
317 if hasattr(Configurable,
"_configurationLocked"):
318 Configurable._configurationLocked =
True
319 self.log.debug(
'basicInit: done')
323 Initialize the application with full Python bindings.
325 self.log.debug(
'gaudiPythonInit: import GaudiPython')
327 self.log.debug(
'gaudiPythonInit: instantiate ApplicationMgr')
330 self.log.debug(
'gaudiPythonInit: done')
335 os.environ.get(
'GAUDIRUN_USE_GAUDIPYTHON')):
340 self.log.debug(
'-'*80)
341 self.log.debug(
'%s: running in serial mode', __name__)
342 self.log.debug(
'-'*80)
348 def runner(app, nevt):
349 self.log.debug(
'initialize')
350 sc = app.initialize()
353 app.printAlgsSequences()
354 self.log.debug(
'start')
357 self.log.debug(
'run(%d)', nevt)
359 self.log.debug(
'stop')
361 self.log.debug(
'finalize')
362 app.finalize().ignore()
363 self.log.debug(
'terminate')
364 sc1 = app.terminate()
369 self.log.debug(
'status code: %s',
370 'SUCCESS' if sc.isSuccess()
else 'FAILURE')
374 statuscode = runner(self.
g, int(self.ip.getProperty(
'EvtMax').
toString()))
377 self.ip.setProperty(
'ReturnCode', str(128 + 11))
380 print 'Exception:', x
382 self.ip.setProperty(
'ReturnCode',
'1')
384 if hasattr(statuscode,
"isSuccess"):
385 success = statuscode.isSuccess()
389 if not success
and self.ip.getProperty(
'ReturnCode').
toString() ==
'0':
391 self.ip.setProperty(
'ReturnCode',
'1')
392 sysTime = time()-sysStart
393 self.log.debug(
'-'*80)
394 self.log.debug(
'%s: serial system finished, time taken: %5.4fs', __name__, sysTime)
395 self.log.debug(
'-'*80)
396 return int(self.ip.getProperty(
'ReturnCode').
toString())
400 self.log.fatal(
"Cannot use custom main loop in multi-process mode, check your options")
405 c = Configurable.allConfigurables
406 self.log.info(
'-'*80)
407 self.log.info(
'%s: Parallel Mode : %i '%(__name__, ncpus))
408 from commands
import getstatusoutput
as gso
409 metadataCommands = [
'uname -a',
411 'echo $GAUDIAPPNAME',
412 'echo $GAUDIAPPVERSION']
413 for comm
in metadataCommands :
417 string =
'%s: %30s : %s '%(__name__, comm, o)
418 self.log.info( string )
420 events = str(c[
'ApplicationMgr'].EvtMax)
422 events =
"Undetermined"
423 self.log.info(
'%s: Events Specified : %s '%(__name__,events))
424 self.log.info(
'-'*80)
426 Parall = gpp.Coord( ncpus, c, self.
log )
429 self.log.info(
'MAIN.PY : received %s from Coordinator'%(sc))
432 sysTime = time()-sysStart
433 self.log.name =
'Gaudi/Main.py Logger'
434 self.log.info(
'-'*80)
435 self.log.info(
'%s: parallel system finished, time taken: %5.4fs', __name__, sysTime)
436 self.log.info(
'-'*80)
def getNeededConfigurables()
def printAlgsSequences(self)
def setupParallelLogging(self)
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
def _writepickle(self, filename)
def gaudiPythonInit(self)
std::string toString(const TYPE &obj)
the generic implementation of the type conversion to the string
def runParallel(self, ncpus)
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)
Property base class allowing Property* collections to be "homogeneous".
def __init__(self, value)
def run
Instantiate and run the application.
def setProperty(self, name, value)