Python twisted.application.service.Service() Examples

The following are 30 code examples of twisted.application.service.Service(). 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.application.service , or try the search function .
Example #1
Source File: test_service.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_service_factory(self):
        """
        ``VolumeScript._create_volume_service`` uses
        ``VolumeScript._service_factory`` to create a ``VolumeService`` (or
        whatever else that hook decides to create).
        """
        expected = Service()
        script = VolumeScript(object())
        self.patch(
            VolumeScript, "_service_factory",
            staticmethod(lambda config_path, pool, reactor: expected))

        options = VolumeOptions()
        options.parseOptions([])
        service = script._create_volume_service(
            object(), object(), options)
        self.assertIs(expected, service) 
Example #2
Source File: test_twistd.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def assertErrorWritten(self, raised, reported):
        """
        Assert L{UnixApplicationRunner.postApplication} writes
        C{reported} to its status pipe if the service raises an
        exception whose message is C{raised}.
        """
        class FakeService(service.Service):

            def startService(self):
                raise RuntimeError(raised)

        errorService = FakeService()
        errorService.setServiceParent(self.runner.application)

        with AlternateReactor(FakeDaemonizingReactor()):
            self.assertRaises(RuntimeError, self.runner.postApplication)
        self.assertEqual(
            self.mockos.actions,
            [('chdir', '.'), ('umask', 0o077), ('fork', True), 'setsid',
             ('fork', True), ('write', -2, reported),
             ('unlink', 'twistd.pid')])
        self.assertEqual(self.mockos.closed, [-3, -2]) 
Example #3
Source File: internet.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def privilegedStartService(self):
        """
        Start listening on the endpoint.
        """
        service.Service.privilegedStartService(self)
        self._waitingForPort = self.endpoint.listen(self.factory)
        raisedNow = []
        def handleIt(err):
            if self._raiseSynchronously:
                raisedNow.append(err)
            elif not err.check(CancelledError):
                log.err(err)
        self._waitingForPort.addErrback(handleIt)
        if raisedNow:
            raisedNow[0].raiseException()
        self._raiseSynchronously = False 
Example #4
Source File: test_application.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_everythingThere(self):
        """
        L{twisted.application.internet} dynamically defines a set of
        L{service.Service} subclasses that in general have corresponding
        reactor.listenXXX or reactor.connectXXX calls.
        """
        trans = 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split()
        for tran in trans[:]:
            if not getattr(interfaces, "IReactor" + tran)(reactor, None):
                trans.remove(tran)
        for tran in trans:
            for side in 'Server Client'.split():
                if tran == "Multicast" and side == "Client":
                    continue
                if tran == "UDP" and side == "Client":
                    continue
                self.assertTrue(hasattr(internet, tran + side))
                method = getattr(internet, tran + side).method
                prefix = {'Server': 'listen', 'Client': 'connect'}[side]
                self.assertTrue(hasattr(reactor, prefix + method) or
                        (prefix == "connect" and method == "UDP"))
                o = getattr(internet, tran + side)()
                self.assertEqual(service.IService(o), o) 
Example #5
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_everythingThere(self):
        """
        L{twisted.application.internet} dynamically defines a set of
        L{service.Service} subclasses that in general have corresponding
        reactor.listenXXX or reactor.connectXXX calls.
        """
        trans = 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split()
        for tran in trans[:]:
            if not getattr(interfaces, "IReactor" + tran)(reactor, None):
                trans.remove(tran)
        for tran in trans:
            for side in 'Server Client'.split():
                if tran == "Multicast" and side == "Client":
                    continue
                if tran == "UDP" and side == "Client":
                    continue
                self.assertTrue(hasattr(internet, tran + side))
                method = getattr(internet, tran + side).method
                prefix = {'Server': 'listen', 'Client': 'connect'}[side]
                self.assertTrue(hasattr(reactor, prefix + method) or
                        (prefix == "connect" and method == "UDP"))
                o = getattr(internet, tran + side)()
                self.assertEqual(service.IService(o), o) 
Example #6
Source File: internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def privilegedStartService(self):
        """
        Start listening on the endpoint.
        """
        service.Service.privilegedStartService(self)
        self._waitingForPort = self.endpoint.listen(self.factory)
        raisedNow = []
        def handleIt(err):
            if self._raiseSynchronously:
                raisedNow.append(err)
            elif not err.check(CancelledError):
                log.err(err)
        self._waitingForPort.addErrback(handleIt)
        if raisedNow:
            raisedNow[0].raiseException()
        self._raiseSynchronously = False 
Example #7
Source File: test_script.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_main_deferred_fires_after_service_stop(self):
        """
        The ``Deferred`` returned by ``AgentScript.main`` doesn't fire
        until after the ``Deferred`` returned by the ``stopService`` method of
        the service created by ``service_factory``.
        """
        shutdown_deferred = Deferred()

        class SlowShutdown(Service):
            def stopService(self):
                return shutdown_deferred

        service = SlowShutdown()
        agent = AgentScript(
            service_factory=lambda reactor, options: service
        )
        stop_deferred = agent.main(self.reactor, self.options)
        self.reactor.fireSystemEvent("shutdown")
        self.assertNoResult(stop_deferred)
        shutdown_deferred.callback(None)
        self.assertIs(None, self.successResultOf(stop_deferred)) 
Example #8
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testPrivileged(self):
        s = service.Service()
        def pss():
            s.privilegedStarted = 1
        s.privilegedStartService = pss
        s1 = service.Service()
        p = service.MultiService()
        s.setServiceParent(p)
        s1.setServiceParent(p)
        p.privilegedStartService()
        self.assertTrue(s.privilegedStarted) 
Example #9
Source File: internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def startService(self):
        service.Service.startService(self)
        callable, args, kwargs = self.call
        # we have to make a new LoopingCall each time we're started, because
        # an active LoopingCall remains active when serialized. If
        # LoopingCall were a _VolatileDataService, we wouldn't need to do
        # this.
        self._loop = task.LoopingCall(callable, *args, **kwargs)
        self._loop.clock = _maybeGlobalReactor(self.clock)
        self._loopFinished = self._loop.start(self.step, now=True)
        self._loopFinished.addErrback(self._failed) 
Example #10
Source File: internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def stopService(self):
        """
        Stop the service.

        @rtype: L{Deferred<defer.Deferred>}
        @return: a L{Deferred<defer.Deferred>} which is fired when the
            currently running call (if any) is finished.
        """
        if self._loop.running:
            self._loop.stop()
        self._loopFinished.addCallback(lambda _:
                service.Service.stopService(self))
        return self._loopFinished 
Example #11
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testService(self):
        self.assertTrue(service.IService.providedBy(service.Service())) 
Example #12
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testRunningChildren1(self):
        s = service.Service()
        p = service.MultiService()
        s.setServiceParent(p)
        self.assertFalse(s.running)
        self.assertFalse(p.running)
        p.startService()
        self.assertTrue(s.running)
        self.assertTrue(p.running)
        p.stopService()
        self.assertFalse(s.running)
        self.assertFalse(p.running) 
Example #13
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testRunningChildren2(self):
        s = service.Service()
        def checkRunning():
            self.assertTrue(s.running)
        t = service.Service()
        t.stopService = checkRunning
        t.startService = checkRunning
        p = service.MultiService()
        s.setServiceParent(p)
        t.setServiceParent(p)
        p.startService()
        p.stopService() 
Example #14
Source File: internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def startService(self):
        service.Service.startService(self)
        if self._port is None:
            self._port = self._getPort() 
Example #15
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testCopying(self):
        s = service.Service()
        s.startService()
        s1 = copy.copy(s)
        self.assertFalse(s1.running)
        self.assertTrue(s.running) 
Example #16
Source File: procmon.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def __getstate__(self):
        dct = service.Service.__getstate__(self)
        del dct['_reactor']
        dct['protocols'] = {}
        dct['delay'] = {}
        dct['timeStarted'] = {}
        dct['murder'] = {}
        dct['restart'] = {}
        del dct['_processes']
        dct['processes'] = self.processes
        return dct 
Example #17
Source File: procmon.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def stopService(self):
        """
        Stop all monitored processes and cancel all scheduled process restarts.
        """
        service.Service.stopService(self)

        # Cancel any outstanding restarts
        for name, delayedCall in list(self.restart.items()):
            if delayedCall.active():
                delayedCall.cancel()

        for name in list(self._processes):
            self.stopProcess(name) 
Example #18
Source File: procmon.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def startService(self):
        """
        Start all monitored processes.
        """
        service.Service.startService(self)
        for name in list(self._processes):
            self.startProcess(name) 
Example #19
Source File: internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def startService(self):
        service.Service.startService(self)
        self._connection = self._getConnection() 
Example #20
Source File: internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def stopService(self):
        service.Service.stopService(self)
        # TODO: if startup failed, should shutdown skip stopListening?
        # _port won't exist
        if self._port is not None:
            d = self._port.stopListening()
            del self._port
            return d 
Example #21
Source File: test_service.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_realService(self):
        """
        Service implements IService.
        """
        myService = Service()
        verifyObject(IService, myService) 
Example #22
Source File: internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def privilegedStartService(self):
        service.Service.privilegedStartService(self)
        self._port = self._getPort() 
Example #23
Source File: internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def __getstate__(self):
        d = service.Service.__getstate__(self)
        for attr in self.volatile:
            if attr in d:
                del d[attr]
        return d 
Example #24
Source File: masterchild.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def addProtocol(self, protocol, port):
        self.log.info(
            "Setting service for protocol {protocol!r} on port {port}...",
            protocol=protocol, port=port,
        )

        # TCP Service
        tcpFactory = SpawningInheritingProtocolFactory(
            self.dispatcher, self.spawningService, protocol
        )
        tcpService = TCPServer(port, tcpFactory)

        tcpService.setServiceParent(self) 
Example #25
Source File: test_script.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_main_stops_service(self):
        """
        When the reactor passed to ``AgentScript.main`` shuts down, the
        service created by the ``service_factory`` is stopped.
        """
        service = Service()
        agent = AgentScript(
            service_factory=lambda reactor, options: service
        )
        agent.main(self.reactor, self.options)
        self.reactor.fireSystemEvent("shutdown")
        self.assertFalse(service.running) 
Example #26
Source File: test_script.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_main_starts_service(self):
        """
        ```AgentScript.main`` starts the service created by its
        ``service_factory`` .
        """
        service = Service()
        agent = AgentScript(
            service_factory=lambda reactor, options: service
        )
        agent.main(self.reactor, self.options)
        self.assertTrue(service.running) 
Example #27
Source File: test_script.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_interface(self):
        """
        ``AgentScript`` instances provide ``ICommandLineScript``.
        """
        self.assertTrue(
            verifyObject(
                ICommandLineScript,
                AgentScript(
                    service_factory=lambda reactor, options: Service()
                )
            )
        ) 
Example #28
Source File: script.py    From flocker with Apache License 2.0 5 votes vote down vote up
def main(self):
        """Parse arguments and run the script's main function via ``react``."""
        # If e.g. --version is called this may throw a SystemExit, so we
        # always do this first before any side-effecty code is run:
        options = self._parse_options(self.sys_module.argv[1:])

        if self.logging:
            log_writer = eliot_logging_service(
                options.eliot_destination, self._reactor, True
            )
        else:
            log_writer = Service()
        log_writer.startService()

        # XXX: We shouldn't be using this private _reactor API. See
        # https://twistedmatrix.com/trac/ticket/6200 and
        # https://twistedmatrix.com/trac/ticket/7527
        def run_and_log(reactor):
            d = maybeDeferred(self.script.main, reactor, options)

            def got_error(failure):
                if failure.check(UsageError):
                    err(failure.value.args)
                    raise SystemExit(1)
                elif not failure.check(SystemExit):
                    err(failure)
                return failure
            d.addErrback(got_error)
            return d
        try:
            self._react(run_and_log, [], _reactor=self._reactor)
        finally:
            log_writer.stopService() 
Example #29
Source File: test_service.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_arguments(self):
        """
        ``VolumeScript.main`` calls the ``main`` method of the script object
        the ``VolumeScript`` was initialized with, passing the same reactor and
        options and also the running ``VolumeService``.
        """
        @implementer(ICommandLineVolumeScript)
        class VolumeServiceScript(object):
            def __init__(self):
                self.calls = []

            def main(self, reactor, options, volume_service):
                self.calls.append((reactor, options, volume_service))

        script = VolumeServiceScript()
        helper = VolumeScript(script)

        reactor = object()
        options = VolumeOptions()
        options.parseOptions([])

        service = Service()
        self.patch(
            VolumeScript, "_service_factory",
            staticmethod(lambda *args, **kwargs: service))

        helper.main(reactor, options)

        self.assertEqual(
            [(reactor, options, service)],
            script.calls
        ) 
Example #30
Source File: test_script.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_deferred_result(self):
        """
        ``VolumeScript.main`` returns a ``Deferred`` on success.
        """
        script = VolumeManagerScript()
        options = VolumeOptions()
        options["config"] = FilePath(self.mktemp())
        dummy_reactor = object()
        result = script.main(dummy_reactor, options, Service())
        self.assertIs(None, self.successResultOf(result))