mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 1 | # |
| 2 | # Copyright 2008 Google Inc. Released under the GPL v2 |
| 3 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 4 | import os, pickle, random, re, resource, select, shutil, signal, StringIO |
mbligh | b289619 | 2009-07-11 00:12:37 +0000 | [diff] [blame] | 5 | import socket, struct, subprocess, sys, time, textwrap, urlparse |
mbligh | 25284cd | 2009-06-08 16:17:24 +0000 | [diff] [blame] | 6 | import warnings, smtplib, logging, urllib2 |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 7 | from autotest_lib.client.common_lib import error, barrier, logging_manager |
mbligh | 81edd79 | 2008-08-26 16:54:02 +0000 | [diff] [blame] | 8 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 9 | def deprecated(func): |
| 10 | """This is a decorator which can be used to mark functions as deprecated. |
| 11 | It will result in a warning being emmitted when the function is used.""" |
| 12 | def new_func(*args, **dargs): |
| 13 | warnings.warn("Call to deprecated function %s." % func.__name__, |
| 14 | category=DeprecationWarning) |
| 15 | return func(*args, **dargs) |
| 16 | new_func.__name__ = func.__name__ |
| 17 | new_func.__doc__ = func.__doc__ |
| 18 | new_func.__dict__.update(func.__dict__) |
| 19 | return new_func |
| 20 | |
| 21 | |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 22 | class _NullStream(object): |
| 23 | def write(self, data): |
| 24 | pass |
| 25 | |
| 26 | |
| 27 | def flush(self): |
| 28 | pass |
| 29 | |
| 30 | |
| 31 | TEE_TO_LOGS = object() |
| 32 | _the_null_stream = _NullStream() |
| 33 | |
showard | b45a466 | 2009-07-15 14:27:56 +0000 | [diff] [blame] | 34 | DEFAULT_STDOUT_LEVEL = logging.DEBUG |
| 35 | DEFAULT_STDERR_LEVEL = logging.ERROR |
| 36 | |
showard | 39986a6 | 2009-12-10 21:41:53 +0000 | [diff] [blame] | 37 | # prefixes for logging stdout/stderr of commands |
| 38 | STDOUT_PREFIX = '[stdout] ' |
| 39 | STDERR_PREFIX = '[stderr] ' |
| 40 | |
| 41 | |
| 42 | def get_stream_tee_file(stream, level, prefix=''): |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 43 | if stream is None: |
| 44 | return _the_null_stream |
| 45 | if stream is TEE_TO_LOGS: |
showard | 39986a6 | 2009-12-10 21:41:53 +0000 | [diff] [blame] | 46 | return logging_manager.LoggingFile(level=level, prefix=prefix) |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 47 | return stream |
| 48 | |
| 49 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 50 | class BgJob(object): |
showard | 170873e | 2009-01-07 00:22:26 +0000 | [diff] [blame] | 51 | def __init__(self, command, stdout_tee=None, stderr_tee=None, verbose=True, |
showard | b45a466 | 2009-07-15 14:27:56 +0000 | [diff] [blame] | 52 | stdin=None, stderr_level=DEFAULT_STDERR_LEVEL): |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 53 | self.command = command |
showard | 39986a6 | 2009-12-10 21:41:53 +0000 | [diff] [blame] | 54 | self.stdout_tee = get_stream_tee_file(stdout_tee, DEFAULT_STDOUT_LEVEL, |
| 55 | prefix=STDOUT_PREFIX) |
| 56 | self.stderr_tee = get_stream_tee_file(stderr_tee, stderr_level, |
| 57 | prefix=STDERR_PREFIX) |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 58 | self.result = CmdResult(command) |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 59 | |
| 60 | # allow for easy stdin input by string, we'll let subprocess create |
| 61 | # a pipe for stdin input and we'll write to it in the wait loop |
| 62 | if isinstance(stdin, basestring): |
| 63 | self.string_stdin = stdin |
| 64 | stdin = subprocess.PIPE |
| 65 | else: |
| 66 | self.string_stdin = None |
| 67 | |
mbligh | bd96b45 | 2008-09-03 23:14:27 +0000 | [diff] [blame] | 68 | if verbose: |
showard | b18134f | 2009-03-20 20:52:18 +0000 | [diff] [blame] | 69 | logging.debug("Running '%s'" % command) |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 70 | self.sp = subprocess.Popen(command, stdout=subprocess.PIPE, |
| 71 | stderr=subprocess.PIPE, |
| 72 | preexec_fn=self._reset_sigpipe, shell=True, |
showard | 170873e | 2009-01-07 00:22:26 +0000 | [diff] [blame] | 73 | executable="/bin/bash", |
| 74 | stdin=stdin) |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 75 | |
| 76 | |
| 77 | def output_prepare(self, stdout_file=None, stderr_file=None): |
| 78 | self.stdout_file = stdout_file |
| 79 | self.stderr_file = stderr_file |
| 80 | |
mbligh | 45ffc43 | 2008-12-09 23:35:17 +0000 | [diff] [blame] | 81 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 82 | def process_output(self, stdout=True, final_read=False): |
| 83 | """output_prepare must be called prior to calling this""" |
| 84 | if stdout: |
| 85 | pipe, buf, tee = self.sp.stdout, self.stdout_file, self.stdout_tee |
| 86 | else: |
| 87 | pipe, buf, tee = self.sp.stderr, self.stderr_file, self.stderr_tee |
| 88 | |
| 89 | if final_read: |
| 90 | # read in all the data we can from pipe and then stop |
| 91 | data = [] |
| 92 | while select.select([pipe], [], [], 0)[0]: |
| 93 | data.append(os.read(pipe.fileno(), 1024)) |
| 94 | if len(data[-1]) == 0: |
| 95 | break |
| 96 | data = "".join(data) |
| 97 | else: |
| 98 | # perform a single read |
| 99 | data = os.read(pipe.fileno(), 1024) |
| 100 | buf.write(data) |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 101 | tee.write(data) |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 102 | |
| 103 | |
| 104 | def cleanup(self): |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 105 | self.stdout_tee.flush() |
| 106 | self.stderr_tee.flush() |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 107 | self.sp.stdout.close() |
| 108 | self.sp.stderr.close() |
| 109 | self.result.stdout = self.stdout_file.getvalue() |
| 110 | self.result.stderr = self.stderr_file.getvalue() |
| 111 | |
| 112 | |
| 113 | def _reset_sigpipe(self): |
| 114 | signal.signal(signal.SIGPIPE, signal.SIG_DFL) |
| 115 | |
mbligh | 81edd79 | 2008-08-26 16:54:02 +0000 | [diff] [blame] | 116 | |
| 117 | def ip_to_long(ip): |
| 118 | # !L is a long in network byte order |
| 119 | return struct.unpack('!L', socket.inet_aton(ip))[0] |
| 120 | |
| 121 | |
| 122 | def long_to_ip(number): |
| 123 | # See above comment. |
| 124 | return socket.inet_ntoa(struct.pack('!L', number)) |
| 125 | |
| 126 | |
| 127 | def create_subnet_mask(bits): |
mbligh | 81edd79 | 2008-08-26 16:54:02 +0000 | [diff] [blame] | 128 | return (1 << 32) - (1 << 32-bits) |
| 129 | |
| 130 | |
| 131 | def format_ip_with_mask(ip, mask_bits): |
| 132 | masked_ip = ip_to_long(ip) & create_subnet_mask(mask_bits) |
| 133 | return "%s/%s" % (long_to_ip(masked_ip), mask_bits) |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 134 | |
mbligh | de0d47e | 2008-03-28 14:37:18 +0000 | [diff] [blame] | 135 | |
jadmanski | e80d471 | 2008-10-03 16:15:59 +0000 | [diff] [blame] | 136 | def normalize_hostname(alias): |
| 137 | ip = socket.gethostbyname(alias) |
| 138 | return socket.gethostbyaddr(ip)[0] |
| 139 | |
| 140 | |
mbligh | d6d043c | 2008-09-27 21:00:45 +0000 | [diff] [blame] | 141 | def get_ip_local_port_range(): |
| 142 | match = re.match(r'\s*(\d+)\s*(\d+)\s*$', |
| 143 | read_one_line('/proc/sys/net/ipv4/ip_local_port_range')) |
| 144 | return (int(match.group(1)), int(match.group(2))) |
| 145 | |
| 146 | |
| 147 | def set_ip_local_port_range(lower, upper): |
| 148 | write_one_line('/proc/sys/net/ipv4/ip_local_port_range', |
| 149 | '%d %d\n' % (lower, upper)) |
| 150 | |
mbligh | 315b941 | 2008-10-01 03:34:11 +0000 | [diff] [blame] | 151 | |
mbligh | 45ffc43 | 2008-12-09 23:35:17 +0000 | [diff] [blame] | 152 | |
| 153 | def send_email(mail_from, mail_to, subject, body): |
| 154 | """ |
| 155 | Sends an email via smtp |
| 156 | |
| 157 | mail_from: string with email address of sender |
| 158 | mail_to: string or list with email address(es) of recipients |
| 159 | subject: string with subject of email |
| 160 | body: (multi-line) string with body of email |
| 161 | """ |
| 162 | if isinstance(mail_to, str): |
| 163 | mail_to = [mail_to] |
| 164 | msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (mail_from, ','.join(mail_to), |
| 165 | subject, body) |
| 166 | try: |
| 167 | mailer = smtplib.SMTP('localhost') |
| 168 | try: |
| 169 | mailer.sendmail(mail_from, mail_to, msg) |
| 170 | finally: |
| 171 | mailer.quit() |
| 172 | except Exception, e: |
| 173 | # Emails are non-critical, not errors, but don't raise them |
| 174 | print "Sending email failed. Reason: %s" % repr(e) |
| 175 | |
| 176 | |
jadmanski | 5182e16 | 2008-05-13 21:48:16 +0000 | [diff] [blame] | 177 | def read_one_line(filename): |
mbligh | 6e8840c | 2008-07-11 18:05:49 +0000 | [diff] [blame] | 178 | return open(filename, 'r').readline().rstrip('\n') |
jadmanski | 5182e16 | 2008-05-13 21:48:16 +0000 | [diff] [blame] | 179 | |
| 180 | |
mbligh | b9d0551 | 2008-10-18 13:53:27 +0000 | [diff] [blame] | 181 | def write_one_line(filename, line): |
| 182 | open_write_close(filename, line.rstrip('\n') + '\n') |
| 183 | |
| 184 | |
| 185 | def open_write_close(filename, data): |
mbligh | 618ac9e | 2008-10-06 17:14:32 +0000 | [diff] [blame] | 186 | f = open(filename, 'w') |
mbligh | b9d0551 | 2008-10-18 13:53:27 +0000 | [diff] [blame] | 187 | try: |
| 188 | f.write(data) |
| 189 | finally: |
| 190 | f.close() |
jadmanski | 5182e16 | 2008-05-13 21:48:16 +0000 | [diff] [blame] | 191 | |
| 192 | |
mbligh | de0d47e | 2008-03-28 14:37:18 +0000 | [diff] [blame] | 193 | def read_keyval(path): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 194 | """ |
| 195 | Read a key-value pair format file into a dictionary, and return it. |
| 196 | Takes either a filename or directory name as input. If it's a |
| 197 | directory name, we assume you want the file to be called keyval. |
| 198 | """ |
| 199 | if os.path.isdir(path): |
| 200 | path = os.path.join(path, 'keyval') |
| 201 | keyval = {} |
jadmanski | 5896298 | 2009-04-21 19:54:34 +0000 | [diff] [blame] | 202 | if os.path.exists(path): |
| 203 | for line in open(path): |
| 204 | line = re.sub('#.*', '', line).rstrip() |
| 205 | if not re.search(r'^[-\.\w]+=', line): |
| 206 | raise ValueError('Invalid format line: %s' % line) |
| 207 | key, value = line.split('=', 1) |
| 208 | if re.search('^\d+$', value): |
| 209 | value = int(value) |
| 210 | elif re.search('^(\d+\.)?\d+$', value): |
| 211 | value = float(value) |
| 212 | keyval[key] = value |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 213 | return keyval |
mbligh | de0d47e | 2008-03-28 14:37:18 +0000 | [diff] [blame] | 214 | |
| 215 | |
jadmanski | cc54917 | 2008-05-21 18:11:51 +0000 | [diff] [blame] | 216 | def write_keyval(path, dictionary, type_tag=None): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 217 | """ |
| 218 | Write a key-value pair format file out to a file. This uses append |
| 219 | mode to open the file, so existing text will not be overwritten or |
| 220 | reparsed. |
jadmanski | cc54917 | 2008-05-21 18:11:51 +0000 | [diff] [blame] | 221 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 222 | If type_tag is None, then the key must be composed of alphanumeric |
| 223 | characters (or dashes+underscores). However, if type-tag is not |
| 224 | null then the keys must also have "{type_tag}" as a suffix. At |
| 225 | the moment the only valid values of type_tag are "attr" and "perf". |
| 226 | """ |
| 227 | if os.path.isdir(path): |
| 228 | path = os.path.join(path, 'keyval') |
| 229 | keyval = open(path, 'a') |
jadmanski | cc54917 | 2008-05-21 18:11:51 +0000 | [diff] [blame] | 230 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 231 | if type_tag is None: |
mbligh | 97227ea | 2009-03-11 17:09:50 +0000 | [diff] [blame] | 232 | key_regex = re.compile(r'^[-\.\w]+$') |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 233 | else: |
| 234 | if type_tag not in ('attr', 'perf'): |
| 235 | raise ValueError('Invalid type tag: %s' % type_tag) |
| 236 | escaped_tag = re.escape(type_tag) |
mbligh | 97227ea | 2009-03-11 17:09:50 +0000 | [diff] [blame] | 237 | key_regex = re.compile(r'^[-\.\w]+\{%s\}$' % escaped_tag) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 238 | try: |
mbligh | 6955e23 | 2009-07-11 00:58:47 +0000 | [diff] [blame] | 239 | for key in sorted(dictionary.keys()): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 240 | if not key_regex.search(key): |
| 241 | raise ValueError('Invalid key: %s' % key) |
mbligh | 6955e23 | 2009-07-11 00:58:47 +0000 | [diff] [blame] | 242 | keyval.write('%s=%s\n' % (key, dictionary[key])) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 243 | finally: |
| 244 | keyval.close() |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 245 | |
| 246 | |
| 247 | def is_url(path): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 248 | """Return true if path looks like a URL""" |
| 249 | # for now, just handle http and ftp |
| 250 | url_parts = urlparse.urlparse(path) |
| 251 | return (url_parts[0] in ('http', 'ftp')) |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 252 | |
| 253 | |
mbligh | b289619 | 2009-07-11 00:12:37 +0000 | [diff] [blame] | 254 | def urlopen(url, data=None, timeout=5): |
| 255 | """Wrapper to urllib2.urlopen with timeout addition.""" |
mbligh | 02ff2d5 | 2008-06-03 15:00:21 +0000 | [diff] [blame] | 256 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 257 | # Save old timeout |
| 258 | old_timeout = socket.getdefaulttimeout() |
| 259 | socket.setdefaulttimeout(timeout) |
| 260 | try: |
mbligh | b289619 | 2009-07-11 00:12:37 +0000 | [diff] [blame] | 261 | return urllib2.urlopen(url, data=data) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 262 | finally: |
| 263 | socket.setdefaulttimeout(old_timeout) |
mbligh | 02ff2d5 | 2008-06-03 15:00:21 +0000 | [diff] [blame] | 264 | |
| 265 | |
mbligh | b289619 | 2009-07-11 00:12:37 +0000 | [diff] [blame] | 266 | def urlretrieve(url, filename, data=None, timeout=300): |
| 267 | """Retrieve a file from given url.""" |
| 268 | logging.debug('Fetching %s -> %s', url, filename) |
| 269 | |
| 270 | src_file = urlopen(url, data=data, timeout=timeout) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 271 | try: |
mbligh | b289619 | 2009-07-11 00:12:37 +0000 | [diff] [blame] | 272 | dest_file = open(filename, 'wb') |
| 273 | try: |
| 274 | shutil.copyfileobj(src_file, dest_file) |
| 275 | finally: |
| 276 | dest_file.close() |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 277 | finally: |
mbligh | b289619 | 2009-07-11 00:12:37 +0000 | [diff] [blame] | 278 | src_file.close() |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 279 | |
mbligh | 02ff2d5 | 2008-06-03 15:00:21 +0000 | [diff] [blame] | 280 | |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 281 | def get_file(src, dest, permissions=None): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 282 | """Get a file from src, which can be local or a remote URL""" |
mbligh | 25284cd | 2009-06-08 16:17:24 +0000 | [diff] [blame] | 283 | if src == dest: |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 284 | return |
mbligh | 25284cd | 2009-06-08 16:17:24 +0000 | [diff] [blame] | 285 | |
| 286 | if is_url(src): |
mbligh | b289619 | 2009-07-11 00:12:37 +0000 | [diff] [blame] | 287 | urlretrieve(src, dest) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 288 | else: |
| 289 | shutil.copyfile(src, dest) |
mbligh | 25284cd | 2009-06-08 16:17:24 +0000 | [diff] [blame] | 290 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 291 | if permissions: |
| 292 | os.chmod(dest, permissions) |
| 293 | return dest |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 294 | |
| 295 | |
| 296 | def unmap_url(srcdir, src, destdir='.'): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 297 | """ |
| 298 | Receives either a path to a local file or a URL. |
| 299 | returns either the path to the local file, or the fetched URL |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 300 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 301 | unmap_url('/usr/src', 'foo.tar', '/tmp') |
| 302 | = '/usr/src/foo.tar' |
| 303 | unmap_url('/usr/src', 'http://site/file', '/tmp') |
| 304 | = '/tmp/file' |
| 305 | (after retrieving it) |
| 306 | """ |
| 307 | if is_url(src): |
| 308 | url_parts = urlparse.urlparse(src) |
| 309 | filename = os.path.basename(url_parts[2]) |
| 310 | dest = os.path.join(destdir, filename) |
| 311 | return get_file(src, dest) |
| 312 | else: |
| 313 | return os.path.join(srcdir, src) |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 314 | |
| 315 | |
| 316 | def update_version(srcdir, preserve_srcdir, new_version, install, |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 317 | *args, **dargs): |
| 318 | """ |
| 319 | Make sure srcdir is version new_version |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 320 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 321 | If not, delete it and install() the new version. |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 322 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 323 | In the preserve_srcdir case, we just check it's up to date, |
| 324 | and if not, we rerun install, without removing srcdir |
| 325 | """ |
| 326 | versionfile = os.path.join(srcdir, '.version') |
| 327 | install_needed = True |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 328 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 329 | if os.path.exists(versionfile): |
| 330 | old_version = pickle.load(open(versionfile)) |
| 331 | if old_version == new_version: |
| 332 | install_needed = False |
mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 333 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 334 | if install_needed: |
| 335 | if not preserve_srcdir and os.path.exists(srcdir): |
| 336 | shutil.rmtree(srcdir) |
| 337 | install(*args, **dargs) |
| 338 | if os.path.exists(srcdir): |
| 339 | pickle.dump(new_version, open(versionfile, 'w')) |
mbligh | 462c015 | 2008-03-13 15:37:10 +0000 | [diff] [blame] | 340 | |
| 341 | |
showard | b45a466 | 2009-07-15 14:27:56 +0000 | [diff] [blame] | 342 | def get_stderr_level(stderr_is_expected): |
| 343 | if stderr_is_expected: |
| 344 | return DEFAULT_STDOUT_LEVEL |
| 345 | return DEFAULT_STDERR_LEVEL |
| 346 | |
| 347 | |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 348 | def run(command, timeout=None, ignore_status=False, |
showard | b45a466 | 2009-07-15 14:27:56 +0000 | [diff] [blame] | 349 | stdout_tee=None, stderr_tee=None, verbose=True, stdin=None, |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 350 | stderr_is_expected=None, args=()): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 351 | """ |
| 352 | Run a command on the host. |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 353 | |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 354 | @param command: the command line string. |
| 355 | @param timeout: time limit in seconds before attempting to kill the |
| 356 | running process. The run() function will take a few seconds |
| 357 | longer than 'timeout' to complete if it has to kill the process. |
| 358 | @param ignore_status: do not raise an exception, no matter what the exit |
| 359 | code of the command is. |
| 360 | @param stdout_tee: optional file-like object to which stdout data |
| 361 | will be written as it is generated (data will still be stored |
| 362 | in result.stdout). |
| 363 | @param stderr_tee: likewise for stderr. |
| 364 | @param verbose: if True, log the command being run. |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 365 | @param stdin: stdin to pass to the executed process (can be a file |
| 366 | descriptor, a file object of a real file or a string). |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 367 | @param args: sequence of strings of arguments to be given to the command |
| 368 | inside " quotes after they have been escaped for that; each |
| 369 | element in the sequence will be given as a separate command |
| 370 | argument |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 371 | |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 372 | @return a CmdResult object |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 373 | |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 374 | @raise CmdError: the exit code of the command execution was not 0 |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 375 | """ |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 376 | for arg in args: |
| 377 | command += ' "%s"' % sh_escape(arg) |
showard | b45a466 | 2009-07-15 14:27:56 +0000 | [diff] [blame] | 378 | if stderr_is_expected is None: |
| 379 | stderr_is_expected = ignore_status |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 380 | |
showard | 170873e | 2009-01-07 00:22:26 +0000 | [diff] [blame] | 381 | bg_job = join_bg_jobs( |
showard | b45a466 | 2009-07-15 14:27:56 +0000 | [diff] [blame] | 382 | (BgJob(command, stdout_tee, stderr_tee, verbose, stdin=stdin, |
| 383 | stderr_level=get_stderr_level(stderr_is_expected)),), |
showard | 170873e | 2009-01-07 00:22:26 +0000 | [diff] [blame] | 384 | timeout)[0] |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 385 | if not ignore_status and bg_job.result.exit_status: |
jadmanski | 9c1098b | 2008-09-02 14:18:48 +0000 | [diff] [blame] | 386 | raise error.CmdError(command, bg_job.result, |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 387 | "Command returned non-zero exit status") |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 388 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 389 | return bg_job.result |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 390 | |
mbligh | 45ffc43 | 2008-12-09 23:35:17 +0000 | [diff] [blame] | 391 | |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 392 | def run_parallel(commands, timeout=None, ignore_status=False, |
| 393 | stdout_tee=None, stderr_tee=None): |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 394 | """ |
| 395 | Behaves the same as run() with the following exceptions: |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 396 | |
| 397 | - commands is a list of commands to run in parallel. |
| 398 | - ignore_status toggles whether or not an exception should be raised |
| 399 | on any error. |
| 400 | |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 401 | @return: a list of CmdResult objects |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 402 | """ |
| 403 | bg_jobs = [] |
| 404 | for command in commands: |
showard | b45a466 | 2009-07-15 14:27:56 +0000 | [diff] [blame] | 405 | bg_jobs.append(BgJob(command, stdout_tee, stderr_tee, |
| 406 | stderr_level=get_stderr_level(ignore_status))) |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 407 | |
| 408 | # Updates objects in bg_jobs list with their process information |
| 409 | join_bg_jobs(bg_jobs, timeout) |
| 410 | |
| 411 | for bg_job in bg_jobs: |
| 412 | if not ignore_status and bg_job.result.exit_status: |
| 413 | raise error.CmdError(command, bg_job.result, |
| 414 | "Command returned non-zero exit status") |
| 415 | |
| 416 | return [bg_job.result for bg_job in bg_jobs] |
| 417 | |
| 418 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 419 | @deprecated |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 420 | def run_bg(command): |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 421 | """Function deprecated. Please use BgJob class instead.""" |
| 422 | bg_job = BgJob(command) |
| 423 | return bg_job.sp, bg_job.result |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 424 | |
| 425 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 426 | def join_bg_jobs(bg_jobs, timeout=None): |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 427 | """Joins the bg_jobs with the current thread. |
| 428 | |
| 429 | Returns the same list of bg_jobs objects that was passed in. |
| 430 | """ |
mbligh | ae69f26 | 2009-04-17 20:14:56 +0000 | [diff] [blame] | 431 | ret, timeout_error = 0, False |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 432 | for bg_job in bg_jobs: |
| 433 | bg_job.output_prepare(StringIO.StringIO(), StringIO.StringIO()) |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 434 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 435 | try: |
| 436 | # We are holding ends to stdin, stdout pipes |
| 437 | # hence we need to be sure to close those fds no mater what |
| 438 | start_time = time.time() |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 439 | timeout_error = _wait_for_commands(bg_jobs, start_time, timeout) |
| 440 | |
| 441 | for bg_job in bg_jobs: |
| 442 | # Process stdout and stderr |
| 443 | bg_job.process_output(stdout=True,final_read=True) |
| 444 | bg_job.process_output(stdout=False,final_read=True) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 445 | finally: |
| 446 | # close our ends of the pipes to the sp no matter what |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 447 | for bg_job in bg_jobs: |
| 448 | bg_job.cleanup() |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 449 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 450 | if timeout_error: |
| 451 | # TODO: This needs to be fixed to better represent what happens when |
| 452 | # running in parallel. However this is backwards compatable, so it will |
| 453 | # do for the time being. |
| 454 | raise error.CmdError(bg_jobs[0].command, bg_jobs[0].result, |
| 455 | "Command(s) did not complete within %d seconds" |
| 456 | % timeout) |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 457 | |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 458 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 459 | return bg_jobs |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 460 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 461 | |
| 462 | def _wait_for_commands(bg_jobs, start_time, timeout): |
| 463 | # This returns True if it must return due to a timeout, otherwise False. |
| 464 | |
mbligh | f0b4a0a | 2008-09-03 20:46:16 +0000 | [diff] [blame] | 465 | # To check for processes which terminate without producing any output |
| 466 | # a 1 second timeout is used in select. |
| 467 | SELECT_TIMEOUT = 1 |
| 468 | |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 469 | read_list = [] |
| 470 | write_list = [] |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 471 | reverse_dict = {} |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 472 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 473 | for bg_job in bg_jobs: |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 474 | read_list.append(bg_job.sp.stdout) |
| 475 | read_list.append(bg_job.sp.stderr) |
| 476 | reverse_dict[bg_job.sp.stdout] = (bg_job, True) |
| 477 | reverse_dict[bg_job.sp.stderr] = (bg_job, False) |
| 478 | if bg_job.string_stdin: |
| 479 | write_list.append(bg_job.sp.stdin) |
| 480 | reverse_dict[bg_job.sp.stdin] = bg_job |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 481 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 482 | if timeout: |
| 483 | stop_time = start_time + timeout |
| 484 | time_left = stop_time - time.time() |
| 485 | else: |
| 486 | time_left = None # so that select never times out |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 487 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 488 | while not timeout or time_left > 0: |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 489 | # select will return when we may write to stdin or when there is |
| 490 | # stdout/stderr output we can read (including when it is |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 491 | # EOF, that is the process has terminated). |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 492 | read_ready, write_ready, _ = select.select(read_list, write_list, [], |
| 493 | SELECT_TIMEOUT) |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 494 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 495 | # os.read() has to be used instead of |
| 496 | # subproc.stdout.read() which will otherwise block |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 497 | for file_obj in read_ready: |
| 498 | bg_job, is_stdout = reverse_dict[file_obj] |
| 499 | bg_job.process_output(is_stdout) |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 500 | |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 501 | for file_obj in write_ready: |
| 502 | # we can write PIPE_BUF bytes without blocking |
| 503 | # POSIX requires PIPE_BUF is >= 512 |
| 504 | bg_job = reverse_dict[file_obj] |
| 505 | file_obj.write(bg_job.string_stdin[:512]) |
| 506 | bg_job.string_stdin = bg_job.string_stdin[512:] |
| 507 | # no more input data, close stdin, remove it from the select set |
| 508 | if not bg_job.string_stdin: |
| 509 | file_obj.close() |
| 510 | write_list.remove(file_obj) |
| 511 | del reverse_dict[file_obj] |
| 512 | |
| 513 | all_jobs_finished = True |
| 514 | for bg_job in bg_jobs: |
| 515 | if bg_job.result.exit_status is not None: |
| 516 | continue |
| 517 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 518 | bg_job.result.exit_status = bg_job.sp.poll() |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 519 | if bg_job.result.exit_status is not None: |
| 520 | # process exited, remove its stdout/stdin from the select set |
| 521 | read_list.remove(bg_job.sp.stdout) |
| 522 | read_list.remove(bg_job.sp.stderr) |
| 523 | del reverse_dict[bg_job.sp.stdout] |
| 524 | del reverse_dict[bg_job.sp.stderr] |
| 525 | else: |
| 526 | all_jobs_finished = False |
| 527 | |
| 528 | if all_jobs_finished: |
| 529 | return False |
mbligh | 8ea61e2 | 2008-05-09 18:09:37 +0000 | [diff] [blame] | 530 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 531 | if timeout: |
| 532 | time_left = stop_time - time.time() |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 533 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 534 | # Kill all processes which did not complete prior to timeout |
jadmanski | 093a068 | 2009-10-13 14:55:43 +0000 | [diff] [blame] | 535 | for bg_job in bg_jobs: |
| 536 | if bg_job.result.exit_status is not None: |
| 537 | continue |
| 538 | |
| 539 | logging.warn('run process timeout (%s) fired on: %s', timeout, |
| 540 | bg_job.command) |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 541 | nuke_subprocess(bg_job.sp) |
mbligh | 095dc64 | 2008-10-01 03:41:35 +0000 | [diff] [blame] | 542 | bg_job.result.exit_status = bg_job.sp.poll() |
mbligh | 8ea61e2 | 2008-05-09 18:09:37 +0000 | [diff] [blame] | 543 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 544 | return True |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 545 | |
| 546 | |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 547 | def pid_is_alive(pid): |
| 548 | """ |
| 549 | True if process pid exists and is not yet stuck in Zombie state. |
| 550 | Zombies are impossible to move between cgroups, etc. |
| 551 | pid can be integer, or text of integer. |
| 552 | """ |
| 553 | path = '/proc/%s/stat' % pid |
| 554 | |
| 555 | try: |
| 556 | stat = read_one_line(path) |
| 557 | except IOError: |
| 558 | if not os.path.exists(path): |
| 559 | # file went away |
| 560 | return False |
| 561 | raise |
| 562 | |
| 563 | return stat.split()[2] != 'Z' |
| 564 | |
| 565 | |
| 566 | def signal_pid(pid, sig): |
| 567 | """ |
| 568 | Sends a signal to a process id. Returns True if the process terminated |
| 569 | successfully, False otherwise. |
| 570 | """ |
| 571 | try: |
| 572 | os.kill(pid, sig) |
| 573 | except OSError: |
| 574 | # The process may have died before we could kill it. |
| 575 | pass |
| 576 | |
| 577 | for i in range(5): |
| 578 | if not pid_is_alive(pid): |
| 579 | return True |
| 580 | time.sleep(1) |
| 581 | |
| 582 | # The process is still alive |
| 583 | return False |
| 584 | |
| 585 | |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 586 | def nuke_subprocess(subproc): |
jadmanski | 09f9203 | 2008-09-17 14:05:27 +0000 | [diff] [blame] | 587 | # check if the subprocess is still alive, first |
| 588 | if subproc.poll() is not None: |
| 589 | return subproc.poll() |
| 590 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 591 | # the process has not terminated within timeout, |
| 592 | # kill it via an escalating series of signals. |
| 593 | signal_queue = [signal.SIGTERM, signal.SIGKILL] |
| 594 | for sig in signal_queue: |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 595 | signal_pid(subproc.pid, sig) |
| 596 | if subproc.poll() is not None: |
| 597 | return subproc.poll() |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 598 | |
| 599 | |
showard | 786da9a | 2009-10-12 20:31:20 +0000 | [diff] [blame] | 600 | def nuke_pid(pid, signal_queue=(signal.SIGTERM, signal.SIGKILL)): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 601 | # the process has not terminated within timeout, |
| 602 | # kill it via an escalating series of signals. |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 603 | for sig in signal_queue: |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 604 | if signal_pid(pid, sig): |
| 605 | return |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 606 | |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 607 | # no signal successfully terminated the process |
| 608 | raise error.AutoservRunError('Could not kill %d' % pid, None) |
mbligh | 298ed59 | 2009-06-15 21:52:57 +0000 | [diff] [blame] | 609 | |
| 610 | |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 611 | def system(command, timeout=None, ignore_status=False): |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 612 | """This function returns the exit status of command.""" |
mbligh | f8dffb1 | 2008-10-29 16:45:26 +0000 | [diff] [blame] | 613 | return run(command, timeout=timeout, ignore_status=ignore_status, |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 614 | stdout_tee=TEE_TO_LOGS, stderr_tee=TEE_TO_LOGS).exit_status |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 615 | |
| 616 | |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 617 | def system_parallel(commands, timeout=None, ignore_status=False): |
| 618 | """This function returns a list of exit statuses for the respective |
| 619 | list of commands.""" |
| 620 | return [bg_jobs.exit_status for bg_jobs in |
mbligh | f8dffb1 | 2008-10-29 16:45:26 +0000 | [diff] [blame] | 621 | run_parallel(commands, timeout=timeout, ignore_status=ignore_status, |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 622 | stdout_tee=TEE_TO_LOGS, stderr_tee=TEE_TO_LOGS)] |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 623 | |
| 624 | |
mbligh | 8ea61e2 | 2008-05-09 18:09:37 +0000 | [diff] [blame] | 625 | def system_output(command, timeout=None, ignore_status=False, |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 626 | retain_output=False, args=()): |
| 627 | """ |
| 628 | Run a command and return the stdout output. |
| 629 | |
| 630 | @param command: command string to execute. |
| 631 | @param timeout: time limit in seconds before attempting to kill the |
| 632 | running process. The function will take a few seconds longer |
| 633 | than 'timeout' to complete if it has to kill the process. |
| 634 | @param ignore_status: do not raise an exception, no matter what the exit |
| 635 | code of the command is. |
| 636 | @param retain_output: set to True to make stdout/stderr of the command |
| 637 | output to be also sent to the logging system |
| 638 | @param args: sequence of strings of arguments to be given to the command |
| 639 | inside " quotes after they have been escaped for that; each |
| 640 | element in the sequence will be given as a separate command |
| 641 | argument |
| 642 | |
| 643 | @return a string with the stdout output of the command. |
| 644 | """ |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 645 | if retain_output: |
mbligh | f8dffb1 | 2008-10-29 16:45:26 +0000 | [diff] [blame] | 646 | out = run(command, timeout=timeout, ignore_status=ignore_status, |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 647 | stdout_tee=TEE_TO_LOGS, stderr_tee=TEE_TO_LOGS, |
| 648 | args=args).stdout |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 649 | else: |
mbligh | c823e8d | 2009-10-02 00:01:35 +0000 | [diff] [blame] | 650 | out = run(command, timeout=timeout, ignore_status=ignore_status, |
| 651 | args=args).stdout |
| 652 | if out[-1:] == '\n': |
| 653 | out = out[:-1] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 654 | return out |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 655 | |
mbligh | 849a0f6 | 2008-08-28 20:12:19 +0000 | [diff] [blame] | 656 | |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 657 | def system_output_parallel(commands, timeout=None, ignore_status=False, |
| 658 | retain_output=False): |
| 659 | if retain_output: |
showard | 108d73e | 2009-06-22 18:14:41 +0000 | [diff] [blame] | 660 | out = [bg_job.stdout for bg_job |
| 661 | in run_parallel(commands, timeout=timeout, |
| 662 | ignore_status=ignore_status, |
| 663 | stdout_tee=TEE_TO_LOGS, stderr_tee=TEE_TO_LOGS)] |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 664 | else: |
mbligh | f8dffb1 | 2008-10-29 16:45:26 +0000 | [diff] [blame] | 665 | out = [bg_job.stdout for bg_job in run_parallel(commands, |
| 666 | timeout=timeout, ignore_status=ignore_status)] |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 667 | for x in out: |
| 668 | if out[-1:] == '\n': out = out[:-1] |
| 669 | return out |
| 670 | |
| 671 | |
mbligh | 9846795 | 2008-11-19 00:25:45 +0000 | [diff] [blame] | 672 | def strip_unicode(input): |
| 673 | if type(input) == list: |
| 674 | return [strip_unicode(i) for i in input] |
| 675 | elif type(input) == dict: |
| 676 | output = {} |
| 677 | for key in input.keys(): |
| 678 | output[str(key)] = strip_unicode(input[key]) |
| 679 | return output |
| 680 | elif type(input) == unicode: |
| 681 | return str(input) |
| 682 | else: |
| 683 | return input |
| 684 | |
| 685 | |
mbligh | a5630a5 | 2008-09-03 22:09:50 +0000 | [diff] [blame] | 686 | def get_cpu_percentage(function, *args, **dargs): |
| 687 | """Returns a tuple containing the CPU% and return value from function call. |
| 688 | |
| 689 | This function calculates the usage time by taking the difference of |
| 690 | the user and system times both before and after the function call. |
| 691 | """ |
| 692 | child_pre = resource.getrusage(resource.RUSAGE_CHILDREN) |
| 693 | self_pre = resource.getrusage(resource.RUSAGE_SELF) |
| 694 | start = time.time() |
| 695 | to_return = function(*args, **dargs) |
| 696 | elapsed = time.time() - start |
| 697 | self_post = resource.getrusage(resource.RUSAGE_SELF) |
| 698 | child_post = resource.getrusage(resource.RUSAGE_CHILDREN) |
| 699 | |
| 700 | # Calculate CPU Percentage |
| 701 | s_user, s_system = [a - b for a, b in zip(self_post, self_pre)[:2]] |
| 702 | c_user, c_system = [a - b for a, b in zip(child_post, child_pre)[:2]] |
| 703 | cpu_percent = (s_user + c_user + s_system + c_system) / elapsed |
| 704 | |
| 705 | return cpu_percent, to_return |
| 706 | |
| 707 | |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 708 | """ |
| 709 | This function is used when there is a need to run more than one |
| 710 | job simultaneously starting exactly at the same time. It basically returns |
| 711 | a modified control file (containing the synchronization code prepended) |
| 712 | whenever it is ready to run the control file. The synchronization |
| 713 | is done using barriers to make sure that the jobs start at the same time. |
| 714 | |
| 715 | Here is how the synchronization is done to make sure that the tests |
| 716 | start at exactly the same time on the client. |
| 717 | sc_bar is a server barrier and s_bar, c_bar are the normal barriers |
| 718 | |
| 719 | Job1 Job2 ...... JobN |
| 720 | Server: | sc_bar |
| 721 | Server: | s_bar ...... s_bar |
| 722 | Server: | at.run() at.run() ...... at.run() |
| 723 | ----------|------------------------------------------------------ |
| 724 | Client | sc_bar |
| 725 | Client | c_bar c_bar ...... c_bar |
| 726 | Client | <run test> <run test> ...... <run test> |
| 727 | |
| 728 | |
| 729 | PARAMS: |
| 730 | control_file : The control file which to which the above synchronization |
| 731 | code would be prepended to |
| 732 | host_name : The host name on which the job is going to run |
| 733 | host_num (non negative) : A number to identify the machine so that we have |
| 734 | different sets of s_bar_ports for each of the machines. |
| 735 | instance : The number of the job |
| 736 | num_jobs : Total number of jobs that are going to run in parallel with |
| 737 | this job starting at the same time |
| 738 | port_base : Port number that is used to derive the actual barrier ports. |
| 739 | |
| 740 | RETURN VALUE: |
| 741 | The modified control file. |
| 742 | |
| 743 | """ |
| 744 | def get_sync_control_file(control, host_name, host_num, |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 745 | instance, num_jobs, port_base=63100): |
| 746 | sc_bar_port = port_base |
| 747 | c_bar_port = port_base |
| 748 | if host_num < 0: |
| 749 | print "Please provide a non negative number for the host" |
| 750 | return None |
| 751 | s_bar_port = port_base + 1 + host_num # The set of s_bar_ports are |
| 752 | # the same for a given machine |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 753 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 754 | sc_bar_timeout = 180 |
| 755 | s_bar_timeout = c_bar_timeout = 120 |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 756 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 757 | # The barrier code snippet is prepended into the conrol file |
| 758 | # dynamically before at.run() is called finally. |
| 759 | control_new = [] |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 760 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 761 | # jobid is the unique name used to identify the processes |
| 762 | # trying to reach the barriers |
| 763 | jobid = "%s#%d" % (host_name, instance) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 764 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 765 | rendv = [] |
| 766 | # rendvstr is a temp holder for the rendezvous list of the processes |
| 767 | for n in range(num_jobs): |
| 768 | rendv.append("'%s#%d'" % (host_name, n)) |
| 769 | rendvstr = ",".join(rendv) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 770 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 771 | if instance == 0: |
| 772 | # Do the setup and wait at the server barrier |
| 773 | # Clean up the tmp and the control dirs for the first instance |
| 774 | control_new.append('if os.path.exists(job.tmpdir):') |
| 775 | control_new.append("\t system('umount -f %s > /dev/null" |
| 776 | "2> /dev/null' % job.tmpdir," |
| 777 | "ignore_status=True)") |
| 778 | control_new.append("\t system('rm -rf ' + job.tmpdir)") |
| 779 | control_new.append( |
| 780 | 'b0 = job.barrier("%s", "sc_bar", %d, port=%d)' |
| 781 | % (jobid, sc_bar_timeout, sc_bar_port)) |
| 782 | control_new.append( |
mbligh | 9c12f77 | 2009-06-22 19:03:55 +0000 | [diff] [blame] | 783 | 'b0.rendezvous_servers("PARALLEL_MASTER", "%s")' |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 784 | % jobid) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 785 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 786 | elif instance == 1: |
| 787 | # Wait at the server barrier to wait for instance=0 |
| 788 | # process to complete setup |
| 789 | b0 = barrier.barrier("PARALLEL_MASTER", "sc_bar", sc_bar_timeout, |
| 790 | port=sc_bar_port) |
mbligh | 9c12f77 | 2009-06-22 19:03:55 +0000 | [diff] [blame] | 791 | b0.rendezvous_servers("PARALLEL_MASTER", jobid) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 792 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 793 | if(num_jobs > 2): |
| 794 | b1 = barrier.barrier(jobid, "s_bar", s_bar_timeout, |
| 795 | port=s_bar_port) |
mbligh | 9c12f77 | 2009-06-22 19:03:55 +0000 | [diff] [blame] | 796 | b1.rendezvous(rendvstr) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 797 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 798 | else: |
| 799 | # For the rest of the clients |
| 800 | b2 = barrier.barrier(jobid, "s_bar", s_bar_timeout, port=s_bar_port) |
mbligh | 9c12f77 | 2009-06-22 19:03:55 +0000 | [diff] [blame] | 801 | b2.rendezvous(rendvstr) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 802 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 803 | # Client side barrier for all the tests to start at the same time |
| 804 | control_new.append('b1 = job.barrier("%s", "c_bar", %d, port=%d)' |
| 805 | % (jobid, c_bar_timeout, c_bar_port)) |
mbligh | 9c12f77 | 2009-06-22 19:03:55 +0000 | [diff] [blame] | 806 | control_new.append("b1.rendezvous(%s)" % rendvstr) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 807 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 808 | # Stick in the rest of the control file |
| 809 | control_new.append(control) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 810 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 811 | return "\n".join(control_new) |
mbligh | c1cbc99 | 2008-05-27 20:01:45 +0000 | [diff] [blame] | 812 | |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 813 | |
mbligh | c5ddfd1 | 2008-08-04 17:15:00 +0000 | [diff] [blame] | 814 | def get_arch(run_function=run): |
| 815 | """ |
| 816 | Get the hardware architecture of the machine. |
| 817 | run_function is used to execute the commands. It defaults to |
| 818 | utils.run() but a custom method (if provided) should be of the |
| 819 | same schema as utils.run. It should return a CmdResult object and |
| 820 | throw a CmdError exception. |
| 821 | """ |
| 822 | arch = run_function('/bin/uname -m').stdout.rstrip() |
| 823 | if re.match(r'i\d86$', arch): |
| 824 | arch = 'i386' |
| 825 | return arch |
| 826 | |
| 827 | |
showard | 4745ecd | 2009-05-26 19:34:56 +0000 | [diff] [blame] | 828 | def get_num_logical_cpus_per_socket(run_function=run): |
mbligh | 9fd9afe | 2009-04-28 18:27:25 +0000 | [diff] [blame] | 829 | """ |
| 830 | Get the number of cores (including hyperthreading) per cpu. |
| 831 | run_function is used to execute the commands. It defaults to |
| 832 | utils.run() but a custom method (if provided) should be of the |
| 833 | same schema as utils.run. It should return a CmdResult object and |
| 834 | throw a CmdError exception. |
| 835 | """ |
showard | 4745ecd | 2009-05-26 19:34:56 +0000 | [diff] [blame] | 836 | siblings = run_function('grep "^siblings" /proc/cpuinfo').stdout.rstrip() |
| 837 | num_siblings = map(int, |
| 838 | re.findall(r'^siblings\s*:\s*(\d+)\s*$', |
| 839 | siblings, re.M)) |
| 840 | if len(num_siblings) == 0: |
| 841 | raise error.TestError('Unable to find siblings info in /proc/cpuinfo') |
| 842 | if min(num_siblings) != max(num_siblings): |
| 843 | raise error.TestError('Number of siblings differ %r' % |
| 844 | num_siblings) |
| 845 | return num_siblings[0] |
mbligh | 9fd9afe | 2009-04-28 18:27:25 +0000 | [diff] [blame] | 846 | |
| 847 | |
jadmanski | 4f90925 | 2008-12-01 20:47:10 +0000 | [diff] [blame] | 848 | def merge_trees(src, dest): |
| 849 | """ |
| 850 | Merges a source directory tree at 'src' into a destination tree at |
| 851 | 'dest'. If a path is a file in both trees than the file in the source |
| 852 | tree is APPENDED to the one in the destination tree. If a path is |
| 853 | a directory in both trees then the directories are recursively merged |
| 854 | with this function. In any other case, the function will skip the |
| 855 | paths that cannot be merged (instead of failing). |
| 856 | """ |
| 857 | if not os.path.exists(src): |
| 858 | return # exists only in dest |
| 859 | elif not os.path.exists(dest): |
| 860 | if os.path.isfile(src): |
| 861 | shutil.copy2(src, dest) # file only in src |
| 862 | else: |
| 863 | shutil.copytree(src, dest, symlinks=True) # dir only in src |
| 864 | return |
| 865 | elif os.path.isfile(src) and os.path.isfile(dest): |
| 866 | # src & dest are files in both trees, append src to dest |
| 867 | destfile = open(dest, "a") |
| 868 | try: |
| 869 | srcfile = open(src) |
| 870 | try: |
| 871 | destfile.write(srcfile.read()) |
| 872 | finally: |
| 873 | srcfile.close() |
| 874 | finally: |
| 875 | destfile.close() |
| 876 | elif os.path.isdir(src) and os.path.isdir(dest): |
| 877 | # src & dest are directories in both trees, so recursively merge |
| 878 | for name in os.listdir(src): |
| 879 | merge_trees(os.path.join(src, name), os.path.join(dest, name)) |
| 880 | else: |
| 881 | # src & dest both exist, but are incompatible |
| 882 | return |
| 883 | |
| 884 | |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 885 | class CmdResult(object): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 886 | """ |
| 887 | Command execution result. |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 888 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 889 | command: String containing the command line itself |
| 890 | exit_status: Integer exit code of the process |
| 891 | stdout: String containing stdout of the process |
| 892 | stderr: String containing stderr of the process |
| 893 | duration: Elapsed wall clock time running the process |
| 894 | """ |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 895 | |
| 896 | |
mbligh | cd63a21 | 2009-05-01 23:04:38 +0000 | [diff] [blame] | 897 | def __init__(self, command="", stdout="", stderr="", |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 898 | exit_status=None, duration=0): |
| 899 | self.command = command |
| 900 | self.exit_status = exit_status |
| 901 | self.stdout = stdout |
| 902 | self.stderr = stderr |
| 903 | self.duration = duration |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 904 | |
| 905 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 906 | def __repr__(self): |
| 907 | wrapper = textwrap.TextWrapper(width = 78, |
| 908 | initial_indent="\n ", |
| 909 | subsequent_indent=" ") |
| 910 | |
| 911 | stdout = self.stdout.rstrip() |
| 912 | if stdout: |
| 913 | stdout = "\nstdout:\n%s" % stdout |
| 914 | |
| 915 | stderr = self.stderr.rstrip() |
| 916 | if stderr: |
| 917 | stderr = "\nstderr:\n%s" % stderr |
| 918 | |
| 919 | return ("* Command: %s\n" |
| 920 | "Exit status: %s\n" |
| 921 | "Duration: %s\n" |
| 922 | "%s" |
| 923 | "%s" |
| 924 | % (wrapper.fill(self.command), self.exit_status, |
| 925 | self.duration, stdout, stderr)) |
mbligh | 63073c9 | 2008-03-31 16:49:32 +0000 | [diff] [blame] | 926 | |
| 927 | |
mbligh | 462c015 | 2008-03-13 15:37:10 +0000 | [diff] [blame] | 928 | class run_randomly: |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 929 | def __init__(self, run_sequentially=False): |
| 930 | # Run sequentially is for debugging control files |
| 931 | self.test_list = [] |
| 932 | self.run_sequentially = run_sequentially |
mbligh | 462c015 | 2008-03-13 15:37:10 +0000 | [diff] [blame] | 933 | |
| 934 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 935 | def add(self, *args, **dargs): |
| 936 | test = (args, dargs) |
| 937 | self.test_list.append(test) |
mbligh | 462c015 | 2008-03-13 15:37:10 +0000 | [diff] [blame] | 938 | |
| 939 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 940 | def run(self, fn): |
| 941 | while self.test_list: |
| 942 | test_index = random.randint(0, len(self.test_list)-1) |
| 943 | if self.run_sequentially: |
| 944 | test_index = 0 |
| 945 | (args, dargs) = self.test_list.pop(test_index) |
| 946 | fn(*args, **dargs) |
mbligh | a700772 | 2009-01-13 00:37:11 +0000 | [diff] [blame] | 947 | |
| 948 | |
showard | 5deef7f | 2009-09-09 18:16:58 +0000 | [diff] [blame] | 949 | def import_site_module(path, module, dummy=None, modulefile=None): |
| 950 | """ |
| 951 | Try to import the site specific module if it exists. |
| 952 | |
| 953 | @param path full filename of the source file calling this (ie __file__) |
| 954 | @param module full module name |
| 955 | @param dummy dummy value to return in case there is no symbol to import |
| 956 | @param modulefile module filename |
| 957 | |
| 958 | @return site specific module or dummy |
| 959 | |
| 960 | @raises ImportError if the site file exists but imports fails |
| 961 | """ |
| 962 | short_module = module[module.rfind(".") + 1:] |
| 963 | |
| 964 | if not modulefile: |
| 965 | modulefile = short_module + ".py" |
| 966 | |
| 967 | if os.path.exists(os.path.join(os.path.dirname(path), modulefile)): |
| 968 | return __import__(module, {}, {}, [short_module]) |
| 969 | return dummy |
| 970 | |
| 971 | |
mbligh | dd66937 | 2009-02-03 21:57:18 +0000 | [diff] [blame] | 972 | def import_site_symbol(path, module, name, dummy=None, modulefile=None): |
| 973 | """ |
| 974 | Try to import site specific symbol from site specific file if it exists |
| 975 | |
| 976 | @param path full filename of the source file calling this (ie __file__) |
| 977 | @param module full module name |
| 978 | @param name symbol name to be imported from the site file |
| 979 | @param dummy dummy value to return in case there is no symbol to import |
| 980 | @param modulefile module filename |
| 981 | |
| 982 | @return site specific symbol or dummy |
| 983 | |
showard | 5deef7f | 2009-09-09 18:16:58 +0000 | [diff] [blame] | 984 | @raises ImportError if the site file exists but imports fails |
mbligh | dd66937 | 2009-02-03 21:57:18 +0000 | [diff] [blame] | 985 | """ |
showard | 5deef7f | 2009-09-09 18:16:58 +0000 | [diff] [blame] | 986 | module = import_site_module(path, module, modulefile=modulefile) |
| 987 | if not module: |
| 988 | return dummy |
mbligh | a700772 | 2009-01-13 00:37:11 +0000 | [diff] [blame] | 989 | |
showard | 5deef7f | 2009-09-09 18:16:58 +0000 | [diff] [blame] | 990 | # special unique value to tell us if the symbol can't be imported |
| 991 | cant_import = object() |
mbligh | a700772 | 2009-01-13 00:37:11 +0000 | [diff] [blame] | 992 | |
showard | 5deef7f | 2009-09-09 18:16:58 +0000 | [diff] [blame] | 993 | obj = getattr(module, name, cant_import) |
| 994 | if obj is cant_import: |
| 995 | logging.error("unable to import site symbol '%s', using non-site " |
| 996 | "implementation", name) |
| 997 | return dummy |
mbligh | 062ed15 | 2009-01-13 00:57:14 +0000 | [diff] [blame] | 998 | |
| 999 | return obj |
| 1000 | |
| 1001 | |
| 1002 | def import_site_class(path, module, classname, baseclass, modulefile=None): |
| 1003 | """ |
| 1004 | Try to import site specific class from site specific file if it exists |
| 1005 | |
| 1006 | Args: |
| 1007 | path: full filename of the source file calling this (ie __file__) |
| 1008 | module: full module name |
| 1009 | classname: class name to be loaded from site file |
mbligh | 0a8c332 | 2009-04-28 18:32:19 +0000 | [diff] [blame] | 1010 | baseclass: base class object to return when no site file present or |
| 1011 | to mixin when site class exists but is not inherited from baseclass |
mbligh | 062ed15 | 2009-01-13 00:57:14 +0000 | [diff] [blame] | 1012 | modulefile: module filename |
| 1013 | |
mbligh | 0a8c332 | 2009-04-28 18:32:19 +0000 | [diff] [blame] | 1014 | Returns: baseclass if site specific class does not exist, the site specific |
| 1015 | class if it exists and is inherited from baseclass or a mixin of the |
| 1016 | site specific class and baseclass when the site specific class exists |
| 1017 | and is not inherited from baseclass |
mbligh | 062ed15 | 2009-01-13 00:57:14 +0000 | [diff] [blame] | 1018 | |
| 1019 | Raises: ImportError if the site file exists but imports fails |
| 1020 | """ |
| 1021 | |
mbligh | dd66937 | 2009-02-03 21:57:18 +0000 | [diff] [blame] | 1022 | res = import_site_symbol(path, module, classname, None, modulefile) |
mbligh | 0a8c332 | 2009-04-28 18:32:19 +0000 | [diff] [blame] | 1023 | if res: |
| 1024 | if not issubclass(res, baseclass): |
| 1025 | # if not a subclass of baseclass then mix in baseclass with the |
| 1026 | # site specific class object and return the result |
| 1027 | res = type(classname, (res, baseclass), {}) |
| 1028 | else: |
| 1029 | res = baseclass |
mbligh | a700772 | 2009-01-13 00:37:11 +0000 | [diff] [blame] | 1030 | |
mbligh | 062ed15 | 2009-01-13 00:57:14 +0000 | [diff] [blame] | 1031 | return res |
| 1032 | |
| 1033 | |
| 1034 | def import_site_function(path, module, funcname, dummy, modulefile=None): |
| 1035 | """ |
| 1036 | Try to import site specific function from site specific file if it exists |
| 1037 | |
| 1038 | Args: |
| 1039 | path: full filename of the source file calling this (ie __file__) |
| 1040 | module: full module name |
| 1041 | funcname: function name to be imported from site file |
| 1042 | dummy: dummy function to return in case there is no function to import |
| 1043 | modulefile: module filename |
| 1044 | |
| 1045 | Returns: site specific function object or dummy |
| 1046 | |
| 1047 | Raises: ImportError if the site file exists but imports fails |
| 1048 | """ |
| 1049 | |
mbligh | dd66937 | 2009-02-03 21:57:18 +0000 | [diff] [blame] | 1050 | return import_site_symbol(path, module, funcname, dummy, modulefile) |
mbligh | fb67603 | 2009-04-01 18:25:38 +0000 | [diff] [blame] | 1051 | |
| 1052 | |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 1053 | def _get_pid_path(program_name): |
| 1054 | my_path = os.path.dirname(__file__) |
| 1055 | return os.path.abspath(os.path.join(my_path, "..", "..", |
| 1056 | "%s.pid" % program_name)) |
| 1057 | |
| 1058 | |
mbligh | fb67603 | 2009-04-01 18:25:38 +0000 | [diff] [blame] | 1059 | def write_pid(program_name): |
| 1060 | """ |
| 1061 | Try to drop <program_name>.pid in the main autotest directory. |
| 1062 | |
| 1063 | Args: |
| 1064 | program_name: prefix for file name |
| 1065 | """ |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 1066 | pidfile = open(_get_pid_path(program_name), "w") |
| 1067 | try: |
| 1068 | pidfile.write("%s\n" % os.getpid()) |
| 1069 | finally: |
| 1070 | pidfile.close() |
mbligh | fb67603 | 2009-04-01 18:25:38 +0000 | [diff] [blame] | 1071 | |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 1072 | |
| 1073 | def delete_pid_file_if_exists(program_name): |
| 1074 | """ |
| 1075 | Tries to remove <program_name>.pid from the main autotest directory. |
| 1076 | """ |
| 1077 | pidfile_path = _get_pid_path(program_name) |
| 1078 | |
| 1079 | try: |
| 1080 | os.remove(pidfile_path) |
| 1081 | except OSError: |
| 1082 | if not os.path.exists(pidfile_path): |
| 1083 | return |
| 1084 | raise |
| 1085 | |
| 1086 | |
| 1087 | def get_pid_from_file(program_name): |
| 1088 | """ |
| 1089 | Reads the pid from <program_name>.pid in the autotest directory. |
| 1090 | |
| 1091 | @param program_name the name of the program |
| 1092 | @return the pid if the file exists, None otherwise. |
| 1093 | """ |
| 1094 | pidfile_path = _get_pid_path(program_name) |
| 1095 | if not os.path.exists(pidfile_path): |
| 1096 | return None |
| 1097 | |
| 1098 | pidfile = open(_get_pid_path(program_name), 'r') |
| 1099 | |
| 1100 | try: |
| 1101 | try: |
| 1102 | pid = int(pidfile.readline()) |
| 1103 | except IOError: |
| 1104 | if not os.path.exists(pidfile_path): |
| 1105 | return None |
| 1106 | raise |
| 1107 | finally: |
| 1108 | pidfile.close() |
| 1109 | |
| 1110 | return pid |
| 1111 | |
| 1112 | |
showard | 8de3713 | 2009-08-31 18:33:08 +0000 | [diff] [blame] | 1113 | def program_is_alive(program_name): |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 1114 | """ |
| 1115 | Checks if the process is alive and not in Zombie state. |
| 1116 | |
| 1117 | @param program_name the name of the program |
| 1118 | @return True if still alive, False otherwise |
| 1119 | """ |
| 1120 | pid = get_pid_from_file(program_name) |
| 1121 | if pid is None: |
| 1122 | return False |
| 1123 | return pid_is_alive(pid) |
| 1124 | |
| 1125 | |
showard | 8de3713 | 2009-08-31 18:33:08 +0000 | [diff] [blame] | 1126 | def signal_program(program_name, sig=signal.SIGTERM): |
showard | 549afad | 2009-08-20 23:33:36 +0000 | [diff] [blame] | 1127 | """ |
| 1128 | Sends a signal to the process listed in <program_name>.pid |
| 1129 | |
| 1130 | @param program_name the name of the program |
| 1131 | @param sig signal to send |
| 1132 | """ |
| 1133 | pid = get_pid_from_file(program_name) |
| 1134 | if pid: |
| 1135 | signal_pid(pid, sig) |
mbligh | 4556178 | 2009-05-11 21:14:34 +0000 | [diff] [blame] | 1136 | |
| 1137 | |
| 1138 | def get_relative_path(path, reference): |
| 1139 | """Given 2 absolute paths "path" and "reference", compute the path of |
| 1140 | "path" as relative to the directory "reference". |
| 1141 | |
| 1142 | @param path the absolute path to convert to a relative path |
| 1143 | @param reference an absolute directory path to which the relative |
| 1144 | path will be computed |
| 1145 | """ |
| 1146 | # normalize the paths (remove double slashes, etc) |
| 1147 | assert(os.path.isabs(path)) |
| 1148 | assert(os.path.isabs(reference)) |
| 1149 | |
| 1150 | path = os.path.normpath(path) |
| 1151 | reference = os.path.normpath(reference) |
| 1152 | |
| 1153 | # we could use os.path.split() but it splits from the end |
| 1154 | path_list = path.split(os.path.sep)[1:] |
| 1155 | ref_list = reference.split(os.path.sep)[1:] |
| 1156 | |
| 1157 | # find the longest leading common path |
| 1158 | for i in xrange(min(len(path_list), len(ref_list))): |
| 1159 | if path_list[i] != ref_list[i]: |
| 1160 | # decrement i so when exiting this loop either by no match or by |
| 1161 | # end of range we are one step behind |
| 1162 | i -= 1 |
| 1163 | break |
| 1164 | i += 1 |
| 1165 | # drop the common part of the paths, not interested in that anymore |
| 1166 | del path_list[:i] |
| 1167 | |
| 1168 | # for each uncommon component in the reference prepend a ".." |
| 1169 | path_list[:0] = ['..'] * (len(ref_list) - i) |
| 1170 | |
| 1171 | return os.path.join(*path_list) |
mbligh | 277a0e4 | 2009-07-11 00:11:45 +0000 | [diff] [blame] | 1172 | |
| 1173 | |
| 1174 | def sh_escape(command): |
| 1175 | """ |
| 1176 | Escape special characters from a command so that it can be passed |
| 1177 | as a double quoted (" ") string in a (ba)sh command. |
| 1178 | |
| 1179 | Args: |
| 1180 | command: the command string to escape. |
| 1181 | |
| 1182 | Returns: |
| 1183 | The escaped command string. The required englobing double |
| 1184 | quotes are NOT added and so should be added at some point by |
| 1185 | the caller. |
| 1186 | |
| 1187 | See also: http://www.tldp.org/LDP/abs/html/escapingsection.html |
| 1188 | """ |
| 1189 | command = command.replace("\\", "\\\\") |
| 1190 | command = command.replace("$", r'\$') |
| 1191 | command = command.replace('"', r'\"') |
| 1192 | command = command.replace('`', r'\`') |
| 1193 | return command |