blob: 7eba4072c18a9a55041f614d448cbf60c6ad9b29 [file] [log] [blame]
showard170873e2009-01-07 00:22:26 +00001#!/usr/bin/python2.4
2
3import pickle, subprocess, os, shutil, socket, sys, time, signal, getpass
showard78d4d972009-01-16 03:04:16 +00004import datetime, traceback, tempfile
showard170873e2009-01-07 00:22:26 +00005import common
6from autotest_lib.client.common_lib import utils, global_config, error
7from autotest_lib.server import hosts, subcommand
showardd1ee1dd2009-01-07 21:33:08 +00008from autotest_lib.scheduler import email_manager, scheduler_config
showard170873e2009-01-07 00:22:26 +00009
10_TEMPORARY_DIRECTORY = 'drone_tmp'
11_TRANSFER_FAILED_FILE = '.transfer_failed'
12
13class _MethodCall(object):
14 def __init__(self, method, args, kwargs):
15 self._method = method
16 self._args = args
17 self._kwargs = kwargs
18
19
20 def execute_on(self, drone_utility):
21 method = getattr(drone_utility, self._method)
22 return method(*self._args, **self._kwargs)
23
24
25 def __str__(self):
26 args = ', '.join(repr(arg) for arg in self._args)
27 kwargs = ', '.join('%s=%r' % (key, value) for key, value in
28 self._kwargs.iteritems())
29 full_args = ', '.join(item for item in (args, kwargs) if item)
30 return '%s(%s)' % (self._method, full_args)
31
32
33def call(method, *args, **kwargs):
34 return _MethodCall(method, args, kwargs)
35
36
37class DroneUtility(object):
38 """
39 This class executes actual OS calls on the drone machine.
40
41 All paths going into and out of this class are absolute.
42 """
43 _PS_ARGS = ['pid', 'pgid', 'ppid', 'comm', 'args']
showard170873e2009-01-07 00:22:26 +000044 _WARNING_DURATION = 60
45
46 def __init__(self):
47 self.warnings = []
48 self._subcommands = []
49
50
51 def initialize(self, results_dir):
52 temporary_directory = os.path.join(results_dir, _TEMPORARY_DIRECTORY)
53 if os.path.exists(temporary_directory):
54 shutil.rmtree(temporary_directory)
55 self._ensure_directory_exists(temporary_directory)
56
57 # make sure there are no old parsers running
58 os.system('killall parse')
59
60
61 def _warn(self, warning):
62 self.warnings.append(warning)
63
64
showard0205a3e2009-01-16 03:03:50 +000065 def _refresh_processes(self, command_name):
showard170873e2009-01-07 00:22:26 +000066 ps_proc = subprocess.Popen(
67 ['/bin/ps', 'x', '-o', ','.join(self._PS_ARGS)],
68 stdout=subprocess.PIPE)
69 ps_output = ps_proc.communicate()[0]
70
71 # split each line into the columns output by ps
72 split_lines = [line.split(None, 4) for line in ps_output.splitlines()]
73 process_infos = [dict(zip(self._PS_ARGS, line_components))
74 for line_components in split_lines]
75
76 processes = []
77 for info in process_infos:
showard0205a3e2009-01-16 03:03:50 +000078 if info['comm'] == command_name:
showard170873e2009-01-07 00:22:26 +000079 processes.append(info)
80
81 return processes
82
83
84 def _read_pidfiles(self, pidfile_paths):
85 pidfiles = {}
86 for pidfile_path in pidfile_paths:
87 if not os.path.exists(pidfile_path):
88 continue
89 try:
90 file_object = open(pidfile_path, 'r')
91 pidfiles[pidfile_path] = file_object.read()
92 file_object.close()
93 except IOError:
94 continue
95 return pidfiles
96
97
98 def refresh(self, pidfile_paths):
99 results = {
100 'pidfiles' : self._read_pidfiles(pidfile_paths),
showard0205a3e2009-01-16 03:03:50 +0000101 'autoserv_processes' : self._refresh_processes('autoserv'),
102 'parse_processes' : self._refresh_processes('parse'),
showard170873e2009-01-07 00:22:26 +0000103 'pidfiles_second_read' : self._read_pidfiles(pidfile_paths),
104 }
105 return results
106
107
108 def _is_process_running(self, process):
109 # TODO: enhance this to check the process args
110 proc_path = os.path.join('/proc', str(process.pid))
111 return os.path.exists(proc_path)
112
113
114 def kill_process(self, process):
115 if self._is_process_running(process):
116 os.kill(process.pid, signal.SIGCONT)
117 os.kill(process.pid, signal.SIGTERM)
118
119
showard78d4d972009-01-16 03:04:16 +0000120 def _convert_old_host_log(self, log_path):
121 """
122 For backwards compatibility only. This can safely be removed in the
123 future.
124
125 The scheduler used to create files at results/hosts/<hostname>, and
126 append all host logs to that file. Now, it creates directories at
127 results/hosts/<hostname>, and places individual timestamped log files
128 into that directory.
129
130 This can be a problem the first time the scheduler runs after upgrading.
131 To work around that, we'll look for a file at the path where the
132 directory should be, and if we find one, we'll automatically convert it
133 to a directory containing the old logfile.
134 """
135 # move the file out of the way
136 temp_dir = tempfile.mkdtemp(suffix='.convert_host_log')
137 base_name = os.path.basename(log_path)
138 temp_path = os.path.join(temp_dir, base_name)
139 os.rename(log_path, temp_path)
140
141 os.mkdir(log_path)
142
143 # and move it into the new directory
144 os.rename(temp_path, os.path.join(log_path, 'old_log'))
145 os.rmdir(temp_dir)
146
147
showard170873e2009-01-07 00:22:26 +0000148 def _ensure_directory_exists(self, path):
showard78d4d972009-01-16 03:04:16 +0000149 if os.path.isdir(path):
150 return
151
152 if os.path.exists(path):
153 # path exists already, but as a file, not a directory
154 if '/hosts/' in path:
155 self._convert_old_host_log(path)
156 return
157 else:
158 raise IOError('Path %s exists as a file, not a directory')
159
160 os.makedirs(path)
showard170873e2009-01-07 00:22:26 +0000161
162
163 def execute_command(self, command, working_directory, log_file,
164 pidfile_name):
165 out_file = None
166 if log_file:
167 self._ensure_directory_exists(os.path.dirname(log_file))
168 try:
169 out_file = open(log_file, 'a')
170 separator = ('*' * 80) + '\n'
171 out_file.write('\n' + separator)
172 out_file.write("%s> %s\n" % (time.strftime("%X %x"), command))
173 out_file.write(separator)
174 except (OSError, IOError):
175 email_manager.manager.log_stacktrace(
176 'Error opening log file %s' % log_file)
177
178 if not out_file:
179 out_file = open('/dev/null', 'w')
180
181 in_devnull = open('/dev/null', 'r')
182
183 self._ensure_directory_exists(working_directory)
184 pidfile_path = os.path.join(working_directory, pidfile_name)
185 if os.path.exists(pidfile_path):
186 self._warn('Pidfile %s already exists' % pidfile_path)
187 os.remove(pidfile_path)
188
189 subprocess.Popen(command, stdout=out_file, stderr=subprocess.STDOUT,
190 stdin=in_devnull)
191 out_file.close()
192 in_devnull.close()
193
194
195 def write_to_file(self, file_path, contents):
196 self._ensure_directory_exists(os.path.dirname(file_path))
197 try:
198 file_object = open(file_path, 'a')
199 file_object.write(contents)
200 file_object.close()
201 except IOError, exc:
202 self._warn('Error write to file %s: %s' % (file_path, exc))
203
204
showardde634ee2009-01-30 01:44:24 +0000205 def copy_file_or_directory(self, source_path, destination_path):
206 """
207 This interface is designed to match server.hosts.abstract_ssh.get_file
208 (and send_file). That is, if the source_path ends with a slash, the
209 contents of the directory are copied; otherwise, the directory iself is
210 copied.
211 """
212 if source_path.rstrip('/') == destination_path.rstrip('/'):
showard170873e2009-01-07 00:22:26 +0000213 return
214 self._ensure_directory_exists(os.path.dirname(destination_path))
showardde634ee2009-01-30 01:44:24 +0000215 if source_path.endswith('/'):
216 # copying a directory's contents to another directory
217 assert os.path.isdir(source_path)
218 assert os.path.isdir(destination_path)
219 for filename in os.listdir(source_path):
220 self.copy_file_or_directory(
221 os.path.join(source_path, filename),
222 os.path.join(destination_path, filename))
223 elif os.path.isdir(source_path):
224 shutil.copytree(source_path, destination_path, symlinks=True)
225 elif os.path.islink(source_path):
226 # copied from shutil.copytree()
227 link_to = os.readlink(source_path)
228 os.symlink(link_to, destination_path)
229 else:
230 shutil.copy(source_path, destination_path)
showard170873e2009-01-07 00:22:26 +0000231
232
showardc408c5e2009-01-08 23:30:53 +0000233 def wait_for_all_async_commands(self):
234 for subproc in self._subcommands:
235 subproc.fork_waitfor()
236 self._subcommands = []
237
238
239 def _poll_async_commands(self):
240 still_running = []
241 for subproc in self._subcommands:
242 if subproc.poll() is None:
243 still_running.append(subproc)
244 self._subcommands = still_running
245
246
247 def _wait_for_some_async_commands(self):
248 self._poll_async_commands()
249 max_processes = scheduler_config.config.max_transfer_processes
250 while len(self._subcommands) >= max_processes:
251 time.sleep(1)
252 self._poll_async_commands()
253
254
showard170873e2009-01-07 00:22:26 +0000255 def run_async_command(self, function, args):
256 subproc = subcommand.subcommand(function, args)
257 self._subcommands.append(subproc)
258 subproc.fork_start()
259
260
showard170873e2009-01-07 00:22:26 +0000261 def _sync_get_file_from(self, hostname, source_path, destination_path):
262 self._ensure_directory_exists(os.path.dirname(destination_path))
263 host = create_host(hostname)
264 host.get_file(source_path, destination_path, delete_dest=True)
265
266
267 def get_file_from(self, hostname, source_path, destination_path):
268 self.run_async_command(self._sync_get_file_from,
269 (hostname, source_path, destination_path))
270
271
272 def _sync_send_file_to(self, hostname, source_path, destination_path,
273 can_fail):
274 host = create_host(hostname)
275 try:
276 host.run('mkdir -p ' + os.path.dirname(destination_path))
277 host.send_file(source_path, destination_path, delete_dest=True)
278 except error.AutoservError:
279 if not can_fail:
280 raise
281
282 if os.path.isdir(source_path):
283 failed_file = os.path.join(source_path, _TRANSFER_FAILED_FILE)
284 file_object = open(failed_file, 'w')
285 try:
286 file_object.write('%s:%s\n%s\n%s' %
287 (hostname, destination_path,
288 datetime.datetime.now(),
289 traceback.format_exc()))
290 finally:
291 file_object.close()
292 else:
293 copy_to = destination_path + _TRANSFER_FAILED_FILE
294 self._ensure_directory_exists(os.path.dirname(copy_to))
showardde634ee2009-01-30 01:44:24 +0000295 self.copy_file_or_directory(source_path, copy_to)
showard170873e2009-01-07 00:22:26 +0000296
297
298 def send_file_to(self, hostname, source_path, destination_path,
299 can_fail=False):
300 self.run_async_command(self._sync_send_file_to,
301 (hostname, source_path, destination_path,
302 can_fail))
303
304
305 def _report_long_execution(self, calls, duration):
306 call_count = {}
307 for call in calls:
308 call_count.setdefault(call._method, 0)
309 call_count[call._method] += 1
310 call_summary = '\n'.join('%d %s' % (count, method)
311 for method, count in call_count.iteritems())
312 self._warn('Execution took %f sec\n%s' % (duration, call_summary))
313
314
315 def execute_calls(self, calls):
316 results = []
317 start_time = time.time()
showardc408c5e2009-01-08 23:30:53 +0000318 max_processes = scheduler_config.config.max_transfer_processes
showard170873e2009-01-07 00:22:26 +0000319 for method_call in calls:
320 results.append(method_call.execute_on(self))
showardd1ee1dd2009-01-07 21:33:08 +0000321 if len(self._subcommands) >= max_processes:
showardc408c5e2009-01-08 23:30:53 +0000322 self._wait_for_some_async_commands()
323 self.wait_for_all_async_commands()
showard170873e2009-01-07 00:22:26 +0000324
325 duration = time.time() - start_time
326 if duration > self._WARNING_DURATION:
327 self._report_long_execution(calls, duration)
328
329 warnings = self.warnings
330 self.warnings = []
331 return dict(results=results, warnings=warnings)
332
333
334def create_host(hostname):
335 username = global_config.global_config.get_config_value(
336 'SCHEDULER', hostname + '_username', default=getpass.getuser())
337 return hosts.SSHHost(hostname, user=username)
338
339
340def parse_input():
341 input_chunks = []
342 chunk_of_input = sys.stdin.read()
343 while chunk_of_input:
344 input_chunks.append(chunk_of_input)
345 chunk_of_input = sys.stdin.read()
346 pickled_input = ''.join(input_chunks)
347
348 try:
349 return pickle.loads(pickled_input)
350 except Exception, exc:
351 separator = '*' * 50
352 raise ValueError('Unpickling input failed\n'
353 'Input: %r\n'
354 'Exception from pickle:\n'
355 '%s\n%s\n%s' %
356 (pickled_input, separator, traceback.format_exc(),
357 separator))
358
359
360def return_data(data):
361 print pickle.dumps(data)
362
363
364def main():
365 calls = parse_input()
366 drone_utility = DroneUtility()
367 return_value = drone_utility.execute_calls(calls)
368 return_data(return_value)
369
370
371if __name__ == '__main__':
372 main()