Large-scale API cleanup
[zeroinstall/zeroinstall-afb.git] / zeroinstall / injector / run.py
blob099a3c09000a9c047a565047dc469cdcf6cd1819
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 info
11 from string import Template
13 from zeroinstall.injector.model import SafeException, EnvironmentBinding, Command
14 from zeroinstall.injector import namespaces, qdom
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 test_selections(selections, prog_args, dry_run, main, wrapper = None):
44 """Run the program in a child process, collecting stdout and stderr.
45 @return: the output produced by the process
46 @since: 0.27
47 """
48 import tempfile
49 output = tempfile.TemporaryFile(prefix = '0launch-test')
50 try:
51 child = os.fork()
52 if child == 0:
53 # We are the child
54 try:
55 try:
56 os.dup2(output.fileno(), 1)
57 os.dup2(output.fileno(), 2)
58 execute_selections(selections, prog_args, dry_run, main)
59 except:
60 import traceback
61 traceback.print_exc()
62 finally:
63 sys.stdout.flush()
64 sys.stderr.flush()
65 os._exit(1)
67 info(_("Waiting for test process to finish..."))
69 pid, status = os.waitpid(child, 0)
70 assert pid == child
72 output.seek(0)
73 results = output.read()
74 if status != 0:
75 results += _("Error from child process: exit code = %d") % status
76 finally:
77 output.close()
79 return results
81 def _process_args(args, element):
82 """Append each <arg> under <element> to args, performing $-expansion."""
83 for child in element.childNodes:
84 if child.uri == namespaces.XMLNS_IFACE and child.name == 'arg':
85 args.append(Template(child.content).substitute(os.environ))
87 def execute_selections(selections, prog_args, dry_run = False, main = None, wrapper = None, stores = None):
88 """Execute program. On success, doesn't return. On failure, raises an Exception.
89 Returns normally only for a successful dry run.
90 @param selections: the selected versions
91 @type selections: L{selections.Selections}
92 @param prog_args: arguments to pass to the program
93 @type prog_args: [str]
94 @param dry_run: if True, just print a message about what would have happened
95 @type dry_run: bool
96 @param main: the name of the binary to run, or None to use the default
97 @type main: str
98 @param wrapper: a command to use to actually run the binary, or None to run the binary directly
99 @type wrapper: str
100 @since: 0.27
101 @precondition: All implementations are in the cache.
103 #assert stores is not None
104 if stores is None:
105 from zeroinstall import zerostore
106 stores = zerostore.Stores()
108 def _do_bindings(impl, bindings):
109 for b in bindings:
110 if isinstance(b, EnvironmentBinding):
111 do_env_binding(b, _get_implementation_path(impl))
113 def _get_implementation_path(impl):
114 return impl.local_path or stores.lookup_any(impl.digests)
116 commands = selections.commands
117 sels = selections.selections
118 for selection in sels.values():
119 _do_bindings(selection, selection.bindings)
120 for dep in selection.dependencies:
121 dep_impl = sels[dep.interface]
122 if not dep_impl.id.startswith('package:'):
123 _do_bindings(dep_impl, dep.bindings)
124 # Process commands' dependencies' bindings too
125 # (do this here because we still want the bindings, even with --main)
126 for command in commands:
127 for dep in command.requires:
128 dep_impl = sels[dep.interface]
129 if not dep_impl.id.startswith('package:'):
130 _do_bindings(dep_impl, dep.bindings)
132 root_sel = sels[selections.interface]
134 assert root_sel is not None
136 if main is not None:
137 # Replace first command with user's input
138 old_path = commands[0].path
139 if main.startswith('/'):
140 main = main[1:] # User specified a path relative to the package root
141 else:
142 assert old_path
143 main = os.path.join(os.path.dirname(old_path), main) # User main is relative to command's name
144 # Copy all child nodes (e.g. <runner>) except for the arguments
145 user_command_element = qdom.Element(namespaces.XMLNS_IFACE, 'command', {'path': main})
146 for child in commands[0].qdom.childNodes:
147 if child.uri == namespaces.XMLNS_IFACE and child.name == 'arg':
148 continue
149 user_command_element.childNodes.append(child)
150 user_command = Command(user_command_element, None)
151 commands = [user_command] + commands[1:]
153 if commands[-1].path is None:
154 raise SafeException("Missing 'path' attribute on <command>")
156 command_iface = selections.interface
157 for command in commands:
158 command_sel = sels[command_iface]
160 command_args = []
162 # Add extra arguments for runner
163 runner = command.get_runner()
164 if runner:
165 command_iface = runner.interface
166 _process_args(command_args, runner.qdom)
168 # Add main program path
169 command_path = command.path
170 if command_path is not None:
171 if command_sel.id.startswith('package:'):
172 prog_path = command_path
173 else:
174 if command_path.startswith('/'):
175 raise SafeException(_("Command path must be relative, but '%s' starts with '/'!") %
176 command_path)
177 prog_path = os.path.join(_get_implementation_path(command_sel), command_path)
179 assert prog_path is not None
180 command_args.append(prog_path)
182 # Add extra arguments for program
183 _process_args(command_args, command.qdom)
185 prog_args = command_args + prog_args
187 if not os.path.exists(prog_args[0]):
188 raise SafeException(_("File '%(program_path)s' does not exist.\n"
189 "(implementation '%(implementation_id)s' + program '%(main)s')") %
190 {'program_path': prog_args[0], 'implementation_id': command_sel.id,
191 'main': commands[-1].path})
192 if wrapper:
193 prog_args = ['/bin/sh', '-c', wrapper + ' "$@"', '-'] + list(prog_args)
195 if dry_run:
196 print _("Would execute: %s") % ' '.join(prog_args)
197 else:
198 info(_("Executing: %s"), prog_args)
199 sys.stdout.flush()
200 sys.stderr.flush()
201 try:
202 os.execv(prog_args[0], prog_args)
203 except OSError, ex:
204 raise SafeException(_("Failed to run '%(program_path)s': %(exception)s") % {'program_path': prog_args[0], 'exception': str(ex)})