blob: fe30fcbcf705c11fb6767b55fc934053887538c7 [file] [log] [blame]
Scott Zawalski6bc41ac2010-09-08 12:47:28 -07001# 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 Sosa471532a2011-02-01 15:10:06 -08007import inspect
Scott Zawalski98ac6b22010-09-08 15:59:23 -07008import os
Tan Gao2990a4d2010-09-22 09:34:27 -07009import re
Doug Anderson6781f942011-01-14 16:21:39 -080010import signal
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070011import subprocess
12import sys
Simon Glass53ed2302011-02-08 18:42:16 -080013from terminal import Color
14
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070015
16_STDOUT_IS_TTY = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
17
Tan Gao2f310882010-09-10 14:50:47 -070018
19class 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
29class RunCommandError(Exception):
30 """Error caught in RunCommand() method."""
31 pass
32
33
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070034def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None,
35 exit_code=False, redirect_stdout=False, redirect_stderr=False,
Doug Anderson6781f942011-01-14 16:21:39 -080036 cwd=None, input=None, enter_chroot=False, shell=False,
Chris Sosa66c8c252011-02-17 11:44:09 -080037 env=None, ignore_sigint=False, combine_stdout_stderr=False):
David James6db8f522010-09-09 10:49:11 -070038 """Runs a command.
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070039
Tan Gao2990a4d2010-09-22 09:34:27 -070040 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 Zawalski6bc41ac2010-09-08 12:47:28 -070051 cwd must point to the scripts directory.
Tan Gao2990a4d2010-09-22 09:34:27 -070052 shell: If shell is True, the specified command will be executed through
53 the shell.
Doug Anderson6781f942011-01-14 16:21:39 -080054 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 Sosa66c8c252011-02-17 11:44:09 -080059 combine_stdout_stderr: Combines stdout and stdin streams into stdout.
Tan Gao2990a4d2010-09-22 09:34:27 -070060
61 Returns:
62 A CommandResult object.
63
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070064 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 Gao2f310882010-09-10 14:50:47 -070071 cmd_result = CommandResult()
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070072
73 # Modify defaults based on parameters.
Tan Gao2990a4d2010-09-22 09:34:27 -070074 if redirect_stdout: stdout = subprocess.PIPE
75 if redirect_stderr: stderr = subprocess.PIPE
Chris Sosa66c8c252011-02-17 11:44:09 -080076 if combine_stdout_stderr: stderr = subprocess.STDOUT
Tan Gao2990a4d2010-09-22 09:34:27 -070077 # TODO(sosa): gpylint complains about redefining built-in 'input'.
78 # Can we rename this variable?
79 if input: stdin = subprocess.PIPE
David James6db8f522010-09-09 10:49:11 -070080 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 Zawalski6bc41ac2010-09-08 12:47:28 -070086
87 # Print out the command before running.
88 if print_cmd:
David James6db8f522010-09-09 10:49:11 -070089 Info('RunCommand: %s' % cmd_str)
Doug Andersona8d22de2011-01-13 16:22:58 -080090 cmd_result.cmd = cmd
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070091
92 try:
David James9102a892010-12-02 10:21:49 -080093 proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout,
Doug Anderson6781f942011-01-14 16:21:39 -080094 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 Zawalski6bc41ac2010-09-08 12:47:28 -0700103 if exit_code:
Tan Gao2f310882010-09-10 14:50:47 -0700104 cmd_result.returncode = proc.returncode
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700105
106 if not error_ok and proc.returncode:
Tan Gao2f310882010-09-10 14:50:47 -0700107 msg = ('Command "%s" failed.\n' % cmd_str +
108 (error_message or cmd_result.error or cmd_result.output or ''))
109 raise RunCommandError(msg)
Tan Gao2990a4d2010-09-22 09:34:27 -0700110 # TODO(sosa): is it possible not to use the catch-all Exception here?
111 except Exception, e:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700112 if not error_ok:
113 raise
114 else:
115 Warning(str(e))
116
Tan Gao2f310882010-09-10 14:50:47 -0700117 return cmd_result
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700118
119
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700120def Die(message):
121 """Emits a red error message and halts execution.
122
Tan Gao2990a4d2010-09-22 09:34:27 -0700123 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700124 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 Gao2990a4d2010-09-22 09:34:27 -0700131# pylint: disable-msg=W0622
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700132def Warning(message):
133 """Emits a yellow warning message and continues execution.
134
Tan Gao2990a4d2010-09-22 09:34:27 -0700135 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700136 message: The message to be emitted.
137 """
138 print >> sys.stderr, (
139 Color(_STDOUT_IS_TTY).Color(Color.YELLOW, '\nWARNING: ' + message))
140
141
142def Info(message):
143 """Emits a blue informational message and continues execution.
144
Tan Gao2990a4d2010-09-22 09:34:27 -0700145 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700146 message: The message to be emitted.
147 """
148 print >> sys.stderr, (
149 Color(_STDOUT_IS_TTY).Color(Color.BLUE, '\nINFO: ' + message))
Scott Zawalski98ac6b22010-09-08 15:59:23 -0700150
151
152def ListFiles(base_dir):
153 """Recurively list files in a directory.
154
Tan Gao2990a4d2010-09-22 09:34:27 -0700155 Args:
Scott Zawalski98ac6b22010-09-08 15:59:23 -0700156 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 Gao2990a4d2010-09-22 09:34:27 -0700174
175
176def IsInsideChroot():
177 """Returns True if we are inside chroot."""
178 return os.path.exists('/etc/debian_chroot')
179
180
181def 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
203def 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
223def 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 Sosa471532a2011-02-01 15:10:06 -0800240
241
242def 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
259def 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
280def 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
286class RunCommandException(Exception):
287 """Raised when there is an error in OldRunCommand."""
288 pass
289
290
291def 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