Python twisted.internet.error.ProcessTerminated() Examples

The following are 30 code examples of twisted.internet.error.ProcessTerminated(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.error , or try the search function .
Example #1
Source File: test_session.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_processEndedWithExitSignalCoreDump(self):
        """
        When processEnded is called, if there is an exit signal in the reason
        it should be sent in an exit-signal message.  The connection should be
        closed.
        """
        self.pp.processEnded(
            Failure(ProcessTerminated(1,
                signal.SIGTERM, 1 << 7))) # 7th bit means core dumped
        self.assertRequestsEqual(
            [(b'exit-signal',
              common.NS(b'TERM') # signal name
              + b'\x01' # core dumped is true
              + common.NS(b'') # error message
              + common.NS(b''), # language tag
              False)])
        self.assertSessionClosed() 
Example #2
Source File: test_session.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_wrapProcessProtocol_Protocol(self):
        """
        L{wrapPRocessProtocol}, when passed a L{Protocol} should return
        something that follows the L{IProcessProtocol} interface, with
        connectionMade() mapping to connectionMade(), outReceived() mapping to
        dataReceived() and processEnded() mapping to connectionLost().
        """
        protocol = MockProtocol()
        protocol.transport = StubTransport()
        process_protocol = session.wrapProcessProtocol(protocol)
        process_protocol.connectionMade()
        process_protocol.outReceived(b'data')
        self.assertEqual(protocol.transport.buf, b'data~')
        process_protocol.processEnded(failure.Failure(
            error.ProcessTerminated(0, None, None)))
        protocol.reason.trap(error.ProcessTerminated) 
Example #3
Source File: process.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def processExited(self, failure):
        err = failure.trap(
            internet_error.ProcessDone, internet_error.ProcessTerminated)

        if err == internet_error.ProcessDone:
            pass

        elif err == internet_error.ProcessTerminated:
            self.failed = True
            self.errmsg = failure.value.exitCode
            if self.errmsg:
                self.log.debug('Process Exited, status %d' % (self.errmsg,))
            else:
                self.log.warn('%r' % failure.value)
        if IS_MAC:
            # TODO: need to exit properly!
            self.errmsg = None
        self.proto = None
        self._turn_state_off() 
Example #4
Source File: test_process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_abnormalTermination(self):
        """
        When a process terminates with a system exit code set to 1,
        C{processEnded} is called with a L{error.ProcessTerminated} error,
        the C{exitCode} attribute reflecting the system exit code.
        """
        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        reactor.spawnProcess(p, pyExe,
                             [pyExe, b'-c', b'import sys; sys.exit(1)'],
                             env=None, usePTY=self.usePTY)

        def check(ignored):
            p.reason.trap(error.ProcessTerminated)
            self.assertEqual(p.reason.value.exitCode, 1)
            self.assertIsNone(p.reason.value.signal)
        d.addCallback(check)
        return d 
Example #5
Source File: test_mail.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_processAliasTimeout(self):
        """
        If the alias child process does not exit within a particular period of
        time, the L{Deferred} returned by L{MessageWrapper.eomReceived} should
        fail with L{ProcessAliasTimeout} and send the I{KILL} signal to the
        child process..
        """
        reactor = task.Clock()
        transport = StubProcess()
        proto = mail.alias.ProcessAliasProtocol()
        proto.makeConnection(transport)

        receiver = mail.alias.MessageWrapper(proto, None, reactor)
        d = receiver.eomReceived()
        reactor.advance(receiver.completionTimeout)
        def timedOut(ignored):
            self.assertEqual(transport.signals, ['KILL'])
            # Now that it has been killed, disconnect the protocol associated
            # with it.
            proto.processEnded(
                ProcessTerminated(self.signalStatus(signal.SIGKILL)))
        self.assertFailure(d, mail.alias.ProcessAliasTimeout)
        d.addCallback(timedOut)
        return d 
Example #6
Source File: test_mail.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_processAliasTimeout(self):
        """
        If the alias child process does not exit within a particular period of
        time, the L{Deferred} returned by L{MessageWrapper.eomReceived} should
        fail with L{ProcessAliasTimeout} and send the I{KILL} signal to the
        child process..
        """
        reactor = task.Clock()
        transport = StubProcess()
        proto = mail.alias.ProcessAliasProtocol()
        proto.makeConnection(transport)

        receiver = mail.alias.MessageWrapper(proto, None, reactor)
        d = receiver.eomReceived()
        reactor.advance(receiver.completionTimeout)
        def timedOut(ignored):
            self.assertEqual(transport.signals, ['KILL'])
            # Now that it has been killed, disconnect the protocol associated
            # with it.
            proto.processEnded(
                ProcessTerminated(self.signalStatus(signal.SIGKILL)))
        self.assertFailure(d, mail.alias.ProcessAliasTimeout)
        d.addCallback(timedOut)
        return d 
Example #7
Source File: test_session.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_wrapProcessProtocol_Protocol(self):
        """
        L{wrapPRocessProtocol}, when passed a L{Protocol} should return
        something that follows the L{IProcessProtocol} interface, with
        connectionMade() mapping to connectionMade(), outReceived() mapping to
        dataReceived() and processEnded() mapping to connectionLost().
        """
        protocol = MockProtocol()
        protocol.transport = StubTransport()
        process_protocol = session.wrapProcessProtocol(protocol)
        process_protocol.connectionMade()
        process_protocol.outReceived(b'data')
        self.assertEqual(protocol.transport.buf, b'data~')
        process_protocol.processEnded(failure.Failure(
            error.ProcessTerminated(0, None, None)))
        protocol.reason.trap(error.ProcessTerminated) 
Example #8
Source File: testtools.py    From flocker with Apache License 2.0 6 votes vote down vote up
def is_process_running(node, name):
    """
    Check if the process `name` is running on `node`.

    :param Node node: the node to check.
    :param bytes name: the name of the process to look for.
    :return Deferred[bool]: a deferred that will fire
        with whether at least one process named `name` is running
        on `node`.
    """
    # pidof will return the pid if the processes is
    # running else exit with status 1 which triggers the
    # errback chain.
    command = [b'pidof', b'-x', name]
    d = node.run_as_root(command)

    def not_existing(failure):
        failure.trap(ProcessTerminated)
        return False
    d.addCallbacks(lambda result: True, not_existing)
    return d 
Example #9
Source File: test_shutdownmanager.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def test_process_ends_after_timeout(self):
        """
        If the process ends after the error checking timeout has passed
        C{result} will not be re-fired.
        """
        message = {"type": "shutdown", "reboot": False, "operation-id": 100}
        self.plugin.perform_shutdown(message)

        stash = []

        def restart_performed(ignore):
            self.assertEqual(stash, [])
            stash.append(True)

        [arguments] = self.process_factory.spawns
        protocol = arguments[0]
        protocol.result.addCallback(restart_performed)
        self.manager.reactor.advance(10)
        protocol.processEnded(Failure(ProcessTerminated(exitCode=1)))
        return protocol.result 
Example #10
Source File: test_process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_abnormalTermination(self):
        """
        When a process terminates with a system exit code set to 1,
        C{processEnded} is called with a L{error.ProcessTerminated} error,
        the C{exitCode} attribute reflecting the system exit code.
        """
        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        reactor.spawnProcess(p, pyExe,
                             [pyExe, b'-c', b'import sys; sys.exit(1)'],
                             env=None, usePTY=self.usePTY)

        def check(ignored):
            p.reason.trap(error.ProcessTerminated)
            self.assertEqual(p.reason.value.exitCode, 1)
            self.assertIsNone(p.reason.value.signal)
        d.addCallback(check)
        return d 
Example #11
Source File: process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _getReason(self, status):
        exitCode = sig = None
        if os.WIFEXITED(status):
            exitCode = os.WEXITSTATUS(status)
        else:
            sig = os.WTERMSIG(status)
        if exitCode or sig:
            return error.ProcessTerminated(exitCode, sig, status)
        return error.ProcessDone(status) 
Example #12
Source File: test_process.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_process(self):
        """
        Test running a process: check its output, it exitCode, some property of
        signalProcess.
        """
        scriptPath = b"twisted.test.process_tester"
        d = defer.Deferred()
        p = TestProcessProtocol()
        p.deferred = d
        reactor.spawnProcess(p, pyExe, [pyExe, b"-u", b"-m", scriptPath],
                             env=properEnv)
        def check(ignored):
            self.assertEqual(p.stages, [1, 2, 3, 4, 5])
            f = p.reason
            f.trap(error.ProcessTerminated)
            self.assertEqual(f.value.exitCode, 23)
            # would .signal be available on non-posix?
            # self.assertIsNone(f.value.signal)
            self.assertRaises(
                error.ProcessExitedAlready, p.transport.signalProcess, 'INT')
            try:
                import process_tester, glob
                for f in glob.glob(process_tester.test_file_match):
                    os.remove(f)
            except:
                pass
        d.addCallback(check)
        return d 
Example #13
Source File: test_process.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_manyProcesses(self):

        def _check(results, protocols):
            for p in protocols:
                self.assertEqual(p.stages, [1, 2, 3, 4, 5],
                                 "[%d] stages = %s" % (id(p.transport),
                                                       str(p.stages)))
                # test status code
                f = p.reason
                f.trap(error.ProcessTerminated)
                self.assertEqual(f.value.exitCode, 23)

        scriptPath = b"twisted.test.process_tester"
        args = [pyExe, b'-u', b"-m", scriptPath]
        protocols = []
        deferreds = []

        for i in range(CONCURRENT_PROCESS_TEST_COUNT):
            p = TestManyProcessProtocol()
            protocols.append(p)
            reactor.spawnProcess(p, pyExe, args, env=properEnv)
            deferreds.append(p.deferred)

        deferredList = defer.DeferredList(deferreds, consumeErrors=True)
        deferredList.addCallback(_check, protocols)
        return deferredList 
Example #14
Source File: test_ssh.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def loseConnection(self):
        if self.closed: return
        self.closed = 1
        self.proto.inConnectionLost()
        self.proto.outConnectionLost()
        self.proto.errConnectionLost()
        self.proto.processEnded(failure.Failure(ProcessTerminated(0, None, None))) 
Example #15
Source File: test_shutdownmanager.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def test_restart_fails(self):
        """
        If an error occurs before the error checking timeout the activity will
        be failed.  Data printed by the process prior to the failure is
        included in the activity's result text.
        """
        message = {"type": "shutdown", "reboot": True, "operation-id": 100}
        self.plugin.perform_shutdown(message)

        def restart_failed(message_id):
            self.assertTrue(self.broker_service.exchanger.is_urgent())
            messages = self.broker_service.message_store.get_pending_messages()
            self.assertEqual(len(messages), 1)
            message = messages[0]
            self.assertEqual(message["type"], "operation-result")
            self.assertEqual(message["api"], b"3.2")
            self.assertEqual(message["operation-id"], 100)
            self.assertEqual(message["timestamp"], 0)
            self.assertEqual(message["status"], FAILED)
            self.assertIn(u"Failure text is reported.", message["result-text"])

            # Check that after failing, we attempt to force the shutdown by
            # switching the binary called
            [spawn1_args, spawn2_args] = self.process_factory.spawns
            protocol = spawn2_args[0]
            self.assertIsInstance(protocol, ProcessProtocol)
            self.assertEqual(spawn2_args[1:3],
                             ("/sbin/reboot", ["/sbin/reboot"]))

        [arguments] = self.process_factory.spawns
        protocol = arguments[0]
        protocol.result.addCallback(restart_failed)
        protocol.childDataReceived(0, b"Failure text is reported.")
        protocol.processEnded(Failure(ProcessTerminated(exitCode=1)))
        return protocol.result 
Example #16
Source File: test_changer.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def test_change_packages_with_failed_reboot(self):
        """
        When a C{reboot-if-necessary} flag is passed in the C{change-packages},
        A C{ShutdownProtocol} is created and the package result change is
        returned, even if the reboot fails.
        """
        self.store.add_task("changer",
                            {"type": "change-packages", "install": [2],
                             "binaries": [(HASH2, 2, PKGDEB2)],
                             "operation-id": 123,
                             "reboot-if-necessary": True})

        def return_good_result(self):
            return "Yeah, I did whatever you've asked for!"
        self.replace_perform_changes(return_good_result)

        result = self.changer.handle_tasks()

        def got_result(result):
            self.assertMessages(self.get_pending_messages(),
                                [{"operation-id": 123,
                                  "result-code": 1,
                                  "result-text": "Yeah, I did whatever you've "
                                                 "asked for!",
                                  "type": "change-packages-result"}])
            self.log_helper.ignore_errors(ShutdownFailedError)

        self.landscape_reactor.advance(5)
        [arguments] = self.process_factory.spawns
        protocol = arguments[0]
        protocol.processEnded(Failure(ProcessTerminated(exitCode=1)))
        self.landscape_reactor.advance(10)
        return result.addCallback(got_result) 
Example #17
Source File: test_cgi.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_prematureEndOfHeaders(self):
        """
        If the process communicating with L{CGIProcessProtocol} ends before
        finishing writing out headers, the response has I{INTERNAL SERVER
        ERROR} as its status code.
        """
        request = DummyRequest([''])
        protocol = twcgi.CGIProcessProtocol(request)
        protocol.processEnded(failure.Failure(error.ProcessTerminated()))
        self.assertEqual(request.responseCode, INTERNAL_SERVER_ERROR) 
Example #18
Source File: _dumbwin32proc.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _getReason(self, status):
        if status == 0:
            return error.ProcessDone(status)
        return error.ProcessTerminated(status) 
Example #19
Source File: test_process.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def processEnded(self, reason):
        """
        Callback C{self.deferred} with L{None} if C{reason} is a
        L{error.ProcessTerminated} failure with C{exitCode} set to 1.
        Otherwise, errback with a C{ValueError} describing the problem.
        """
        if not reason.check(error.ProcessTerminated):
            return self.deferred.errback(
                ValueError("wrong termination: %s" % (reason,)))
        v = reason.value
        if v.exitCode != 1:
            return self.deferred.errback(
                ValueError("Wrong exit code: %s" % (v.exitCode,)))
        self.deferred.callback(None) 
Example #20
Source File: test_session.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_processEndedWithExitSignalNoCoreDump(self):
        """
        When processEnded is called, if there is an exit signal in the
        reason it should be sent in an exit-signal message.  If no
        core was dumped, don't set the core-dump bit.
        """
        self.pp.processEnded(
            Failure(ProcessTerminated(1, signal.SIGTERM, 0)))
        # see comments in test_processEndedWithExitSignalCoreDump for the
        # meaning of the parts in the request
        self.assertRequestsEqual(
             [(b'exit-signal', common.NS(b'TERM') + b'\x00' + common.NS(b'') +
               common.NS(b''), False)])
        self.assertSessionClosed() 
Example #21
Source File: test_session.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def loseConnection(self):
        """
        If we're asked to disconnect (and we haven't already) shut down
        the C{ProcessProtocol} with a 0 exit code.
        """
        if self.closed:
            return
        self.closed = 1
        self.proto.inConnectionLost()
        self.proto.outConnectionLost()
        self.proto.errConnectionLost()
        self.proto.processEnded(failure.Failure(
                error.ProcessTerminated(0, None, None))) 
Example #22
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_nonZeroExitSignal(self):
        """
        When the command exits with a non-zero signal, the protocol's
        C{connectionLost} method is called with a L{Failure} wrapping an
        exception which encapsulates that status.

        Additional packet contents are logged at the C{info} level.
        """
        logObserver = EventLoggingObserver()
        globalLogPublisher.addObserver(logObserver)
        self.addCleanup(globalLogPublisher.removeObserver, logObserver)

        exitCode = None
        signal = 15
        # See https://tools.ietf.org/html/rfc4254#section-6.10
        packet = b"".join([
            common.NS(b'TERM'),     # Signal name (without "SIG" prefix);
                                    # string
            b'\x01',                # Core dumped; boolean
            common.NS(b'message'),  # Error message; string (UTF-8 encoded)
            common.NS(b'en-US'),    # Language tag; string
        ])
        exc = self._exitStatusTest(b'exit-signal', packet)
        exc.trap(ProcessTerminated)
        self.assertEqual(exitCode, exc.value.exitCode)
        self.assertEqual(signal, exc.value.signal)

        logNamespace = "twisted.conch.endpoints._CommandChannel"
        hamcrest.assert_that(
            logObserver,
            hamcrest.has_item(
                hamcrest.has_entries(
                    {
                        "log_level": hamcrest.equal_to(LogLevel.info),
                        "log_namespace": logNamespace,
                        "shortSignalName": b"TERM",
                        "coreDumped": True,
                        "errorMessage": u"message",
                        "languageTag": b"en-US",
                    },
                ))) 
Example #23
Source File: test_recvline.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def tearDown(self):
        # Kill the child process.  We're done with it.
        try:
            self.clientTransport.signalProcess("KILL")
        except (error.ProcessExitedAlready, OSError):
            pass
        def trap(failure):
            failure.trap(error.ProcessTerminated)
            self.assertIsNone(failure.value.exitCode)
            self.assertEqual(failure.value.status, 9)
        return self.testTerminal.onDisconnection.addErrback(trap) 
Example #24
Source File: test_ssh.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def loseConnection(self):
        if self.closed: return
        self.closed = 1
        self.proto.inConnectionLost()
        self.proto.outConnectionLost()
        self.proto.errConnectionLost()
        self.proto.processEnded(failure.Failure(ProcessTerminated(0, None, None))) 
Example #25
Source File: test_ssh.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def loseConnection(self):
        if self.closed: return
        self.closed = 1
        self.proto.inConnectionLost()
        self.proto.outConnectionLost()
        self.proto.errConnectionLost()
        self.proto.processEnded(failure.Failure(ProcessTerminated(0, None, None))) 
Example #26
Source File: test_ssh.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def loseConnection(self):
        if self.closed: return
        self.closed = 1
        self.proto.inConnectionLost()
        self.proto.outConnectionLost()
        self.proto.errConnectionLost()
        self.proto.processEnded(failure.Failure(ProcessTerminated(0, None, None))) 
Example #27
Source File: test_ssh.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def loseConnection(self):
        """
        Disconnect the protocol associated with this transport.
        """
        if self.closed:
            return
        self.closed = 1
        self.proto.inConnectionLost()
        self.proto.outConnectionLost()
        self.proto.errConnectionLost()
        self.proto.processEnded(failure.Failure(ProcessTerminated(255, None, None))) 
Example #28
Source File: endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def request_exit_status(self, data):
        """
        When the server sends the command's exit status, record it for later
        delivery to the protocol.

        @param data: The network-order four byte representation of the exit
            status of the command.
        @type data: L{bytes}
        """
        (status,) = unpack('>L', data)
        if status != 0:
            self._reason = ProcessTerminated(status, None, None) 
Example #29
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_processEnded(self):
        """
        Exceptions other than L{error.ProcessDone} with status=0 are turned
        into L{error.ConnectionLost}.
        """
        d = self.ep.connect(self.factory)
        self.successResultOf(d)
        wpp = self.reactor.processProtocol

        wpp.processEnded(Failure(error.ProcessTerminated()))
        self.assertEqual(wpp.protocol.reason.check(error.ConnectionLost),
                         error.ConnectionLost) 
Example #30
Source File: process.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _getReason(self, status):
        exitCode = sig = None
        if os.WIFEXITED(status):
            exitCode = os.WEXITSTATUS(status)
        else:
            sig = os.WTERMSIG(status)
        if exitCode or sig:
            return error.ProcessTerminated(exitCode, sig, status)
        return error.ProcessDone(status)