blob: 4b68ef5e27daaad559cb54e253a6ff7693847c86 [file] [log] [blame]
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02001# osmo_gsm_tester: process management
2#
3# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
4#
5# Author: Neels Hofmeyr <neels@hofmeyr.de>
6#
7# This program is free software: you can redistribute it and/or modify
Harald Welte27205342017-06-03 09:51:45 +02008# it under the terms of the GNU General Public License as
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02009# published by the Free Software Foundation, either version 3 of the
10# License, or (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Harald Welte27205342017-06-03 09:51:45 +020015# GNU General Public License for more details.
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020016#
Harald Welte27205342017-06-03 09:51:45 +020017# You should have received a copy of the GNU General Public License
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020018# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
Neels Hofmeyr3531a192017-03-28 14:30:28 +020020import os
21import time
22import subprocess
23import signal
Pau Espin Pedrol0d8deec2017-06-23 11:43:38 +020024from datetime import datetime
Neels Hofmeyr3531a192017-03-28 14:30:28 +020025
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020026from . import log, test, event_loop
Neels Hofmeyr3531a192017-03-28 14:30:28 +020027from .util import Dir
28
29class Process(log.Origin):
30
31 process_obj = None
32 outputs = None
33 result = None
34 killed = None
35
36 def __init__(self, name, run_dir, popen_args, **popen_kwargs):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +020037 super().__init__(log.C_RUN, name)
Neels Hofmeyr3531a192017-03-28 14:30:28 +020038 self.name_str = name
Neels Hofmeyr3531a192017-03-28 14:30:28 +020039 self.run_dir = run_dir
40 self.popen_args = popen_args
41 self.popen_kwargs = popen_kwargs
42 self.outputs = {}
43 if not isinstance(self.run_dir, Dir):
44 self.run_dir = Dir(os.path.abspath(str(self.run_dir)))
45
46 def set_env(self, key, value):
47 env = self.popen_kwargs.get('env') or {}
48 env[key] = value
49 self.popen_kwargs['env'] = env
50
51 def make_output_log(self, name):
52 '''
53 create a non-existing log output file in run_dir to pipe stdout and
54 stderr from this process to.
55 '''
56 path = self.run_dir.new_child(name)
57 f = open(path, 'w')
58 self.dbg(path)
Pau Espin Pedrol0d8deec2017-06-23 11:43:38 +020059 f.write('(launched: %s)\n' % datetime.now().strftime(log.LONG_DATEFMT))
Neels Hofmeyr3531a192017-03-28 14:30:28 +020060 f.flush()
61 self.outputs[name] = (path, f)
62 return f
63
64 def launch(self):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +020065 log.dbg('cd %r; %s %s' % (
66 os.path.abspath(str(self.run_dir)),
67 ' '.join(['%s=%r'%(k,v) for k,v in self.popen_kwargs.get('env', {}).items()]),
68 ' '.join(self.popen_args)))
Neels Hofmeyr3531a192017-03-28 14:30:28 +020069
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +020070 self.process_obj = subprocess.Popen(
71 self.popen_args,
72 stdout=self.make_output_log('stdout'),
73 stderr=self.make_output_log('stderr'),
74 stdin=subprocess.PIPE,
75 shell=False,
76 cwd=self.run_dir.path,
77 **self.popen_kwargs)
78 self.set_name(self.name_str, pid=self.process_obj.pid)
79 self.log('Launched')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020080
81 def _poll_termination(self, time_to_wait_for_term=5):
82 wait_step = 0.001
83 waited_time = 0
84 while True:
85 # poll returns None if proc is still running
86 self.result = self.process_obj.poll()
87 if self.result is not None:
88 return True
89 waited_time += wait_step
90 # make wait_step approach 1.0
91 wait_step = (1. + 5. * wait_step) / 6.
92 if waited_time >= time_to_wait_for_term:
93 break
94 time.sleep(wait_step)
95 return False
96
97 def terminate(self):
98 if self.process_obj is None:
99 return
100 if self.result is not None:
101 return
102
103 while True:
104 # first try SIGINT to allow stdout+stderr flushing
105 self.log('Terminating (SIGINT)')
106 os.kill(self.process_obj.pid, signal.SIGINT)
107 self.killed = signal.SIGINT
108 if self._poll_termination():
109 break
110
111 # SIGTERM maybe?
112 self.log('Terminating (SIGTERM)')
113 self.process_obj.terminate()
114 self.killed = signal.SIGTERM
115 if self._poll_termination():
116 break
117
118 # out of patience
119 self.log('Terminating (SIGKILL)')
120 self.process_obj.kill()
121 self.killed = signal.SIGKILL
122 break;
123
124 self.process_obj.wait()
125 self.cleanup()
126
127 def cleanup(self):
128 self.close_output_logs()
129 if self.result == 0:
130 self.log('Terminated: ok', rc=self.result)
131 elif self.killed:
132 self.log('Terminated', rc=self.result)
133 else:
134 self.err('Terminated: ERROR', rc=self.result)
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200135 #self.log_stdout_tail()
136 self.log_stderr_tail()
137
138 def log_stdout_tail(self):
139 m = self.get_stdout_tail(prefix='| ')
140 if not m:
141 return
142 self.log('stdout:\n', m, '\n')
143
144 def log_stderr_tail(self):
145 m = self.get_stderr_tail(prefix='| ')
146 if not m:
147 return
148 self.log('stderr:\n', m, '\n')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200149
150 def close_output_logs(self):
151 self.dbg('Cleanup')
152 for k, v in self.outputs.items():
153 path, f = v
154 if f:
155 f.flush()
156 f.close()
157 self.outputs[k] = (path, None)
158
159 def poll(self):
160 if self.process_obj is None:
161 return
162 if self.result is not None:
163 return
164 self.result = self.process_obj.poll()
165 if self.result is not None:
166 self.cleanup()
167
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200168 def is_running(self, poll_first=True):
169 if poll_first:
170 self.poll()
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200171 return self.process_obj is not None and self.result is None
172
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200173 def get_output(self, which):
174 v = self.outputs.get(which)
175 if not v:
176 return None
177 path, f = v
178 with open(path, 'r') as f2:
179 return f2.read()
180
181 def get_output_tail(self, which, tail=10, prefix=''):
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200182 out = self.get_output(which)
183 if not out:
184 return None
185 out = out.splitlines()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200186 tail = min(len(out), tail)
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200187 return prefix + ('\n' + prefix).join(out[-tail:])
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200188
189 def get_stdout(self):
190 return self.get_output('stdout')
191
192 def get_stderr(self):
193 return self.get_output('stderr')
194
195 def get_stdout_tail(self, tail=10, prefix=''):
196 return self.get_output_tail('stdout', tail, prefix)
197
198 def get_stderr_tail(self, tail=10, prefix=''):
199 return self.get_output_tail('stderr', tail, prefix)
200
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200201 def terminated(self, poll_first=True):
202 if poll_first:
203 self.poll()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200204 return self.result is not None
205
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200206 def wait(self, timeout=300):
Pau Espin Pedrol927344b2017-05-22 16:38:49 +0200207 event_loop.wait(self, self.terminated, timeout=timeout)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200208
209
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200210class RemoteProcess(Process):
211
Pau Espin Pedrol3895fec2017-04-28 16:13:03 +0200212 def __init__(self, name, run_dir, remote_user, remote_host, remote_cwd, popen_args, **popen_kwargs):
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200213 super().__init__(name, run_dir, popen_args, **popen_kwargs)
Pau Espin Pedrol3895fec2017-04-28 16:13:03 +0200214 self.remote_user = remote_user
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200215 self.remote_host = remote_host
216 self.remote_cwd = remote_cwd
217
218 # hacky: instead of just prepending ssh, i.e. piping stdout and stderr
219 # over the ssh link, we should probably run on the remote side,
220 # monitoring the process remotely.
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200221 if self.remote_cwd:
222 cd = 'cd "%s"; ' % self.remote_cwd
223 else:
224 cd = ''
Pau Espin Pedrol3895fec2017-04-28 16:13:03 +0200225 self.popen_args = ['ssh', self.remote_user+'@'+self.remote_host,
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200226 '%s%s' % (cd,
227 ' '.join(self.popen_args))]
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200228 self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200229
230# vim: expandtab tabstop=4 shiftwidth=4