2 Executes a set of implementations as a program.
5 # Copyright (C) 2009, Thomas Leonard
6 # See the README file for details, or visit http://0install.net.
8 from zeroinstall
import _
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
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
35 @param main: the name of the binary to run, or None to use the default
37 @param wrapper: a command to use to actually run the binary, or None to run the binary directly
39 @precondition: C{policy.ready and policy.get_uncached_implementations() == []}
41 execute_selections(policy
.solver
.selections
, prog_args
, dry_run
, main
, wrapper
)
43 def _do_bindings(impl
, 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
58 output
= tempfile
.TemporaryFile(prefix
= '0launch-test')
65 os
.dup2(output
.fileno(), 1)
66 os
.dup2(output
.fileno(), 2)
67 execute_selections(selections
, prog_args
, dry_run
, main
)
76 info(_("Waiting for test process to finish..."))
78 pid
, status
= os
.waitpid(child
, 0)
82 results
= output
.read()
84 results
+= _("Error from child process: exit code = %d") % status
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
99 @param main: the name of the binary to run, or None to use the default
101 @param wrapper: a command to use to actually run the binary, or None to run the binary directly
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
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
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
]
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
154 if command_path
.startswith('/'):
155 raise SafeException(_("Command path must be relative, but '%s' starts with '/'!") %
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()
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
})
173 prog_args
= ['/bin/sh', '-c', wrapper
+ ' "$@"', '-'] + list(prog_args
)
176 print _("Would execute: %s") % ' '.join(prog_args
)
178 info(_("Executing: %s"), prog_args
)
182 os
.execv(prog_args
[0], prog_args
)
184 raise SafeException(_("Failed to run '%(program_path)s': %(exception)s") % {'program_path': prog_args
[0], 'exception': str(ex
)})