3 from Gaudi
import Configuration
6 log = logging.getLogger(__name__)
10 Helper to convert values to old .opts format.
12 >>> print toOpt('some "text"')
14 >>> print toOpt('first\\nsecond')
17 >>> print toOpt({'a': [1, 2, '3']})
20 if isinstance(value, basestring):
21 return '"{0}"'.
format(value.replace(
'"',
'\\"'))
22 elif isinstance(value, dict):
24 for k, v
in value.iteritems()))
25 elif hasattr(value,
'__iter__'):
26 return '[{0}]'.
format(
', '.join(
map(toOpt, value)))
30 class gaudimain(object) :
35 from Configurables
import ApplicationMgr
37 if "GAUDIAPPNAME" in os.environ:
38 appMgr.AppName = str(os.environ[
"GAUDIAPPNAME"])
39 if "GAUDIAPPVERSION" in os.environ:
40 appMgr.AppVersion = str(os.environ[
"GAUDIAPPVERSION"])
41 self.log = logging.getLogger(__name__)
42 self.printsequence =
False
44 def setupParallelLogging( self ) :
49 import multiprocessing
51 from time
import ctime
53 datetime = datetime.replace(
' ',
'_')
54 outfile = open(
'gaudirun-%s.log'%(datetime),
'w' )
56 streamhandler = logging.StreamHandler(strm=outfile)
57 console = logging.StreamHandler()
59 formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s" )
61 streamhandler.setFormatter(formatter)
62 console.setFormatter(formatter)
66 self.log = multiprocessing.log_to_stderr()
67 self.log.setLevel( logging.INFO )
68 self.log.name =
'Gaudi/Main.py Logger'
69 self.log.handlers = []
71 self.log.addHandler(streamhandler)
72 self.log.addHandler(console)
73 self.log.removeHandler(console)
75 self.log.setLevel = logging.INFO
78 def generatePyOutput(self, all = False):
79 from pprint
import pformat
80 conf_dict = Configuration.configurationDict(all)
81 return pformat(conf_dict)
83 def generateOptsOutput(self, all = False):
84 from pprint
import pformat
85 conf_dict = Configuration.configurationDict(all)
87 names = conf_dict.keys()
90 props = conf_dict[n].keys()
93 out.append(
'%s.%s = %s;' % (n,p,
toOpt(conf_dict[n][p])))
96 def _writepickle(self, filename) :
99 output = open(filename,
'wb')
104 to_dump[n] = Configuration.allConfigurables[n]
105 pickle.dump(to_dump, output, -1)
108 def printconfig(self, old_format = False, all = False) :
109 msg =
'Dumping all configurables and properties'
111 msg +=
' (different from default)'
113 conf_dict = Configuration.configurationDict(all)
115 print self.generateOptsOutput(all)
117 print self.generatePyOutput(all)
119 def writeconfig(self, filename, all = False):
120 write = {
".pkl" :
lambda filename, all: self._writepickle(filename),
121 ".py" :
lambda filename, all: open(filename,
"w").write(self.generatePyOutput(all) +
"\n"),
122 ".opts":
lambda filename, all: open(filename,
"w").write(self.generateOptsOutput(all) +
"\n"),
124 from os.path
import splitext
125 ext = splitext(filename)[1]
127 write[ext](filename, all)
129 log.error(
"Unknown file type '%s'. Must be any of %r.", ext, write.keys())
132 def _printsequence(self):
133 if not self.printsequence:
137 def printAlgo( algName, appMgr, prefix = ' ') :
138 print prefix + algName
139 alg = appMgr.algorithm( algName.split(
"/" )[ -1 ] )
140 prop = alg.properties()
141 if prop.has_key(
"Members" ) :
142 subs = prop[
"Members" ].
value()
143 for i
in subs : printAlgo( i.strip(
'"' ), appMgr, prefix +
" " )
144 elif prop.has_key(
"DetectorList" ) :
145 subs = prop[
"DetectorList" ].
value()
146 for i
in subs : printAlgo( algName.split(
"/" )[ -1 ] + i.strip(
'"' ) +
"Seq", appMgr, prefix +
" ")
148 mp = self.g.properties()
149 print "\n ****************************** Algorithm Sequence **************************** \n"
150 for i
in mp[
"TopAlg"].
value(): printAlgo( i, self.g )
151 print "\n ****************************************************************************** \n"
155 def run(self, ncpus = None):
158 result = self.runSerial()
161 result = self.runParallel(ncpus)
165 def runSerial(self) :
168 self.log.debug(
'-'*80)
169 self.log.debug(
'%s: running in serial mode', __name__)
170 self.log.debug(
'-'*80)
173 self._printsequence()
174 runner = self.mainLoop
or (
lambda app, nevt: app.run(nevt))
176 statuscode = runner(self.g, self.g.EvtMax)
179 self.g.ReturnCode = 128 + 11
183 self.g.ReturnCode = 1
185 if hasattr(statuscode,
"isSuccess"):
186 success = statuscode.isSuccess()
189 success = self.g.exit().isSuccess()
and success
190 if not success
and self.g.ReturnCode == 0:
192 self.g.ReturnCode = 1
193 sysTime = time()-sysStart
194 self.log.debug(
'-'*80)
195 self.log.debug(
'%s: serial system finished, time taken: %5.4fs', __name__, sysTime)
196 self.log.debug(
'-'*80)
197 return self.g.ReturnCode
199 def runParallel(self, ncpus) :
201 self.log.fatal(
"Cannot use custom main loop in multi-process mode, check your options")
203 self.setupParallelLogging( )
206 c = Configurable.allConfigurables
207 self.log.info(
'-'*80)
208 self.log.info(
'%s: Parallel Mode : %i '%(__name__, ncpus))
209 from commands
import getstatusoutput
as gso
210 metadataCommands = [
'uname -a',
212 'echo $GAUDIAPPNAME',
213 'echo $GAUDIAPPVERSION']
214 for comm
in metadataCommands :
218 string =
'%s: %30s : %s '%(__name__, comm, o)
219 self.log.info( string )
221 events = str(c[
'ApplicationMgr'].EvtMax)
223 events =
"Undetermined"
224 self.log.info(
'%s: Events Specified : %s '%(__name__,events))
225 self.log.info(
'-'*80)
227 Parall = gpp.Coord( ncpus, c, self.log )
230 self.log.info(
'MAIN.PY : received %s from Coordinator'%(sc))
233 sysTime = time()-sysStart
234 self.log.name =
'Gaudi/Main.py Logger'
235 self.log.info(
'-'*80)
236 self.log.info(
'%s: parallel system finished, time taken: %5.4fs', __name__, sysTime)
237 self.log.info(
'-'*80)