Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 1 | # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """Common python commands used by various build scripts.""" |
| 6 | |
Chris Sosa | 471532a | 2011-02-01 15:10:06 -0800 | [diff] [blame] | 7 | import inspect |
Scott Zawalski | 98ac6b2 | 2010-09-08 15:59:23 -0700 | [diff] [blame] | 8 | import os |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 9 | import re |
Doug Anderson | 6781f94 | 2011-01-14 16:21:39 -0800 | [diff] [blame] | 10 | import signal |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 11 | import subprocess |
| 12 | import sys |
Simon Glass | 53ed230 | 2011-02-08 18:42:16 -0800 | [diff] [blame] | 13 | from terminal import Color |
| 14 | |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 15 | |
| 16 | _STDOUT_IS_TTY = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() |
| 17 | |
Tan Gao | 2f31088 | 2010-09-10 14:50:47 -0700 | [diff] [blame] | 18 | |
| 19 | class CommandResult(object): |
| 20 | """An object to store various attributes of a child process.""" |
| 21 | |
| 22 | def __init__(self): |
| 23 | self.cmd = None |
| 24 | self.error = None |
| 25 | self.output = None |
| 26 | self.returncode = None |
| 27 | |
| 28 | |
| 29 | class RunCommandError(Exception): |
| 30 | """Error caught in RunCommand() method.""" |
| 31 | pass |
| 32 | |
| 33 | |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 34 | def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, |
| 35 | exit_code=False, redirect_stdout=False, redirect_stderr=False, |
Doug Anderson | 6781f94 | 2011-01-14 16:21:39 -0800 | [diff] [blame] | 36 | cwd=None, input=None, enter_chroot=False, shell=False, |
Chris Sosa | 66c8c25 | 2011-02-17 11:44:09 -0800 | [diff] [blame] | 37 | env=None, ignore_sigint=False, combine_stdout_stderr=False): |
David James | 6db8f52 | 2010-09-09 10:49:11 -0700 | [diff] [blame] | 38 | """Runs a command. |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 39 | |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 40 | Args: |
| 41 | cmd: cmd to run. Should be input to subprocess.Popen. |
| 42 | print_cmd: prints the command before running it. |
| 43 | error_ok: does not raise an exception on error. |
| 44 | error_message: prints out this message when an error occurrs. |
| 45 | exit_code: returns the return code of the shell command. |
| 46 | redirect_stdout: returns the stdout. |
| 47 | redirect_stderr: holds stderr output until input is communicated. |
| 48 | cwd: the working directory to run this cmd. |
| 49 | input: input to pipe into this command through stdin. |
| 50 | enter_chroot: this command should be run from within the chroot. If set, |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 51 | cwd must point to the scripts directory. |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 52 | shell: If shell is True, the specified command will be executed through |
| 53 | the shell. |
Doug Anderson | 6781f94 | 2011-01-14 16:21:39 -0800 | [diff] [blame] | 54 | env: If non-None, this is the environment for the new process. |
| 55 | ignore_sigint: If True, we'll ignore signal.SIGINT before calling the |
| 56 | child. This is the desired behavior if we know our child will handle |
| 57 | Ctrl-C. If we don't do this, I think we and the child will both get |
| 58 | Ctrl-C at the same time, which means we'll forcefully kill the child. |
Chris Sosa | 66c8c25 | 2011-02-17 11:44:09 -0800 | [diff] [blame] | 59 | combine_stdout_stderr: Combines stdout and stdin streams into stdout. |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 60 | |
| 61 | Returns: |
| 62 | A CommandResult object. |
| 63 | |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 64 | Raises: |
| 65 | Exception: Raises generic exception on error with optional error_message. |
| 66 | """ |
| 67 | # Set default for variables. |
| 68 | stdout = None |
| 69 | stderr = None |
| 70 | stdin = None |
Tan Gao | 2f31088 | 2010-09-10 14:50:47 -0700 | [diff] [blame] | 71 | cmd_result = CommandResult() |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 72 | |
| 73 | # Modify defaults based on parameters. |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 74 | if redirect_stdout: stdout = subprocess.PIPE |
| 75 | if redirect_stderr: stderr = subprocess.PIPE |
Chris Sosa | 66c8c25 | 2011-02-17 11:44:09 -0800 | [diff] [blame] | 76 | if combine_stdout_stderr: stderr = subprocess.STDOUT |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 77 | # TODO(sosa): gpylint complains about redefining built-in 'input'. |
| 78 | # Can we rename this variable? |
| 79 | if input: stdin = subprocess.PIPE |
David James | 6db8f52 | 2010-09-09 10:49:11 -0700 | [diff] [blame] | 80 | if isinstance(cmd, basestring): |
| 81 | if enter_chroot: cmd = './enter_chroot.sh -- ' + cmd |
| 82 | cmd_str = cmd |
| 83 | else: |
| 84 | if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd |
| 85 | cmd_str = ' '.join(cmd) |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 86 | |
| 87 | # Print out the command before running. |
| 88 | if print_cmd: |
David James | 6db8f52 | 2010-09-09 10:49:11 -0700 | [diff] [blame] | 89 | Info('RunCommand: %s' % cmd_str) |
Doug Anderson | a8d22de | 2011-01-13 16:22:58 -0800 | [diff] [blame] | 90 | cmd_result.cmd = cmd |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 91 | |
| 92 | try: |
David James | 9102a89 | 2010-12-02 10:21:49 -0800 | [diff] [blame] | 93 | proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, |
Doug Anderson | 6781f94 | 2011-01-14 16:21:39 -0800 | [diff] [blame] | 94 | stderr=stderr, shell=shell, env=env) |
| 95 | if ignore_sigint: |
| 96 | old_sigint = signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 97 | try: |
| 98 | (cmd_result.output, cmd_result.error) = proc.communicate(input) |
| 99 | finally: |
| 100 | if ignore_sigint: |
| 101 | signal.signal(signal.SIGINT, old_sigint) |
| 102 | |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 103 | if exit_code: |
Tan Gao | 2f31088 | 2010-09-10 14:50:47 -0700 | [diff] [blame] | 104 | cmd_result.returncode = proc.returncode |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 105 | |
| 106 | if not error_ok and proc.returncode: |
Tan Gao | 2f31088 | 2010-09-10 14:50:47 -0700 | [diff] [blame] | 107 | msg = ('Command "%s" failed.\n' % cmd_str + |
| 108 | (error_message or cmd_result.error or cmd_result.output or '')) |
| 109 | raise RunCommandError(msg) |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 110 | # TODO(sosa): is it possible not to use the catch-all Exception here? |
| 111 | except Exception, e: |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 112 | if not error_ok: |
| 113 | raise |
| 114 | else: |
| 115 | Warning(str(e)) |
| 116 | |
Tan Gao | 2f31088 | 2010-09-10 14:50:47 -0700 | [diff] [blame] | 117 | return cmd_result |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 118 | |
| 119 | |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 120 | def Die(message): |
| 121 | """Emits a red error message and halts execution. |
| 122 | |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 123 | Args: |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 124 | message: The message to be emitted before exiting. |
| 125 | """ |
| 126 | print >> sys.stderr, ( |
| 127 | Color(_STDOUT_IS_TTY).Color(Color.RED, '\nERROR: ' + message)) |
| 128 | sys.exit(1) |
| 129 | |
| 130 | |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 131 | # pylint: disable-msg=W0622 |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 132 | def Warning(message): |
| 133 | """Emits a yellow warning message and continues execution. |
| 134 | |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 135 | Args: |
Scott Zawalski | 6bc41ac | 2010-09-08 12:47:28 -0700 | [diff] [blame] | 136 | message: The message to be emitted. |
| 137 | """ |
| 138 | print >> sys.stderr, ( |
| 139 | Color(_STDOUT_IS_TTY).Color(Color.YELLOW, '\nWARNING: ' + message)) |
| 140 | |
| 141 | |
David James | 0315636 | 2011-03-04 20:28:26 -0800 | [diff] [blame^] | 142 | def Info(message): |
| 143 | """Emits a blue informational message and continues execution. |
| 144 | |
| 145 | Args: |
| 146 | message: The message to be emitted. |
| 147 | """ |
| 148 | print >> sys.stderr, ( |
| 149 | Color(_STDOUT_IS_TTY).Color(Color.BLUE, '\nINFO: ' + message)) |
Scott Zawalski | 98ac6b2 | 2010-09-08 15:59:23 -0700 | [diff] [blame] | 150 | |
| 151 | |
| 152 | def ListFiles(base_dir): |
| 153 | """Recurively list files in a directory. |
| 154 | |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 155 | Args: |
Scott Zawalski | 98ac6b2 | 2010-09-08 15:59:23 -0700 | [diff] [blame] | 156 | base_dir: directory to start recursively listing in. |
| 157 | |
| 158 | Returns: |
| 159 | A list of files relative to the base_dir path or |
| 160 | An empty list of there are no files in the directories. |
| 161 | """ |
| 162 | directories = [base_dir] |
| 163 | files_list = [] |
| 164 | while directories: |
| 165 | directory = directories.pop() |
| 166 | for name in os.listdir(directory): |
| 167 | fullpath = os.path.join(directory, name) |
| 168 | if os.path.isfile(fullpath): |
| 169 | files_list.append(fullpath) |
| 170 | elif os.path.isdir(fullpath): |
| 171 | directories.append(fullpath) |
| 172 | |
| 173 | return files_list |
Tan Gao | 2990a4d | 2010-09-22 09:34:27 -0700 | [diff] [blame] | 174 | |
| 175 | |
| 176 | def IsInsideChroot(): |
| 177 | """Returns True if we are inside chroot.""" |
| 178 | return os.path.exists('/etc/debian_chroot') |
| 179 | |
| 180 | |
| 181 | def GetSrcRoot(): |
| 182 | """Get absolute path to src/scripts/ directory. |
| 183 | |
| 184 | Assuming test script will always be run from descendent of src/scripts. |
| 185 | |
| 186 | Returns: |
| 187 | A string, absolute path to src/scripts directory. None if not found. |
| 188 | """ |
| 189 | src_root = None |
| 190 | match_str = '/src/scripts/' |
| 191 | test_script_path = os.path.abspath('.') |
| 192 | |
| 193 | path_list = re.split(match_str, test_script_path) |
| 194 | if path_list: |
| 195 | src_root = os.path.join(path_list[0], match_str.strip('/')) |
| 196 | Info ('src_root = %r' % src_root) |
| 197 | else: |
| 198 | Info ('No %r found in %r' % (match_str, test_script_path)) |
| 199 | |
| 200 | return src_root |
| 201 | |
| 202 | |
| 203 | def GetChromeosVersion(str_obj): |
| 204 | """Helper method to parse output for CHROMEOS_VERSION_STRING. |
| 205 | |
| 206 | Args: |
| 207 | str_obj: a string, which may contain Chrome OS version info. |
| 208 | |
| 209 | Returns: |
| 210 | A string, value of CHROMEOS_VERSION_STRING environment variable set by |
| 211 | chromeos_version.sh. Or None if not found. |
| 212 | """ |
| 213 | if str_obj is not None: |
| 214 | match = re.search('CHROMEOS_VERSION_STRING=([0-9_.]+)', str_obj) |
| 215 | if match and match.group(1): |
| 216 | Info ('CHROMEOS_VERSION_STRING = %s' % match.group(1)) |
| 217 | return match.group(1) |
| 218 | |
| 219 | Info ('CHROMEOS_VERSION_STRING NOT found') |
| 220 | return None |
| 221 | |
| 222 | |
| 223 | def GetOutputImageDir(board, cros_version): |
| 224 | """Construct absolute path to output image directory. |
| 225 | |
| 226 | Args: |
| 227 | board: a string. |
| 228 | cros_version: a string, Chrome OS version. |
| 229 | |
| 230 | Returns: |
| 231 | a string: absolute path to output directory. |
| 232 | """ |
| 233 | src_root = GetSrcRoot() |
| 234 | rel_path = 'build/images/%s' % board |
| 235 | # ASSUME: --build_attempt always sets to 1 |
| 236 | version_str = '-'.join([cros_version, 'a1']) |
| 237 | output_dir = os.path.join(os.path.dirname(src_root), rel_path, version_str) |
| 238 | Info ('output_dir = %s' % output_dir) |
| 239 | return output_dir |
Chris Sosa | 471532a | 2011-02-01 15:10:06 -0800 | [diff] [blame] | 240 | |
| 241 | |
| 242 | def FindRepoDir(path=None): |
| 243 | """Returns the nearest higher-level repo dir from the specified path. |
| 244 | |
| 245 | Args: |
| 246 | path: The path to use. Defaults to cwd. |
| 247 | """ |
| 248 | if path is None: |
| 249 | path = os.getcwd() |
| 250 | path = os.path.abspath(path) |
| 251 | while path != '/': |
| 252 | repo_dir = os.path.join(path, '.repo') |
| 253 | if os.path.isdir(repo_dir): |
| 254 | return repo_dir |
| 255 | path = os.path.dirname(path) |
| 256 | return None |
| 257 | |
| 258 | |
| 259 | def ReinterpretPathForChroot(path): |
| 260 | """Returns reinterpreted path from outside the chroot for use inside. |
| 261 | |
| 262 | Args: |
| 263 | path: The path to reinterpret. Must be in src tree. |
| 264 | """ |
| 265 | root_path = os.path.join(FindRepoDir(path), '..') |
| 266 | |
| 267 | path_abs_path = os.path.abspath(path) |
| 268 | root_abs_path = os.path.abspath(root_path) |
| 269 | |
| 270 | # Strip the repository root from the path and strip first /. |
| 271 | relative_path = path_abs_path.replace(root_abs_path, '')[1:] |
| 272 | |
| 273 | if relative_path == path_abs_path: |
| 274 | raise Exception('Error: path is outside your src tree, cannot reinterpret.') |
| 275 | |
| 276 | new_path = os.path.join('/home', os.getenv('USER'), 'trunk', relative_path) |
| 277 | return new_path |
| 278 | |
| 279 | |
| 280 | def GetCallerName(): |
| 281 | """Returns the name of the calling module with __main__.""" |
| 282 | top_frame = inspect.stack()[-1][0] |
| 283 | return os.path.basename(top_frame.f_code.co_filename) |
| 284 | |
| 285 | |
| 286 | class RunCommandException(Exception): |
| 287 | """Raised when there is an error in OldRunCommand.""" |
| 288 | pass |
| 289 | |
| 290 | |
| 291 | def OldRunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, |
| 292 | exit_code=False, redirect_stdout=False, redirect_stderr=False, |
| 293 | cwd=None, input=None, enter_chroot=False, num_retries=0): |
| 294 | """Legacy run shell command. |
| 295 | |
| 296 | Arguments: |
| 297 | cmd: cmd to run. Should be input to subprocess.POpen. If a string, |
| 298 | converted to an array using split(). |
| 299 | print_cmd: prints the command before running it. |
| 300 | error_ok: does not raise an exception on error. |
| 301 | error_message: prints out this message when an error occurrs. |
| 302 | exit_code: returns the return code of the shell command. |
| 303 | redirect_stdout: returns the stdout. |
| 304 | redirect_stderr: holds stderr output until input is communicated. |
| 305 | cwd: the working directory to run this cmd. |
| 306 | input: input to pipe into this command through stdin. |
| 307 | enter_chroot: this command should be run from within the chroot. If set, |
| 308 | cwd must point to the scripts directory. |
| 309 | num_retries: the number of retries to perform before dying |
| 310 | |
| 311 | Returns: |
| 312 | If exit_code is True, returns the return code of the shell command. |
| 313 | Else returns the output of the shell command. |
| 314 | |
| 315 | Raises: |
| 316 | Exception: Raises RunCommandException on error with optional error_message. |
| 317 | """ |
| 318 | # Set default for variables. |
| 319 | stdout = None |
| 320 | stderr = None |
| 321 | stdin = None |
| 322 | output = '' |
| 323 | |
| 324 | # Modify defaults based on parameters. |
| 325 | if redirect_stdout: stdout = subprocess.PIPE |
| 326 | if redirect_stderr: stderr = subprocess.PIPE |
| 327 | if input: stdin = subprocess.PIPE |
| 328 | if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd |
| 329 | |
| 330 | # Print out the command before running. |
| 331 | if print_cmd: |
| 332 | Info('PROGRAM(%s) -> RunCommand: %r in dir %s' % |
| 333 | (GetCallerName(), cmd, cwd)) |
| 334 | |
| 335 | for retry_count in range(num_retries + 1): |
| 336 | try: |
| 337 | proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, |
| 338 | stdout=stdout, stderr=stderr) |
| 339 | (output, error) = proc.communicate(input) |
| 340 | if exit_code and retry_count == num_retries: |
| 341 | return proc.returncode |
| 342 | |
| 343 | if proc.returncode == 0: |
| 344 | break |
| 345 | |
| 346 | raise RunCommandException('Command "%r" failed.\n' % (cmd) + |
| 347 | (error_message or error or output or '')) |
| 348 | except RunCommandException as e: |
| 349 | if not error_ok and retry_count == num_retries: |
| 350 | raise e |
| 351 | else: |
| 352 | Warning(str(e)) |
| 353 | if print_cmd: |
| 354 | Info('PROGRAM(%s) -> RunCommand: retrying %r in dir %s' % |
| 355 | (GetCallerName(), cmd, cwd)) |
| 356 | |
| 357 | return output |