20"""Update this process's environment by applying the binding. 21 @param binding: the binding to apply 22 @type binding: L{model.EnvironmentBinding} 23 @param path: the selected implementation 24 @type path: str""" 25ifbinding.insertisnotNoneandpathisNone: 26# Skip insert bindings for package implementations 27logger.debug("not setting %s as we selected a package implementation",binding.name) 28return 29os.environ[binding.name]=binding.get_value(path, 30os.environ.get(binding.name,None)) 31logger.info("%s=%s",binding.name,os.environ[binding.name])
34"""Run the program in a child process, collecting stdout and stderr. 35 @return: the output produced by the process 36 @since: 0.27""" 37importtempfile 38output=tempfile.TemporaryFile(prefix='0launch-test') 39try: 40child=os.fork() 41ifchild==0: 42# We are the child 43try: 44try: 45os.dup2(output.fileno(),1) 46os.dup2(output.fileno(),2) 47execute_selections(selections,prog_args,dry_run,main) 48except: 49importtraceback 50traceback.print_exc() 51finally: 52sys.stdout.flush() 53sys.stderr.flush() 54os._exit(1) 55 56logger.info(_("Waiting for test process to finish...")) 57 58pid,status=os.waitpid(child,0) 59assertpid==child 60 61output.seek(0) 62results=output.read() 63ifstatus!=0: 64results+=_("Error from child process: exit code = %d")%status 65finally: 66output.close() 67 68returnresults
105"""Create a list of strings to be passed to exec to run the <command>s in the selections.106 @param command_iface: the interface of the program being run107 @type command_iface: str108 @param command_name: the name of the command being run109 @type command_name: str110 @param user_command: a custom command to use instead111 @type user_command: L{model.Command}112 @type dry_run: bool113 @return: the argument list114 @rtype: [str]"""115116ifnot(command_nameoruser_command):117raiseSafeException(_("Can't run: no command specified!"))118119prog_args=[]120sels=self.selections.selections121122whilecommand_nameoruser_command:123command_sel=sels[command_iface]124125ifuser_commandisNone:126command=command_sel.get_command(command_name)127else:128command=user_command129user_command=None130131command_args=[]132133# Add extra arguments for runner134runner=command.get_runner()135ifrunner:136command_iface=runner.interface137command_name=runner.command138_process_args(command_args,runner.qdom)139else:140command_iface=None141command_name=None142143# Add main program path144command_path=command.path145ifcommand_pathisnotNone:146ifcommand_sel.id.startswith('package:'):147prog_path=command_path148else:149ifcommand_path.startswith('/'):150raiseSafeException(_("Command path must be relative, but '%s' starts with '/'!")%151command_path)152prog_path=os.path.join(command_sel.get_path(self.stores),command_path)153154assertprog_pathisnotNone155156ifnotos.path.exists(prog_path)andnotdry_run:157raiseSafeException(_("File '%(program_path)s' does not exist.\n"158"(implementation '%(implementation_id)s' + program '%(main)s')")%159{'program_path':prog_path,'implementation_id':command_sel.id,160'main':command_path})161162command_args.append(prog_path)163164# Add extra arguments for program165_process_args(command_args,command.qdom)166167prog_args=command_args+prog_args168169# Each command is run by the next, but the last one is run by exec, and we170# need a path for that.171ifcommand.pathisNone:172raiseSafeException("Missing 'path' attribute on <command>")173174returnprog_args
177"""Do all the environment bindings in the selections (setting os.environ)."""178self._exec_bindings=[]179180def_do_bindings(impl,bindings,iface):181forbinbindings:182self.do_binding(impl,b,iface)
208"""Called by L{prepare_env} for each binding.209 Sub-classes may wish to override this.210 @param impl: the selected implementation211 @type impl: L{selections.Selection}212 @param binding: the binding to be processed213 @type binding: L{model.Binding}214 @param iface: the interface containing impl215 @type iface: L{model.Interface}"""216ifisinstance(binding,EnvironmentBinding):217ifimpl.id.startswith('package:'):218path=None# (but still do the binding, e.g. for values)219else:220path=impl.get_path(self.stores)221do_env_binding(binding,path)222elifisinstance(binding,ExecutableBinding):223ifisinstance(iface,Dependency):224importwarnings225warnings.warn("Pass an interface URI instead",DeprecationWarning,2)226iface=iface.interface227self._exec_bindings.append((binding,iface))
270# Create the runenv.py helper script under ~/.cache if missing or out-of-date271main_dir=basedir.save_cache_path(namespaces.config_site,namespaces.config_prog)272runenv=os.path.join(main_dir,'runenv.py')273expected_contents="#!%s\nfrom zeroinstall.injector import _runenv; _runenv.main()\n"%sys.executable274275actual_contents=None276ifos.path.exists(runenv):277withopen(runenv)ass:278actual_contents=s.read()279280ifactual_contents!=expected_contents:281importtempfile282tmp=tempfile.NamedTemporaryFile('w',dir=main_dir,delete=False)283logger.info("Updating %s",runenv)284tmp.write(expected_contents)285tmp.close()286os.chmod(tmp.name,0o555)287os.rename(tmp.name,runenv)288289self._checked_runenv=True
292"""Execute program. On success, doesn't return. On failure, raises an Exception.293 Returns normally only for a successful dry run.294 @param selections: the selected versions295 @type selections: L{selections.Selections}296 @param prog_args: arguments to pass to the program297 @type prog_args: [str]298 @param dry_run: if True, just print a message about what would have happened299 @type dry_run: bool300 @param main: the name of the binary to run, or None to use the default301 @type main: str302 @param wrapper: a command to use to actually run the binary, or None to run the binary directly303 @type wrapper: str304 @type stores: L{zeroinstall.zerostore.Stores} | None305 @since: 0.27306 @precondition: All implementations are in the cache."""307#assert stores is not None308ifstoresisNone:309fromzeroinstallimportzerostore310stores=zerostore.Stores()311312setup=Setup(stores,selections)313314commands=selections.commands315ifmainisnotNone:316# Replace first command with user's input317ifmain.startswith('/'):318main=main[1:]# User specified a path relative to the package root319else:320old_path=commands[0].pathifcommandselseNone321ifnotold_path:322raiseSafeException(_("Can't use a relative replacement main when there is no original one!"))323main=os.path.join(os.path.dirname(old_path),main)# User main is relative to command's name324# Copy all child nodes (e.g. <runner>) except for the arguments325user_command_element=qdom.Element(namespaces.XMLNS_IFACE,'command',{'path':main})326ifcommands:327forchildincommands[0].qdom.childNodes:328ifchild.uri==namespaces.XMLNS_IFACEandchild.namein('arg','for-each'):329continue330user_command_element.childNodes.append(child)331user_command=Command(user_command_element,None)332else:333user_command=None334335setup.prepare_env()336prog_args=setup.build_command(selections.interface,selections.command,user_command,dry_run=dry_run)+prog_args337338ifwrapper:339prog_args=['/bin/sh','-c',wrapper+' "$@"','-']+list(prog_args)340341ifdry_run:342print(_("[dry-run] would execute: %s")%' '.join(prog_args))343else:344logger.info(_("Executing: %s"),prog_args)345sys.stdout.flush()346sys.stderr.flush()347try:348env=os.environ.copy()349forxin['0install-runenv-ZEROINSTALL_GPG','ZEROINSTALL_GPG']:350ifxinenv:351delenv[x]352353os.execve(prog_args[0],prog_args,env)354exceptOSErrorasex:355raiseSafeException(_("Failed to run '%(program_path)s': %(exception)s")%{'program_path':prog_args[0],'exception':str(ex)})