1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
|
'''
Tools for piping a process to the terminal for std I/O.
Buffering and low-level filtering. Thread management.
'''
import re
import subprocess
from subprocess import Popen, PIPE
from threading import Thread, Event
import os
import signal
class DataBox():
''' container for pre-processed trace data '''
def __init__(self):
self.comments = []
self.instrdef = []
self.particle_blocks = []
# event objects
self.instrdone = Event()
self.instrdone.clear()
self.particlesdone = Event()
self.particlesdone.clear()
def add_comment(self, line):
self.comments.append(line)
def add_instrdef(self, line):
self.instrdef.append(line)
def add_particleblock(self, block):
self.particle_blocks.append(block)
def set_instrdone(self):
self.instrdone.set()
def set_particlesdone(self):
self.particlesdone.set()
def get_instrdef(self):
self.instrdone.wait()
return ''.join(self.instrdef)
def get_particles(self):
self.particlesdone.wait()
return ''.join(self.particle_blocks)
def get_comments(self):
self.instrdone.wait()
self.particlesdone.wait()
return ''.join(self.comments)
class LineHandlerState(object):
def __init__(self, setcurrent, next, databox, args=None):
'''
Abstract state for all line handler states - instrdef, particles, etc.
setcurrent: a fuction of state, line
allstates: a dictionary of all states given typename
databox: global data destination / buffer
'''
self.setcurrent = setcurrent
self.next = next
self.databox = databox
self.args = args
def add_line(self, line):
''' override to implement a state '''
pass
class PromptState(LineHandlerState):
def add_line(self, line):
# switch case
if re.match(r'INSTRUMENT:\n', line):
self.setcurrent(self.next, line)
return
# prompt case
print(line.rstrip('\n'))
self.databox.add_comment(line)
if re.search(r'\]:', line):
if not self.args['use_defaultpars']:
inpt = input()
self.process.stdin.write(inpt + '\n')
self.process.stdin.flush()
else:
self.process.stdin.write('\n')
self.process.stdin.flush()
def setprocess(self, process):
self.process = process
class InstrState(LineHandlerState):
def __init__(self, setcurrent, next, databox, args=None):
self.idx = 0
self.first = True
self.second = False
super(InstrState, self).__init__(setcurrent, next, databox, args)
def add_line(self, line):
if self.first and re.match('INSTRUMENT:', line):
self.databox.add_instrdef(line)
self.first = False
self.second = True
elif self.second and re.match(r'Instrument \'[\w\-]+\' \([/\w\\\:\-]+.instr\)', line):
self.databox.add_instrdef(line)
self.second = False
elif re.match('COMPONENT:', line):
self.databox.add_instrdef(line)
elif re.match('POS:', line):
self.databox.add_instrdef(line)
elif re.match('MCDISPLAY: start', line):
self.databox.set_instrdone()
self.setcurrent(self.next, line)
else:
self.databox.add_comment(line)
class McdisplayState(LineHandlerState):
def add_line(self, line):
if re.match('MCDISPLAY: ', line):
self.databox.add_instrdef(line)
elif re.match('MANTID_PIXEL: ', line):
self.databox.add_instrdef(line)
elif re.match('MANTID_RECTANGULAR_DET: ', line):
self.databox.add_instrdef(line)
elif re.match('MANTID_BANANA_DET: ', line):
self.databox.add_instrdef(line)
elif re.match('INSTRUMENT END:', line):
self.databox.add_instrdef(line)
elif re.match('ENTER:', line):
self.databox.set_instrdone()
self.setcurrent(self.next, line)
else:
self.databox.add_comment(line)
class ParticlesTraceState(LineHandlerState):
def __init__(self, setcurrent, next, databox, args=None):
self.process = None
self.block = []
self.active = False
self.leaveflag = False
self.inspect = None
if args:
self.inspect = args.get('inspect', None)
super(ParticlesTraceState, self).__init__(setcurrent, next, databox, args)
self.max_particles = 1000
if args:
self.max_particles = args.get('max_particles', 1000)
self.block_count = 0
def add_line(self, line):
def check(line):
if len(line) > 5:
return line[:5] in ('SCATT', 'STATE', 'COMP:', 'ABSOR')
if re.match('LEAVE:', line):
self.block.append(line)
self.leaveflag = True
self.active = False
elif self.active and check(line):
self.block.append(line)
elif re.match('ENTER:', line):
self.block.append(line)
self.active = True
elif self.leaveflag and check(line):
self.block.append(line)
# inspect
accept_block = True
if self.inspect:
accept_block = False
for b in self.block:
if re.match('COMP: "%s"' % self.inspect, b):
accept_block = True
break
if accept_block:
self.databox.add_particleblock(''.join(self.block))
if self.block_count > self.max_particles:
print('max particle count exceeded, blocking all further trace particle trace lines...')
self.setcurrent(self.next, None)
self.block_count += 1
self.block = []
self.leaveflag = False
else:
self.databox.add_comment(line)
class PostParticletraceState(LineHandlerState):
''' this state does nothing, so nothing happens from now on '''
waskilled = False
def add_line(self, line):
# Only kill if PID still can be killed, buffered stream data
# means that we could enter here multiple times still.
try:
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
except:
# The above os.killpg works fine on Unix, but on Win32 we can instead
try:
subprocess.call(['taskkill', '/F', '/T', '/PID', str(self.process.pid)])
except:
pass
self.waskilled = True
def setprocess(self, process):
self.process = process
class ThreadException(Exception):
pass
class TraceReader(Thread):
def _setcurrent(self, current, line):
self.current = current
current.add_line(line)
def __init__(self, cmd, inspect=None, use_defaultpars=False, max_particles=1000):
self.exc_obj = None
# set up state machine
allstates = {}
databox = DataBox()
allstates['post_particles'] = PostParticletraceState(self._setcurrent, None, databox=databox)
allstates['particles'] = ParticlesTraceState(self._setcurrent, next=allstates['post_particles'], databox=databox,
args={'inspect': inspect, 'max_particles': max_particles})
allstates['mcdisplay'] = McdisplayState(self._setcurrent, next=allstates['particles'], databox=databox)
allstates['instr'] = InstrState(self._setcurrent, next=allstates['mcdisplay'], databox=databox)
allstates['prompt'] = PromptState(self._setcurrent, next=allstates['instr'], databox=databox,
args={'use_defaultpars': use_defaultpars})
# remember
self.current = allstates['prompt']
self.allstates = allstates
self.databox = databox
self.cmd = cmd
Thread.__init__(self)
self.daemon = True
self.debug = False
def run(self):
try:
''' create a process given command and read, print and write to it depending on state '''
# os.setsid defineds a fresh process group so that the calling Python survives when the
# simulation is potentially terminated.
if not os.name == 'nt':
process = Popen(self.cmd, shell=True, preexec_fn=os.setsid, universal_newlines=True,
stdout=PIPE,
stderr=PIPE,
stdin=PIPE
)
else:
process = Popen(self.cmd, shell=True, universal_newlines=True,
stdout=PIPE,
stderr=PIPE,
stdin=PIPE
)
# special case: give the prompt state access to process to allow automation flag,
# and particles to end the process in max particle count is exceeded
self.allstates['prompt'].setprocess(process)
self.allstates['post_particles'].setprocess(process)
poll = process.poll()
while poll == None:
for data in process.stdout:
self.current.add_line(data)
if self.debug:
print("debug - TraceReader read line: %s" % data.strip())
for data in process.stderr:
print(data.strip())
poll = process.poll()
# fail state exit status from mcrun process
if poll != 0:
if not self.allstates['post_particles'].waskilled:
self.databox.set_instrdone()
self.databox.set_particlesdone()
raise Exception("TraceReader - mcrun process exited with code: %s" % str(poll))
# If we made it all the way here, sim has ended or been killed
self.databox.set_particlesdone()
except Exception as e:
self.exc_obj = e
class TestTraceReader:
''' can be used with data from a file '''
def _setcurrent(self, current, line):
self.current = current
current.add_line(line)
def __init__(self, text):
self.exc_obj = None
allstates = {}
databox = DataBox()
allstates['particles'] = ParticlesTraceState(self._setcurrent, next=None, databox=databox)
allstates['mcdisplay'] = McdisplayState(self._setcurrent, next=allstates['particles'], databox=databox)
allstates['instr'] = InstrState(self._setcurrent, next=allstates['mcdisplay'], databox=databox)
# remember
self.current = allstates['instr']
self.allstates = allstates
self.databox = databox
for line in text.splitlines():
self.current.add_line(line + '\n')
self.databox.set_particlesdone()
def start(self):
pass
def join(self, timeout=-1):
pass
class McrunPipeMan(object):
'''
Proxy class for setting up the McrunPipeThread thread and LineBuffer.
These are intended to provide parallel processing and piping, due to
potentially long simulation execution times.
'''
cmd = ''
instrdef_start = ''
instrdef_end = ''
def __init__(self, cmd, inspect=None, send_enter=False):
self.cmd = cmd
self.reader = TraceReader(cmd=cmd, inspect=inspect, use_defaultpars=send_enter)
def start_pipe(self):
self.reader.start()
def join(self):
self.reader.join(1000)
if self.reader.exc_obj:
print(self.reader.databox.get_comments())
raise self.reader.exc_obj
def read_particles(self):
return self.reader.databox.get_particles()
def read_instrdef(self):
return self.reader.databox.get_instrdef()
def read_comments(self):
return self.reader.databox.get_comments()
|