blob: 2e5a8c6bab43383abbe248043b8356fcac22e469 [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."""
Don Garrettb85946a2011-03-10 18:11:08 -080031 def __init__(self, msg, cmd):
32 self.cmd = cmd
33 Exception.__init__(self, msg)
Tan Gao2f310882010-09-10 14:50:47 -070034
Don Garrettb85946a2011-03-10 18:11:08 -080035 def __eq__(self, other):
36 return (type(self) == type(other) and
37 str(self) == str(other) and
38 self.cmd == other.cmd)
39
40 def __ne__(self, other):
41 return not self.__eq__(other)
Tan Gao2f310882010-09-10 14:50:47 -070042
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070043def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None,
44 exit_code=False, redirect_stdout=False, redirect_stderr=False,
Doug Anderson6781f942011-01-14 16:21:39 -080045 cwd=None, input=None, enter_chroot=False, shell=False,
Chris Sosa66c8c252011-02-17 11:44:09 -080046 env=None, ignore_sigint=False, combine_stdout_stderr=False):
David James6db8f522010-09-09 10:49:11 -070047 """Runs a command.
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070048
Tan Gao2990a4d2010-09-22 09:34:27 -070049 Args:
50 cmd: cmd to run. Should be input to subprocess.Popen.
51 print_cmd: prints the command before running it.
52 error_ok: does not raise an exception on error.
53 error_message: prints out this message when an error occurrs.
54 exit_code: returns the return code of the shell command.
55 redirect_stdout: returns the stdout.
56 redirect_stderr: holds stderr output until input is communicated.
57 cwd: the working directory to run this cmd.
58 input: input to pipe into this command through stdin.
59 enter_chroot: this command should be run from within the chroot. If set,
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070060 cwd must point to the scripts directory.
Tan Gao2990a4d2010-09-22 09:34:27 -070061 shell: If shell is True, the specified command will be executed through
62 the shell.
Doug Anderson6781f942011-01-14 16:21:39 -080063 env: If non-None, this is the environment for the new process.
64 ignore_sigint: If True, we'll ignore signal.SIGINT before calling the
65 child. This is the desired behavior if we know our child will handle
66 Ctrl-C. If we don't do this, I think we and the child will both get
67 Ctrl-C at the same time, which means we'll forcefully kill the child.
Chris Sosa66c8c252011-02-17 11:44:09 -080068 combine_stdout_stderr: Combines stdout and stdin streams into stdout.
Tan Gao2990a4d2010-09-22 09:34:27 -070069
70 Returns:
71 A CommandResult object.
72
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070073 Raises:
74 Exception: Raises generic exception on error with optional error_message.
75 """
76 # Set default for variables.
77 stdout = None
78 stderr = None
79 stdin = None
Tan Gao2f310882010-09-10 14:50:47 -070080 cmd_result = CommandResult()
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070081
82 # Modify defaults based on parameters.
Tan Gao2990a4d2010-09-22 09:34:27 -070083 if redirect_stdout: stdout = subprocess.PIPE
84 if redirect_stderr: stderr = subprocess.PIPE
Chris Sosa66c8c252011-02-17 11:44:09 -080085 if combine_stdout_stderr: stderr = subprocess.STDOUT
Tan Gao2990a4d2010-09-22 09:34:27 -070086 # TODO(sosa): gpylint complains about redefining built-in 'input'.
87 # Can we rename this variable?
88 if input: stdin = subprocess.PIPE
David James6db8f522010-09-09 10:49:11 -070089 if isinstance(cmd, basestring):
90 if enter_chroot: cmd = './enter_chroot.sh -- ' + cmd
91 cmd_str = cmd
92 else:
93 if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd
94 cmd_str = ' '.join(cmd)
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070095
96 # Print out the command before running.
97 if print_cmd:
David James6db8f522010-09-09 10:49:11 -070098 Info('RunCommand: %s' % cmd_str)
Doug Andersona8d22de2011-01-13 16:22:58 -080099 cmd_result.cmd = cmd
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700100
101 try:
David James9102a892010-12-02 10:21:49 -0800102 proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout,
Doug Anderson6781f942011-01-14 16:21:39 -0800103 stderr=stderr, shell=shell, env=env)
104 if ignore_sigint:
105 old_sigint = signal.signal(signal.SIGINT, signal.SIG_IGN)
106 try:
107 (cmd_result.output, cmd_result.error) = proc.communicate(input)
108 finally:
109 if ignore_sigint:
110 signal.signal(signal.SIGINT, old_sigint)
111
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700112 if exit_code:
Tan Gao2f310882010-09-10 14:50:47 -0700113 cmd_result.returncode = proc.returncode
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700114
115 if not error_ok and proc.returncode:
Tan Gao2f310882010-09-10 14:50:47 -0700116 msg = ('Command "%s" failed.\n' % cmd_str +
117 (error_message or cmd_result.error or cmd_result.output or ''))
Don Garrettb85946a2011-03-10 18:11:08 -0800118 raise RunCommandError(msg, cmd)
Tan Gao2990a4d2010-09-22 09:34:27 -0700119 # TODO(sosa): is it possible not to use the catch-all Exception here?
120 except Exception, e:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700121 if not error_ok:
122 raise
123 else:
124 Warning(str(e))
125
Tan Gao2f310882010-09-10 14:50:47 -0700126 return cmd_result
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700127
128
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700129def Die(message):
130 """Emits a red error message and halts execution.
131
Tan Gao2990a4d2010-09-22 09:34:27 -0700132 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700133 message: The message to be emitted before exiting.
134 """
135 print >> sys.stderr, (
136 Color(_STDOUT_IS_TTY).Color(Color.RED, '\nERROR: ' + message))
137 sys.exit(1)
138
139
Tan Gao2990a4d2010-09-22 09:34:27 -0700140# pylint: disable-msg=W0622
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700141def Warning(message):
142 """Emits a yellow warning message and continues execution.
143
Tan Gao2990a4d2010-09-22 09:34:27 -0700144 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700145 message: The message to be emitted.
146 """
147 print >> sys.stderr, (
148 Color(_STDOUT_IS_TTY).Color(Color.YELLOW, '\nWARNING: ' + message))
149
150
David James03156362011-03-04 20:28:26 -0800151def Info(message):
152 """Emits a blue informational message and continues execution.
153
154 Args:
155 message: The message to be emitted.
156 """
157 print >> sys.stderr, (
158 Color(_STDOUT_IS_TTY).Color(Color.BLUE, '\nINFO: ' + message))
Scott Zawalski98ac6b22010-09-08 15:59:23 -0700159
160
161def ListFiles(base_dir):
162 """Recurively list files in a directory.
163
Tan Gao2990a4d2010-09-22 09:34:27 -0700164 Args:
Scott Zawalski98ac6b22010-09-08 15:59:23 -0700165 base_dir: directory to start recursively listing in.
166
167 Returns:
168 A list of files relative to the base_dir path or
169 An empty list of there are no files in the directories.
170 """
171 directories = [base_dir]
172 files_list = []
173 while directories:
174 directory = directories.pop()
175 for name in os.listdir(directory):
176 fullpath = os.path.join(directory, name)
177 if os.path.isfile(fullpath):
178 files_list.append(fullpath)
179 elif os.path.isdir(fullpath):
180 directories.append(fullpath)
181
182 return files_list
Tan Gao2990a4d2010-09-22 09:34:27 -0700183
184
185def IsInsideChroot():
186 """Returns True if we are inside chroot."""
187 return os.path.exists('/etc/debian_chroot')
188
189
190def GetSrcRoot():
191 """Get absolute path to src/scripts/ directory.
192
193 Assuming test script will always be run from descendent of src/scripts.
194
195 Returns:
196 A string, absolute path to src/scripts directory. None if not found.
197 """
198 src_root = None
199 match_str = '/src/scripts/'
200 test_script_path = os.path.abspath('.')
201
202 path_list = re.split(match_str, test_script_path)
203 if path_list:
204 src_root = os.path.join(path_list[0], match_str.strip('/'))
205 Info ('src_root = %r' % src_root)
206 else:
207 Info ('No %r found in %r' % (match_str, test_script_path))
208
209 return src_root
210
211
212def GetChromeosVersion(str_obj):
213 """Helper method to parse output for CHROMEOS_VERSION_STRING.
214
215 Args:
216 str_obj: a string, which may contain Chrome OS version info.
217
218 Returns:
219 A string, value of CHROMEOS_VERSION_STRING environment variable set by
220 chromeos_version.sh. Or None if not found.
221 """
222 if str_obj is not None:
223 match = re.search('CHROMEOS_VERSION_STRING=([0-9_.]+)', str_obj)
224 if match and match.group(1):
225 Info ('CHROMEOS_VERSION_STRING = %s' % match.group(1))
226 return match.group(1)
227
228 Info ('CHROMEOS_VERSION_STRING NOT found')
229 return None
230
231
232def GetOutputImageDir(board, cros_version):
233 """Construct absolute path to output image directory.
234
235 Args:
236 board: a string.
237 cros_version: a string, Chrome OS version.
238
239 Returns:
240 a string: absolute path to output directory.
241 """
242 src_root = GetSrcRoot()
243 rel_path = 'build/images/%s' % board
244 # ASSUME: --build_attempt always sets to 1
245 version_str = '-'.join([cros_version, 'a1'])
246 output_dir = os.path.join(os.path.dirname(src_root), rel_path, version_str)
247 Info ('output_dir = %s' % output_dir)
248 return output_dir
Chris Sosa471532a2011-02-01 15:10:06 -0800249
250
251def FindRepoDir(path=None):
252 """Returns the nearest higher-level repo dir from the specified path.
253
254 Args:
255 path: The path to use. Defaults to cwd.
256 """
257 if path is None:
258 path = os.getcwd()
259 path = os.path.abspath(path)
260 while path != '/':
261 repo_dir = os.path.join(path, '.repo')
262 if os.path.isdir(repo_dir):
263 return repo_dir
264 path = os.path.dirname(path)
265 return None
266
267
268def ReinterpretPathForChroot(path):
269 """Returns reinterpreted path from outside the chroot for use inside.
270
271 Args:
272 path: The path to reinterpret. Must be in src tree.
273 """
274 root_path = os.path.join(FindRepoDir(path), '..')
275
276 path_abs_path = os.path.abspath(path)
277 root_abs_path = os.path.abspath(root_path)
278
279 # Strip the repository root from the path and strip first /.
280 relative_path = path_abs_path.replace(root_abs_path, '')[1:]
281
282 if relative_path == path_abs_path:
283 raise Exception('Error: path is outside your src tree, cannot reinterpret.')
284
285 new_path = os.path.join('/home', os.getenv('USER'), 'trunk', relative_path)
286 return new_path
287
288
289def GetCallerName():
290 """Returns the name of the calling module with __main__."""
291 top_frame = inspect.stack()[-1][0]
292 return os.path.basename(top_frame.f_code.co_filename)
293
294
295class RunCommandException(Exception):
296 """Raised when there is an error in OldRunCommand."""
Don Garrettb85946a2011-03-10 18:11:08 -0800297 def __init__(self, msg, cmd):
298 self.cmd = cmd
299 Exception.__init__(self, msg)
300
301 def __eq__(self, other):
302 return (type(self) == type(other) and
303 str(self) == str(other) and
304 self.cmd == other.cmd)
305
306 def __ne__(self, other):
307 return not self.__eq__(other)
Chris Sosa471532a2011-02-01 15:10:06 -0800308
309
310def OldRunCommand(cmd, print_cmd=True, error_ok=False, error_message=None,
311 exit_code=False, redirect_stdout=False, redirect_stderr=False,
312 cwd=None, input=None, enter_chroot=False, num_retries=0):
313 """Legacy run shell command.
314
315 Arguments:
316 cmd: cmd to run. Should be input to subprocess.POpen. If a string,
317 converted to an array using split().
318 print_cmd: prints the command before running it.
319 error_ok: does not raise an exception on error.
320 error_message: prints out this message when an error occurrs.
321 exit_code: returns the return code of the shell command.
322 redirect_stdout: returns the stdout.
323 redirect_stderr: holds stderr output until input is communicated.
324 cwd: the working directory to run this cmd.
325 input: input to pipe into this command through stdin.
326 enter_chroot: this command should be run from within the chroot. If set,
327 cwd must point to the scripts directory.
328 num_retries: the number of retries to perform before dying
329
330 Returns:
331 If exit_code is True, returns the return code of the shell command.
332 Else returns the output of the shell command.
333
334 Raises:
335 Exception: Raises RunCommandException on error with optional error_message.
336 """
337 # Set default for variables.
338 stdout = None
339 stderr = None
340 stdin = None
341 output = ''
342
343 # Modify defaults based on parameters.
344 if redirect_stdout: stdout = subprocess.PIPE
345 if redirect_stderr: stderr = subprocess.PIPE
346 if input: stdin = subprocess.PIPE
347 if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd
348
349 # Print out the command before running.
350 if print_cmd:
351 Info('PROGRAM(%s) -> RunCommand: %r in dir %s' %
352 (GetCallerName(), cmd, cwd))
353
354 for retry_count in range(num_retries + 1):
355 try:
356 proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin,
357 stdout=stdout, stderr=stderr)
358 (output, error) = proc.communicate(input)
359 if exit_code and retry_count == num_retries:
360 return proc.returncode
361
362 if proc.returncode == 0:
363 break
364
365 raise RunCommandException('Command "%r" failed.\n' % (cmd) +
Don Garrettb85946a2011-03-10 18:11:08 -0800366 (error_message or error or output or ''),
367 cmd)
Chris Sosa471532a2011-02-01 15:10:06 -0800368 except RunCommandException as e:
369 if not error_ok and retry_count == num_retries:
370 raise e
371 else:
372 Warning(str(e))
373 if print_cmd:
374 Info('PROGRAM(%s) -> RunCommand: retrying %r in dir %s' %
375 (GetCallerName(), cmd, cwd))
376
377 return output