Kuang-che Wu | 6e4beca | 2018-06-27 17:45:02 +0800 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 2 | # Copyright 2017 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | """Bisect command line interface.""" |
| 6 | |
| 7 | from __future__ import print_function |
| 8 | import argparse |
| 9 | import datetime |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 10 | import json |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 11 | import logging |
| 12 | import os |
| 13 | import re |
Kuang-che Wu | 443633f | 2019-02-27 00:58:33 +0800 | [diff] [blame] | 14 | import signal |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 15 | import textwrap |
| 16 | import time |
| 17 | |
| 18 | from bisect_kit import common |
Kuang-che Wu | 385279d | 2017-09-27 14:48:28 +0800 | [diff] [blame] | 19 | from bisect_kit import configure |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 20 | from bisect_kit import core |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 21 | from bisect_kit import errors |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 22 | from bisect_kit import strategy |
| 23 | from bisect_kit import util |
| 24 | |
| 25 | logger = logging.getLogger(__name__) |
| 26 | |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 27 | DEFAULT_SESSION_NAME = 'default' |
| 28 | DEFAULT_CONFIDENCE = 0.999 |
| 29 | |
Kuang-che Wu | 0476d1f | 2019-03-04 19:27:01 +0800 | [diff] [blame] | 30 | # Exit code of bisect eval script. These values are chosen compatible with 'git |
| 31 | # bisect'. |
| 32 | EXIT_CODE_OLD = 0 |
| 33 | EXIT_CODE_NEW = 1 |
| 34 | EXIT_CODE_SKIP = 125 |
| 35 | EXIT_CODE_FATAL = 128 |
| 36 | |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 37 | |
| 38 | class ArgTypeError(argparse.ArgumentTypeError): |
| 39 | """An error for argument validation failure. |
| 40 | |
| 41 | This not only tells users the argument is wrong but also gives correct |
| 42 | example. The main purpose of this error is for argtype_multiplexer, which |
| 43 | cascades examples from multiple ArgTypeError. |
| 44 | """ |
| 45 | |
| 46 | def __init__(self, msg, example): |
| 47 | self.msg = msg |
| 48 | if isinstance(example, list): |
| 49 | self.example = example |
| 50 | else: |
| 51 | self.example = [example] |
| 52 | full_msg = '%s (example value: %s)' % (self.msg, ', '.join(self.example)) |
| 53 | super(ArgTypeError, self).__init__(full_msg) |
| 54 | |
| 55 | |
| 56 | def argtype_notempty(s): |
| 57 | """Validates argument is not an empty string. |
| 58 | |
| 59 | Args: |
| 60 | s: string to validate. |
| 61 | |
| 62 | Raises: |
| 63 | ArgTypeError if argument is empty string. |
| 64 | """ |
| 65 | if not s: |
| 66 | msg = 'should not be empty' |
| 67 | raise ArgTypeError(msg, 'foo') |
| 68 | return s |
| 69 | |
| 70 | |
| 71 | def argtype_int(s): |
| 72 | """Validate argument is a number. |
| 73 | |
| 74 | Args: |
| 75 | s: string to validate. |
| 76 | |
| 77 | Raises: |
| 78 | ArgTypeError if argument is not a number. |
| 79 | """ |
| 80 | try: |
| 81 | return str(int(s)) |
| 82 | except ValueError: |
| 83 | raise ArgTypeError('should be a number', '123') |
| 84 | |
| 85 | |
Kuang-che Wu | 603cdad | 2019-01-18 21:32:55 +0800 | [diff] [blame] | 86 | def argtype_re(pattern, example): |
| 87 | r"""Validate argument matches `pattern`. |
| 88 | |
| 89 | Args: |
| 90 | pattern: regex pattern |
| 91 | example: example string which matches `pattern` |
| 92 | |
| 93 | Returns: |
| 94 | A new argtype function which matches regex `pattern` |
| 95 | """ |
| 96 | assert re.match(pattern, example) |
| 97 | |
| 98 | def validate(s): |
| 99 | if re.match(pattern, s): |
| 100 | return s |
| 101 | if re.escape(pattern) == pattern: |
| 102 | raise ArgTypeError('should be "%s"' % pattern, pattern) |
| 103 | raise ArgTypeError('should match "%s"' % pattern, |
| 104 | '"%s" like %s' % (pattern, example)) |
| 105 | |
| 106 | return validate |
| 107 | |
| 108 | |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 109 | def argtype_multiplexer(*args): |
| 110 | r"""argtype multiplexer |
| 111 | |
Kuang-che Wu | 603cdad | 2019-01-18 21:32:55 +0800 | [diff] [blame] | 112 | This function takes a list of argtypes and creates a new function matching |
| 113 | them. Moreover, it gives error message with examples. |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 114 | |
Kuang-che Wu | baaa453 | 2018-08-15 17:08:10 +0800 | [diff] [blame] | 115 | Examples: |
Kuang-che Wu | 603cdad | 2019-01-18 21:32:55 +0800 | [diff] [blame] | 116 | >>> argtype = argtype_multiplexer(argtype_int, |
| 117 | argtype_re(r'^r\d+$', 'r123')) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 118 | >>> argtype('123') |
| 119 | 123 |
| 120 | >>> argtype('r456') |
| 121 | r456 |
| 122 | >>> argtype('hello') |
Kuang-che Wu | 603cdad | 2019-01-18 21:32:55 +0800 | [diff] [blame] | 123 | ArgTypeError: Invalid argument (example value: 123, "r\d+$" like r123) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 124 | |
| 125 | Args: |
| 126 | *args: list of argtypes or regex pattern. |
| 127 | |
| 128 | Returns: |
| 129 | A new argtype function which matches *args. |
| 130 | """ |
| 131 | |
| 132 | def validate(s): |
| 133 | examples = [] |
| 134 | for t in args: |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 135 | try: |
| 136 | return t(s) |
| 137 | except ArgTypeError as e: |
| 138 | examples += e.example |
| 139 | |
| 140 | msg = 'Invalid argument' |
| 141 | raise ArgTypeError(msg, examples) |
| 142 | |
| 143 | return validate |
| 144 | |
| 145 | |
| 146 | def argtype_multiplier(argtype): |
| 147 | """A new argtype that supports multiplier suffix of the given argtype. |
| 148 | |
Kuang-che Wu | baaa453 | 2018-08-15 17:08:10 +0800 | [diff] [blame] | 149 | Examples: |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 150 | Supports the given argtype accepting "foo" as argument, this function |
| 151 | generates a new argtype function which accepts argument like "foo*3". |
| 152 | |
| 153 | Returns: |
| 154 | A new argtype function which returns (arg, times) where arg is accepted |
| 155 | by input `argtype` and times is repeating count. Note that if multiplier is |
| 156 | omitted, "times" is 1. |
| 157 | """ |
| 158 | |
| 159 | def helper(s): |
| 160 | m = re.match(r'^(.+)\*(\d+)$', s) |
| 161 | try: |
| 162 | if m: |
| 163 | return argtype(m.group(1)), int(m.group(2)) |
Kuang-che Wu | 68db08a | 2018-03-30 11:50:34 +0800 | [diff] [blame] | 164 | return argtype(s), 1 |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 165 | except ArgTypeError as e: |
| 166 | # It should be okay to gives multiplier example only for the first one |
| 167 | # because it is just "example", no need to enumerate all possibilities. |
| 168 | raise ArgTypeError(e.msg, e.example + [e.example[0] + '*3']) |
| 169 | |
| 170 | return helper |
| 171 | |
| 172 | |
| 173 | def argtype_dir_path(s): |
| 174 | """Validate argument is an existing directory. |
| 175 | |
| 176 | Args: |
| 177 | s: string to validate. |
| 178 | |
| 179 | Raises: |
| 180 | ArgTypeError if the path is not a directory. |
| 181 | """ |
| 182 | if not os.path.exists(s): |
| 183 | raise ArgTypeError('should be an existing directory', '/path/to/somewhere') |
| 184 | if not os.path.isdir(s): |
| 185 | raise ArgTypeError('should be a directory', '/path/to/somewhere') |
| 186 | |
| 187 | # Normalize, trim trailing path separators. |
| 188 | if len(s) > 1 and s[-1] == os.path.sep: |
| 189 | s = s[:-1] |
| 190 | return s |
| 191 | |
| 192 | |
| 193 | def _collect_bisect_result_values(values, line): |
| 194 | """Collect bisect result values from output line. |
| 195 | |
| 196 | Args: |
| 197 | values: Collected values are appending to this list. |
| 198 | line: One line of output string. |
| 199 | """ |
| 200 | m = re.match(r'^BISECT_RESULT_VALUES=(.+)', line) |
| 201 | if m: |
| 202 | try: |
| 203 | values.extend(map(float, m.group(1).split())) |
| 204 | except ValueError: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 205 | raise errors.InternalError( |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 206 | 'BISECT_RESULT_VALUES should be list of floats: %r' % m.group(1)) |
| 207 | |
| 208 | |
Kuang-che Wu | 8851888 | 2017-09-22 16:57:25 +0800 | [diff] [blame] | 209 | def check_executable(program): |
| 210 | """Checks whether a program is executable. |
| 211 | |
| 212 | Args: |
| 213 | program: program path in question |
| 214 | |
| 215 | Returns: |
| 216 | string as error message if `program` is not executable, or None otherwise. |
| 217 | It will return None if unable to determine as well. |
| 218 | """ |
| 219 | returncode = util.call('which', program) |
| 220 | if returncode == 127: # No 'which' on this platform, skip the check. |
| 221 | return None |
| 222 | if returncode == 0: # is executable |
| 223 | return None |
| 224 | |
| 225 | hint = '' |
| 226 | if not os.path.exists(program): |
| 227 | hint = 'Not in PATH?' |
| 228 | elif not os.path.isfile(program): |
| 229 | hint = 'Not a file' |
| 230 | elif not os.access(program, os.X_OK): |
| 231 | hint = 'Forgot to chmod +x?' |
| 232 | elif '/' not in program: |
| 233 | hint = 'Forgot to prepend "./" ?' |
| 234 | return '%r is not executable. %s' % (program, hint) |
| 235 | |
| 236 | |
Kuang-che Wu | 443633f | 2019-02-27 00:58:33 +0800 | [diff] [blame] | 237 | def format_returncode(returncode): |
| 238 | if returncode < 0: |
| 239 | signum = -returncode |
| 240 | signame = 'Unknown' |
| 241 | for k, v in vars(signal).items(): |
| 242 | if k.startswith('SIG') and '_' not in k and v == signum: |
| 243 | signame = k |
| 244 | return 'terminated by signal %d (%s)' % (signum, signame) |
| 245 | |
| 246 | return 'exited with code %d' % returncode |
| 247 | |
| 248 | |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 249 | def do_evaluate(evaluate_cmd, domain, rev): |
| 250 | """Invokes evaluator command. |
| 251 | |
| 252 | The `evaluate_cmd` can get the target revision from the environment variable |
| 253 | named 'BISECT_REV'. |
| 254 | |
| 255 | The result is determined according to the exit code of evaluator: |
| 256 | 0: 'old' |
Kuang-che Wu | 0476d1f | 2019-03-04 19:27:01 +0800 | [diff] [blame] | 257 | 1..124, 126, 127: 'new' |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 258 | 125: 'skip' |
Kuang-che Wu | 0476d1f | 2019-03-04 19:27:01 +0800 | [diff] [blame] | 259 | 128..255: fatal error |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 260 | terminated by signal: fatal error |
| 261 | |
| 262 | p.s. the definition of result is compatible with git-bisect(1). |
| 263 | |
| 264 | It also extracts additional values from evaluate_cmd's stdout lines which |
| 265 | match the following format: |
| 266 | BISECT_RESULT_VALUES=<float>[, <float>]* |
| 267 | |
| 268 | Args: |
| 269 | evaluate_cmd: evaluator command. |
| 270 | domain: a bisect_kit.core.Domain instance. |
| 271 | rev: version to evaluate. |
| 272 | |
| 273 | Returns: |
| 274 | (result, values): |
| 275 | result is one of 'old', 'new', 'skip'. |
| 276 | values are additional collected values, like performance score. |
| 277 | |
| 278 | Raises: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 279 | errors.ExecutionFatalError if evaluator returned fatal error code. |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 280 | """ |
| 281 | env = os.environ.copy() |
| 282 | env['BISECT_REV'] = rev |
| 283 | domain.setenv(env, rev) |
| 284 | |
| 285 | values = [] |
| 286 | p = util.Popen( |
| 287 | evaluate_cmd, |
| 288 | env=env, |
| 289 | stdout_callback=lambda line: _collect_bisect_result_values(values, line)) |
| 290 | returncode = p.wait() |
Kuang-che Wu | 0476d1f | 2019-03-04 19:27:01 +0800 | [diff] [blame] | 291 | if returncode < 0 or returncode >= 128: |
Kuang-che Wu | 443633f | 2019-02-27 00:58:33 +0800 | [diff] [blame] | 292 | raise errors.ExecutionFatalError( |
| 293 | 'eval failed: %s' % format_returncode(returncode)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 294 | |
| 295 | if returncode == 0: |
| 296 | return 'old', values |
| 297 | if returncode == 125: |
| 298 | return 'skip', values |
| 299 | return 'new', values |
| 300 | |
| 301 | |
| 302 | def do_switch(switch_cmd, domain, rev): |
| 303 | """Invokes switcher command. |
| 304 | |
| 305 | The `switch_cmd` can get the target revision from the environment variable |
| 306 | named 'BISECT_REV'. |
| 307 | |
| 308 | The result is determined according to the exit code of switcher: |
| 309 | 0: switch succeeded |
Kuang-che Wu | 0476d1f | 2019-03-04 19:27:01 +0800 | [diff] [blame] | 310 | 1..127: 'skip' |
| 311 | 128..255: fatal error |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 312 | terminated by signal: fatal error |
| 313 | |
| 314 | In other words, any non-fatal errors are considered as 'skip'. |
| 315 | |
| 316 | Args: |
| 317 | switch_cmd: switcher command. |
| 318 | domain: a bisect_kit.core.Domain instance. |
| 319 | rev: version to switch. |
| 320 | |
| 321 | Returns: |
| 322 | None if switch successfully, 'skip' otherwise. |
| 323 | |
| 324 | Raises: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 325 | errors.ExecutionFatalError if switcher returned fatal error code. |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 326 | """ |
| 327 | env = os.environ.copy() |
| 328 | env['BISECT_REV'] = rev |
| 329 | domain.setenv(env, rev) |
| 330 | |
| 331 | returncode = util.call(*switch_cmd, env=env) |
Kuang-che Wu | 0476d1f | 2019-03-04 19:27:01 +0800 | [diff] [blame] | 332 | if returncode < 0 or returncode >= 128: |
Kuang-che Wu | 443633f | 2019-02-27 00:58:33 +0800 | [diff] [blame] | 333 | raise errors.ExecutionFatalError( |
| 334 | 'switch failed: %s' % format_returncode(returncode)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 335 | |
| 336 | if returncode != 0: |
| 337 | return 'skip' |
| 338 | return None |
| 339 | |
| 340 | |
Kuang-che Wu | 68db08a | 2018-03-30 11:50:34 +0800 | [diff] [blame] | 341 | class BisectorCommandLine(object): |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 342 | """Bisector command line interface. |
| 343 | |
| 344 | The typical usage pattern: |
| 345 | |
| 346 | if __name__ == '__main__': |
Kuang-che Wu | 68db08a | 2018-03-30 11:50:34 +0800 | [diff] [blame] | 347 | BisectorCommandLine(CustomDomain).main() |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 348 | |
| 349 | where CustomDomain is a derived class of core.BisectDomain. See |
Kuang-che Wu | 0217059 | 2018-07-09 21:42:44 +0800 | [diff] [blame] | 350 | bisect_list.py as example. |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 351 | |
| 352 | If you need to control the bisector using python code, the easier way is |
| 353 | passing command line arguments to main() function. For example, |
| 354 | bisector = Bisector(CustomDomain) |
| 355 | bisector.main('init', '--old', '123', '--new', '456') |
| 356 | bisector.main('config', 'switch', 'true') |
| 357 | bisector.main('config', 'eval', 'true') |
| 358 | bisector.main('run') |
| 359 | """ |
| 360 | |
| 361 | def __init__(self, domain_cls): |
| 362 | self.domain_cls = domain_cls |
| 363 | self.domain = None |
| 364 | self.states = None |
| 365 | self.strategy = None |
| 366 | |
| 367 | @property |
| 368 | def config(self): |
| 369 | return self.states.config |
| 370 | |
Kuang-che Wu | 1dc5bd7 | 2019-01-19 00:14:46 +0800 | [diff] [blame] | 371 | def _format_status(self, status): |
| 372 | if status in ('old', 'new'): |
Kuang-che Wu | b6756d4 | 2019-01-25 12:19:55 +0800 | [diff] [blame] | 373 | return '%s behavior' % status |
Kuang-che Wu | 1dc5bd7 | 2019-01-19 00:14:46 +0800 | [diff] [blame] | 374 | return status |
| 375 | |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 376 | def _add_sample(self, rev, status, **kwargs): |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 377 | idx = self.states.rev2idx(rev) |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 378 | self.states.add_sample(idx, status, **kwargs) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 379 | self.strategy.update(idx, status) |
| 380 | |
| 381 | def cmd_reset(self, _opts): |
| 382 | """Resets bisect session and clean up saved result.""" |
| 383 | self.states.reset() |
| 384 | |
| 385 | def cmd_init(self, opts): |
| 386 | """Initializes bisect session. |
| 387 | |
| 388 | See init command's help message for more detail. |
| 389 | """ |
| 390 | config, revlist = self.domain_cls.init(opts) |
Kuang-che Wu | 42551dd | 2018-01-16 17:27:20 +0800 | [diff] [blame] | 391 | logger.info('found %d revs to bisect', len(revlist)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 392 | logger.debug('revlist %r', revlist) |
| 393 | if 'new' not in config: |
| 394 | config['new'] = opts.new |
| 395 | if 'old' not in config: |
| 396 | config['old'] = opts.old |
| 397 | assert len(revlist) >= 2 |
| 398 | assert config['new'] in revlist |
| 399 | assert config['old'] in revlist |
| 400 | old_idx = revlist.index(config['old']) |
| 401 | new_idx = revlist.index(config['new']) |
| 402 | assert old_idx < new_idx |
| 403 | |
Kuang-che Wu | 81cde45 | 2019-04-08 16:56:51 +0800 | [diff] [blame] | 404 | config.update( |
| 405 | confidence=opts.confidence, |
| 406 | noisy=opts.noisy, |
| 407 | old_value=opts.old_value, |
| 408 | new_value=opts.new_value) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 409 | |
| 410 | self.states.init(config, revlist) |
| 411 | self.states.save() |
| 412 | |
| 413 | def _switch_and_eval(self, rev, prev_rev=None): |
| 414 | """Switches and evaluates given version. |
| 415 | |
| 416 | If current version equals to target, switch step will be skip. |
| 417 | |
| 418 | Args: |
| 419 | rev: Target version. |
| 420 | prev_rev: Previous version. |
| 421 | |
| 422 | Returns: |
| 423 | (step, status, values): |
| 424 | step: Last step executed ('switch' or 'eval'). |
| 425 | status: Execution result ('old', 'new', or 'skip'). |
| 426 | values: Collected values from eval step. None if last step is 'switch'. |
| 427 | """ |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 428 | if prev_rev != rev: |
| 429 | logger.debug('switch to rev=%s', rev) |
| 430 | t0 = time.time() |
| 431 | status = do_switch(self.config['switch'], self.domain, rev) |
| 432 | t1 = time.time() |
| 433 | if status == 'skip': |
| 434 | logger.debug('switch failed => skip') |
| 435 | return 'switch', status, None |
| 436 | self.states.data['stats']['switch_count'] += 1 |
| 437 | self.states.data['stats']['switch_time'] += t1 - t0 |
| 438 | |
| 439 | logger.debug('eval rev=%s', rev) |
| 440 | t0 = time.time() |
| 441 | status, values = do_evaluate(self.config['eval'], self.domain, rev) |
| 442 | t1 = time.time() |
| 443 | if status == 'skip': |
| 444 | return 'eval', status, values |
Kuang-che Wu | 81cde45 | 2019-04-08 16:56:51 +0800 | [diff] [blame] | 445 | |
| 446 | if self.strategy.is_value_bisection(): |
| 447 | status = self.strategy.classify_result_from_values(values) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 448 | self.states.data['stats']['eval_count'] += 1 |
| 449 | self.states.data['stats']['eval_time'] += t1 - t0 |
| 450 | |
| 451 | return 'eval', status, values |
| 452 | |
Kuang-che Wu | 889f68e | 2018-10-29 14:12:13 +0800 | [diff] [blame] | 453 | def _next_idx_iter(self, opts, force): |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 454 | if opts.revs: |
| 455 | for rev in opts.revs: |
| 456 | idx = self.states.rev2idx(rev) |
| 457 | logger.info('try idx=%d rev=%s (command line specified)', idx, rev) |
| 458 | yield idx, rev |
| 459 | if opts.once: |
| 460 | break |
| 461 | else: |
Kuang-che Wu | 889f68e | 2018-10-29 14:12:13 +0800 | [diff] [blame] | 462 | while force or not self.strategy.is_done(): |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 463 | idx = self.strategy.next_idx() |
| 464 | rev = self.states.idx2rev(idx) |
| 465 | logger.info('try idx=%d rev=%s', idx, rev) |
| 466 | yield idx, rev |
Kuang-che Wu | 889f68e | 2018-10-29 14:12:13 +0800 | [diff] [blame] | 467 | force = False |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 468 | if opts.once: |
| 469 | break |
| 470 | |
| 471 | def cmd_run(self, opts): |
| 472 | """Performs bisection. |
| 473 | |
| 474 | See run command's help message for more detail. |
| 475 | |
| 476 | Raises: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 477 | errors.VerificationFailed: The bisection range is verified false. We |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 478 | expect 'old' at the first rev and 'new' at last rev. |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 479 | errors.UnableToProceed: Too many errors to narrow down further the |
| 480 | bisection range. |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 481 | """ |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 482 | # Set dummy values in case exception raised before loop. |
| 483 | idx, rev = -1, None |
| 484 | try: |
| 485 | assert self.config.get('switch') |
| 486 | assert self.config.get('eval') |
| 487 | self.strategy.rebuild() |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 488 | |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 489 | prev_rev = None |
| 490 | force = opts.force |
| 491 | for idx, rev in self._next_idx_iter(opts, force): |
| 492 | if not force: |
| 493 | # Bail out if bisection range is unlikely true in order to prevent |
| 494 | # wasting time. This is necessary because some configurations (say, |
| 495 | # confidence) may be changed before cmd_run() and thus the bisection |
| 496 | # range becomes not acceptable. |
| 497 | self.strategy.check_verification_range() |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 498 | |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 499 | step, status, values = self._switch_and_eval(rev, prev_rev=prev_rev) |
Kuang-che Wu | 81cde45 | 2019-04-08 16:56:51 +0800 | [diff] [blame] | 500 | if self.strategy.is_value_bisection(): |
| 501 | logger.info('rev=%s status => %s: %s', rev, |
| 502 | self._format_status(status), values) |
| 503 | else: |
| 504 | logger.info('rev=%s status => %s', rev, self._format_status(status)) |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 505 | force = False |
| 506 | |
Kuang-che Wu | 978b65a | 2019-03-12 09:50:40 +0800 | [diff] [blame] | 507 | self.states.add_sample(idx, status, values=values) |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 508 | self.states.save() |
| 509 | |
| 510 | # Bail out if bisection range is unlikely true. |
Kuang-che Wu | 889f68e | 2018-10-29 14:12:13 +0800 | [diff] [blame] | 511 | self.strategy.check_verification_range() |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 512 | |
Kuang-che Wu | 978b65a | 2019-03-12 09:50:40 +0800 | [diff] [blame] | 513 | self.strategy.update(idx, status) |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 514 | self.strategy.show_summary() |
| 515 | |
| 516 | if step == 'switch' and status == 'skip': |
| 517 | # Previous switch failed and thus the current version is unknown. Set |
| 518 | # it None, so next switch operation won't be bypassed (due to |
| 519 | # optimization). |
| 520 | prev_rev = None |
| 521 | else: |
| 522 | prev_rev = rev |
| 523 | |
| 524 | logger.info('done') |
| 525 | old_idx, new_idx = self.strategy.get_range() |
| 526 | self.states.add_history('done') |
Kuang-che Wu | 889f68e | 2018-10-29 14:12:13 +0800 | [diff] [blame] | 527 | self.states.save() |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 528 | except Exception as e: |
| 529 | exception_name = e.__class__.__name__ |
| 530 | self.states.add_history( |
| 531 | 'failed', text='%s: %s' % (exception_name, e), index=idx, rev=rev) |
| 532 | self.states.save() |
| 533 | raise |
| 534 | finally: |
Kuang-che Wu | 978b65a | 2019-03-12 09:50:40 +0800 | [diff] [blame] | 535 | if rev and sum(self.strategy.prob) > 0: |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 536 | # progress so far |
| 537 | old_idx, new_idx = self.strategy.get_range() |
| 538 | self.states.add_history( |
| 539 | 'range', |
| 540 | old=self.states.idx2rev(old_idx), |
| 541 | new=self.states.idx2rev(new_idx)) |
| 542 | self.states.save() |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 543 | |
| 544 | def cmd_view(self, opts): |
Kuang-che Wu | e80bb87 | 2018-11-15 19:45:25 +0800 | [diff] [blame] | 545 | """Shows remaining candidates.""" |
Kuang-che Wu | 15874b6 | 2019-01-11 21:10:27 +0800 | [diff] [blame] | 546 | try: |
| 547 | self.strategy.rebuild() |
| 548 | # Rebuild twice in order to re-estimate noise. |
| 549 | self.strategy.rebuild() |
| 550 | except errors.VerificationFailed: |
| 551 | # Do nothing, go ahead to show existing information anyway. |
| 552 | pass |
Kuang-che Wu | e80bb87 | 2018-11-15 19:45:25 +0800 | [diff] [blame] | 553 | |
| 554 | old_idx, new_idx = self.strategy.get_range() |
| 555 | old, new = map(self.states.idx2rev, [old_idx, new_idx]) |
| 556 | highlight_old_idx, highlight_new_idx = self.strategy.get_range( |
| 557 | self.strategy.confidence / 10.0) |
| 558 | summary = { |
| 559 | 'rev_info': [vars(info).copy() for info in self.states.rev_info], |
| 560 | 'current_range': (old, new), |
| 561 | 'highlight_range': |
| 562 | map(self.states.idx2rev, [highlight_old_idx, highlight_new_idx]), |
| 563 | 'prob': |
| 564 | self.strategy.prob, |
| 565 | 'remaining_steps': |
| 566 | self.strategy.remaining_steps(), |
| 567 | } |
| 568 | |
| 569 | if opts.verbose or opts.json: |
| 570 | interesting_indexes = set(range(len(summary['rev_info']))) |
| 571 | else: |
| 572 | interesting_indexes = set([old_idx, new_idx]) |
Kuang-che Wu | 15874b6 | 2019-01-11 21:10:27 +0800 | [diff] [blame] | 573 | if self.strategy.prob: |
| 574 | for i, p in enumerate(self.strategy.prob): |
| 575 | if p > 0.05: |
| 576 | interesting_indexes.add(i) |
Kuang-che Wu | e80bb87 | 2018-11-15 19:45:25 +0800 | [diff] [blame] | 577 | |
| 578 | self.domain.fill_candidate_summary(summary, interesting_indexes) |
| 579 | |
| 580 | if opts.json: |
| 581 | print(json.dumps(summary, indent=2, sort_keys=True)) |
| 582 | else: |
| 583 | self.show_summary(summary, interesting_indexes, verbose=opts.verbose) |
| 584 | |
| 585 | def show_summary(self, summary, interesting_indexes, verbose=False): |
| 586 | old, new = summary['current_range'] |
| 587 | old_idx, new_idx = map(self.states.data['revlist'].index, [old, new]) |
| 588 | |
Kuang-che Wu | accf920 | 2019-01-04 15:40:42 +0800 | [diff] [blame] | 589 | for link in summary.get('links', []): |
| 590 | print('%s: %s' % (link['name'], link['url'])) |
| 591 | if 'note' in link: |
| 592 | print(link['note']) |
Kuang-che Wu | e80bb87 | 2018-11-15 19:45:25 +0800 | [diff] [blame] | 593 | |
| 594 | print('Range: (%s, %s], %s revs left' % (old, new, (new_idx - old_idx))) |
Kuang-che Wu | a8c987f | 2019-01-18 14:26:43 +0800 | [diff] [blame] | 595 | if summary.get('remaining_steps'): |
Kuang-che Wu | e80bb87 | 2018-11-15 19:45:25 +0800 | [diff] [blame] | 596 | print('(roughly %d steps)' % summary['remaining_steps']) |
| 597 | |
| 598 | for i, rev_info in enumerate(summary['rev_info']): |
| 599 | if (not verbose and not old_idx <= i <= new_idx and |
| 600 | not rev_info['result_counter']): |
| 601 | continue |
| 602 | |
| 603 | detail = [] |
Kuang-che Wu | 05e416e | 2019-02-21 12:33:52 +0800 | [diff] [blame] | 604 | if self.strategy.is_noisy() and summary['prob']: |
Kuang-che Wu | a8c987f | 2019-01-18 14:26:43 +0800 | [diff] [blame] | 605 | detail.append('%.4f%%' % (summary['prob'][i] * 100)) |
Kuang-che Wu | e80bb87 | 2018-11-15 19:45:25 +0800 | [diff] [blame] | 606 | if rev_info['result_counter']: |
| 607 | detail.append(str(rev_info['result_counter'])) |
| 608 | values = sorted(rev_info['values']) |
| 609 | if len(values) == 1: |
| 610 | detail.append('%.3f' % values[0]) |
| 611 | elif len(values) > 1: |
| 612 | detail.append('n=%d,avg=%.3f,median=%.3f,min=%.3f,max=%.3f' % |
| 613 | (len(values), sum(values) / len(values), |
| 614 | values[len(values) // 2], values[0], values[-1])) |
| 615 | |
| 616 | print('[%d] %s\t%s' % (i, rev_info['rev'], ' '.join(detail))) |
| 617 | if i in interesting_indexes: |
| 618 | if 'comment' in rev_info: |
| 619 | print('\t%s' % rev_info['comment']) |
| 620 | for action in rev_info.get('actions', []): |
| 621 | if 'text' in action: |
| 622 | print('\t%s' % action['text']) |
| 623 | if 'link' in action: |
| 624 | print('\t%s' % action['link']) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 625 | |
| 626 | def current_status(self, session=None, session_base=None): |
| 627 | """Gets current bisect status. |
| 628 | |
| 629 | Returns: |
| 630 | A dict describing current status. It contains following items: |
| 631 | inited: True iff the session file is initialized (init command has been |
| 632 | invoked). If not, below items are omitted. |
| 633 | old: Start of current estimated range. |
| 634 | new: End of current estimated range. |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 635 | verified: The bisect range is already verified. |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 636 | estimated_noise: New estimated noise. |
| 637 | done: True if bisection is done, otherwise False. |
| 638 | """ |
| 639 | self._create_states(session=session, session_base=session_base) |
| 640 | if self.states.load(): |
| 641 | self.strategy = strategy.NoisyBinarySearch( |
| 642 | self.states.rev_info, |
| 643 | self.states.rev2idx(self.config['old']), |
| 644 | self.states.rev2idx(self.config['new']), |
Kuang-che Wu | 81cde45 | 2019-04-08 16:56:51 +0800 | [diff] [blame] | 645 | old_value=self.config['old_value'], |
| 646 | new_value=self.config['new_value'], |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 647 | confidence=self.config['confidence'], |
| 648 | observation=self.config['noisy']) |
Kuang-che Wu | 15874b6 | 2019-01-11 21:10:27 +0800 | [diff] [blame] | 649 | try: |
| 650 | self.strategy.rebuild() |
| 651 | except errors.VerificationFailed: |
| 652 | # Do nothing, go ahead to show existing information anyway. |
| 653 | pass |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 654 | left, right = self.strategy.get_range() |
| 655 | estimated_noise = self.strategy.get_noise_observation() |
| 656 | |
| 657 | result = dict( |
| 658 | inited=True, |
| 659 | old=self.states.idx2rev(left), |
| 660 | new=self.states.idx2rev(right), |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 661 | verified=self.strategy.is_range_verified(), |
Kuang-che Wu | dd7f6f0 | 2018-06-28 18:19:30 +0800 | [diff] [blame] | 662 | estimated_noise=estimated_noise, |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 663 | done=self.strategy.is_done()) |
| 664 | else: |
| 665 | result = dict(inited=False) |
| 666 | return result |
| 667 | |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 668 | def cmd_log(self, opts): |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 669 | """Prints what has been done so far.""" |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 670 | history = [] |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 671 | for entry in self.states.data['history']: |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 672 | if opts.before and entry['timestamp'] >= opts.before: |
| 673 | continue |
| 674 | if opts.after and entry['timestamp'] <= opts.after: |
| 675 | continue |
| 676 | history.append(entry) |
| 677 | |
| 678 | if opts.json: |
| 679 | print(json.dumps(history, indent=2)) |
| 680 | return |
| 681 | |
| 682 | for entry in history: |
| 683 | entry_time = datetime.datetime.fromtimestamp(int(entry['timestamp'])) |
| 684 | if entry.get('event', 'sample') == 'sample': |
| 685 | print('{datetime} {rev} {status} {values} {comment}'.format( |
| 686 | datetime=entry_time, |
| 687 | rev=entry['rev'], |
| 688 | status=entry['status'] + ('*%d' % entry['times'] |
| 689 | if entry.get('times', 1) > 1 else ''), |
| 690 | values=entry.get('values', ''), |
| 691 | comment=entry.get('comment', ''))) |
| 692 | else: |
| 693 | print('%s %r' % (entry_time, entry)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 694 | |
| 695 | def cmd_next(self, _opts): |
| 696 | """Prints next suggested rev to bisect.""" |
| 697 | self.strategy.rebuild() |
| 698 | if self.strategy.is_done(): |
| 699 | print('done') |
| 700 | return |
| 701 | |
| 702 | idx = self.strategy.next_idx() |
| 703 | rev = self.states.idx2rev(idx) |
| 704 | print(rev) |
| 705 | |
| 706 | def cmd_switch(self, opts): |
| 707 | """Switches to given rev without eval.""" |
| 708 | assert self.config.get('switch') |
| 709 | |
| 710 | self.strategy.rebuild() |
| 711 | |
| 712 | if opts.rev == 'next': |
| 713 | idx = self.strategy.next_idx() |
| 714 | rev = self.states.idx2rev(idx) |
| 715 | else: |
Kuang-che Wu | 752228c | 2018-09-05 13:54:22 +0800 | [diff] [blame] | 716 | rev = self.domain_cls.intra_revtype(opts.rev) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 717 | assert rev |
| 718 | |
| 719 | logger.info('switch to %s', rev) |
| 720 | status = do_switch(self.config['switch'], self.domain, rev) |
| 721 | if status: |
| 722 | print('switch failed') |
| 723 | |
| 724 | def _add_revs_status_helper(self, revs, status): |
| 725 | self.strategy.rebuild() |
| 726 | for rev, times in revs: |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 727 | self._add_sample(rev, status, times=times, comment='manual') |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 728 | self.states.save() |
| 729 | |
| 730 | def cmd_new(self, opts): |
| 731 | """Tells bisect engine the said revs have "new" behavior.""" |
| 732 | logger.info('set [%s] as new', opts.revs) |
| 733 | self._add_revs_status_helper(opts.revs, 'new') |
| 734 | |
| 735 | def cmd_old(self, opts): |
| 736 | """Tells bisect engine the said revs have "old" behavior.""" |
| 737 | logger.info('set [%s] as old', opts.revs) |
| 738 | self._add_revs_status_helper(opts.revs, 'old') |
| 739 | |
| 740 | def cmd_skip(self, opts): |
| 741 | """Tells bisect engine the said revs have "skip" behavior.""" |
| 742 | logger.info('set [%s] as skip', opts.revs) |
| 743 | self._add_revs_status_helper(opts.revs, 'skip') |
| 744 | |
| 745 | def _create_states(self, session=None, session_base=None): |
| 746 | if not session: |
| 747 | session = DEFAULT_SESSION_NAME |
| 748 | if not session_base: |
Kuang-che Wu | 41e8b59 | 2018-09-25 17:01:30 +0800 | [diff] [blame] | 749 | session_base = configure.get('SESSION_BASE', common.DEFAULT_SESSION_BASE) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 750 | |
| 751 | session_file = os.path.join(session_base, session, self.domain_cls.__name__) |
| 752 | |
| 753 | if self.states: |
| 754 | assert self.states.session_file == session_file |
| 755 | else: |
Kuang-che Wu | c578193 | 2018-10-05 00:30:19 +0800 | [diff] [blame] | 756 | self.states = core.BisectStates(session_file) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 757 | |
| 758 | def cmd_config(self, opts): |
| 759 | """Configures additional setting. |
| 760 | |
| 761 | See config command's help message for more detail. |
| 762 | """ |
| 763 | self.states.load() |
| 764 | self.domain = self.domain_cls(self.states.config) |
| 765 | if not opts.value: |
| 766 | print(self.states.config[opts.key]) |
| 767 | return |
| 768 | |
| 769 | if opts.key in ['switch', 'eval']: |
Kuang-che Wu | 8851888 | 2017-09-22 16:57:25 +0800 | [diff] [blame] | 770 | result = check_executable(opts.value[0]) |
| 771 | if result: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 772 | raise errors.ArgumentError('%s command' % opts.key, result) |
Kuang-che Wu | 8851888 | 2017-09-22 16:57:25 +0800 | [diff] [blame] | 773 | |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 774 | self.states.config[opts.key] = opts.value |
| 775 | |
| 776 | elif opts.key == 'confidence': |
| 777 | if len(opts.value) != 1: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 778 | raise errors.ArgumentError( |
| 779 | 'confidence value', |
| 780 | 'expected 1 value, %d values given' % len(opts.value)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 781 | try: |
| 782 | self.states.config[opts.key] = float(opts.value[0]) |
| 783 | except ValueError: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 784 | raise errors.ArgumentError('confidence value', |
| 785 | 'invalid float value: %r' % opts.value[0]) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 786 | |
| 787 | elif opts.key == 'noisy': |
| 788 | if len(opts.value) != 1: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 789 | raise errors.ArgumentError( |
| 790 | 'noisy value', |
| 791 | 'expected 1 value, %d values given' % len(opts.value)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 792 | self.states.config[opts.key] = opts.value[0] |
| 793 | |
| 794 | else: |
Kuang-che Wu | e121fae | 2018-11-09 16:18:39 +0800 | [diff] [blame] | 795 | # unreachable |
| 796 | assert 0 |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 797 | |
| 798 | self.states.save() |
| 799 | |
| 800 | def create_argument_parser(self, prog): |
Kuang-che Wu | b237626 | 2017-11-20 18:05:24 +0800 | [diff] [blame] | 801 | if self.domain_cls.help: |
| 802 | description = self.domain_cls.help |
| 803 | else: |
| 804 | description = 'Bisector for %s' % self.domain_cls.__name__ |
| 805 | description += textwrap.dedent(''' |
| 806 | When running switcher and evaluator, it will set BISECT_REV environment |
| 807 | variable, indicates current rev to switch/evaluate. |
| 808 | ''') |
| 809 | |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 810 | parser = argparse.ArgumentParser( |
| 811 | prog=prog, |
| 812 | formatter_class=argparse.RawDescriptionHelpFormatter, |
Kuang-che Wu | b237626 | 2017-11-20 18:05:24 +0800 | [diff] [blame] | 813 | description=description) |
Kuang-che Wu | 385279d | 2017-09-27 14:48:28 +0800 | [diff] [blame] | 814 | common.add_common_arguments(parser) |
| 815 | parser.add_argument( |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 816 | '--session_base', |
Kuang-che Wu | 41e8b59 | 2018-09-25 17:01:30 +0800 | [diff] [blame] | 817 | default=configure.get('SESSION_BASE', common.DEFAULT_SESSION_BASE), |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 818 | help='Directory to store sessions (default: %(default)r)') |
| 819 | parser.add_argument( |
| 820 | '--session', |
| 821 | default=DEFAULT_SESSION_NAME, |
| 822 | help='Session name (default: %(default)r)') |
| 823 | subparsers = parser.add_subparsers( |
| 824 | dest='command', title='commands', metavar='<command>') |
| 825 | |
| 826 | parser_reset = subparsers.add_parser( |
| 827 | 'reset', help='Reset bisect session and clean up saved result') |
| 828 | parser_reset.set_defaults(func=self.cmd_reset) |
| 829 | |
| 830 | parser_init = subparsers.add_parser( |
| 831 | 'init', |
| 832 | help='Initializes bisect session', |
| 833 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 834 | description=textwrap.dedent(''' |
| 835 | Besides arguments for 'init' command, you also need to set 'switch' |
| 836 | and 'eval' command line via 'config' command. |
| 837 | $ bisector config switch <switch command and arguments> |
| 838 | $ bisector config eval <eval command and arguments> |
| 839 | |
| 840 | The value of --noisy and --confidence could be changed by 'config' |
| 841 | command after 'init' as well. |
| 842 | ''')) |
| 843 | parser_init.add_argument( |
| 844 | '--old', |
| 845 | required=True, |
| 846 | type=self.domain_cls.revtype, |
| 847 | help='Start of bisect range, which has old behavior') |
| 848 | parser_init.add_argument( |
| 849 | '--new', |
| 850 | required=True, |
| 851 | type=self.domain_cls.revtype, |
| 852 | help='End of bisect range, which has new behavior') |
| 853 | parser_init.add_argument( |
| 854 | '--noisy', |
| 855 | help='Enable noisy binary search and specify prior result. ' |
| 856 | 'For example, "old=1/10,new=2/3" means old fail rate is 1/10 ' |
| 857 | 'and new fail rate increased to 2/3. ' |
| 858 | 'Skip if not flaky, say, "new=2/3" means old is always good.') |
| 859 | parser_init.add_argument( |
Kuang-che Wu | 81cde45 | 2019-04-08 16:56:51 +0800 | [diff] [blame] | 860 | '--old_value', |
| 861 | type=float, |
| 862 | help='For performance test, value of old behavior') |
| 863 | parser_init.add_argument( |
| 864 | '--new_value', |
| 865 | type=float, |
| 866 | help='For performance test, value of new behavior') |
| 867 | parser_init.add_argument( |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 868 | '--confidence', |
| 869 | type=float, |
| 870 | default=DEFAULT_CONFIDENCE, |
| 871 | help='Confidence level (default: %(default)r)') |
| 872 | parser_init.set_defaults(func=self.cmd_init) |
| 873 | self.domain_cls.add_init_arguments(parser_init) |
| 874 | |
| 875 | parser_config = subparsers.add_parser( |
| 876 | 'config', help='Configures additional setting') |
| 877 | parser_config.add_argument( |
| 878 | 'key', |
| 879 | choices=['switch', 'eval', 'confidence', 'noisy'], |
| 880 | metavar='key', |
| 881 | help='What config to change. choices=[%(choices)s]') |
| 882 | parser_config.add_argument( |
| 883 | 'value', nargs=argparse.REMAINDER, help='New value') |
| 884 | parser_config.set_defaults(func=self.cmd_config) |
| 885 | |
| 886 | parser_run = subparsers.add_parser( |
| 887 | 'run', |
| 888 | help='Performs bisection', |
| 889 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 890 | description=textwrap.dedent(''' |
| 891 | This command does switch and eval to determine candidates having old or |
| 892 | new behavior. |
| 893 | |
| 894 | By default, it attempts to try versions in binary search manner until |
| 895 | found the first version having new behavior. |
| 896 | |
| 897 | If version numbers are specified on command line, it just tries those |
| 898 | versions and record the result. |
| 899 | |
| 900 | Example: |
| 901 | Bisect automatically. |
| 902 | $ %(prog)s |
| 903 | |
| 904 | Switch and run version "2.13" and "2.14" and then stop. |
| 905 | $ %(prog)s 2.13 2.14 |
| 906 | ''')) |
| 907 | parser_run.add_argument( |
| 908 | '-1', '--once', action='store_true', help='Only run one step') |
| 909 | parser_run.add_argument( |
Kuang-che Wu | 889f68e | 2018-10-29 14:12:13 +0800 | [diff] [blame] | 910 | '--force', |
| 911 | action='store_true', |
| 912 | help="Run at least once even it's already done") |
| 913 | parser_run.add_argument( |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 914 | 'revs', |
| 915 | nargs='*', |
Kuang-che Wu | 752228c | 2018-09-05 13:54:22 +0800 | [diff] [blame] | 916 | type=self.domain_cls.intra_revtype, |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 917 | help='revs to switch+eval; ' |
| 918 | 'default is calculating automatically and run until done') |
| 919 | parser_run.set_defaults(func=self.cmd_run) |
| 920 | |
| 921 | parser_switch = subparsers.add_parser( |
| 922 | 'switch', help='Switch to given rev without eval') |
| 923 | parser_switch.add_argument( |
Kuang-che Wu | 603cdad | 2019-01-18 21:32:55 +0800 | [diff] [blame] | 924 | 'rev', |
| 925 | type=argtype_multiplexer(self.domain_cls.intra_revtype, |
| 926 | argtype_re('next', 'next'))) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 927 | parser_switch.set_defaults(func=self.cmd_switch) |
| 928 | |
| 929 | parser_old = subparsers.add_parser( |
| 930 | 'old', help='Tells bisect engine the said revs have "old" behavior') |
| 931 | parser_old.add_argument( |
Kuang-che Wu | 752228c | 2018-09-05 13:54:22 +0800 | [diff] [blame] | 932 | 'revs', |
| 933 | nargs='+', |
| 934 | type=argtype_multiplier(self.domain_cls.intra_revtype)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 935 | parser_old.set_defaults(func=self.cmd_old) |
| 936 | |
| 937 | parser_new = subparsers.add_parser( |
| 938 | 'new', help='Tells bisect engine the said revs have "new" behavior') |
| 939 | parser_new.add_argument( |
Kuang-che Wu | 752228c | 2018-09-05 13:54:22 +0800 | [diff] [blame] | 940 | 'revs', |
| 941 | nargs='+', |
| 942 | type=argtype_multiplier(self.domain_cls.intra_revtype)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 943 | parser_new.set_defaults(func=self.cmd_new) |
| 944 | |
| 945 | parser_skip = subparsers.add_parser( |
| 946 | 'skip', help='Tells bisect engine the said revs have "skip" behavior') |
| 947 | parser_skip.add_argument( |
Kuang-che Wu | 752228c | 2018-09-05 13:54:22 +0800 | [diff] [blame] | 948 | 'revs', |
| 949 | nargs='+', |
| 950 | type=argtype_multiplier(self.domain_cls.intra_revtype)) |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 951 | parser_skip.set_defaults(func=self.cmd_skip) |
| 952 | |
| 953 | parser_view = subparsers.add_parser( |
| 954 | 'view', help='Shows current progress and candidates') |
Kuang-che Wu | e80bb87 | 2018-11-15 19:45:25 +0800 | [diff] [blame] | 955 | parser_view.add_argument('--verbose', '-v', action='store_true') |
| 956 | parser_view.add_argument('--json', action='store_true') |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 957 | parser_view.set_defaults(func=self.cmd_view) |
| 958 | |
| 959 | parser_log = subparsers.add_parser( |
| 960 | 'log', help='Prints what has been done so far') |
Kuang-che Wu | 8b65409 | 2018-11-09 17:56:25 +0800 | [diff] [blame] | 961 | parser_log.add_argument('--before', type=float) |
| 962 | parser_log.add_argument('--after', type=float) |
| 963 | parser_log.add_argument( |
| 964 | '--json', action='store_true', help='Machine readable output') |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 965 | parser_log.set_defaults(func=self.cmd_log) |
| 966 | |
| 967 | parser_next = subparsers.add_parser( |
| 968 | 'next', help='Prints next suggested rev to bisect') |
| 969 | parser_next.set_defaults(func=self.cmd_next) |
| 970 | |
| 971 | return parser |
| 972 | |
| 973 | def main(self, *args, **kwargs): |
| 974 | """Command line main function. |
| 975 | |
| 976 | Args: |
| 977 | *args: Command line arguments. |
| 978 | **kwargs: additional non command line arguments passed by script code. |
| 979 | { |
| 980 | 'prog': Program name; optional. |
| 981 | } |
| 982 | """ |
Kuang-che Wu | 385279d | 2017-09-27 14:48:28 +0800 | [diff] [blame] | 983 | common.init() |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 984 | parser = self.create_argument_parser(kwargs.get('prog')) |
| 985 | opts = parser.parse_args(args or None) |
| 986 | common.config_logging(opts) |
| 987 | |
| 988 | self._create_states(session=opts.session, session_base=opts.session_base) |
| 989 | if opts.command not in ('init', 'reset', 'config'): |
| 990 | self.states.load() |
| 991 | self.domain = self.domain_cls(self.states.config) |
| 992 | self.strategy = strategy.NoisyBinarySearch( |
| 993 | self.states.rev_info, |
| 994 | self.states.rev2idx(self.config['old']), |
| 995 | self.states.rev2idx(self.config['new']), |
Kuang-che Wu | 81cde45 | 2019-04-08 16:56:51 +0800 | [diff] [blame] | 996 | old_value=self.config['old_value'], |
| 997 | new_value=self.config['new_value'], |
Kuang-che Wu | 88875db | 2017-07-20 10:47:53 +0800 | [diff] [blame] | 998 | confidence=self.config['confidence'], |
| 999 | observation=self.config['noisy']) |
| 1000 | |
| 1001 | return opts.func(opts) |