forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaexpect.py
executable file
·1438 lines (1184 loc) · 53.8 KB
/
aexpect.py
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""
A class and functions used for running and controlling child processes.
@copyright: 2008-2009 Red Hat Inc.
"""
import os, sys, pty, select, termios, fcntl
BASE_DIR = os.path.join('/tmp', 'aexpect_spawn')
# The following helper functions are shared by the server and the client.
def _lock(filename):
if not os.path.exists(filename):
open(filename, "w").close()
fd = os.open(filename, os.O_RDWR)
fcntl.lockf(fd, fcntl.LOCK_EX)
return fd
def _unlock(fd):
fcntl.lockf(fd, fcntl.LOCK_UN)
os.close(fd)
def _locked(filename):
try:
fd = os.open(filename, os.O_RDWR)
except Exception:
return False
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except Exception:
os.close(fd)
return True
fcntl.lockf(fd, fcntl.LOCK_UN)
os.close(fd)
return False
def _wait(filename):
fd = _lock(filename)
_unlock(fd)
def _get_filenames(base_dir, a_id):
return [os.path.join(base_dir, s + a_id) for s in
"shell-pid-", "status-", "output-", "inpipe-",
"lock-server-running-", "lock-client-starting-"]
def _get_reader_filename(base_dir, a_id, reader):
return os.path.join(base_dir, "outpipe-%s-%s" % (reader, a_id))
# The following is the server part of the module.
if __name__ == "__main__":
a_id = sys.stdin.readline().strip()
echo = sys.stdin.readline().strip() == "True"
readers = sys.stdin.readline().strip().split(",")
command = sys.stdin.readline().strip() + " && echo %s > /dev/null" % a_id
# Define filenames to be used for communication
(shell_pid_filename,
status_filename,
output_filename,
inpipe_filename,
lock_server_running_filename,
lock_client_starting_filename) = _get_filenames(BASE_DIR, a_id)
# Populate the reader filenames list
reader_filenames = [_get_reader_filename(BASE_DIR, a_id, reader)
for reader in readers]
# Set $TERM = dumb
os.putenv("TERM", "dumb")
(shell_pid, shell_fd) = pty.fork()
if shell_pid == 0:
# Child process: run the command in a subshell
os.execv("/bin/sh", ["/bin/sh", "-c", command])
else:
# Parent process
lock_server_running = _lock(lock_server_running_filename)
# Set terminal echo on/off and disable pre- and post-processing
attr = termios.tcgetattr(shell_fd)
attr[0] &= ~termios.INLCR
attr[0] &= ~termios.ICRNL
attr[0] &= ~termios.IGNCR
attr[1] &= ~termios.OPOST
if echo:
attr[3] |= termios.ECHO
else:
attr[3] &= ~termios.ECHO
termios.tcsetattr(shell_fd, termios.TCSANOW, attr)
# Open output file
output_file = open(output_filename, "w")
# Open input pipe
os.mkfifo(inpipe_filename)
inpipe_fd = os.open(inpipe_filename, os.O_RDWR)
# Open output pipes (readers)
reader_fds = []
for filename in reader_filenames:
os.mkfifo(filename)
reader_fds.append(os.open(filename, os.O_RDWR))
# Write shell PID to file
fileobj = open(shell_pid_filename, "w")
fileobj.write(str(shell_pid))
fileobj.close()
# Print something to stdout so the client can start working
print "Server %s ready" % a_id
sys.stdout.flush()
# Initialize buffers
buffers = ["" for reader in readers]
# Read from child and write to files/pipes
while True:
check_termination = False
# Make a list of reader pipes whose buffers are not empty
fds = [fd for (i, fd) in enumerate(reader_fds) if buffers[i]]
# Wait until there's something to do
r, w, x = select.select([shell_fd, inpipe_fd], fds, [], 0.5)
# If a reader pipe is ready for writing --
for (i, fd) in enumerate(reader_fds):
if fd in w:
bytes_written = os.write(fd, buffers[i])
buffers[i] = buffers[i][bytes_written:]
# If there's data to read from the child process --
if shell_fd in r:
try:
data = os.read(shell_fd, 16384)
except OSError:
data = ""
if not data:
check_termination = True
# Remove carriage returns from the data -- they often cause
# trouble and are normally not needed
data = data.replace("\r", "")
output_file.write(data)
output_file.flush()
for i in range(len(readers)):
buffers[i] += data
# If os.read() raised an exception or there was nothing to read --
if check_termination or shell_fd not in r:
pid, status = os.waitpid(shell_pid, os.WNOHANG)
if pid:
status = os.WEXITSTATUS(status)
break
# If there's data to read from the client --
if inpipe_fd in r:
data = os.read(inpipe_fd, 1024)
os.write(shell_fd, data)
# Write the exit status to a file
fileobj = open(status_filename, "w")
fileobj.write(str(status))
fileobj.close()
# Wait for the client to finish initializing
_wait(lock_client_starting_filename)
# Delete FIFOs
for filename in [inpipe_filename]:
try:
os.unlink(filename)
except OSError:
pass
# Close all files and pipes
output_file.close()
os.close(inpipe_fd)
for fd in reader_fds:
os.close(fd)
_unlock(lock_server_running)
sys.exit(0)
# The following is the client part of the module.
import subprocess, time, signal, re, threading, logging
import utils_misc
class ExpectError(Exception):
def __init__(self, patterns, output):
Exception.__init__(self, patterns, output)
self.patterns = patterns
self.output = output
def _pattern_str(self):
if len(self.patterns) == 1:
return "pattern %r" % self.patterns[0]
else:
return "patterns %r" % self.patterns
def __str__(self):
return ("Unknown error occurred while looking for %s (output: %r)" %
(self._pattern_str(), self.output))
class ExpectTimeoutError(ExpectError):
def __str__(self):
return ("Timeout expired while looking for %s (output: %r)" %
(self._pattern_str(), self.output))
class ExpectProcessTerminatedError(ExpectError):
def __init__(self, patterns, status, output):
ExpectError.__init__(self, patterns, output)
self.status = status
def __str__(self):
return ("Process terminated while looking for %s "
"(status: %s, output: %r)" % (self._pattern_str(),
self.status, self.output))
class ShellError(Exception):
def __init__(self, cmd, output):
Exception.__init__(self, cmd, output)
self.cmd = cmd
self.output = output
def __str__(self):
return ("Could not execute shell command %r (output: %r)" %
(self.cmd, self.output))
class ShellTimeoutError(ShellError):
def __str__(self):
return ("Timeout expired while waiting for shell command to "
"complete: %r (output: %r)" % (self.cmd, self.output))
class ShellProcessTerminatedError(ShellError):
# Raised when the shell process itself (e.g. ssh, netcat, telnet)
# terminates unexpectedly
def __init__(self, cmd, status, output):
ShellError.__init__(self, cmd, output)
self.status = status
def __str__(self):
return ("Shell process terminated while waiting for command to "
"complete: %r (status: %s, output: %r)" %
(self.cmd, self.status, self.output))
class ShellCmdError(ShellError):
# Raised when a command executed in a shell terminates with a nonzero
# exit code (status)
def __init__(self, cmd, status, output):
ShellError.__init__(self, cmd, output)
self.status = status
def __str__(self):
return ("Shell command failed: %r (status: %s, output: %r)" %
(self.cmd, self.status, self.output))
class ShellStatusError(ShellError):
# Raised when the command's exit status cannot be obtained
def __str__(self):
return ("Could not get exit status of command: %r (output: %r)" %
(self.cmd, self.output))
def run_bg(command, termination_func=None, output_func=None, output_prefix="",
timeout=1.0, auto_close=True):
"""
Run command as a subprocess. Call output_func with each line of output
from the subprocess (prefixed by output_prefix). Call termination_func
when the subprocess terminates. Return when timeout expires or when the
subprocess exits -- whichever occurs first.
@brief: Run a subprocess in the background and collect its output and
exit status.
@param command: The shell command to execute
@param termination_func: A function to call when the process terminates
(should take an integer exit status parameter)
@param output_func: A function to call with each line of output from
the subprocess (should take a string parameter)
@param output_prefix: A string to pre-pend to each line of the output,
before passing it to stdout_func
@param timeout: Time duration (in seconds) to wait for the subprocess to
terminate before returning
@param auto_close: If True, close() the instance automatically when its
reference count drops to zero (default False).
@return: A Expect object.
"""
process = Expect(command=command,
termination_func=termination_func,
output_func=output_func,
output_prefix=output_prefix,
auto_close=auto_close)
end_time = time.time() + timeout
while time.time() < end_time and process.is_alive():
time.sleep(0.1)
return process
def run_fg(command, output_func=None, output_prefix="", timeout=1.0):
"""
Run command as a subprocess. Call output_func with each line of output
from the subprocess (prefixed by prefix). Return when timeout expires or
when the subprocess exits -- whichever occurs first. If timeout expires
and the subprocess is still running, kill it before returning.
@brief: Run a subprocess in the foreground and collect its output and
exit status.
@param command: The shell command to execute
@param output_func: A function to call with each line of output from
the subprocess (should take a string parameter)
@param output_prefix: A string to pre-pend to each line of the output,
before passing it to stdout_func
@param timeout: Time duration (in seconds) to wait for the subprocess to
terminate before killing it and returning
@return: A 2-tuple containing the exit status of the process and its
STDOUT/STDERR output. If timeout expires before the process
terminates, the returned status is None.
"""
process = run_bg(command, None, output_func, output_prefix, timeout)
output = process.get_output()
if process.is_alive():
status = None
else:
status = process.get_status()
process.close()
return (status, output)
class Spawn:
"""
This class is used for spawning and controlling a child process.
A new instance of this class can either run a new server (a small Python
program that reads output from the child process and reports it to the
client and to a text file) or attach to an already running server.
When a server is started it runs the child process.
The server writes output from the child's STDOUT and STDERR to a text file.
The text file can be accessed at any time using get_output().
In addition, the server opens as many pipes as requested by the client and
writes the output to them.
The pipes are requested and accessed by classes derived from Spawn.
These pipes are referred to as "readers".
The server also receives input from the client and sends it to the child
process.
An instance of this class can be pickled. Every derived class is
responsible for restoring its own state by properly defining
__getinitargs__().
The first named pipe is used by _tail(), a function that runs in the
background and reports new output from the child as it is produced.
The second named pipe is used by a set of functions that read and parse
output as requested by the user in an interactive manner, similar to
pexpect.
When unpickled it automatically
resumes _tail() if needed.
"""
def __init__(self, command=None, a_id=None, auto_close=False, echo=False,
linesep="\n"):
"""
Initialize the class and run command as a child process.
@param command: Command to run, or None if accessing an already running
server.
@param a_id: ID of an already running server, if accessing a running
server, or None if starting a new one.
@param auto_close: If True, close() the instance automatically when its
reference count drops to zero (default False).
@param echo: Boolean indicating whether echo should be initially
enabled for the pseudo terminal running the subprocess. This
parameter has an effect only when starting a new server.
@param linesep: Line separator to be appended to strings sent to the
child process by sendline().
"""
self.a_id = a_id or utils_misc.generate_random_string(8)
self.log_file = None
# Define filenames for communication with server
try:
os.makedirs(BASE_DIR)
except Exception:
pass
(self.shell_pid_filename,
self.status_filename,
self.output_filename,
self.inpipe_filename,
self.lock_server_running_filename,
self.lock_client_starting_filename) = _get_filenames(BASE_DIR,
self.a_id)
# Remember some attributes
self.auto_close = auto_close
self.echo = echo
self.linesep = linesep
# Make sure the 'readers' and 'close_hooks' attributes exist
if not hasattr(self, "readers"):
self.readers = []
if not hasattr(self, "close_hooks"):
self.close_hooks = []
# Define the reader filenames
self.reader_filenames = dict(
(reader, _get_reader_filename(BASE_DIR, self.a_id, reader))
for reader in self.readers)
# Let the server know a client intends to open some pipes;
# if the executed command terminates quickly, the server will wait for
# the client to release the lock before exiting
lock_client_starting = _lock(self.lock_client_starting_filename)
# Start the server (which runs the command)
if command:
sub = subprocess.Popen("%s %s" % (sys.executable, __file__),
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
# Send parameters to the server
sub.stdin.write("%s\n" % self.a_id)
sub.stdin.write("%s\n" % echo)
sub.stdin.write("%s\n" % ",".join(self.readers))
sub.stdin.write("%s\n" % command)
# Wait for the server to complete its initialization
while not "Server %s ready" % self.a_id in sub.stdout.readline():
pass
# Open the reading pipes
self.reader_fds = {}
try:
assert(_locked(self.lock_server_running_filename))
for reader, filename in self.reader_filenames.items():
self.reader_fds[reader] = os.open(filename, os.O_RDONLY)
except Exception:
pass
# Allow the server to continue
_unlock(lock_client_starting)
# The following two functions are defined to make sure the state is set
# exclusively by the constructor call as specified in __getinitargs__().
def __getstate__(self):
pass
def __setstate__(self, state):
pass
def __getinitargs__(self):
# Save some information when pickling -- will be passed to the
# constructor upon unpickling
return (None, self.a_id, self.auto_close, self.echo, self.linesep)
def __del__(self):
self._close_reader_fds()
if self.auto_close:
self.close()
def _add_reader(self, reader):
"""
Add a reader whose file descriptor can be obtained with _get_fd().
Should be called before __init__(). Intended for use by derived
classes.
@param reader: The name of the reader.
"""
if not hasattr(self, "readers"):
self.readers = []
self.readers.append(reader)
def _add_close_hook(self, hook):
"""
Add a close hook function to be called when close() is called.
The function will be called after the process terminates but before
final cleanup. Intended for use by derived classes.
@param hook: The hook function.
"""
if not hasattr(self, "close_hooks"):
self.close_hooks = []
self.close_hooks.append(hook)
def _get_fd(self, reader):
"""
Return an open file descriptor corresponding to the specified reader
pipe. If no such reader exists, or the pipe could not be opened,
return None. Intended for use by derived classes.
@param reader: The name of the reader.
"""
return self.reader_fds.get(reader)
def _close_reader_fds(self):
"""
Close all reader file descriptors.
"""
for fd in self.reader_fds.values():
try:
os.close(fd)
except OSError:
pass
def get_id(self):
"""
Return the instance's a_id attribute, which may be used to access the
process in the future.
"""
return self.a_id
def get_pid(self):
"""
Return the PID of the process.
Note: this may be the PID of the shell process running the user given
command.
"""
try:
fileobj = open(self.shell_pid_filename, "r")
pid = int(fileobj.read())
fileobj.close()
return pid
except Exception:
return None
def get_status(self):
"""
Wait for the process to exit and return its exit status, or None
if the exit status is not available.
"""
_wait(self.lock_server_running_filename)
try:
fileobj = open(self.status_filename, "r")
status = int(fileobj.read())
fileobj.close()
return status
except Exception:
return None
def get_output(self):
"""
Return the STDOUT and STDERR output of the process so far.
"""
try:
fileobj = open(self.output_filename, "r")
output = fileobj.read()
fileobj.close()
return output
except Exception:
return ""
def is_alive(self):
"""
Return True if the process is running.
"""
return _locked(self.lock_server_running_filename)
def close(self, sig=signal.SIGKILL):
"""
Kill the child process if it's alive and remove temporary files.
@param sig: The signal to send the process when attempting to kill it.
"""
# Kill it if it's alive
if self.is_alive():
utils_misc.kill_process_tree(self.get_pid(), sig)
# Wait for the server to exit
_wait(self.lock_server_running_filename)
# Call all cleanup routines
for hook in self.close_hooks:
hook(self)
# Close reader file descriptors
self._close_reader_fds()
self.reader_fds = {}
# Remove all used files
for filename in (_get_filenames(BASE_DIR, self.a_id)):
try:
os.unlink(filename)
except OSError:
pass
def set_linesep(self, linesep):
"""
Sets the line separator string (usually "\\n").
@param linesep: Line separator string.
"""
self.linesep = linesep
def send(self, cont=""):
"""
Send a string to the child process.
@param cont: String to send to the child process.
"""
try:
fd = os.open(self.inpipe_filename, os.O_RDWR)
os.write(fd, cont)
os.close(fd)
except Exception:
pass
def sendline(self, cont=""):
"""
Send a string followed by a line separator to the child process.
@param cont: String to send to the child process.
"""
self.send(cont + self.linesep)
_thread_kill_requested = False
def kill_tail_threads():
"""
Kill all Tail threads.
After calling this function no new threads should be started.
"""
global _thread_kill_requested
_thread_kill_requested = True
for t in threading.enumerate():
if hasattr(t, "name") and t.name.startswith("tail_thread"):
t.join(10)
_thread_kill_requested = False
class Tail(Spawn):
"""
This class runs a child process in the background and sends its output in
real time, line-by-line, to a callback function.
See Spawn's docstring.
This class uses a single pipe reader to read data in real time from the
child process and report it to a given callback function.
When the child process exits, its exit status is reported to an additional
callback function.
When this class is unpickled, it automatically resumes reporting output.
"""
def __init__(self, command=None, a_id=None, auto_close=False, echo=False,
linesep="\n", termination_func=None, termination_params=(),
output_func=None, output_params=(), output_prefix=""):
"""
Initialize the class and run command as a child process.
@param command: Command to run, or None if accessing an already running
server.
@param a_id: ID of an already running server, if accessing a running
server, or None if starting a new one.
@param auto_close: If True, close() the instance automatically when its
reference count drops to zero (default False).
@param echo: Boolean indicating whether echo should be initially
enabled for the pseudo terminal running the subprocess. This
parameter has an effect only when starting a new server.
@param linesep: Line separator to be appended to strings sent to the
child process by sendline().
@param termination_func: Function to call when the process exits. The
function must accept a single exit status parameter.
@param termination_params: Parameters to send to termination_func
before the exit status.
@param output_func: Function to call whenever a line of output is
available from the STDOUT or STDERR streams of the process.
The function must accept a single string parameter. The string
does not include the final newline.
@param output_params: Parameters to send to output_func before the
output line.
@param output_prefix: String to prepend to lines sent to output_func.
"""
# Add a reader and a close hook
self._add_reader("tail")
self._add_close_hook(Tail._join_thread)
self._add_close_hook(Tail._close_log_file)
# Init the superclass
Spawn.__init__(self, command, a_id, auto_close, echo, linesep)
# Remember some attributes
self.termination_func = termination_func
self.termination_params = termination_params
self.output_func = output_func
self.output_params = output_params
self.output_prefix = output_prefix
# Start the thread in the background
self.tail_thread = None
if termination_func or output_func:
self._start_thread()
def __getinitargs__(self):
return Spawn.__getinitargs__(self) + (self.termination_func,
self.termination_params,
self.output_func,
self.output_params,
self.output_prefix)
def set_termination_func(self, termination_func):
"""
Set the termination_func attribute. See __init__() for details.
@param termination_func: Function to call when the process terminates.
Must take a single parameter -- the exit status.
"""
self.termination_func = termination_func
if termination_func and not self.tail_thread:
self._start_thread()
def set_termination_params(self, termination_params):
"""
Set the termination_params attribute. See __init__() for details.
@param termination_params: Parameters to send to termination_func
before the exit status.
"""
self.termination_params = termination_params
def set_output_func(self, output_func):
"""
Set the output_func attribute. See __init__() for details.
@param output_func: Function to call for each line of STDOUT/STDERR
output from the process. Must take a single string parameter.
"""
self.output_func = output_func
if output_func and not self.tail_thread:
self._start_thread()
def set_output_params(self, output_params):
"""
Set the output_params attribute. See __init__() for details.
@param output_params: Parameters to send to output_func before the
output line.
"""
self.output_params = output_params
def set_output_prefix(self, output_prefix):
"""
Set the output_prefix attribute. See __init__() for details.
@param output_prefix: String to pre-pend to each line sent to
output_func (see set_output_callback()).
"""
self.output_prefix = output_prefix
def set_log_file(self, filename):
"""
Set a log file name for this tail instance.
@param filename: Base name of the log.
"""
self.log_file = filename
def _close_log_file(self):
if self.log_file is not None:
utils_misc.close_log_file(self.log_file)
def _tail(self):
def print_line(text):
# Pre-pend prefix and remove trailing whitespace
text = self.output_prefix + text.rstrip()
# Pass text to output_func
try:
params = self.output_params + (text,)
self.output_func(*params)
except TypeError:
pass
try:
fd = self._get_fd("tail")
bfr = ""
while True:
global _thread_kill_requested
if _thread_kill_requested:
return
try:
# See if there's any data to read from the pipe
r, w, x = select.select([fd], [], [], 0.05)
except Exception:
break
if fd in r:
# Some data is available; read it
new_data = os.read(fd, 1024)
if not new_data:
break
bfr += new_data
# Send the output to output_func line by line
# (except for the last line)
if self.output_func:
lines = bfr.split("\n")
for line in lines[:-1]:
print_line(line)
# Leave only the last line
last_newline_index = bfr.rfind("\n")
bfr = bfr[last_newline_index + 1:]
else:
# No output is available right now; flush the bfr
if bfr:
print_line(bfr)
bfr = ""
# The process terminated; print any remaining output
if bfr:
print_line(bfr)
# Get the exit status, print it and send it to termination_func
status = self.get_status()
if status is None:
return
print_line("(Process terminated with status %s)" % status)
try:
params = self.termination_params + (status,)
self.termination_func(*params)
except TypeError:
pass
finally:
self.tail_thread = None
def _start_thread(self):
self.tail_thread = threading.Thread(target=self._tail,
name="tail_thread_%s" % self.a_id)
self.tail_thread.start()
def _join_thread(self):
# Wait for the tail thread to exit
# (it's done this way because self.tail_thread may become None at any
# time)
t = self.tail_thread
if t:
t.join()
class Expect(Tail):
"""
This class runs a child process in the background and provides expect-like
services.
It also provides all of Tail's functionality.
"""
def __init__(self, command=None, a_id=None, auto_close=True, echo=False,
linesep="\n", termination_func=None, termination_params=(),
output_func=None, output_params=(), output_prefix=""):
"""
Initialize the class and run command as a child process.
@param command: Command to run, or None if accessing an already running
server.
@param a_id: ID of an already running server, if accessing a running
server, or None if starting a new one.
@param auto_close: If True, close() the instance automatically when its
reference count drops to zero (default False).
@param echo: Boolean indicating whether echo should be initially
enabled for the pseudo terminal running the subprocess. This
parameter has an effect only when starting a new server.
@param linesep: Line separator to be appended to strings sent to the
child process by sendline().
@param termination_func: Function to call when the process exits. The
function must accept a single exit status parameter.
@param termination_params: Parameters to send to termination_func
before the exit status.
@param output_func: Function to call whenever a line of output is
available from the STDOUT or STDERR streams of the process.
The function must accept a single string parameter. The string
does not include the final newline.
@param output_params: Parameters to send to output_func before the
output line.
@param output_prefix: String to prepend to lines sent to output_func.
"""
# Add a reader
self._add_reader("expect")
# Init the superclass
Tail.__init__(self, command, a_id, auto_close, echo, linesep,
termination_func, termination_params,
output_func, output_params, output_prefix)
def __getinitargs__(self):
return Tail.__getinitargs__(self)
def read_nonblocking(self, internal_timeout=None, timeout=None):
"""
Read from child until there is nothing to read for timeout seconds.
@param internal_timeout: Time (seconds) to wait before we give up
reading from the child process, or None to
use the default value.
@param timeout: Timeout for reading child process output.
"""
if internal_timeout is None:
internal_timeout = 0.1
end_time = None
if timeout:
end_time = time.time() + timeout
fd = self._get_fd("expect")
data = ""
while True:
try:
r, w, x = select.select([fd], [], [], internal_timeout)
except Exception:
return data
if fd in r:
new_data = os.read(fd, 1024)
if not new_data:
return data
data += new_data
else:
return data
if end_time and time.time() > end_time:
return data
def match_patterns(self, cont, patterns):
"""
Match cont against a list of patterns.
Return the index of the first pattern that matches a substring of cont.
None and empty strings in patterns are ignored.
If no match is found, return None.
@param cont: input string
@param patterns: List of strings (regular expression patterns).
"""
for i in range(len(patterns)):
if not patterns[i]:
continue
if re.search(patterns[i], cont):
return i
def match_patterns_multiline(self, cont, patterns):
"""
Match list of lines against a list of patterns.
Return the index of the first pattern that matches a substring of cont.
None and empty strings in patterns are ignored.
If no match is found, return None.
@param cont: List of strings (input strings)
@param patterns: List of strings (regular expression patterns). The
pattern priority is from the last to first.
"""
for i in range(-len(patterns), 0):
if not patterns[i]:
continue
for line in cont:
if re.search(patterns[i], line):
return i
def read_until_output_matches(self, patterns, filter_func=lambda x: x,
timeout=60, internal_timeout=None,
print_func=None, match_func=None):
"""
Read using read_nonblocking until a match is found using match_patterns,