OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/python | |
sosa
2011/02/02 01:16:19
same
diandersAtChromium
2011/02/02 01:49:10
Done.
| |
2 # | |
3 # Copyright (c) 2011 The Chromium OS Authors. All rights reserved. | |
4 # Use of this source code is governed by a BSD-style license that can be | |
5 # found in the LICENSE file. | |
6 | |
7 """Utility functions shared between files in the chromite shell.""" | |
8 | |
9 | |
10 # Python imports | |
11 import ConfigParser | |
12 import cPickle | |
13 import os | |
14 import sys | |
15 import tempfile | |
16 | |
17 | |
18 # Local imports | |
19 from chromite.lib import cros_build_lib as cros_lib | |
20 from chromite.lib import text_menu | |
21 | |
22 | |
23 # Find the Chromite root and Chromium OS root... Note: in the chroot we may | |
24 # choose to install Chromite somewhere (/usr/lib/chromite?), so we use the | |
25 # environment variable to get the right place if it exists. | |
26 CHROMITE_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') | |
27 SRCROOT_PATH = os.environ.get('CROS_WORKON_SRCROOT', | |
28 os.path.realpath(os.path.join(CHROMITE_PATH, | |
29 '..'))) | |
30 | |
31 | |
32 # Commands can take one of these two types of specs. Note that if a command | |
33 # takes a build spec, we will find the associated chroot spec. This should be | |
34 # a human-readable string. It is printed and also is the name of the spec | |
35 # directory. | |
36 BUILD_SPEC_TYPE = 'build' | |
37 CHROOT_SPEC_TYPE = 'chroot' | |
38 | |
39 | |
40 # This is a special target that indicates that you want to do something just | |
41 # to the host. This means different things to different commands. | |
42 # TODO(dianders): Good idea or bad idea? | |
43 _HOST_TARGET = 'HOST' | |
44 | |
45 | |
46 def GetBoardDir(build_config): | |
47 """Returns the board directory (inside the chroot) given the name. | |
48 | |
49 Args: | |
50 build_config: A SafeConfigParser representing the config that we're | |
51 building. | |
52 | |
53 Returns: | |
54 The absolute path to the board. | |
55 """ | |
56 target_name = build_config.get('BUILD', 'target') | |
57 | |
58 # Extra checks on these, since we sometimes might do a rm -f on the board | |
59 # directory and these could cause some really bad behavior. | |
60 assert target_name, "Didn't expect blank target name." | |
61 assert len(target_name.split()) == 1, 'Target name should have no whitespace.' | |
62 | |
63 return os.path.join('/', 'build', target_name) | |
64 | |
65 | |
66 def GetChrootAbsDir(chroot_config): | |
67 """Returns the absolute chroot directory the chroot config. | |
68 | |
69 Args: | |
70 chroot_config: A SafeConfigParser representing the config for the chroot. | |
71 | |
72 Returns: | |
73 The chroot directory, always absolute. | |
74 """ | |
75 chroot_dir = chroot_config.get('CHROOT', 'path') | |
76 chroot_dir = os.path.join(SRCROOT_PATH, chroot_dir) | |
77 | |
78 return chroot_dir | |
79 | |
80 | |
81 def DoesChrootExist(chroot_config): | |
82 """Return True if the chroot folder exists. | |
83 | |
84 Args: | |
85 chroot_config: A SafeConfigParser representing the config for the chroot. | |
86 | |
87 Returns: | |
88 True if the chroot folder exists. | |
89 """ | |
90 chroot_dir = GetChrootAbsDir(chroot_config) | |
91 return os.path.isdir(chroot_dir) | |
92 | |
93 | |
94 def FindSpec(spec_name, spec_type=BUILD_SPEC_TYPE, can_show_ui=True): | |
95 """Find the spec with the given name. | |
96 | |
97 This tries to be smart about helping the user to find the right spec. See | |
98 the spec_name parameter for details. | |
99 | |
100 Args: | |
101 spec_name: Can be any of the following: | |
102 1. A full path to a spec file (including the .spec suffix). This is | |
103 checked first (i.e. if os.path.isfile(spec_name), we assume we've | |
104 got this case). | |
105 2. The full name of a spec file somewhere in the spec search path | |
106 (not including the .spec suffix). This is checked second. Putting | |
107 this check second means that if one spec name is a substring of | |
108 another, you can still specify the shorter spec name and know you | |
109 won't get a menu (the exact match prevents the menu). | |
110 3. A substring that will be used to pare-down a menu of spec files | |
111 found in the spec search path. Can be the empty string to show a | |
112 menu of all spec files in the spec path. NOTE: Only possible if | |
113 can_show_ui is True. | |
114 spec_type: The type of spec this is: 'chroot' or 'build'. | |
115 can_show_ui: If True, enables the spec name to be a substring since we can | |
116 then show a menu if the substring matches more than one thing. | |
117 | |
118 Returns: | |
119 A path to the spec file. | |
120 """ | |
121 spec_suffix = '.spec' | |
122 | |
123 # Handle 'HOST' for spec name w/ no searching, so it counts as an exact match. | |
124 if spec_type == BUILD_SPEC_TYPE and spec_name == _HOST_TARGET.lower(): | |
125 return _HOST_TARGET | |
126 | |
127 # If we have an exact path name, that's it. No searching. | |
128 if os.path.isfile(spec_name): | |
129 return spec_name | |
130 | |
131 # Figure out what our search path should be. | |
132 # ...make these lists in anticipation of the need to support specs that live | |
133 # in private overlays. | |
134 # TODO(dianders): Should specs be part of the shell, or part of the main | |
135 # chromite? | |
136 search_path = [ | |
137 os.path.join(CHROMITE_PATH, 'specs', spec_type), | |
138 ] | |
139 | |
140 # Look for an exact match of a spec name. An exact match will go through with | |
141 # no menu. | |
142 if spec_name: | |
143 for dir_path in search_path: | |
144 spec_path = os.path.join(dir_path, spec_name + spec_suffix) | |
145 if os.path.isfile(spec_path): | |
146 return spec_path | |
147 | |
148 # cros_lib.Die right away if we can't show UI and didn't have an exact match. | |
149 if not can_show_ui: | |
150 cros_lib.Die("Couldn't find %s spec: %s" % (spec_type, spec_name)) | |
151 | |
152 # No full path and no exact match. Move onto a menu. | |
153 # First step is to construct the options. We'll store in a dict keyed by | |
154 # spec name. | |
155 options = {} | |
156 for dir_path in search_path: | |
157 for file_name in os.listdir(dir_path): | |
158 # Find any files that end with ".spec" in a case-insensitive manner. | |
159 if not file_name.lower().endswith(spec_suffix): | |
160 continue | |
161 | |
162 this_spec_name, _ = os.path.splitext(file_name) | |
163 | |
164 # Skip if this spec file doesn't contain our substring. We are _always_ | |
165 # case insensitive here to be helpful to the user. | |
166 if spec_name.lower() not in this_spec_name.lower(): | |
167 continue | |
168 | |
169 # Disallow the spec to appear twice in the search path. This is the | |
170 # safest thing for now. We could revisit it later if we ever found a | |
171 # good reason (and if we ever have more than one directory in the | |
172 # search path). | |
173 if this_spec_name in options: | |
174 cros_lib.Die('Spec %s was found in two places in the search path' % | |
175 this_spec_name) | |
176 | |
177 # Combine to get a full path. | |
178 full_path = os.path.join(dir_path, file_name) | |
179 | |
180 # Ignore directories or anything else that isn't a file. | |
181 if not os.path.isfile(full_path): | |
182 continue | |
183 | |
184 # OK, it's good. Store the path. | |
185 options[this_spec_name] = full_path | |
186 | |
187 # Add 'HOST'. All caps so it sorts first. | |
188 if (spec_type == BUILD_SPEC_TYPE and | |
189 spec_name.lower() in _HOST_TARGET.lower()): | |
190 options[_HOST_TARGET] = _HOST_TARGET | |
191 | |
192 # If no match, die. | |
193 if not options: | |
194 cros_lib.Die("Couldn't find any matching %s specs for: %s" % (spec_type, spe c_name)) | |
sosa
2011/02/02 01:16:19
80 chars
diandersAtChromium
2011/02/02 01:49:10
Done.
| |
195 | |
196 # Avoid showing the user a menu if the user's search string matched exactly | |
197 # one item. | |
198 if spec_name and len(options) == 1: | |
199 _, spec_path = options.popitem() | |
200 return spec_path | |
201 | |
202 # If more than one, show a menu... | |
203 option_keys = sorted(options.iterkeys()) | |
204 choice = text_menu.TextMenu(option_keys, 'Choose a %s spec' % spec_type) | |
205 | |
206 if choice is None: | |
207 cros_lib.Die('OK, cancelling...') | |
208 else: | |
209 return options[option_keys[choice]] | |
210 | |
211 | |
212 def ReadConfig(spec_path): | |
213 """Read the a build config or chroot config from a spec file. | |
214 | |
215 This includes adding thue proper _default stuff in. | |
216 | |
217 Args: | |
218 spec_path: The path to the build or chroot spec. | |
219 | |
220 Returns: | |
221 config: A SafeConfigParser representing the config. | |
222 """ | |
223 spec_name, _ = os.path.splitext(os.path.basename(spec_path)) | |
224 spec_dir = os.path.dirname(spec_path) | |
225 | |
226 config = ConfigParser.SafeConfigParser({'name': spec_name}) | |
227 config.read(os.path.join(spec_dir, '_defaults')) | |
228 config.read(spec_path) | |
229 | |
230 return config | |
231 | |
232 | |
233 def GetBuildConfigFromArgs(argv): | |
234 """Helper for commands that take a build config in the arg list. | |
235 | |
236 This function can cros_lib.Die() in some instances. | |
237 | |
238 Args: | |
239 argv: A list of command line arguments. If non-empty, [0] should be the | |
240 build spec. These will not be modified. | |
241 | |
242 Returns: | |
243 argv: The argv with the build spec stripped off. This might be argv[1:] or | |
244 just argv. Not guaranteed to be new memory. | |
245 build_config: The SafeConfigParser for the build config; might be None if | |
246 this is a host config. TODO(dianders): Should there be a build spec for | |
247 the host? | |
248 """ | |
249 # The spec name is optional. If no arguments, we'll show a menu... | |
250 # Note that if there are arguments, but the first argument is a flag, we'll | |
251 # assume that we got called before OptionParser. In that case, they might | |
252 # have specified options but still want the board menu. | |
253 if argv and not argv[0].startswith('-'): | |
254 spec_name = argv[0] | |
255 argv = argv[1:] | |
256 else: | |
257 spec_name = '' | |
258 | |
259 spec_path = FindSpec(spec_name) | |
260 | |
261 if spec_path == _HOST_TARGET: | |
262 return argv, None | |
263 | |
264 build_config = ReadConfig(spec_path) | |
265 | |
266 # TODO(dianders): Add a config checker class that makes sure that the | |
267 # target is not a blank string. Might also be good to make sure that the | |
268 # target has no whitespace (so we don't screw up a subcommand invoked | |
269 # through a shell). | |
270 | |
271 return argv, build_config | |
272 | |
273 | |
274 def EnterChroot(chroot_config, fn, *args, **kwargs): | |
275 """Re-run the given function inside the chroot. | |
276 | |
277 When the function is run, it will be run in a SEPARATE INSTANCE of chromite, | |
278 which will be run in the chroot. This is a little weird. Specifically: | |
279 - When the callee executes, it will be a separate python instance. | |
280 - Globals will be reset back to defaults. | |
281 - A different version of python (with different modules) may end up running | |
282 the script in the chroot. | |
283 - All arguments are pickled up into a temp file, whose path is passed on the | |
284 command line. | |
285 - That means that args must be pickleable. | |
286 - It also means that modifications to the parameters by the callee are not | |
287 visible to the caller. | |
288 - Even the function is "pickled". The way the pickle works, I belive, is it | |
289 just passes the name of the function. If this name somehow resolves | |
290 differently in the chroot, you may get weirdness. | |
291 - Since we're in the chroot, obviously files may have different paths. It's | |
292 up to you to convert parameters if you need to. | |
293 - The stdin, stdout, and stderr aren't touched. | |
294 | |
295 Args: | |
296 chroot_config: A SafeConfigParser representing the config for the chroot. | |
297 fn: Either: a) the function to call or b) A tuple of an object and the | |
298 name of the method to call. | |
299 args: All other arguments will be passed to the function as is. | |
300 kwargs: All other arguments will be passed to the function as is. | |
301 """ | |
302 # Make sure that the chroot exists... | |
303 chroot_dir = GetChrootAbsDir(chroot_config) | |
304 if not DoesChrootExist(chroot_config): | |
305 cros_lib.Die('Chroot dir does not exist; try the "build host" command.\n %s .' % | |
sosa
2011/02/02 01:16:19
80 chars
diandersAtChromium
2011/02/02 01:49:10
Done.
| |
306 chroot_dir) | |
307 | |
308 cros_lib.Info('ENTERING THE CHROOT') | |
309 | |
310 # Save state to a temp file (inside the chroot!) using pickle. | |
311 tmp_dir = os.path.join(chroot_dir, 'tmp') | |
312 state_file = tempfile.NamedTemporaryFile(prefix='chromite', dir=tmp_dir) | |
313 try: | |
314 cPickle.dump((fn, args, kwargs), state_file, cPickle.HIGHEST_PROTOCOL) | |
315 state_file.flush() | |
316 | |
317 # Translate temp file name into a chroot path... | |
318 chroot_state_path = os.path.join('/tmp', os.path.basename(state_file.name)) | |
319 | |
320 # Put together command. We're going to force the shell to do all of the | |
321 # splitting of arguments, since we're throwing all of the flags from the | |
322 # config file in there. | |
323 # TODO(dianders): It might be nice to run chromite as: | |
324 # python -m chromite.chromite_main | |
325 # ...but, at the moment, that fails if you're in src/scripts | |
326 # which already has a chromite folder. | |
327 cmd = ( | |
328 './enter_chroot.sh --chroot="%s" %s --' | |
329 ' python ../../chromite/shell/main.py --resume-state %s') % ( | |
330 chroot_dir, | |
331 chroot_config.get('CHROOT', 'enter_chroot_flags'), | |
332 chroot_state_path) | |
333 | |
334 # We'll put CWD as src/scripts when running the command. Since everyone | |
335 # running by hand has their cwd there, it is probably the safest. | |
336 cwd = os.path.join(SRCROOT_PATH, 'src', 'scripts') | |
337 | |
338 # Run it. We allow "error" so we don't print a confusing error message | |
339 # filled with out resume-state garbage on control-C. | |
340 cmd_result = cros_lib.RunCommand(cmd, shell=True, cwd=cwd, print_cmd=False, | |
341 exit_code=True, error_ok=True, ignore_sigint=True) | |
342 | |
343 if cmd_result.returncode: | |
344 cros_lib.Die('Chroot exited with error code %d' % cmd_result.returncode) | |
345 finally: | |
346 # Make sure things get closed (and deleted), even upon exception. | |
347 state_file.close() | |
348 | |
349 | |
350 def EnterChrootMainHook(argv): | |
351 """Should be called as the first line in main() to support EnterChroot(). | |
352 | |
353 We'll check whether the --resume-state argument is there. This function won't | |
354 return if we detect the --resume-state argument. If we don't detect the | |
355 --resume-state argument, we'll just return. | |
356 | |
357 Args: | |
358 argv: The value of sys.argv | |
sosa
2011/02/02 01:16:19
um why not just take sys.argv then?
diandersAtChromium
2011/02/02 01:49:10
Wanted to be explicit that this works on sys.argv,
| |
359 """ | |
360 if argv[1:2] == ['--resume-state']: | |
361 # Internal mechanism (not documented to users) to resume in the chroot. | |
362 # ...actual resume state file is passed in argv[2] for simplicity... | |
363 assert len(argv) == 3, 'Resume State not passed properly.' | |
364 fn, args, kwargs = cPickle.load(open(argv[2], 'rb')) | |
365 | |
366 # Handle calling a method in a class; that can't be directly pickled. | |
367 if isinstance(fn, tuple): | |
368 obj, method = fn | |
369 fn = getattr(obj, method) | |
370 | |
371 fn(*args, **kwargs) | |
372 | |
373 # Exit | |
374 sys.exit(0) | |
davidjames
2011/02/02 01:15:18
Can we move the sys.exit(0) out of here and into t
sosa
2011/02/02 01:16:19
I don't really like this sys.exit here
diandersAtChromium
2011/02/02 01:49:10
OK, we now return True if we handled things. It's
| |
OLD | NEW |