def launch(config): os.chdir(config['basedir']) sys.path.insert(0, os.path.abspath(config['basedir'])) # see if we can launch the application without actually having to # spawn twistd, since spawning processes correctly is a real hassle # on windows. argv = [ sys.executable, "-c", # this is copied from bin/twistd. twisted-2.0.0 through 2.4.0 use # _twistw.run . Twisted-2.5.0 and later use twistd.run, even for # windows. "from twisted.scripts import twistd; twistd.run()", "--no_save", "--logfile=twistd.log", # windows doesn't use the same default "--python=buildbot.tac" ] # ProcessProtocol just ignores all output proc = reactor.spawnProcess(protocol.ProcessProtocol(), sys.executable, argv, env=os.environ) if platformType == "win32": with open("twistd.pid", "w") as pidfile: pidfile.write("{0}".format(proc.pid))
def launch(self, request, handler, command): if command in self._launched_apps: for window in self.screen.get_windows(): if window.get_pid() == self._launched_apps[command]: log.msg('Activating window: %s' % window.get_name()) window.activate(int(time.time())) return handler.success(request) for flag in 'UuFfDdNnickvm': command = command.replace('%%%s' % flag, '') command = command.replace( '~', os.getenv('HOME')) # Is it really necessary ? splited_command = shlex.split( str(command) ) # The shlex module currently does not support Unicode input. pp = protocol.ProcessProtocol() def process_ended(status_code): del self._launched_apps[command] pp.processEnded = process_ended f = reactor.spawnProcess( pp, '/usr/bin/setsid', # setsid - run a program in a new session ['setsid'] + splited_command, env=os.environ) self._launched_apps[command] = f.pid handler.success(request)
def execute(self, cmd, event=None): execute = defer.succeed(None) def execute_next(fn, *a, **kw): execute.addCallback(lambda r: fn(*a, **kw)) execute.addErrback(lambda f: True) if cmd.startswith('$'): if event is not None: # Collect all the event args and format them into the command string event_dict = event.serialize() event_args = SafeDict( {k: decode_if_bytes(event_dict[k]) for k in event_dict}) cmd = cmd.format_map(event_args) cmd = cmd[1:] d = defer.Deferred() p = protocol.ProcessProtocol() p.outReceived = lambda d: [ execute_next(self.execute_reduced, l, cmd) for l in d.split("\n") ] p.processEnded = lambda r: d.callback(None) reactor.spawnProcess(p, self.plugin.shell, [self.plugin.shell, '-c', cmd]) d.addCallback(lambda r: execute) return d else: return self.execute_reduced(cmd, event)
def execute(self, cmd): execute = defer.succeed(None) def execute_next(fn, *a, **kw): execute.addCallback(lambda r: fn(*a, **kw)) execute.addErrback(lambda f: True) if cmd.startswith('$'): cmd = cmd[1:] d = defer.Deferred() p = protocol.ProcessProtocol() p.outReceived = lambda d: [ execute_next(self.execute_reduced, l, cmd) for l in d.split("\n") ] p.processEnded = lambda r: d.callback(None) reactor.spawnProcess(p, self.plugin.shell, [self.plugin.shell, '-c', cmd]) d.addCallback(lambda r: execute) return d else: return self.execute_reduced(cmd)
def open_(self, request, handler, uri): if '~' in uri: uri = uri.replace('~', os.environ['HOME']) reactor.spawnProcess( protocol.ProcessProtocol(), '/usr/bin/setsid', # setsid - run a program in a new session ['setsid', 'nautilus', uri.encode('utf-8')], env=os.environ) handler.success(request)
def test_wrongArguments(self): """ Test invalid arguments to spawnProcess: arguments and environment must only contains string or unicode, and not null bytes. """ exe = sys.executable p = protocol.ProcessProtocol() badEnvs = [{ "foo": 2 }, { "foo": "egg\0a" }, { 3: "bar" }, { "bar\0foo": "bar" }] badArgs = [[exe, 2], "spam", [exe, "foo\0bar"]] # Sanity check - this will fail for people who have mucked with # their site configuration in a stupid way, but there's nothing we # can do about that. badUnicode = u'\N{SNOWMAN}' try: badUnicode.encode(sys.getdefaultencoding()) except UnicodeEncodeError: # Okay, that unicode doesn't encode, put it in as a bad environment # key. badEnvs.append({badUnicode: 'value for bad unicode key'}) badEnvs.append({'key for bad unicode value': badUnicode}) badArgs.append([exe, badUnicode]) else: # It _did_ encode. Most likely, Gtk2 is being used and the # default system encoding is UTF-8, which can encode anything. # In any case, if implicit unicode -> str conversion works for # that string, we can't test that TypeError gets raised instead, # so just leave it off. pass for env in badEnvs: self.assertRaises(TypeError, reactor.spawnProcess, p, exe, [exe, "-c", ""], env=env) for args in badArgs: self.assertRaises(TypeError, reactor.spawnProcess, p, exe, args, env=None)
def open_(self, request, handler, path='/', root='home'): if root == 'home' or root == 'HOME': root = os.getenv('HOME') f = reactor.spawnProcess( protocol.ProcessProtocol(), '/usr/bin/setsid', # setsid - run a program in a new session ['setsid', 'xdg-open', '%s/%s' % (root, path.strip('/'))], env=os.environ) handler.success(request)
def getpage_callback(factory, result): if 'joli-length' in factory.response_headers and \ (len(result) == int(factory.response_headers['joli-length'][0]) == int(factory.response_headers['content-length'][0])): log.msg('Internet connection seems to work') else: log.msg( 'Internet connections seems to be redirected. Launching wifi-connect.' ) reactor.spawnProcess( protocol.ProcessProtocol(), '/usr/bin/setsid', # setsid - run a program in a new session [ 'setsid', '/usr/lib/jolicloud-daemon/utils/wifi-connect' ], env=os.environ)
def do_backup(self, *a): timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) path = self.path.format(timestamp=timestamp, name=self.parent.server_name) if not os.path.exists(os.path.dirname(path)): try: os.makedirs(os.path.dirname(path)) except IOError: self.console( "Warning: {0} does't exist and I can't create it".format( os.path.dirname(path)), kind='error') return if self.mode == "include": add = set() for e in self.spec.split(";"): add |= set(glob.glob(e)) elif self.mode == "exclude": add = set(glob.glob('*')) for e in self.spec.split(";"): add -= set(glob.glob(e)) cmd = ['tar'] cmd.extend(shlex.split(self.tar_flags)) cmd.append(path) cmd.extend(add) def p_ended(path): self.console("map backup saved to %s" % path) if self.autosave_enabled_prev: self.send('save-on') self.backup_stage = 0 self.proto = None if self.done_backup: d = self.done_backup self.done_backup = None d.callback(None) self.proto = protocol.ProcessProtocol() self.proto.processEnded = lambda reason: p_ended(path) self.proto.childDataReceived = lambda fd, d: self.console(d.strip()) reactor.spawnProcess(self.proto, "/bin/tar", cmd)
def guestmode(self, request, handler, action='status'): if 'admin' not in self._groups: return handler.failed(request) # TODO: Permission denied if action not in ['status', 'enable', 'disable']: return handler.failed(request) # TODO: Wrong params args = [action.encode('utf-8')] if action == 'enable': reactor.spawnProcess( protocol.ProcessProtocol(), '/usr/bin/pkexec', [ 'pkexec', '/usr/lib/jolicloud-daemon/utils/migrate-nm-connections' ], env=os.environ) class GetProcessOutput(protocol.ProcessProtocol): out = '' def outReceived(self, data): self.out += data def errReceived(self, data): log.msg("[utils/guestmode] [stderr] %s" % data) def processEnded(self, status_object): if status_object.value.exitCode != 0: return handler.failed(request) if action == 'status': handler.send_data(request, self.out.strip()) handler.success(request) reactor.spawnProcess( GetProcessOutput(), '/usr/bin/pkexec', ['pkexec', '/usr/lib/jolicloud-daemon/utils/guestmode'] + args, env=os.environ)