Bug fixes for command support
[zeroinstall/zeroinstall-limyreth.git] / zeroinstall / injector / run.py
blobc159bece82613bffa767ac488e6df0b1220422fd
1 """
2 Executes a set of implementations as a program.
3 """
5 # Copyright (C) 2009, Thomas Leonard
6 # See the README file for details, or visit http://0install.net.
8 from zeroinstall import _
9 import os, sys
10 from logging import debug, info
12 from zeroinstall.injector.model import SafeException, EnvironmentBinding, Command
13 from zeroinstall.injector import namespaces, qdom
14 from zeroinstall.injector.iface_cache import iface_cache
16 def do_env_binding(binding, path):
17 """Update this process's environment by applying the binding.
18 @param binding: the binding to apply
19 @type binding: L{model.EnvironmentBinding}
20 @param path: the selected implementation
21 @type path: str"""
22 os.environ[binding.name] = binding.get_value(path,
23 os.environ.get(binding.name, None))
24 info("%s=%s", binding.name, os.environ[binding.name])
26 def execute(policy, prog_args, dry_run = False, main = None, wrapper = None):
27 """Execute program. On success, doesn't return. On failure, raises an Exception.
28 Returns normally only for a successful dry run.
29 @param policy: a policy with the selected versions
30 @type policy: L{policy.Policy}
31 @param prog_args: arguments to pass to the program
32 @type prog_args: [str]
33 @param dry_run: if True, just print a message about what would have happened
34 @type dry_run: bool
35 @param main: the name of the binary to run, or None to use the default
36 @type main: str
37 @param wrapper: a command to use to actually run the binary, or None to run the binary directly
38 @type wrapper: str
39 @precondition: C{policy.ready and policy.get_uncached_implementations() == []}
40 """
41 execute_selections(policy.solver.selections, prog_args, dry_run, main, wrapper)
43 def _do_bindings(impl, bindings):
44 for b in bindings:
45 if isinstance(b, EnvironmentBinding):
46 do_env_binding(b, _get_implementation_path(impl))
48 def _get_implementation_path(impl):
49 return impl.local_path or iface_cache.stores.lookup_any(impl.digests)
51 def test_selections(selections, prog_args, dry_run, main, wrapper = None):
52 """Run the program in a child process, collecting stdout and stderr.
53 @return: the output produced by the process
54 @since: 0.27
55 """
56 args = []
57 import tempfile
58 output = tempfile.TemporaryFile(prefix = '0launch-test')
59 try:
60 child = os.fork()
61 if child == 0:
62 # We are the child
63 try:
64 try:
65 os.dup2(output.fileno(), 1)
66 os.dup2(output.fileno(), 2)
67 execute_selections(selections, prog_args, dry_run, main)
68 except:
69 import traceback
70 traceback.print_exc()
71 finally:
72 sys.stdout.flush()
73 sys.stderr.flush()
74 os._exit(1)
76 info(_("Waiting for test process to finish..."))
78 pid, status = os.waitpid(child, 0)
79 assert pid == child
81 output.seek(0)
82 results = output.read()
83 if status != 0:
84 results += _("Error from child process: exit code = %d") % status
85 finally:
86 output.close()
88 return results
90 def execute_selections(selections, prog_args, dry_run = False, main = None, wrapper = None):
91 """Execute program. On success, doesn't return. On failure, raises an Exception.
92 Returns normally only for a successful dry run.
93 @param selections: the selected versions
94 @type selections: L{selections.Selections}
95 @param prog_args: arguments to pass to the program
96 @type prog_args: [str]
97 @param dry_run: if True, just print a message about what would have happened
98 @type dry_run: bool
99 @param main: the name of the binary to run, or None to use the default
100 @type main: str
101 @param wrapper: a command to use to actually run the binary, or None to run the binary directly
102 @type wrapper: str
103 @since: 0.27
104 @precondition: All implementations are in the cache.
106 commands = selections.commands
107 sels = selections.selections
108 for selection in sels.values():
109 _do_bindings(selection, selection.bindings)
110 for dep in selection.dependencies:
111 dep_impl = sels[dep.interface]
112 if not dep_impl.id.startswith('package:'):
113 _do_bindings(dep_impl, dep.bindings)
114 # Process commands' dependencies' bindings too
115 # (do this here because we still want the bindings, even with --main)
116 for command in commands:
117 for dep in command.requires:
118 dep_impl = sels[dep.interface]
119 if not dep_impl.id.startswith('package:'):
120 _do_bindings(dep_impl, dep.bindings)
122 root_sel = sels[selections.interface]
124 assert root_sel is not None
126 if main is not None:
127 # Replace first command with user's input
128 old_path = commands[0].path
129 if main.startswith('/'):
130 main = main[1:] # User specified a path relative to the package root
131 else:
132 assert old_path
133 main = os.path.join(os.path.dirname(old_path), main) # User main is relative to command's name
134 user_command = Command(qdom.Element(namespaces.XMLNS_IFACE, 'command', {'path': main}), None)
135 commands = [user_command] + commands[1:]
137 if commands[-1].path is None:
138 raise SafeException("Missing 'path' attribute on <command>")
140 command_iface = selections.interface
141 for command in commands:
142 command_sel = sels[command_iface]
144 command_args = []
145 for child in command.qdom.childNodes:
146 if child.uri == namespaces.XMLNS_IFACE and child.name == 'arg':
147 command_args.append(child.content)
149 command_path = command.path
151 if command_sel.id.startswith('package:'):
152 prog_path = command_path
153 else:
154 if command_path.startswith('/'):
155 raise SafeException(_("Command path must be relative, but '%s' starts with '/'!") %
156 command_path)
157 prog_path = os.path.join(_get_implementation_path(command_sel), command_path)
159 assert prog_path is not None
161 prog_args = [prog_path] + command_args + prog_args
163 runner = command.get_runner()
164 if runner:
165 command_iface = runner.interface
167 if not os.path.exists(prog_args[0]):
168 raise SafeException(_("File '%(program_path)s' does not exist.\n"
169 "(implementation '%(implementation_id)s' + program '%(main)s')") %
170 {'program_path': prog_args[0], 'implementation_id': command_sel.id,
171 'main': commands[-1].path})
172 if wrapper:
173 prog_args = ['/bin/sh', '-c', wrapper + ' "$@"', '-'] + list(prog_args)
175 if dry_run:
176 print _("Would execute: %s") % ' '.join(prog_args)
177 else:
178 info(_("Executing: %s"), prog_args)
179 sys.stdout.flush()
180 sys.stderr.flush()
181 try:
182 os.execv(prog_args[0], prog_args)
183 except OSError, ex:
184 raise SafeException(_("Failed to run '%(program_path)s': %(exception)s") % {'program_path': prog_args[0], 'exception': str(ex)})