blob: c2e54b715d619813bfc30fc9a157870c72ffd5c4 [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,
37 env=None, ignore_sigint=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.
Tan Gao2990a4d2010-09-22 09:34:27 -070059
60 Returns:
61 A CommandResult object.
62
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070063 Raises:
64 Exception: Raises generic exception on error with optional error_message.
65 """
66 # Set default for variables.
67 stdout = None
68 stderr = None
69 stdin = None
Tan Gao2f310882010-09-10 14:50:47 -070070 cmd_result = CommandResult()
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070071
72 # Modify defaults based on parameters.
Tan Gao2990a4d2010-09-22 09:34:27 -070073 if redirect_stdout: stdout = subprocess.PIPE
74 if redirect_stderr: stderr = subprocess.PIPE
75 # TODO(sosa): gpylint complains about redefining built-in 'input'.
76 # Can we rename this variable?
77 if input: stdin = subprocess.PIPE
David James6db8f522010-09-09 10:49:11 -070078 if isinstance(cmd, basestring):
79 if enter_chroot: cmd = './enter_chroot.sh -- ' + cmd
80 cmd_str = cmd
81 else:
82 if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd
83 cmd_str = ' '.join(cmd)
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070084
85 # Print out the command before running.
86 if print_cmd:
David James6db8f522010-09-09 10:49:11 -070087 Info('RunCommand: %s' % cmd_str)
Doug Andersona8d22de2011-01-13 16:22:58 -080088 cmd_result.cmd = cmd
Scott Zawalski6bc41ac2010-09-08 12:47:28 -070089
90 try:
David James9102a892010-12-02 10:21:49 -080091 proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout,
Doug Anderson6781f942011-01-14 16:21:39 -080092 stderr=stderr, shell=shell, env=env)
93 if ignore_sigint:
94 old_sigint = signal.signal(signal.SIGINT, signal.SIG_IGN)
95 try:
96 (cmd_result.output, cmd_result.error) = proc.communicate(input)
97 finally:
98 if ignore_sigint:
99 signal.signal(signal.SIGINT, old_sigint)
100
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700101 if exit_code:
Tan Gao2f310882010-09-10 14:50:47 -0700102 cmd_result.returncode = proc.returncode
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700103
104 if not error_ok and proc.returncode:
Tan Gao2f310882010-09-10 14:50:47 -0700105 msg = ('Command "%s" failed.\n' % cmd_str +
106 (error_message or cmd_result.error or cmd_result.output or ''))
107 raise RunCommandError(msg)
Tan Gao2990a4d2010-09-22 09:34:27 -0700108 # TODO(sosa): is it possible not to use the catch-all Exception here?
109 except Exception, e:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700110 if not error_ok:
111 raise
112 else:
113 Warning(str(e))
114
Tan Gao2f310882010-09-10 14:50:47 -0700115 return cmd_result
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700116
117
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700118def Die(message):
119 """Emits a red error message and halts execution.
120
Tan Gao2990a4d2010-09-22 09:34:27 -0700121 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700122 message: The message to be emitted before exiting.
123 """
124 print >> sys.stderr, (
125 Color(_STDOUT_IS_TTY).Color(Color.RED, '\nERROR: ' + message))
126 sys.exit(1)
127
128
Tan Gao2990a4d2010-09-22 09:34:27 -0700129# pylint: disable-msg=W0622
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700130def Warning(message):
131 """Emits a yellow warning message and continues execution.
132
Tan Gao2990a4d2010-09-22 09:34:27 -0700133 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700134 message: The message to be emitted.
135 """
136 print >> sys.stderr, (
137 Color(_STDOUT_IS_TTY).Color(Color.YELLOW, '\nWARNING: ' + message))
138
139
140def Info(message):
141 """Emits a blue informational message and continues execution.
142
Tan Gao2990a4d2010-09-22 09:34:27 -0700143 Args:
Scott Zawalski6bc41ac2010-09-08 12:47:28 -0700144 message: The message to be emitted.
145 """
146 print >> sys.stderr, (
147 Color(_STDOUT_IS_TTY).Color(Color.BLUE, '\nINFO: ' + message))
Scott Zawalski98ac6b22010-09-08 15:59:23 -0700148
149
150def ListFiles(base_dir):
151 """Recurively list files in a directory.
152
Tan Gao2990a4d2010-09-22 09:34:27 -0700153 Args:
Scott Zawalski98ac6b22010-09-08 15:59:23 -0700154 base_dir: directory to start recursively listing in.
155
156 Returns:
157 A list of files relative to the base_dir path or
158 An empty list of there are no files in the directories.
159 """
160 directories = [base_dir]
161 files_list = []
162 while directories:
163 directory = directories.pop()
164 for name in os.listdir(directory):
165 fullpath = os.path.join(directory, name)
166 if os.path.isfile(fullpath):
167 files_list.append(fullpath)
168 elif os.path.isdir(fullpath):
169 directories.append(fullpath)
170
171 return files_list
Tan Gao2990a4d2010-09-22 09:34:27 -0700172
173
174def IsInsideChroot():
175 """Returns True if we are inside chroot."""
176 return os.path.exists('/etc/debian_chroot')
177
178
179def GetSrcRoot():
180 """Get absolute path to src/scripts/ directory.
181
182 Assuming test script will always be run from descendent of src/scripts.
183
184 Returns:
185 A string, absolute path to src/scripts directory. None if not found.
186 """
187 src_root = None
188 match_str = '/src/scripts/'
189 test_script_path = os.path.abspath('.')
190
191 path_list = re.split(match_str, test_script_path)
192 if path_list:
193 src_root = os.path.join(path_list[0], match_str.strip('/'))
194 Info ('src_root = %r' % src_root)
195 else:
196 Info ('No %r found in %r' % (match_str, test_script_path))
197
198 return src_root
199
200
201def GetChromeosVersion(str_obj):
202 """Helper method to parse output for CHROMEOS_VERSION_STRING.
203
204 Args:
205 str_obj: a string, which may contain Chrome OS version info.
206
207 Returns:
208 A string, value of CHROMEOS_VERSION_STRING environment variable set by
209 chromeos_version.sh. Or None if not found.
210 """
211 if str_obj is not None:
212 match = re.search('CHROMEOS_VERSION_STRING=([0-9_.]+)', str_obj)
213 if match and match.group(1):
214 Info ('CHROMEOS_VERSION_STRING = %s' % match.group(1))
215 return match.group(1)
216
217 Info ('CHROMEOS_VERSION_STRING NOT found')
218 return None
219
220
221def GetOutputImageDir(board, cros_version):
222 """Construct absolute path to output image directory.
223
224 Args:
225 board: a string.
226 cros_version: a string, Chrome OS version.
227
228 Returns:
229 a string: absolute path to output directory.
230 """
231 src_root = GetSrcRoot()
232 rel_path = 'build/images/%s' % board
233 # ASSUME: --build_attempt always sets to 1
234 version_str = '-'.join([cros_version, 'a1'])
235 output_dir = os.path.join(os.path.dirname(src_root), rel_path, version_str)
236 Info ('output_dir = %s' % output_dir)
237 return output_dir
Chris Sosa471532a2011-02-01 15:10:06 -0800238
239
240def FindRepoDir(path=None):
241 """Returns the nearest higher-level repo dir from the specified path.
242
243 Args:
244 path: The path to use. Defaults to cwd.
245 """
246 if path is None:
247 path = os.getcwd()
248 path = os.path.abspath(path)
249 while path != '/':
250 repo_dir = os.path.join(path, '.repo')
251 if os.path.isdir(repo_dir):
252 return repo_dir
253 path = os.path.dirname(path)
254 return None
255
256
257def ReinterpretPathForChroot(path):
258 """Returns reinterpreted path from outside the chroot for use inside.
259
260 Args:
261 path: The path to reinterpret. Must be in src tree.
262 """
263 root_path = os.path.join(FindRepoDir(path), '..')
264
265 path_abs_path = os.path.abspath(path)
266 root_abs_path = os.path.abspath(root_path)
267
268 # Strip the repository root from the path and strip first /.
269 relative_path = path_abs_path.replace(root_abs_path, '')[1:]
270
271 if relative_path == path_abs_path:
272 raise Exception('Error: path is outside your src tree, cannot reinterpret.')
273
274 new_path = os.path.join('/home', os.getenv('USER'), 'trunk', relative_path)
275 return new_path
276
277
278def GetCallerName():
279 """Returns the name of the calling module with __main__."""
280 top_frame = inspect.stack()[-1][0]
281 return os.path.basename(top_frame.f_code.co_filename)
282
283
284class RunCommandException(Exception):
285 """Raised when there is an error in OldRunCommand."""
286 pass
287
288
289def OldRunCommand(cmd, print_cmd=True, error_ok=False, error_message=None,
290 exit_code=False, redirect_stdout=False, redirect_stderr=False,
291 cwd=None, input=None, enter_chroot=False, num_retries=0):
292 """Legacy run shell command.
293
294 Arguments:
295 cmd: cmd to run. Should be input to subprocess.POpen. If a string,
296 converted to an array using split().
297 print_cmd: prints the command before running it.
298 error_ok: does not raise an exception on error.
299 error_message: prints out this message when an error occurrs.
300 exit_code: returns the return code of the shell command.
301 redirect_stdout: returns the stdout.
302 redirect_stderr: holds stderr output until input is communicated.
303 cwd: the working directory to run this cmd.
304 input: input to pipe into this command through stdin.
305 enter_chroot: this command should be run from within the chroot. If set,
306 cwd must point to the scripts directory.
307 num_retries: the number of retries to perform before dying
308
309 Returns:
310 If exit_code is True, returns the return code of the shell command.
311 Else returns the output of the shell command.
312
313 Raises:
314 Exception: Raises RunCommandException on error with optional error_message.
315 """
316 # Set default for variables.
317 stdout = None
318 stderr = None
319 stdin = None
320 output = ''
321
322 # Modify defaults based on parameters.
323 if redirect_stdout: stdout = subprocess.PIPE
324 if redirect_stderr: stderr = subprocess.PIPE
325 if input: stdin = subprocess.PIPE
326 if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd
327
328 # Print out the command before running.
329 if print_cmd:
330 Info('PROGRAM(%s) -> RunCommand: %r in dir %s' %
331 (GetCallerName(), cmd, cwd))
332
333 for retry_count in range(num_retries + 1):
334 try:
335 proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin,
336 stdout=stdout, stderr=stderr)
337 (output, error) = proc.communicate(input)
338 if exit_code and retry_count == num_retries:
339 return proc.returncode
340
341 if proc.returncode == 0:
342 break
343
344 raise RunCommandException('Command "%r" failed.\n' % (cmd) +
345 (error_message or error or output or ''))
346 except RunCommandException as e:
347 if not error_ok and retry_count == num_retries:
348 raise e
349 else:
350 Warning(str(e))
351 if print_cmd:
352 Info('PROGRAM(%s) -> RunCommand: retrying %r in dir %s' %
353 (GetCallerName(), cmd, cwd))
354
355 return output