twisted.application.internet.TCPServer

Here are the examples of the python api twisted.application.internet.TCPServer taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

63 Examples 7

Page 1 Selected Page 2

Example 1

Project: mythbox Source File: test_application.py
    def testTCP(self):
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.setServiceParent(s)
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        internet.TCPClient('127.0.0.1', num, factory).setServiceParent(s)
        factory.d.addCallback(self.assertEqual, 'lalala')
        factory.d.addCallback(lambda x : s.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d

Example 2

Project: SubliminalCollaborator Source File: test_application.py
    def test_reactorParametrizationInServer(self):
        """
        L{internet._AbstractServer} supports a C{reactor} keyword argument
        that can be used to parametrize the reactor used to listen for
        connections.
        """
        reactor = MemoryReactor()

        factory = object()
        t = internet.TCPServer(1234, factory, reactor=reactor)
        t.startService()
        self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))

Example 3

Project: opencanary Source File: __init__.py
Function: get_service
    def getService(self):
        """Return service to be run

        This handles the easy case where the CanaryService class is
        also the Factory/Datagram class. Subclasses should override
        this if more intricracy is needed.
        """
        if isinstance(self, Factory):
            return internet.TCPServer(self.port, self)
        elif isinstance(self, DatagramProtocol):
            return internet.UDPServer(self.port, self)

        err = 'The class %s does not inherit from either Factory or DatagramProtocol.' % (
            self.__class__.__name__
            )
        raise Exception(err)

Example 4

Project: carbon Source File: manhole.py
Function: build
  @classmethod
  def build(cls, root_service):
    if not settings.ENABLE_MANHOLE:
      return

    factory = createManholeListener()
    service = TCPServer(
      settings.MANHOLE_PORT,
      factory,
      interface=settings.MANHOLE_INTERFACE)
    service.setServiceParent(root_service)

Example 5

Project: django-conch Source File: conch.py
def make_service(args):
    checker = DjangoSuperuserCredChecker()

    def chainProtocolFactory():
        return insults.ServerProtocol(
            args['protocol_factory'],
            *args.get('protocol_args', ()),
            **args.get('protocol_kwargs', {}))

    realm = TerminalRealm()
    realm.chainedProtocolFactory = chainProtocolFactory
    ptl = portal.Portal(realm, [checker])
    f = ConchFactory(ptl)
    return internet.TCPServer(args['ssh_port'], f)

Example 6

Project: opencanary Source File: telnet.py
    def getService(self):
        r = Realm()
        p = portal.Portal(r)
        f = protocol.ServerFactory()
        f.canaryservice = self
        f.logger = self.logger
        f.banner = self.banner
        f.protocol = lambda: TelnetTransport(AlertAuthTelnetProtocol, p)
        return internet.TCPServer(self.port, f, interface=self.listen_addr)

Example 7

Project: mythbox Source File: test_application.py
    def test_reactorParametrizationInServerMultipleStart(self):
        """
        Like L{test_reactorParametrizationInServer}, but stop and restart the
        service and check that the given reactor is still used.
        """
        reactor = MemoryReactor()

        factory = object()
        t = internet.TCPServer(1234, factory, reactor=reactor)
        t.startService()
        self.assertEquals(reactor.tcpServers.pop()[:2], (1234, factory))
        t.stopService()
        t.startService()
        self.assertEquals(reactor.tcpServers.pop()[:2], (1234, factory))

Example 8

Project: worker Source File: server.py
def run():

    config.read()
    logs.api()

    top_service = service.MultiService()

    db = Db()
    datalib.db = db
    db.setServiceParent(top_service)

    http_service = internet.TCPServer(config.HTTP_PORT, Site(db), interface=config.HTTP_ADDR)
    http_service.setServiceParent(top_service)

    top_service.startService()

    reactor.addSystemEventTrigger('before', 'shutdown', top_service.stopService)

    reactor.run()

Example 9

Project: starpy Source File: frontend.py
def main():
	"""Create the web-site"""
	s = SurveySetup()
	s.putChild( 'record', RecordFunction() )
	site = appserver.NevowSite(s)
	webServer = internet.TCPServer(8080, site)
	webServer.startService()

Example 10

Project: SubliminalCollaborator Source File: test_application.py
    def test_reactorParametrizationInServerMultipleStart(self):
        """
        Like L{test_reactorParametrizationInServer}, but stop and restart the
        service and check that the given reactor is still used.
        """
        reactor = MemoryReactor()

        factory = protocol.Factory()
        t = internet.TCPServer(1234, factory, reactor=reactor)
        t.startService()
        self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))
        t.stopService()
        t.startService()
        self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))

Example 11

Project: spinoff Source File: startnode.py
    def make_manhole_server(self, port, username, password):
        from twisted.application.internet import TCPServer
        from twisted.cred.portal import Portal
        from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
        from twisted.conch.manhole import ColoredManhole
        from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
        from twisted.conch.insults.insults import ServerProtocol

        rlm = TerminalRealm()
        rlm.chainedProtocolFactory = lambda: ServerProtocol(ColoredManhole, None)

        auth_checker = InMemoryUsernamePasswordDatabaseDontUse(**{username: password})

        return TCPServer(port, ConchFactory(Portal(rlm, [auth_checker])))

Example 12

Project: filesync-server Source File: stats.py
def create_status_service(storage, parent_service, port,
                          user_id=0, ssl_context_factory=None):
    """Create the status service."""
    root = resource.Resource()
    root.putChild('status', _Status(storage, user_id))
    root.putChild('+meliae', MeliaeResource())
    root.putChild('+gc-stats', GCResource())
    site = server.Site(root)
    if ssl_context_factory is None:
        service = TCPServer(port, site)
    else:
        service = SSLServer(port, site, ssl_context_factory)
    service.setServiceParent(parent_service)
    return service

Example 13

Project: opencanary Source File: ftp.py
    def getService(self):
        p = Portal(FTPRealm(FTP_PATH), [DenyAllAccess()])
        f = FTPFactory(p)
        f.protocol = LoggingFTP
        f.welcomeMessage = self.banner
        f.canaryservice = self
        return internet.TCPServer(self.port, f, interface=self.listen_addr)

Example 14

Project: twisted-intro Source File: fastpoetry_plugin.py
    def makeService(self, options):
        top_service = service.MultiService()

        poetry_service = PoetryService(options['poem'])
        poetry_service.setServiceParent(top_service)

        factory = PoetryFactory(poetry_service)
        tcp_service = internet.TCPServer(int(options['port']), factory,
                                         interface=options['iface'])
        tcp_service.setServiceParent(top_service)

        return top_service

Example 15

Project: mythbox Source File: socks.py
Function: make_service
def makeService(config):
    if config["interface"] != "127.0.0.1":
        print
        print "WARNING:"
        print "  You have chosen to listen on a non-local interface."
        print "  This may allow intruders to access your local network"
        print "  if you run this on a firewall."
        print
    t = socks.SOCKSv4Factory(config['log'])
    portno = int(config['port'])
    return internet.TCPServer(portno, t, interface=config['interface'])

Example 16

Project: mythbox Source File: test_application.py
    def testConnectionGettingRefused(self):
        factory = protocol.ServerFactory()
        factory.protocol = wire.Echo
        t = internet.TCPServer(0, factory)
        t.startService()
        num = t._port.getHost().port
        t.stopService()
        d = defer.Deferred()
        factory = protocol.ClientFactory()
        factory.clientConnectionFailed = lambda *args: d.callback(None)
        c = internet.TCPClient('127.0.0.1', num, factory)
        c.startService()
        return d

Example 17

Project: opencanary Source File: ssh.py
    def getService(self):
        factory = HoneyPotSSHFactory(version=self.version, logger=self.logger)
        factory.canaryservice = self
        factory.portal = portal.Portal(HoneyPotRealm())

        rsa_pubKeyString, rsa_privKeyString = getRSAKeys()
        dsa_pubKeyString, dsa_privKeyString = getDSAKeys()
        factory.portal.registerChecker(HoneypotPasswordChecker(logger=factory.logger))
        factory.portal.registerChecker(CanaryPublicKeyChecker(logger=factory.logger))
        factory.publicKeys = {'ssh-rsa': keys.Key.fromString(data=rsa_pubKeyString),
                              'ssh-dss': keys.Key.fromString(data=dsa_pubKeyString)}
        factory.privateKeys = {'ssh-rsa': keys.Key.fromString(data=rsa_privKeyString),
                               'ssh-dss': keys.Key.fromString(data=dsa_privKeyString)}
        return internet.TCPServer(self.port, factory, interface=self.listen_addr)

Example 18

Project: SubliminalCollaborator Source File: tap.py
def makeService(config):
    ca, cl = _buildResolvers(config)

    f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
    p = dns.DNSDatagramProtocol(f)
    f.noisy = 0
    ret = service.MultiService()
    for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
        s = klass(config['port'], arg, interface=config['interface'])
        s.setServiceParent(ret)
    for svc in config.svcs:
        svc.setServiceParent(ret)
    return ret

Example 19

Project: mythbox Source File: test_application.py
    def test_reactorParametrizationInServer(self):
        """
        L{internet._AbstractServer} supports a C{reactor} keyword argument
        that can be used to parametrize the reactor used to listen for
        connections.
        """
        reactor = MemoryReactor()

        factory = object()
        t = internet.TCPServer(1234, factory, reactor=reactor)
        t.startService()
        self.assertEquals(reactor.tcpServers.pop()[:2], (1234, factory))

Example 20

Project: droned Source File: drone.py
def start():
    global service
    if not running():
        kwargs = {'timeout': 60 * 60 * 12, 'logPath': None}
        try: kwargs.update({'timeout': config.DRONED_SERVER_TIMEOUT})
        except: pass
        dr = static.File(config.DRONED_WEBROOT)

        dr.putChild('_getprime', Prime())
        dr.putChild('_command', Control())
        dr.putChild('gremlin', Gremlin())

        site = DroneSite(dr, **kwargs)
        service = internet.TCPServer(config.DRONED_PORT, site) 
        service.setName(SERVICENAME)
        service.setServiceParent(parentService)

Example 21

Project: foolscap Source File: common.py
    def makeNullServer(self):
        f = protocol.Factory()
        f.protocol = protocol.Protocol # discards everything
        s = internet.TCPServer(0, f)
        s.startService()
        self.services.append(s)
        portnum = s._port.getHost().port
        return portnum

Example 22

Project: foolscap Source File: common.py
    def makeHTTPServer(self):
        try:
            from twisted.web import server, resource, static
        except ImportError:
            raise unittest.SkipTest('this test needs twisted.web')
        root = resource.Resource()
        root.putChild("", static.Data("hello\n", "text/plain"))
        s = internet.TCPServer(0, server.Site(root))
        s.startService()
        self.services.append(s)
        portnum = s._port.getHost().port
        return portnum

Example 23

Project: mamba-framework Source File: dummy_plugin.py
Function: make_service
    def makeService(self, options):
        """Construct a TCPServer from a factory defined in pericote
        """
        factory, application = MambaApplicationFactory(settings)
        httpserver = internet.TCPServer(int(options['port']), factory)
        httpserver.setName('{} Application'.format(settings.name))
        httpserver.setServiceParent(application)

        return httpserver

Example 24

Project: filesync-server Source File: ssl_proxy.py
def create_status_service(proxy_server, port):
    """Create the status service."""
    root = resource.Resource()
    root.putChild('status', _Status(proxy_server))
    site = server.Site(root)
    service = TCPServer(port, site)
    return service

Example 25

Project: txstatsd Source File: httpinfo.py
def makeService(options, processor, statsd_service):

    if options["http-port"] is None:
        return service.MultiService()

    root = resource.Resource()
    root.putChild("status", Status(processor, statsd_service))
    root.putChild("metrics", Metrics(processor))
    root.putChild("list_metrics", ListMetrics(processor))
    site = server.Site(root)
    s = internet.TCPServer(int(options["http-port"]), site)
    return s

Example 26

Project: media-nommer Source File: feederd.py
    def makeService(self, options):
        """
        Construct a TCPServer from a Site factory, along with our URL
        structure module.
        """
        self.load_settings(options)
        self.upload_user_settings()
        self.load_job_cache()
        self.start_tasks()

        factory = Site(APIResource())
        server = internet.TCPServer(int(options['port']), factory)
        server.setName('WebAPI')
        return server

Example 27

Project: Kenshin Source File: service.py
def createCacheService(options):
    from rurouni.cache import MetricCache
    from rurouni.protocols import CacheManagementHandler

    MetricCache.init()
    state.events.metricReceived.addHandler(MetricCache.put)
    root_service = createBaseService(options)

    factory = ServerFactory()
    factory.protocol = CacheManagementHandler
    service = TCPServer(int(settings.CACHE_QUERY_PORT), factory,
                        interface=settings.CACHE_QUERY_INTERFACE)
    service.setServiceParent(root_service)

    from rurouni.writer import WriterService
    service = WriterService()
    service.setServiceParent(root_service)

    return root_service

Example 28

Project: nodeset.core Source File: scripts.py
def run_shell():
    from twisted.manhole.telnet import ShellFactory
    from nodeset.core import node
    
    application = ts.Application('nodeset-shell')
    n = node.ShellNode()
    n.setServiceParent(application)
    
    
    sfactory = ShellFactory()
    #sfactory.namespace['node'] = n
    #sfactory.namespace['service'] = application
    
    n.setShell(sfactory)
        
    shell = internet.TCPServer(10331, sfactory)
    shell.setServiceParent(application)
    
    run(application)

Example 29

Project: txloadbalancer Source File: service.py
Function: proxy_factory
    def proxyFactory(self, name, port, factory, interface):
        """
        A factory for creating proxy servers.
        """
        # update the proxy manager's proxy instance
        proxyService = internet.TCPServer(port, factory, interface=interface)
        proxyService.setName(name)
        proxyService.setServiceParent(self.proxyCollection)
        return proxyService

Example 30

Project: mythbox Source File: test_application.py
    def testPrivileged(self):
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.privileged = 1
        t.privilegedStartService()
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        c = internet.TCPClient('127.0.0.1', num, factory)
        c.startService()
        factory.d.addCallback(self.assertEqual, 'lalala')
        factory.d.addCallback(lambda x : c.stopService())
        factory.d.addCallback(lambda x : t.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d

Example 31

Project: carbon Source File: protocols.py
  @classmethod
  def build(cls, root_service):
    plugin_up = cls.plugin_name.upper()
    interface = settings.get('%s_RECEIVER_INTERFACE' % plugin_up, None)
    port = int(settings.get('%s_RECEIVER_PORT' % plugin_up, 0))
    protocol = cls

    if not port:
      return

    if hasattr(protocol, 'datagramReceived'):
      service = UDPServer(port, protocol(), interface=interface)
      service.setServiceParent(root_service)
    else:
      factory = CarbonReceiverFactory()
      factory.protocol = protocol
      service = TCPServer(port, factory, interface=interface)
      service.setServiceParent(root_service)

Example 32

Project: opencanary Source File: http.py
Function: get_service
    def getService(self):
        page = BasicLogin(factory=self)
        root = StaticNoDirListing(self.staticdir)
        root.createErrorPages(self)
        root.putChild("", RedirectCustomHeaders("/index.html", factory=self))
        root.putChild("index.html", page)
        wrapped = EncodingResourceWrapper(root, [GzipEncoderFactory()])
        site = Site(wrapped)
        return internet.TCPServer(self.port, site, interface=self.listen_addr)

Example 33

Project: SubliminalCollaborator Source File: ftp.py
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r, config.get('credCheckers', []))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP

    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f)

Example 34

Project: vertex Source File: depserv.py
Function: add_server
    def addServer(self, normalPort, sslPort, f, name):
        """Add a TCP and an SSL server. Name them `name` and `name`+'s'."""
        tcp = internet.TCPServer(normalPort,f)
        tcp.setName(name)
        self.servers.append(tcp)
        if sslPort is not None:
            ssl = internet.SSLServer(sslPort, f, contextFactory=self.sslfac)
            ssl.setName(name+'s')
            self.servers.append(ssl)

Example 35

Project: scrapyrt Source File: cmdline.py
def get_application(arguments):
    ServiceRoot = load_object(settings.SERVICE_ROOT)
    site = Site(ServiceRoot())
    application = Application('scrapyrt')
    server = TCPServer(arguments.port, site, interface=arguments.ip)
    server.setServiceParent(application)
    return application

Example 36

Project: media-nommer Source File: ec2nommerd.py
    def makeService(self, options):
        """
        Construct a TCPServer from a Site factory, along with our URL
        structure module.
        """
        self.download_settings()
        self.load_settings(options)
        self.start_tasks(options)
        return internet.TCPServer(int(options['port']), Site(APIResource))

Example 37

Project: scrapyd Source File: app.py
def application(config):
    app = Application("Scrapyd")
    http_port = config.getint('http_port', 6800)
    bind_address = config.get('bind_address', '0.0.0.0')
    poll_interval = config.getfloat('poll_interval', 5)

    poller = QueuePoller(config)
    eggstorage = FilesystemEggStorage(config)
    scheduler = SpiderScheduler(config)
    environment = Environment(config)

    app.setComponent(IPoller, poller)
    app.setComponent(IEggStorage, eggstorage)
    app.setComponent(ISpiderScheduler, scheduler)
    app.setComponent(IEnvironment, environment)

    laupath = config.get('launcher', 'scrapyd.launcher.Launcher')
    laucls = load_object(laupath)
    launcher = laucls(config, app)

    webpath = config.get('webroot', 'scrapyd.website.Root')
    webcls = load_object(webpath)

    timer = TimerService(poll_interval, poller.poll)
    webservice = TCPServer(http_port, server.Site(webcls(config, app)), interface=bind_address)
    log.msg(format="Scrapyd web console available at http://%(bind_address)s:%(http_port)s/",
            bind_address=bind_address, http_port=http_port)

    launcher.setServiceParent(app)
    timer.setServiceParent(app)
    webservice.setServiceParent(app)

    return app

Example 38

Project: tahoe-lafs Source File: webish.py
    def startService(self):
        def _got_port(lp):
            self._portnum = lp.getHost().port
            # what is our webport?
            assert self._scheme
            self._url = "%s://127.0.0.1:%d/" % (self._scheme, self._portnum)
            self._started.callback(None)
            return lp
        def _fail(f):
            self._started.errback(f)
            return f

        service.MultiService.startService(self)
        s = self._listener
        if hasattr(s, 'endpoint') and hasattr(s, '_waitingForPort'):
            # Twisted 10.2 gives us a StreamServerEndpointService. This is
            # ugly but should do for now.
            classname = s.endpoint.__class__.__name__
            if classname.startswith('SSL'):
                self._scheme = 'https'
            else:
                self._scheme = 'http'
            s._waitingForPort.addCallbacks(_got_port, _fail)
        elif isinstance(s, internet.TCPServer):
            # Twisted <= 10.1
            self._scheme = 'http'
            _got_port(s._port)
        elif isinstance(s, internet.SSLServer):
            # Twisted <= 10.1
            self._scheme = 'https'
            _got_port(s._port)
        else:
            # who knows, probably some weirdo future version of Twisted
            self._started.errback(AssertionError("couldn't find out the scheme or port for the web-API server"))

Example 39

Project: airpnp Source File: AirPlayService.py
    def __init__(self, apserver, name=None, host="0.0.0.0", port=22555, index=-1, device_id=None):
        MultiService.__init__(self)

        self.apserver = IAirPlayServer(apserver)

        if device_id:
            self.deviceid = device_id
        else:
            macstr = "%012X" % uuid.getnode()
            self.deviceid = ''.join("%s:" % macstr[i:i + 2] for i in range(0, len(macstr), 2))[:-1]

        # 0x77 instead of 0x07 in order to support AirPlay from ordinary apps;
        # also means that the body for play will be a binary plist.
        self.features = 0x77
        self.model = "AppleTV2,1"

        # create TCP server
        TCPServer(port, self.create_site(), 100, interface=host).setServiceParent(self)

        # create avahi service
        if (name is None):
            name = "Airplay Service on " + platform.node()
        zconf = ZeroconfService(name, port=port, stype="_airplay._tcp",
                                text=["deviceid=" + self.deviceid, "features=" + hex(self.features), "model=" + self.model],
                                index=index)
        zconf.setServiceParent(self)

        # for logging
        self.name_ = name
        self.host = host
        self.port = port

Example 40

Project: nodeset.core Source File: twistedapi.py
def runApp(config, application):
    """
    twistd runApp modified, added second argument application
    @param config: run option (--option i.e.)
    @type config: NodeSetAppOptions
    @param applicatin: application instance
    @type application: Application
    """
    runner = NodeSetApplicationRunner(config)
    runner.application = application
    
    if config['manhole']:
        from twisted.manhole.telnet import ShellFactory
        
        sfactory = ShellFactory()
        #sfactory.namespace['node'] = n
        #sfactory.namespace['service'] = application
    
        #n.setShell(sfactory)
        sfactory.setService(application)
        sfactory.namespace['services'] = []
        for v in application._adapterCache.values():
            
            if hasattr(v, 'services'):
                for s in v.services:
                    if s not in sfactory.namespace['services']:
                        sfactory.namespace['services'].append(s)
            
        shell = internet.TCPServer(config['manhole'], sfactory)
        shell.setServiceParent(application)
        
    #level = getattr(logging, config['loglevel'])
    
    #if config['logfile']:
    #    import os
    #    logfile = log.NodeSetLog(os.path.basename(config['logfile']), os.path.dirname(config['logfile']) or '.')
    #    application.setComponent(ILogObserver, log.NodeSetLogObserver(logfile, level).emit)

        
    Configurator._config = config
    
    runner.run()

Example 41

Project: opencanary Source File: httpproxy.py
Function: get_service
    def getService(self):
        AlertProxyRequest.FACTORY = self
        f = HTTPProxyFactory()
        return internet.TCPServer(self.port, f, interface=self.listen_addr)

Example 42

Project: twilionagios Source File: twilio_nagios.py
  def makeService(self, options):
    site = server.Site(TwilioNagios(options['objects'], options['status']))
    return internet.TCPServer(int(options['port']),site)

Example 43

Project: opencanary Source File: mssql.py
Function: get_service
    def getService(self):
        factory = SQLFactory()
        factory.canaryservice = self
        return internet.TCPServer(self.port, factory, interface=self.listen_addr)

Example 44

Project: nodeset.core Source File: scripts.py
def run_web_node():
    
    config = WebNodeOptions()
    application = ts.Application('nodeset-web-node')
    #sc = ts.IServiceCollection(application)
      
    try:
        config.parseOptions()


        from twisted.web import static, script, resource

        from nodeset.core import web
        n = web.WebBridgeNode()
        n.setServiceParent(application)
     
        n.start()
        
        if config.subOptions.has_key('path'):
            root = static.File(config.subOptions['path'])
            root.ignoreExt(".rpy")
            root.processors = {'.rpy': script.ResourceScript}
        else:
            root = resource.Resource()
        
        site = web.NodeSetSite(root, n, logPath=config.subOptions['logfile'])

        root.putChild('subscribe', web.NodeSetSubscribe())
        root.putChild('publish', web.NodeSetPublish())
        
        webservice = internet.TCPServer(config.subOptions['port'], site)
        webservice.setServiceParent(application)
        
        #d = dispatcher.EventDispatcher(config['listen'])
        #d.setServiceParent(application)
    except usage.error, ue:
        #print config
        print ue
    else:
        runApp(config, application)

Example 45

Project: idavoll Source File: tap_http.py
def makeService(config):
    s = tap.makeService(config)

    bs = s.getServiceNamed('backend')
    cs = s.getServiceNamed('component')

    # Set up XMPP service for subscribing to remote nodes

    if config['backend'] == 'pgsql':
        from idavoll.pgsql_storage import GatewayStorage
        gst = GatewayStorage(bs.storage.dbpool)
    elif config['backend'] == 'memory':
        from idavoll.memory_storage import GatewayStorage
        gst = GatewayStorage()

    ss = RemoteSubscriptionService(config['jid'], gst)
    ss.setHandlerParent(cs)
    ss.startService()

    # Set up web service

    root = resource.Resource()

    # Set up resources that exposes the backend
    root.putChild('create', gateway.CreateResource(bs, config['jid'],
                                                   config['jid']))
    root.putChild('delete', gateway.DeleteResource(bs, config['jid'],
                                                   config['jid']))
    root.putChild('publish', gateway.PublishResource(bs, config['jid'],
                                                     config['jid']))
    root.putChild('list', gateway.ListResource(bs))

    # Set up resources for accessing remote pubsub nodes.
    root.putChild('subscribe', gateway.RemoteSubscribeResource(ss))
    root.putChild('unsubscribe', gateway.RemoteUnsubscribeResource(ss))
    root.putChild('items', gateway.RemoteItemsResource(ss))

    site = server.Site(root)
    w = internet.TCPServer(int(config['webport']), site)
    w.setServiceParent(s)

    # Set up a manhole

    namespace = {'service': s,
                 'component': cs,
                 'backend': bs,
                 'root': root}

    f = getManholeFactory(namespace, admin='admin')
    manholeService = strports.service('2222', f)
    manholeService.setServiceParent(s)

    return s

Example 46

Project: txstatsd Source File: service.py
def createService(options):
    """Create a txStatsD service."""
    from carbon.routers import ConsistentHashingRouter
    from carbon.client import CarbonClientManager
    from carbon.conf import settings

    settings.MAX_QUEUE_SIZE = options["max-queue-size"]
    settings.MAX_DATAPOINTS_PER_MESSAGE = options["max-datapoints-per-message"]

    root_service = MultiService()
    root_service.setName("statsd")

    prefix = options["prefix"]
    if prefix is None:
        prefix = "statsd"

    instance_name = options["instance-name"]
    if not instance_name:
        instance_name = platform.node()

    # initialize plugins
    plugin_metrics = []
    for plugin in getPlugins(IMetricFactory):
        plugin.configure(options)
        plugin_metrics.append(plugin)

    processor = None
    if options["dump-mode"]:
        # LoggingMessageProcessor supersedes
        #  any other processor class in "dump-mode"
        assert not hasattr(log, 'info')
        log.info = log.msg  # for compatibility with LMP logger interface
        processor = functools.partial(LoggingMessageProcessor, logger=log)

    if options["statsd-compliance"]:
        processor = (processor or MessageProcessor)(plugins=plugin_metrics)
        input_router = Router(processor, options['routing'], root_service)
        connection = InternalClient(input_router)
        metrics = Metrics(connection)
    else:
        processor = (processor or ConfigurableMessageProcessor)(
            message_prefix=prefix,
            internal_metrics_prefix=prefix + "." + instance_name + ".",
            plugins=plugin_metrics)
        input_router = Router(processor, options['routing'], root_service)
        connection = InternalClient(input_router)
        metrics = ExtendedMetrics(connection)

    if not options["carbon-cache-host"]:
        options["carbon-cache-host"].append("127.0.0.1")
    if not options["carbon-cache-port"]:
        options["carbon-cache-port"].append(2004)
    if not options["carbon-cache-name"]:
        options["carbon-cache-name"].append(None)

    reporting = ReportingService(instance_name)
    reporting.setServiceParent(root_service)

    reporting.schedule(report_client_manager_stats,
                       options["flush-interval"] / 1000,
                       metrics.gauge)

    if options["report"] is not None:
        from txstatsd import process
        from twisted.internet import reactor

        reporting.schedule(
            process.report_reactor_stats(reactor), 60, metrics.gauge)
        reports = [name.strip() for name in options["report"].split(",")]
        for report_name in reports:
            if report_name == "reactor":
                inspector = ReactorInspectorService(reactor, metrics,
                                                    loop_time=0.05)
                inspector.setServiceParent(root_service)

            for reporter in getattr(process, "%s_STATS" %
                                    report_name.upper(), ()):
                reporting.schedule(reporter, 60, metrics.gauge)

    # XXX Make this configurable.
    router = ConsistentHashingRouter()
    carbon_client = CarbonClientManager(router)
    carbon_client.setServiceParent(root_service)

    for host, port, name in zip(options["carbon-cache-host"],
                                options["carbon-cache-port"],
                                options["carbon-cache-name"]):
        carbon_client.startClient((host, port, name))

    statsd_service = StatsDService(carbon_client, input_router,
                                   options["flush-interval"])
    statsd_service.setServiceParent(root_service)

    statsd_server_protocol = StatsDServerProtocol(
        input_router,
        monitor_message=options["monitor-message"],
        monitor_response=options["monitor-response"])

    listener = UDPServer(options["listen-port"], statsd_server_protocol)
    listener.setServiceParent(root_service)

    if options["listen-tcp-port"] is not None:
        statsd_tcp_server_factory = StatsDTCPServerFactory(
            input_router,
            monitor_message=options["monitor-message"],
            monitor_response=options["monitor-response"])

        listener = TCPServer(options["listen-tcp-port"],
                             statsd_tcp_server_factory)
        listener.setServiceParent(root_service)

    httpinfo_service = httpinfo.makeService(options, processor, statsd_service)
    httpinfo_service.setServiceParent(root_service)

    return root_service

Example 47

Project: eth-proxy Source File: server.py
def setup_finalize(event, application):
       
    from twisted.application import service, internet
    from twisted.internet import reactor, ssl
    from twisted.web.server import Site
    from twisted.python import log
    #from twisted.enterprise import adbapi
    import OpenSSL.SSL
    
    from services import ServiceEventHandler
    
    import socket_transport
    import http_transport
    import websocket_transport
    
    from stratum import settings
    
    signing_key = None
        
    # Attach HTTPS Poll Transport service to application
    try:
        sslContext = ssl.DefaultOpenSSLContextFactory(settings.SSL_PRIVKEY, settings.SSL_CACERT)
    except OpenSSL.SSL.Error:
        sslContext = None
        print "Cannot initiate SSL context, are SSL_PRIVKEY or SSL_CACERT missing?"
        print "This will skip all SSL-based transports."
        
    # Set up thread pool size for service threads
    reactor.suggestThreadPoolSize(settings.THREAD_POOL_SIZE) 
    
    if settings.LISTEN_SOCKET_TRANSPORT:
        # Attach Socket Transport service to application
        socket = internet.TCPServer(settings.LISTEN_SOCKET_TRANSPORT,
                                socket_transport.SocketTransportFactory(debug=settings.DEBUG,
                                                                        signing_key=signing_key,
                                                                        signing_id=settings.SIGNING_ID,
                                                                        event_handler=ServiceEventHandler,
                                                                        tcp_proxy_protocol_enable=settings.TCP_PROXY_PROTOCOL))
        socket.setServiceParent(application)

    # Build the HTTP interface
    httpsite = Site(http_transport.Root(debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID,
                                        event_handler=ServiceEventHandler))
    httpsite.sessionFactory = http_transport.HttpSession

    if settings.LISTEN_HTTP_TRANSPORT:    
        # Attach HTTP Poll Transport service to application
        http = internet.TCPServer(settings.LISTEN_HTTP_TRANSPORT, httpsite)
        http.setServiceParent(application)

    if settings.LISTEN_HTTPS_TRANSPORT and sslContext:
            https = internet.SSLServer(settings.LISTEN_HTTPS_TRANSPORT, httpsite, contextFactory = sslContext)
            https.setServiceParent(application)
    
    if settings.LISTEN_WS_TRANSPORT:
        from autobahn.websocket import listenWS
        log.msg("Starting WS transport on %d" % settings.LISTEN_WS_TRANSPORT)
        ws = websocket_transport.WebsocketTransportFactory(settings.LISTEN_WS_TRANSPORT,
                                                           debug=settings.DEBUG,
                                                           signing_key=signing_key,
                                                           signing_id=settings.SIGNING_ID,
                                                           event_handler=ServiceEventHandler,
                                                           tcp_proxy_protocol_enable=settings.TCP_PROXY_PROTOCOL)
        listenWS(ws)
    
    if settings.LISTEN_WSS_TRANSPORT and sslContext:  
        from autobahn.websocket import listenWS
        log.msg("Starting WSS transport on %d" % settings.LISTEN_WSS_TRANSPORT)
        wss = websocket_transport.WebsocketTransportFactory(settings.LISTEN_WSS_TRANSPORT, is_secure=True,
                                                            debug=settings.DEBUG,
                                                            signing_key=signing_key,
                                                            signing_id=settings.SIGNING_ID,
                                                            event_handler=ServiceEventHandler)
        listenWS(wss, contextFactory=sslContext)
    

    return event

Example 48

Project: hookah Source File: hookah_plugin.py
    def makeService(self, options):
        """
        Construct a TCPServer from a factory defined in myproject.
        """
        return internet.TCPServer(int(options["port"]), Site(HookahResource.setup()))

Example 49

Project: fmspy Source File: fmspy_plugin.py
    def makeService(self, options):
        """
        Construct a TCPServer from a factory defined in myproject.
        """
        observer = log.FileLogObserver(sys.stderr)
        log.addObserver(observer.emit)

        from fmspy.config import config
        
        if options['rtmp-port'] != 1935:
            config.set('RTMP', 'port', options['rtmp-port'])
        if options['rtmp-interface'] != '':
            config.set('RTMP', 'interface', options['rtmp-interface'])

        from twisted.application import internet, service
        from fmspy.rtmp.protocol import RTMPServerFactory

        s = service.MultiService()

        h = internet.TCPServer(config.getint('RTMP', 'port'), RTMPServerFactory(), config.getint('RTMP', 'backlog'), config.get('RTMP', 'interface'))
        h.setServiceParent(s)

        log.msg('RTMP server at port %d.' % config.getint('RTMP', 'port'))

        from fmspy.application import app_factory

        def appsLoaded(_):
            log.msg("Applications loaded.")

        def appsError(fail):
            log.err(fail, "Applications failed to load.")

        app_factory.load_applications().addCallbacks(appsLoaded, appsError)

        if config.getboolean('HTTP', 'enabled'):
            from twisted.web import server, static, resource

            root = resource.Resource()

            if config.getboolean('HTTP', 'examples-enabled'):
                examples_path = 'examples/'

                try:
                    from pkg_resources import Requirement, resource_filename, DistributionNotFound

                    try:
                        examples_path = resource_filename(Requirement.parse("fmspy"), "share/examples")
                    except DistributionNotFound:
                        pass

                except ImportError:
                    pass 

                root.putChild('examples', static.File(examples_path))

                h = internet.TCPServer(config.getint('HTTP', 'port'), server.Site(root))
                h.setServiceParent(s)

                log.msg('HTTP server at port %d.' % config.getint('HTTP', 'port'))

        log.removeObserver(observer.emit)

        return s

Example 50

Project: openross Source File: bobross_plugin.py
    def makeService(self, options):
        """
        Construct a TCPServer from a factory defined in bobross
        """
        return internet.TCPServer(int(options['port']), factory.get_factory())
See More Examples - Go to Next Page
Page 1 Selected Page 2