Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 1 | #pylint: disable-msg=C0111 |
| 2 | |
Gaurav Shah | a7fb896 | 2011-08-16 15:06:32 -0700 | [diff] [blame] | 3 | # Copyright (c) 2011 The Chromium OS Authors. All rights reserved. |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 4 | # Use of this source code is governed by a BSD-style license that can be |
| 5 | # found in the LICENSE file. |
| 6 | |
Elly Jones | 2f0ebba | 2011-10-27 13:43:20 -0400 | [diff] [blame] | 7 | import logging, os, platform, re, signal, tempfile, time, uuid |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 8 | from autotest_lib.client.common_lib import error |
Vadim Bendebury | e797092 | 2011-04-07 17:07:37 -0700 | [diff] [blame] | 9 | from autotest_lib.client.common_lib import utils |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 10 | |
rginda | f25f73f | 2010-04-07 14:55:25 -0700 | [diff] [blame] | 11 | class TimeoutError(error.TestError): |
| 12 | """Error raised when we time out when waiting on a condition.""" |
David James | d51ac9c | 2011-09-10 00:45:24 -0700 | [diff] [blame] | 13 | pass |
rginda | f25f73f | 2010-04-07 14:55:25 -0700 | [diff] [blame] | 14 | |
| 15 | |
Vadim Bendebury | e797092 | 2011-04-07 17:07:37 -0700 | [diff] [blame] | 16 | class Crossystem(object): |
| 17 | """A wrapper for the crossystem utility.""" |
| 18 | |
| 19 | def __init__(self, client): |
| 20 | self.cros_system_data = {} |
| 21 | self._client = client |
| 22 | |
| 23 | def init(self): |
| 24 | self.cros_system_data = {} |
| 25 | (_, fname) = tempfile.mkstemp() |
| 26 | f = open(fname, 'w') |
| 27 | self._client.run('crossystem', stdout_tee=f) |
| 28 | f.close() |
| 29 | text = utils.read_file(fname) |
| 30 | for line in text.splitlines(): |
| 31 | assignment_string = line.split('#')[0] |
| 32 | if not assignment_string.count('='): |
| 33 | continue |
| 34 | (name, value) = assignment_string.split('=', 1) |
| 35 | self.cros_system_data[name.strip()] = value.strip() |
| 36 | os.remove(fname) |
| 37 | |
| 38 | def __getattr__(self, name): |
| 39 | """ |
| 40 | Retrieve a crosssystem attribute. |
| 41 | |
| 42 | The call crossystemobject.name() will return the crossystem reported |
| 43 | string. |
| 44 | """ |
| 45 | return lambda : self.cros_system_data[name] |
| 46 | |
| 47 | |
Chris Masone | af85909 | 2012-11-19 16:44:44 -0800 | [diff] [blame] | 48 | def get_oldest_pid_by_name(name): |
| 49 | """ |
| 50 | Return the oldest pid of a process whose name perfectly matches |name|. |
| 51 | |
| 52 | name is an egrep expression, which will be matched against the entire name |
| 53 | of processes on the system. For example: |
| 54 | |
| 55 | get_oldest_pid_by_name('chrome') |
| 56 | |
| 57 | on a system running |
| 58 | 8600 ? 00:00:04 chrome |
| 59 | 8601 ? 00:00:00 chrome |
| 60 | 8602 ? 00:00:00 chrome-sandbox |
| 61 | |
| 62 | would return 8600, as that's the oldest process that matches. |
| 63 | chrome-sandbox would not be matched. |
| 64 | |
| 65 | Arguments: |
| 66 | name: egrep expression to match. Will be anchored at the beginning and |
| 67 | end of the match string. |
| 68 | |
| 69 | Returns: |
| 70 | pid as an integer, or None if one cannot be found. |
| 71 | |
| 72 | Raises: |
| 73 | ValueError if pgrep returns something odd. |
| 74 | """ |
| 75 | str_pid = utils.system_output( |
| 76 | 'pgrep -o ^%s$' % name, ignore_status=True).rstrip() |
| 77 | if str_pid: |
| 78 | return int(str_pid) |
| 79 | |
| 80 | |
Dan Shi | 03c3e44 | 2013-10-22 14:41:23 -0700 | [diff] [blame] | 81 | def get_oldest_by_name(name): |
| 82 | """Return pid and command line of oldest process whose name matches |name|. |
| 83 | |
| 84 | @param name: egrep expression to match desired process name. |
| 85 | @return: A tuple of (pid, command_line) of the oldest process whose name |
| 86 | matches |name|. |
| 87 | |
| 88 | """ |
| 89 | pid = get_oldest_pid_by_name(name) |
| 90 | if pid: |
| 91 | command_line = utils.system_output('ps -p %i -o command=' % pid, |
| 92 | ignore_status=True).rstrip() |
| 93 | return (pid, command_line) |
| 94 | |
| 95 | |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 96 | def get_chrome_remote_debugging_port(): |
| 97 | """Returns remote debugging port for Chrome. |
| 98 | |
| 99 | Parse chrome process's command line argument to get the remote debugging |
| 100 | port. |
| 101 | """ |
| 102 | pid, command = get_oldest_by_name('chrome') |
| 103 | matches = re.search('--remote-debugging-port=([0-9]+)', command) |
| 104 | if matches: |
| 105 | return int(matches.group(1)) |
| 106 | |
| 107 | |
Rohit Makasana | c018b97 | 2013-07-29 21:25:39 +0530 | [diff] [blame] | 108 | def get_process_list(name, command_line=None): |
| 109 | """ |
| 110 | Return the list of pid for matching process |name command_line|. |
| 111 | |
| 112 | on a system running |
| 113 | 31475 ? 0:06 /opt/google/chrome/chrome --allow-webui-compositing - |
| 114 | 31478 ? 0:00 /opt/google/chrome/chrome-sandbox /opt/google/chrome/ |
| 115 | 31485 ? 0:00 /opt/google/chrome/chrome --type=zygote --log-level=1 |
| 116 | 31532 ? 1:05 /opt/google/chrome/chrome --type=renderer |
| 117 | |
| 118 | get_process_list('chrome') |
| 119 | would return ['31475', '31485', '31532'] |
| 120 | |
| 121 | get_process_list('chrome', '--type=renderer') |
| 122 | would return ['31532'] |
| 123 | |
| 124 | Arguments: |
| 125 | name: process name to search for. If command_line is provided, name is |
| 126 | matched against full command line. If command_line is not provided, |
| 127 | name is only matched against the process name. |
| 128 | command line: when command line is passed, the full process command line |
| 129 | is used for matching. |
| 130 | |
| 131 | Returns: |
| 132 | list of PIDs of the matching processes. |
| 133 | |
| 134 | """ |
| 135 | # TODO(rohitbm) crbug.com/268861 |
| 136 | flag = '-x' if not command_line else '-f' |
| 137 | name = '\'%s.*%s\'' % (name, command_line) if command_line else name |
| 138 | str_pid = utils.system_output( |
| 139 | 'pgrep %s %s' % (flag, name), ignore_status=True).rstrip() |
| 140 | return str_pid |
| 141 | |
| 142 | |
David James | d51ac9c | 2011-09-10 00:45:24 -0700 | [diff] [blame] | 143 | def nuke_process_by_name(name, with_prejudice=False): |
| 144 | try: |
Chris Masone | af85909 | 2012-11-19 16:44:44 -0800 | [diff] [blame] | 145 | pid = get_oldest_pid_by_name(name) |
David James | d51ac9c | 2011-09-10 00:45:24 -0700 | [diff] [blame] | 146 | except Exception as e: |
| 147 | logging.error(e) |
| 148 | return |
Chris Masone | 7d6af68 | 2013-08-06 13:47:44 -0700 | [diff] [blame] | 149 | if pid is None: |
| 150 | raise error.AutoservPidAlreadyDeadError( |
| 151 | 'No process matching %s.' % name) |
David James | d51ac9c | 2011-09-10 00:45:24 -0700 | [diff] [blame] | 152 | if with_prejudice: |
| 153 | utils.nuke_pid(pid, [signal.SIGKILL]) |
| 154 | else: |
| 155 | utils.nuke_pid(pid) |
| 156 | |
| 157 | |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 158 | def poll_for_condition( |
rginda | f25f73f | 2010-04-07 14:55:25 -0700 | [diff] [blame] | 159 | condition, exception=None, timeout=10, sleep_interval=0.1, desc=None): |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 160 | """Poll until a condition becomes true. |
| 161 | |
Jon Salz | 4f646a3 | 2011-11-30 14:42:51 +0800 | [diff] [blame] | 162 | Arguments: |
| 163 | condition: function taking no args and returning bool |
| 164 | exception: exception to throw if condition doesn't become true |
| 165 | timeout: maximum number of seconds to wait |
| 166 | sleep_interval: time to sleep between polls |
| 167 | desc: description of default TimeoutError used if 'exception' is None |
| 168 | |
| 169 | Returns: |
| 170 | The true value that caused the poll loop to terminate. |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 171 | |
| 172 | Raises: |
rginda | f25f73f | 2010-04-07 14:55:25 -0700 | [diff] [blame] | 173 | 'exception' arg if supplied; site_utils.TimeoutError otherwise |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 174 | """ |
| 175 | start_time = time.time() |
| 176 | while True: |
Jon Salz | 4f646a3 | 2011-11-30 14:42:51 +0800 | [diff] [blame] | 177 | value = condition() |
| 178 | if value: |
| 179 | return value |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 180 | if time.time() + sleep_interval - start_time > timeout: |
rginda | f25f73f | 2010-04-07 14:55:25 -0700 | [diff] [blame] | 181 | if exception: |
Gaurav Shah | a7fb896 | 2011-08-16 15:06:32 -0700 | [diff] [blame] | 182 | logging.error(exception) |
rginda | f25f73f | 2010-04-07 14:55:25 -0700 | [diff] [blame] | 183 | raise exception |
| 184 | |
| 185 | if desc: |
| 186 | desc = 'Timed out waiting for condition: %s' % desc |
| 187 | else: |
| 188 | desc = 'Timed out waiting for unnamed condition' |
Gaurav Shah | a7fb896 | 2011-08-16 15:06:32 -0700 | [diff] [blame] | 189 | logging.error(desc) |
Mitsuru Oshima | 5d3e454 | 2010-08-18 13:46:06 -0700 | [diff] [blame] | 190 | raise TimeoutError, desc |
rginda | f25f73f | 2010-04-07 14:55:25 -0700 | [diff] [blame] | 191 | |
Daniel Erat | 3e3f7f4 | 2010-03-29 17:19:14 -0700 | [diff] [blame] | 192 | time.sleep(sleep_interval) |
Thieu Le | 1904d00 | 2010-11-30 17:10:24 -0800 | [diff] [blame] | 193 | |
| 194 | |
| 195 | def save_vm_state(checkpoint): |
| 196 | """Saves the current state of the virtual machine. |
| 197 | |
| 198 | This function is a NOOP if the test is not running under a virtual machine |
| 199 | with the USB serial port redirected. |
| 200 | |
| 201 | Arguments: |
| 202 | checkpoint - Name used to identify this state |
| 203 | |
| 204 | Returns: |
| 205 | None |
| 206 | """ |
| 207 | # The QEMU monitor has been redirected to the guest serial port located at |
| 208 | # /dev/ttyUSB0. To save the state of the VM, we just send the 'savevm' |
| 209 | # command to the serial port. |
| 210 | proc = platform.processor() |
| 211 | if 'QEMU' in proc and os.path.exists('/dev/ttyUSB0'): |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 212 | logging.info('Saving VM state "%s"', checkpoint) |
Thieu Le | 1904d00 | 2010-11-30 17:10:24 -0800 | [diff] [blame] | 213 | serial = open('/dev/ttyUSB0', 'w') |
| 214 | serial.write("savevm %s\r\n" % checkpoint) |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 215 | logging.info('Done saving VM state "%s"', checkpoint) |
Mandeep Singh Baines | 142ac8d | 2011-02-18 13:31:08 -0800 | [diff] [blame] | 216 | |
| 217 | |
| 218 | def check_raw_dmesg(dmesg, message_level, whitelist): |
| 219 | """Checks dmesg for unexpected warnings. |
| 220 | |
| 221 | This function parses dmesg for message with message_level <= message_level |
| 222 | which do not appear in the whitelist. |
| 223 | |
| 224 | Arguments: |
| 225 | dmesg - string containing raw dmesg buffer |
| 226 | message_level - minimum message priority to check |
| 227 | whitelist - messages to ignore |
| 228 | |
| 229 | Returns: |
| 230 | List of unexpected warnings |
| 231 | """ |
Vadim Bendebury | e797092 | 2011-04-07 17:07:37 -0700 | [diff] [blame] | 232 | whitelist_re = re.compile(r'(%s)' % '|'.join(whitelist)) |
Mandeep Singh Baines | 142ac8d | 2011-02-18 13:31:08 -0800 | [diff] [blame] | 233 | unexpected = [] |
| 234 | for line in dmesg.splitlines(): |
| 235 | if int(line[1]) <= message_level: |
Vadim Bendebury | e797092 | 2011-04-07 17:07:37 -0700 | [diff] [blame] | 236 | stripped_line = line.split('] ', 1)[1] |
| 237 | if whitelist_re.search(stripped_line): |
| 238 | continue |
| 239 | unexpected.append(stripped_line) |
Mandeep Singh Baines | 142ac8d | 2011-02-18 13:31:08 -0800 | [diff] [blame] | 240 | return unexpected |
Vadim Bendebury | 29916f2 | 2011-04-13 10:54:47 -0700 | [diff] [blame] | 241 | |
| 242 | def verify_mesg_set(mesg, regex, whitelist): |
| 243 | """Verifies that the exact set of messages are present in a text. |
| 244 | |
| 245 | This function finds all strings in the text matching a certain regex, and |
| 246 | then verifies that all expected strings are present in the set, and no |
| 247 | unexpected strings are there. |
| 248 | |
| 249 | Arguments: |
| 250 | mesg - the mutiline text to be scanned |
| 251 | regex - regular expression to match |
| 252 | whitelist - messages to find in the output, a list of strings |
| 253 | (potentially regexes) to look for in the filtered output. All these |
| 254 | strings must be there, and no other strings should be present in the |
| 255 | filtered output. |
| 256 | |
| 257 | Returns: |
| 258 | string of inconsistent findings (i.e. an empty string on success). |
| 259 | """ |
| 260 | |
| 261 | rv = [] |
| 262 | |
| 263 | missing_strings = [] |
| 264 | present_strings = [] |
| 265 | for line in mesg.splitlines(): |
| 266 | if not re.search(r'%s' % regex, line): |
| 267 | continue |
| 268 | present_strings.append(line.split('] ', 1)[1]) |
| 269 | |
| 270 | for string in whitelist: |
| 271 | for present_string in list(present_strings): |
| 272 | if re.search(r'^%s$' % string, present_string): |
| 273 | present_strings.remove(present_string) |
| 274 | break |
| 275 | else: |
| 276 | missing_strings.append(string) |
| 277 | |
| 278 | if present_strings: |
| 279 | rv.append('unexpected strings:') |
| 280 | rv.extend(present_strings) |
| 281 | if missing_strings: |
| 282 | rv.append('missing strings:') |
| 283 | rv.extend(missing_strings) |
| 284 | |
| 285 | return '\n'.join(rv) |
Ahmad Sharif | f8e9262 | 2011-05-24 12:37:39 -0700 | [diff] [blame] | 286 | |
| 287 | |
Mike Frysinger | e72f7e4 | 2012-03-16 14:49:11 -0400 | [diff] [blame] | 288 | def target_is_pie(): |
| 289 | """Returns whether the toolchain produces a PIE (position independent |
Ahmad Sharif | f8e9262 | 2011-05-24 12:37:39 -0700 | [diff] [blame] | 290 | executable) by default. |
| 291 | |
| 292 | Arguments: |
| 293 | None |
| 294 | |
| 295 | Returns: |
Mike Frysinger | e72f7e4 | 2012-03-16 14:49:11 -0400 | [diff] [blame] | 296 | True if the target toolchain produces a PIE by default. |
Ahmad Sharif | f8e9262 | 2011-05-24 12:37:39 -0700 | [diff] [blame] | 297 | False otherwise. |
| 298 | """ |
| 299 | |
| 300 | |
Mike Frysinger | e72f7e4 | 2012-03-16 14:49:11 -0400 | [diff] [blame] | 301 | command = 'echo | ${CC} -E -dD -P - | grep -i pie' |
Ahmad Sharif | f8e9262 | 2011-05-24 12:37:39 -0700 | [diff] [blame] | 302 | result = utils.system_output(command, retain_output=True, |
| 303 | ignore_status=True) |
Mike Frysinger | e72f7e4 | 2012-03-16 14:49:11 -0400 | [diff] [blame] | 304 | if re.search('#define __PIE__', result): |
Ahmad Sharif | f8e9262 | 2011-05-24 12:37:39 -0700 | [diff] [blame] | 305 | return True |
| 306 | else: |
| 307 | return False |
Elly Jones | 686c2f4 | 2011-10-24 16:45:07 -0400 | [diff] [blame] | 308 | |
Sonny Rao | 172edad | 2012-02-07 23:23:58 +0000 | [diff] [blame] | 309 | def target_is_x86(): |
| 310 | """Returns whether the toolchain produces an x86 object |
| 311 | |
| 312 | Arguments: |
| 313 | None |
| 314 | |
| 315 | Returns: |
| 316 | True if the target toolchain produces an x86 object |
| 317 | False otherwise. |
| 318 | """ |
| 319 | |
| 320 | |
Mike Frysinger | e72f7e4 | 2012-03-16 14:49:11 -0400 | [diff] [blame] | 321 | command = 'echo | ${CC} -E -dD -P - | grep -i 86' |
Sonny Rao | 172edad | 2012-02-07 23:23:58 +0000 | [diff] [blame] | 322 | result = utils.system_output(command, retain_output=True, |
| 323 | ignore_status=True) |
Mike Frysinger | e72f7e4 | 2012-03-16 14:49:11 -0400 | [diff] [blame] | 324 | if re.search('__i386__', result) or re.search('__x86_64__', result): |
Sonny Rao | 172edad | 2012-02-07 23:23:58 +0000 | [diff] [blame] | 325 | return True |
| 326 | else: |
| 327 | return False |
| 328 | |
Elly Jones | 686c2f4 | 2011-10-24 16:45:07 -0400 | [diff] [blame] | 329 | def mounts(): |
| 330 | ret = [] |
| 331 | for line in file('/proc/mounts'): |
| 332 | m = re.match(r'(?P<src>\S+) (?P<dest>\S+) (?P<type>\S+) (?P<opts>\S+).*', line) |
| 333 | if m: |
| 334 | ret.append(m.groupdict()) |
| 335 | return ret |
| 336 | |
| 337 | def is_mountpoint(path): |
| 338 | return path in [ m['dest'] for m in mounts() ] |
| 339 | |
| 340 | def require_mountpoint(path): |
| 341 | """ |
| 342 | Raises an exception if path is not a mountpoint. |
| 343 | """ |
| 344 | if not is_mountpoint(path): |
| 345 | raise error.TestFail('Path not mounted: "%s"' % path) |
Elly Jones | 2f0ebba | 2011-10-27 13:43:20 -0400 | [diff] [blame] | 346 | |
| 347 | def random_username(): |
| 348 | return str(uuid.uuid4()) + '@example.com' |
Simran Basi | c6f1f7a | 2012-10-16 10:47:46 -0700 | [diff] [blame] | 349 | |
| 350 | |
| 351 | def parse_cmd_output(command, run_method=utils.run): |
| 352 | """Runs a command on a host object to retrieve host attributes. |
| 353 | |
| 354 | The command should output to stdout in the format of: |
| 355 | <key> = <value> # <optional_comment> |
| 356 | |
| 357 | |
| 358 | @param command: Command to execute on the host. |
| 359 | @param run_method: Function to use to execute the command. Defaults to |
| 360 | utils.run so that the command will be executed locally. |
| 361 | Can be replace with a host.run call so that it will |
| 362 | execute on a DUT or external machine. Method must accept |
| 363 | a command argument, stdout_tee and stderr_tee args and |
| 364 | return a result object with a string attribute stdout |
| 365 | which will be parsed. |
| 366 | |
| 367 | @returns a dictionary mapping host attributes to their values. |
| 368 | """ |
| 369 | result = {} |
| 370 | # Suppresses stdout so that the files are not printed to the logs. |
| 371 | cmd_result = run_method(command, stdout_tee=None, stderr_tee=None) |
| 372 | for line in cmd_result.stdout.splitlines(): |
| 373 | # Lines are of the format "<key> = <value> # <comment>" |
| 374 | key_value = re.match('^\s*(?P<key>[^ ]+)\s*=\s*(?P<value>[^ ]+)' |
| 375 | '(?:\s*#.*)?$', line) |
| 376 | if key_value: |
| 377 | result[key_value.group('key')] = key_value.group('value') |
Chris Masone | af85909 | 2012-11-19 16:44:44 -0800 | [diff] [blame] | 378 | return result |
Mike Truty | 77f06bc | 2013-03-30 09:43:05 -0500 | [diff] [blame] | 379 | |
| 380 | |
| 381 | def set_from_keyval_output(out, delimiter=' '): |
| 382 | """Parse delimiter-separated key-val output into a set of tuples. |
| 383 | |
| 384 | Output is expected to be multiline text output from a command. |
| 385 | Stuffs the key-vals into tuples in a set to be later compared. |
| 386 | |
| 387 | e.g. deactivated 0 |
| 388 | disableForceClear 0 |
| 389 | ==> set(('deactivated', '0'), ('disableForceClear', '0')) |
| 390 | |
| 391 | @param out: multiple lines of space-separated key-val pairs. |
| 392 | @param delimiter: character that separates key from val. Usually a |
| 393 | space but may be '=' or something else. |
| 394 | @return set of key-val tuples. |
| 395 | """ |
| 396 | results = set() |
| 397 | kv_match_re = re.compile('([^ ]+)%s(.*)' % delimiter) |
| 398 | for linecr in out.splitlines(): |
| 399 | match = kv_match_re.match(linecr.strip()) |
| 400 | if match: |
| 401 | results.add((match.group(1), match.group(2))) |
| 402 | return results |
Ilja H. Friedel | 42052a2 | 2014-03-05 22:54:01 -0800 | [diff] [blame] | 403 | |
| 404 | |
| 405 | def get_cpu_usage(): |
| 406 | """Returns machine's CPU usage. |
| 407 | |
| 408 | This function uses /proc/stat to identify CPU usage. |
| 409 | Returns: |
| 410 | A dictionary with 'user', 'nice', 'system' and 'idle' values. |
| 411 | Sample dictionary: |
| 412 | { |
| 413 | 'user': 254544, |
| 414 | 'nice': 9, |
| 415 | 'system': 254768, |
| 416 | 'idle': 2859878, |
| 417 | } |
| 418 | """ |
| 419 | proc_stat = open('/proc/stat') |
| 420 | cpu_usage_str = proc_stat.readline().split() |
| 421 | proc_stat.close() |
| 422 | return { |
| 423 | 'user': int(cpu_usage_str[1]), |
| 424 | 'nice': int(cpu_usage_str[2]), |
| 425 | 'system': int(cpu_usage_str[3]), |
| 426 | 'idle': int(cpu_usage_str[4]) |
| 427 | } |
| 428 | |
| 429 | |
| 430 | def compute_active_cpu_time(cpu_usage_start, cpu_usage_end): |
| 431 | """Computes the fraction of CPU time spent non-idling. |
| 432 | |
| 433 | This function should be invoked using before/after values from calls to |
| 434 | get_cpu_usage(). |
| 435 | """ |
| 436 | time_active_end = (cpu_usage_end['user'] + cpu_usage_end['nice'] + |
| 437 | cpu_usage_end['system']) |
| 438 | time_active_start = (cpu_usage_start['user'] + cpu_usage_start['nice'] + |
| 439 | cpu_usage_start['system']) |
| 440 | total_time_end = (cpu_usage_end['user'] + cpu_usage_end['nice'] + |
| 441 | cpu_usage_end['system'] + cpu_usage_end['idle']) |
| 442 | total_time_start = (cpu_usage_start['user'] + cpu_usage_start['nice'] + |
| 443 | cpu_usage_start['system'] + cpu_usage_start['idle']) |
| 444 | return ((float(time_active_end) - time_active_start) / |
| 445 | (total_time_end - total_time_start)) |
| 446 | |
| 447 | |
| 448 | def is_pgo_mode(): |
| 449 | return 'USE_PGO' in os.environ |
| 450 | |
| 451 | |
| 452 | def wait_for_idle_cpu(timeout, utilization): |
| 453 | """Waits for the CPU to become idle (< utilization). |
| 454 | |
| 455 | Args: |
| 456 | timeout: The longest time in seconds to wait before throwing an error. |
| 457 | utilization: The CPU usage below which the system should be considered |
| 458 | idle (between 0 and 1.0 independent of cores/hyperthreads). |
| 459 | """ |
| 460 | time_passed = 0.0 |
| 461 | fraction_active_time = 1.0 |
| 462 | sleep_time = 1 |
| 463 | logging.info('Starting to wait up to %.1fs for idle CPU...', timeout) |
| 464 | while fraction_active_time >= utilization: |
| 465 | cpu_usage_start = get_cpu_usage() |
| 466 | # Split timeout interval into not too many chunks to limit log spew. |
| 467 | # Start at 1 second, increase exponentially |
| 468 | time.sleep(sleep_time) |
| 469 | time_passed += sleep_time |
| 470 | sleep_time = min(16.0, 2.0 * sleep_time) |
| 471 | cpu_usage_end = get_cpu_usage() |
| 472 | fraction_active_time = \ |
| 473 | compute_active_cpu_time(cpu_usage_start, cpu_usage_end) |
| 474 | logging.info('After waiting %.1fs CPU utilization is %f.', |
| 475 | time_passed, fraction_active_time) |
| 476 | if time_passed > timeout: |
| 477 | logging.warning('CPU did not become idle.') |
| 478 | log_process_activity() |
| 479 | # crosbug.com/37389 |
| 480 | if is_pgo_mode(): |
| 481 | logging.info('Still continuing because we are in PGO mode.') |
| 482 | return True |
| 483 | |
| 484 | return False |
| 485 | logging.info('Wait for idle CPU took %fs (utilization = %f).', |
| 486 | time_passed, fraction_active_time) |
| 487 | return True |
| 488 | |
| 489 | |
| 490 | def log_process_activity(): |
| 491 | """Logs the output of top. |
| 492 | |
| 493 | Useful to debug performance tests and to find runaway processes. |
| 494 | """ |
| 495 | logging.info('Logging current process activity using top.') |
| 496 | cmd = 'top -b -n1 -c' |
| 497 | output = utils.run(cmd) |
| 498 | logging.info(output) |
| 499 | |
| 500 | |
| 501 | def wait_for_cool_cpu(): |
| 502 | # TODO(ihf): Implement this. |
| 503 | return True |
| 504 | |
| 505 | |
| 506 | def wait_for_cool_idle_perf_machine(): |
| 507 | # Wait for 60 seconds for the CPU usage to fall under 10%. |
| 508 | if not wait_for_idle_cpu(60, 0.1): |
| 509 | return False |
| 510 | return wait_for_cool_cpu() |
| 511 | |