Esempio n. 1
0
File: tap.py Progetto: Almad/twisted
def makeService(config):
    s = service.MultiService()
    if config['root']:
        root = config['root']
        if config['indexes']:
            config['root'].indexNames = config['indexes']
    else:
        # This really ought to be web.Admin or something
        root = demo.Test()

    if isinstance(root, static.File):
        root.registry.setComponent(interfaces.IServiceCollection, s)

    if config['logfile']:
        site = server.Site(root, logPath=config['logfile'])
    else:
        site = server.Site(root)

    site.displayTracebacks = not config["notracebacks"]

    if config['personal']:
        personal = strports.service(
            config['port'], makePersonalServerFactory(site))
        personal.setServiceParent(s)
    else:
        if config['https']:
            from twisted.internet.ssl import DefaultOpenSSLContextFactory
            i = internet.SSLServer(int(config['https']), site,
                          DefaultOpenSSLContextFactory(config['privkey'],
                                                       config['certificate']))
            i.setServiceParent(s)
        strports.service(config['port'], site).setServiceParent(s)

    return s
Esempio n. 2
0
def makeService(config):
    """
    Create the service serving the mkcert data.
    """
    from twisted.internet import reactor

    # We need a HTTP connection pool for rproxy.
    pool = HTTPConnectionPool(reactor)

    proxyResource = RProxyResource(
        hosts=hosts,
        pool=pool,
        customHeaders=customHeaders,
        reactor=reactor
    )
    redirectResource = RedirectResource()

    secureSite = Site(proxyResource)
    insecureSite = Site(redirectResource)

    multiService = service.MultiService()
    multiService.addService(
        strports.service('le:/certs:tcp:' + HTTPS_PORT, secureSite)
    )
    multiService.addService(
        strports.service("tcp:" + HTTP_PORT, insecureSite)
    )
    return multiService
Esempio n. 3
0
def makeService(config):
    s = service.MultiService()

    router = component.Router()

    # Set up the XMPP server service

    serverService = server.ServerService(router, secret=config['server-secret'])
    serverService.domains = config['domains']
    serverService.logTraffic = config['verbose']

    # Hook up XMPP server-to-server service
    s2sFactory = server.XMPPS2SServerFactory(serverService)
    s2sFactory.logTraffic = config['verbose']
    s2sService = strports.service(config['server-port'], s2sFactory)
    s2sService.setServiceParent(s)

    # Hook up XMPP external server-side component service
    cFactory = component.XMPPComponentServerFactory(router,
                                                    config['component-secret'])

    cFactory.logTraffic = config['verbose']
    cServer = strports.service(config['component-port'], cFactory)
    cServer.setServiceParent(s)

    return s
Esempio n. 4
0
File: data.py Progetto: srothan/io
def makeService (config_global, config, ) :
    sys.path.insert(0, config_global.get("root"), )
    os.environ["DJANGO_SETTINGS_MODULE"] = config.get("django-settings")

    _ms = service.MultiService()

    # `HTTP` interface
    _resource = RootResource()
    _resource.putChild("file", FileResource(config.get("file-directory"), ), )

    strports.service(
        "tcp:%d%s" % (
            config.get("file-port"),
            config_global.get("interface"),
        ),
        HTTPFactory(
                _resource,
                is_stand="--nodaemon" in sys.argv or "-n" in sys.argv,
                quite=config_global.get("quite"),
            ),
    ).setServiceParent(_ms, )

    XMPPClient(
            "io.data@%s" % config_global.get("hostname"),
            "io.data",
            host=config_global.get("xmpp-host"),
            port=config_global.get("xmpp-port"),
            file_directory=config.get("file-directory"),
        ).setServiceParent(_ms, )

    return _ms
Esempio n. 5
0
def makeService(config):
    from twisted.internet import reactor

    multi = service.MultiService()

    domain = config['domain']
    mutils.maybeWarnAboutDomain(reactor, domain)

    closureLibrary = FilePath(config['closure-library'])
    mutils.maybeWarnAboutClosureLibrary(reactor, closureLibrary)

    socketPorts = []
    for minervaStrport in config['minerva']:
            _, _args, _ = strports.parse(minervaStrport, object())
            socketPorts.append(_args[0])

    fileCache = FileCache(lambda: reactor.seconds(), -1)
    stf, httpSite = site.setupMinerva(
            reactor, fileCache, socketPorts, domain, closureLibrary
    )
    httpSite.displayTracebacks = not config["no-tracebacks"]

    for httpStrport in config['http']:
            httpServer = strports.service(httpStrport, httpSite)
            httpServer.setServiceParent(multi)

    for minervaStrport in config['minerva']:
            minervaServer = strports.service(minervaStrport, stf)
            minervaServer.setServiceParent(multi)

    return multi
Esempio n. 6
0
    def test_serviceDeprecatedDefault(self):
        """
        L{strports.service} still accepts a 'default' argument, which will
        affect the parsing of 'default' (i.e. 'not containing a colon')
        endpoint descriptions, but this behavior is deprecated.
        """
        svc = strports.service("8080", None, "unix")
        self.assertIsInstance(svc.endpoint, UNIXServerEndpoint)
        warnings = self.flushWarnings([self.test_serviceDeprecatedDefault])
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "The 'default' parameter was deprecated in Twisted 10.2.0.  "
            "Use qualified endpoint descriptions; for example, 'tcp:8080'.")
        self.assertEqual(len(warnings), 1)

        # Almost the same case, but slightly tricky - explicitly passing the old
        # default value, None, also must trigger a deprecation warning.
        svc = strports.service("tcp:8080", None, None)
        self.assertIsInstance(svc.endpoint, TCP4ServerEndpoint)
        warnings = self.flushWarnings([self.test_serviceDeprecatedDefault])
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "The 'default' parameter was deprecated in Twisted 10.2.0.")
        self.assertEqual(len(warnings), 1)
Esempio n. 7
0
 def __init__(self, relayport, transitport, advertise_version):
     service.MultiService.__init__(self)
     self.db = get_db("relay.sqlite")
     welcome = {
         "current_version": __version__,
         # adding .motd will cause all clients to display the message,
         # then keep running normally
         #"motd": "Welcome to the public relay.\nPlease enjoy this service.",
         #
         # adding .error will cause all clients to fail, with this message
         #"error": "This server has been disabled, see URL for details.",
         }
     if advertise_version:
         welcome["current_version"] = advertise_version
     self.root = Root()
     site = server.Site(self.root)
     self.relayport_service = strports.service(relayport, site)
     self.relayport_service.setServiceParent(self)
     self.relay = Relay(self.db, welcome) # accessible from tests
     self.root.putChild("wormhole-relay", self.relay)
     t = internet.TimerService(EXPIRATION_CHECK_PERIOD,
                               self.relay.prune_old_channels)
     t.setServiceParent(self)
     if transitport:
         self.transit = Transit()
         self.transit.setServiceParent(self) # for the timer
         self.transport_service = strports.service(transitport, self.transit)
         self.transport_service.setServiceParent(self)
Esempio n. 8
0
def makeService(config):
    if config['logfile']:
        logObserver = log.FileAccessLoggingObserver(config['logfile'])
    else:
        logObserver = log.DefaultCommonAccessLoggingObserver()

    if config['root']:
        if config['indexes']:
            config['root'].indexNames = config['indexes']

        root = log.LogWrapperResource(config['root'])

    s = Web2Service(logObserver)

    site = server.Site(root)
    chan = channel.HTTPFactory(site)

    if config['https']:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        i = internet.SSLServer(
            int(config['https']), chan,
            DefaultOpenSSLContextFactory(config['privkey'],
                                         config['certificate']))
        i.setServiceParent(s)

    strports.service(config['port'], chan).setServiceParent(s)

    return s
Esempio n. 9
0
File: tap.py Progetto: lzimm/360io
def makeService(config):
    if config['logfile']:
        logObserver = log.FileAccessLoggingObserver(config['logfile'])
    else:
        logObserver = log.DefaultCommonAccessLoggingObserver()

    if config['root']:
        if config['indexes']:
            config['root'].indexNames = config['indexes']
            
        root = log.LogWrapperResource(config['root'])


    s = Web2Service(logObserver)

    site = server.Site(root)
    chan = channel.HTTPFactory(site)
    
    if config['https']:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        i = internet.SSLServer(int(config['https']), chan,
                               DefaultOpenSSLContextFactory(config['privkey'],
                                                            config['certificate']))
        i.setServiceParent(s)
        
    strports.service(config['port'], chan
                     ).setServiceParent(s)

    return s
Esempio n. 10
0
def makeService(config):
    s = service.MultiService()
    if config['root']:
        root = config['root']
        if config['indexes']:
            config['root'].indexNames = config['indexes']
    else:
        # This really ought to be web.Admin or something
        root = demo.Test()

    if isinstance(root, static.File):
        root.registry.setComponent(interfaces.IServiceCollection, s)

    if config['logfile']:
        site = server.Site(root, logPath=config['logfile'])
    else:
        site = server.Site(root)

    site.displayTracebacks = not config["notracebacks"]

    if config['personal']:
        personal = strports.service(
            config['port'], makePersonalServerFactory(site))
        personal.setServiceParent(s)
    else:
        if config['https']:
            from twisted.internet.ssl import DefaultOpenSSLContextFactory
            i = internet.SSLServer(int(config['https']), site,
                          DefaultOpenSSLContextFactory(config['privkey'],
                                                       config['certificate']))
            i.setServiceParent(s)
        strports.service(config['port'], site).setServiceParent(s)

    return s
Esempio n. 11
0
def makeService(config):
	from twisted.internet import reactor, task

	multi = service.MultiService()

	domain = config['domain']
	mutils.maybeWarnAboutDomain(reactor, domain)

	closureLibrary = FilePath(config['closure-library'])
	mutils.maybeWarnAboutClosureLibrary(reactor, closureLibrary)

	socketPorts = []
	for minervaStrport in config['minerva']:
		_, _args, _ = strports.parse(minervaStrport, object())
		socketPorts.append(_args[0])

	doReloading = bool(int(os.environ.get('PYRELOADING', '0')))
	fileCache = FileCache(lambda: reactor.seconds(), 0.1 if doReloading else -1)
	stf, httpSite = demosminerva_site.makeMinervaAndHttp(
		reactor, fileCache, socketPorts, domain, closureLibrary)
	httpSite.displayTracebacks = not config["no-tracebacks"]

	for httpStrport in config['http']:
		httpServer = strports.service(httpStrport, httpSite)
		httpServer.setServiceParent(multi)

	for minervaStrport in config['minerva']:
		minervaServer = strports.service(minervaStrport, stf)
		minervaServer.setServiceParent(multi)

	if doReloading:
		mutils.enablePyquitter(reactor)

	return multi
Esempio n. 12
0
    def test_serviceDeprecatedDefault(self):
        """
        L{strports.service} still accepts a 'default' argument, which will
        affect the parsing of 'default' (i.e. 'not containing a colon')
        endpoint descriptions, but this behavior is deprecated.
        """
        svc = strports.service("8080", None, "unix")
        self.assertIsInstance(svc.endpoint, UNIXServerEndpoint)
        warnings = self.flushWarnings([self.test_serviceDeprecatedDefault])
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "The 'default' parameter was deprecated in Twisted 10.2.0.  "
            "Use qualified endpoint descriptions; for example, 'tcp:8080'.")
        self.assertEqual(len(warnings), 1)

        # Almost the same case, but slightly tricky - explicitly passing the
        # old default value, None, also must trigger a deprecation warning.
        svc = strports.service("tcp:8080", None, None)
        self.assertIsInstance(svc.endpoint, TCP4ServerEndpoint)
        warnings = self.flushWarnings([self.test_serviceDeprecatedDefault])
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "The 'default' parameter was deprecated in Twisted 10.2.0.")
        self.assertEqual(len(warnings), 1)
Esempio n. 13
0
    def makeService(self, options):
        master = Master(options)

        web = Web(master)
        strports.service(options["web"], web).setServiceParent(master)

        return master
Esempio n. 14
0
def makeService(options):
    """Create a manhole server service.

    @type options: C{dict}
    @param options: A mapping describing the configuration of
    the desired service.  Recognized key/value pairs are::

        "telnetPort": strports description of the address on which
                      to listen for telnet connections.  If None,
                      no telnet service will be started.

        "sshPort": strports description of the address on which to
                   listen for ssh connections.  If None, no ssh
                   service will be started.

        "namespace": dictionary containing desired initial locals
                     for manhole connections.  If None, an empty
                     dictionary will be used.

        "passwd": Name of a passwd(5)-format username/password file.

    @rtype: L{twisted.application.service.IService}
    @return: A manhole service.
    """

    svc = service.MultiService()

    namespace = options['namespace']
    if namespace is None:
        namespace = {}

    checker = checkers.FilePasswordDB(options['passwd'])

    if options['telnetPort']:
        telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol,
                                   insults.ServerProtocol,
                                   manhole.ColoredManhole,
                                   namespace)

        telnetPortal = portal.Portal(telnetRealm, [checker])

        telnetFactory = protocol.ServerFactory()
        telnetFactory.protocol = makeTelnetProtocol(telnetPortal)
        telnetService = strports.service(options['telnetPort'],
                                         telnetFactory)
        telnetService.setServiceParent(svc)

    if options['sshPort']:
        sshRealm = manhole_ssh.TerminalRealm()
        sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace)

        sshPortal = portal.Portal(sshRealm, [checker])
        sshFactory = manhole_ssh.ConchFactory(sshPortal)
        sshService = strports.service(options['sshPort'],
                                      sshFactory)
        sshService.setServiceParent(svc)

    return svc
Esempio n. 15
0
def makeService(options):
    """Create a manhole server service.

    @type options: C{dict}
    @param options: A mapping describing the configuration of
    the desired service.  Recognized key/value pairs are::

        "telnetPort": strports description of the address on which
                      to listen for telnet connections.  If None,
                      no telnet service will be started.

        "sshPort": strports description of the address on which to
                   listen for ssh connections.  If None, no ssh
                   service will be started.

        "namespace": dictionary containing desired initial locals
                     for manhole connections.  If None, an empty
                     dictionary will be used.

        "passwd": Name of a passwd(5)-format username/password file.

    @rtype: L{twisted.application.service.IService}
    @return: A manhole service.
    """

    svc = service.MultiService()

    namespace = options['namespace']
    if namespace is None:
        namespace = {}

    checker = checkers.FilePasswordDB(options['passwd'])

    if options['telnetPort']:
        telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol,
                                   insults.ServerProtocol,
                                   manhole.ColoredManhole,
                                   namespace)

        telnetPortal = portal.Portal(telnetRealm, [checker])

        telnetFactory = protocol.ServerFactory()
        telnetFactory.protocol = makeTelnetProtocol(telnetPortal)
        telnetService = strports.service(options['telnetPort'],
                                         telnetFactory)
        telnetService.setServiceParent(svc)

    if options['sshPort']:
        sshRealm = manhole_ssh.TerminalRealm()
        sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace)

        sshPortal = portal.Portal(sshRealm, [checker])
        sshFactory = manhole_ssh.ConchFactory(sshPortal)
        sshService = strports.service(options['sshPort'],
                                      sshFactory)
        sshService.setServiceParent(svc)

    return svc
Esempio n. 16
0
File: tap.py Progetto: jirwin/mimic
def makeService(config):
    """
    Set up the otter-api service.
    """
    s = MultiService()
    core = MimicCore.fromPlugins(Clock())
    root = MimicRoot(core)
    site = Site(root.app.resource())
    site.displayTracebacks = False
    service(config['listen'], site).setServiceParent(s)
    return s
 def makeService(self, options):
     s = service.MultiService()
     pool = threadpool.ThreadPool()
     reactor.callWhenRunning(pool.start)
     reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
     root = wsgi.WSGIResource(reactor, pool, wsgi_param.application)
     site = server.Site(root)
     strports.service('tcp:8000', site).setServiceParent(s)
     ts = internet.TimerService(1, update, wsgi_param.application, reactor)
     ts.setServiceParent(s)
     return s
 def makeService(self, options):
     s = service.MultiService()
     pool = threadpool.ThreadPool()
     reactor.callWhenRunning(pool.start)
     reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
     root = wsgi.WSGIResource(reactor, pool, wsgi_param.application)
     site = server.Site(root)
     strports.service('tcp:8000', site).setServiceParent(s)
     factory = protocol.Factory.forProtocol(UpdateMessage)
     factory.application = wsgi_param.application
     strports.service('tcp:8001', factory).setServiceParent(s)
     return s
Esempio n. 19
0
 def makeService(self, options):
     s = MultiService()
     tps = ThreadPoolService()
     tps.setServiceParent(s)
     site = Site(
         RootResource(
             store=Store(options['dbdir']),
             steamKey=options['steamkey'],
             paypalSandbox=options['paypal-sandbox'],
             threadPool=tps.threadpool))
     strports.service(options['port'], site).setServiceParent(s)
     return s
Esempio n. 20
0
def makeService(config):
    computername = unicode(os.popen("/usr/sbin/networksetup -getcomputername",
                                    "r").readlines()[0]).strip()
    s = service.MultiService()

    for host_config in config['hosts']:

        prepareMultiService(s, host_config)

        if host_config['vhosts']:

            vhost_root = vhost.NameVirtualHost()
            vhost_root.default = host_config['root']

            for vhost_config in host_config['vhosts']:

                prepareMultiService(s, vhost_config)

                vhost_root.addHost(vhost_config['fqdn'], vhost_config['root'])

            host_config['root'] = vhost_root

        if config['logfile']:
            site = server.Site(host_config['root'], logPath=config['logfile'])
        else:
            site = server.Site(host_config['root'])

        site.displayTracebacks = not config["notracebacks"]

        if not host_config['shape'] is None:
            site.protocol = shaper.gen_token_bucket(site.protocol,
                                                    *host_config['shape'])

        port = host_config['port']
        if ":" in str(host_config['port']):
            port = host_config['port'].split(':', 2)[1]
        port = int(port)

        if not host_config['bonjour']:
            host_config['bonjour'].append(u"Mediacast-Webserver (%s on port %d)")

        for bonjour_desc in host_config['bonjour']:
            if '%s' in bonjour_desc and '%d' in bonjour_desc:
                bonjour_desc %= (computername, port)
            elif '%s' in bonjour_desc:
                bonjour_desc %= computername
            elif '%d' in bonjour_desc:
                bonjour_desc %= port
            bonjour.mDNSService(bonjour_desc, "_http._tcp", port).setServiceParent(s)

        strports.service(host_config['port'], site).setServiceParent(s)

    return s
Esempio n. 21
0
 def makeService(self, options):
     application = pyramid_dynamic.application
     pool = threadpool.ThreadPool(minthreads=1, maxthreads=100)
     reactor.callWhenRunning(pool.start)
     reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
     root = wsgi.WSGIResource(reactor, pool, application)
     site = server.Site(root)
     control = protocol.Factory()
     control.protocol = lambda: amp.AMP(locator=AppConfiguration())
     ret = service.MultiService()
     strports.service('tcp:8000', site).setServiceParent(ret)
     strports.service('tcp:8001', control).setServiceParent(ret)
     return ret
Esempio n. 22
0
    def startService(self):
        def chainedProtocolFactory():
            def getManhole():
                return Manhole({"store": self.store})

            protocol = insults.ServerProtocol(ColoredManhole)
            protocol.protocolFactory = getManhole
            return protocol

        checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**{str(self.username): self.password})
        realm = TerminalRealm()
        realm.chainedProtocolFactory = chainedProtocolFactory
        p = portal.Portal(realm, [checker])
        strports.service(self.listen, ConchFactory(p)).setServiceParent(self.parent)
Esempio n. 23
0
def makeService(config):
    """
    Set up the otter-api service.
    """
    s = MultiService()
    if config['realtime']:
        from twisted.internet import reactor as clock
    else:
        clock = Clock()
    core = MimicCore.fromPlugins(clock)
    root = MimicRoot(core, clock)
    site = get_site(root.app.resource(), logging=bool(config['verbose']))
    service(config['listen'], site).setServiceParent(s)
    return s
Esempio n. 24
0
def makeService(config):
    """
    Set up the otter-api service.
    """
    s = MultiService()
    if config['realtime']:
        from twisted.internet import reactor as clock
    else:
        clock = Clock()
    core = MimicCore.fromPlugins(clock)
    root = MimicRoot(core, clock)
    site = get_site(root.app.resource(), logging=bool(config['verbose']))
    service(config['listen'], site).setServiceParent(s)
    return s
Esempio n. 25
0
 def makeService(self, options):
     """
     Construct a TCPServer from a factory defined in myproject.
     """
     player = Player(reactor)
     reactor.addSystemEventTrigger("before", "shutdown", player.kill)
     s = service.MultiService()
     payload_service = strports.service(options["payload"],                                   
                                        CustomServer(PayloadProtocol, player))
     payload_service.setServiceParent(s)
     control_service = strports.service(options["control"],
                                        CustomServer(ControlProtocol, player))
     control_service.setServiceParent(s)
     return s
Esempio n. 26
0
def makeService(config):
    s = MultiService()

    proxy = strports.service(
        config['proxy'],
        server.Site(
            TrickProxyResource(config['requestTricks'],
                               config['responseTricks'])))
    proxy.setServiceParent(s)

    ui = strports.service(config['ui'], server.Site(Root()))
    ui.setServiceParent(s)

    return s
Esempio n. 27
0
    def makeService(self, config):
        s = service.MultiService()
        if config['root']:
            root = config['root']
            if config['indexes']:
                config['root'].indexNames = config['indexes']
        else:
            # This really ought to be web.Admin or something
            root = demo.Test()

        if isinstance(root, static.File):
            root.registry.setComponent(interfaces.IServiceCollection, s)

        if config['logfile']:
            site = server.Site(root, logPath=config['logfile'])
        else:
            site = server.Site(root)

        site.displayTracebacks = not config["notracebacks"]
        
        if config['personal']:
            personal = strports.service(
                config['port'], makePersonalServerFactory(site))
            personal.setServiceParent(s)
        else:
            if config['https']:
                from twisted.internet.ssl import DefaultOpenSSLContextFactory
                if config['sslmethod'].lower() == "sslv2":
                    ssl_method = SSL.SSLv2_METHOD
                elif config['sslmethod'].lower() == "sslv3":
                    ssl_method = SSL.SSLv3_METHOD
                elif config['sslmethod'].lower() == "sslv23":
                    ssl_method = SSL.SSLv23_METHOD
                elif config['sslmethod'].lower() == "tlsv1":
                    ssl_method = SSL.TLSv1_METHOD
                elif config['sslmethod'].lower() == "tlsv1_1":
                    ssl_method = SSL.TLSv1_1_METHOD
                elif config['sslmethod'].lower() == "tlsv1_2":
                    ssl_method = SSL.TLSv1_2_METHOD
                else:
                    raise usage.UsageError("Invalid SSL method: %s" % config['sslmethod'].lower())
            
                i = internet.SSLServer(int(config['https']), site,
                              DefaultOpenSSLContextFactory(config['privkey'],
                                                           config['certificate'],
                                                           ssl_method))
                i.setServiceParent(s)
            strports.service(config['port'], site).setServiceParent(s)

        return s
Esempio n. 28
0
 def makeService(self, options):
     """
     Construct a TCPServer from a factory defined in myproject.
     """
     player = Player(reactor)
     reactor.addSystemEventTrigger("before", "shutdown", player.kill)
     s = service.MultiService()
     payload_service = strports.service(
         options["payload"], CustomServer(PayloadProtocol, player))
     payload_service.setServiceParent(s)
     control_service = strports.service(
         options["control"], CustomServer(ControlProtocol, player))
     control_service.setServiceParent(s)
     return s
Esempio n. 29
0
def makeService(config):
    """
    Set up the otter-api service.
    """
    s = MultiService()
    if config['realtime']:
        from twisted.internet import reactor as clock
    else:
        clock = Clock()
    core = MimicCore.fromPlugins(clock)
    root = MimicRoot(core, clock)
    site = Site(root.app.resource())
    site.displayTracebacks = False
    service(config['listen'], site).setServiceParent(s)
    return s
Esempio n. 30
0
File: tap.py Progetto: dreid/loki
def makeService(config):
    s = MultiService()

    proxy = strports.service(
        config['proxy'],
        server.Site(TrickProxyResource(config['requestTricks'], config['responseTricks'])))
    proxy.setServiceParent(s)

    ui = strports.service(
        config['ui'],
        server.Site(Root())
    )
    ui.setServiceParent(s)

    return s
Esempio n. 31
0
    def __init__(self, highscore, config):
        service.MultiService.__init__(self)
        self.setName('highscore.www')
        self.highscore = highscore
        self.config = config

        self.port = config.www.get('port', 8080)
        self.port_service = None
        self.site = None
        self.site_public_html = None

        self.root = root = static.Data('placeholder', 'text/plain')
        resource
        #root.putChild('', resource.HighscoresResource(self.highscore))

        print(util.sibpath(__file__, 'content'))
        self.root = root  = static.File(util.sibpath(__file__, 'content'))
        root.putChild('api', resource.ApiResource(self.highscore))
        root.putChild('plugins', resource.PluginsResource(self.highscore))

        self.site = server.Site(root)

        port = "tcp:%d" % self.port if type(self.port) == int else self.port
        self.port_service = strports.service(port, self.site)
        self.port_service.setServiceParent(self)
Esempio n. 32
0
def makeService(config):
    """
    Create a punjab service to run
    """
    from twisted.web import server, resource, static
    from twisted.application import internet

    from . import httpb

    serviceCollection = PunjabService()

    if config['html_dir']:
        r = static.File(config['html_dir'])
    else:
        print("The html directory is needed.")
        return

    if config['white_list']:
        httpb.HttpbService.white_list = config['white_list'].split(',')

    if config['black_list']:
        httpb.HttpbService.black_list = config['black_list'].split(',')

    if config['httpb']:
        b = httpb.HttpbService(config['verbose'], config['polling'])
        if config['httpb'] == '':
            r.putChild(b'http-bind', resource.IResource(b))
        else:
            r.putChild(config['httpb'].encode('utf-8'), resource.IResource(b))

    if config['site_log_file']:
        site = server.Site(r, logPath=config['site_log_file'])
    else:
        site = server.Site(r)

    if config['strports']:
        for strport in config['strports']:
            sm = strports.service(
                strport,
                site,
            )
            sm.setServiceParent(serviceCollection)
    elif config['ssl']:
        from OpenSSL import SSL
        from punjab.ssl import OpenSSLContextFactoryChaining
        ssl_context = OpenSSLContextFactoryChaining(config['ssl_privkey'],
                                                    config['ssl_cert'],
                                                    SSL.SSLv23_METHOD,)
        sm = internet.SSLServer(int(config['port']),
                                site,
                                ssl_context,
                                backlog=int(config['verbose']))
        sm.setServiceParent(serviceCollection)
    else:
        sm = internet.TCPServer(int(config['port']), site)

        sm.setServiceParent(serviceCollection)

    serviceCollection.httpb = b
    return serviceCollection
Esempio n. 33
0
File: manhole.py Progetto: DT021/wau
def makeService(config):
    port, user, password = config['port'], config['user'], config['password']
    p = portal.Portal(
        service.Realm(
            service.Service(config["tracebacks"], config.get('namespace'))),
        [checkers.InMemoryUsernamePasswordDatabaseDontUse(**{user: password})])
    return strports.service(port, pb.PBServerFactory(p, config["tracebacks"]))
Esempio n. 34
0
    def __init__(self, basedir, node, db):
        service.MultiService.__init__(self)
        self.basedir = basedir
        self.node = node
        self.db = db

        root = Root(db)
        if node.relay:
            r = Relay()
            rapi = RelayAPI(db, node.relay)
            r.putChild("api", rapi)
            root.putChild("relay", r)
        if node.client:
            self.db.cursor().execute("DELETE FROM `webui_access_tokens`")
            self.db.commit()
            c = Control(db)
            capi = API(c, db, node.client)
            c.putChild("api", capi)
            client_events = Events(c, db, node.client)
            c.putChild("events", client_events)
            root.putChild("control", c)

        site = server.Site(root)
        webport = str(node.get_node_config("webport"))
        self.port_service = strports.service(webport, site)
        self.port_service.setServiceParent(self)
Esempio n. 35
0
    def buildServer(self, webport, nodeurl_path, staticdir):
        self.webport = webport
        self.site = site = appserver.NevowSite(self.root)
        self.site.requestFactory = MyRequest
        self.site.remember(MyExceptionHandler(), inevow.ICanHandleException)
        self.staticdir = staticdir  # so tests can check
        if staticdir:
            self.root.putChild("static", static.File(staticdir))
        if re.search(r'^\d', webport):
            webport = "tcp:" + webport  # twisted warns about bare "0" or "3456"
        s = strports.service(webport, site)
        s.setServiceParent(self)

        self._scheme = None
        self._portnum = None
        self._url = None
        self._listener = s  # stash it so we can query for the portnum

        self._started = defer.Deferred()
        if nodeurl_path:

            def _write_nodeurl_file(ign):
                # this file will be created with default permissions
                line = self.getURL() + "\n"
                fileutil.write_atomically(nodeurl_path, line, mode="")

            self._started.addCallback(_write_nodeurl_file)
Esempio n. 36
0
 def setupWebsocket(self, status):
     from txws import WebSocketFactory
     f = Factory()
     f.protocol = websocketstatus.WSBuildHandler
     f.status = status
     service = strports.service(self.dashboard, WebSocketFactory(f))
     service.setServiceParent(self)
 def makeService(self, options):
     root = resource.Resource()
     fname = pkg_resources.resource_filename("static_server", "a_file.html")
     static_resource = static.File(fname)
     root.putChild('', static_resource)
     site = server.Site(root)
     return strports.service('tcp:8000', site)
Esempio n. 38
0
    def __init__(self, client, accountfile, accounturl, ftp_portstr):
        service.MultiService.__init__(self)

        # make sure we're using a patched Twisted that uses IWriteFile.close:
        # see docs/frontends/FTP-and-SFTP.txt and
        # http://twistedmatrix.com/trac/ticket/3462 for details.
        if "close" not in ftp.IWriteFile.names():
            raise AssertionError("your twisted is lacking a vital patch, see docs/frontends/FTP-and-SFTP.txt")

        r = Dispatcher(client)
        p = portal.Portal(r)

        if accountfile:
            c = AccountFileChecker(self, accountfile)
            p.registerChecker(c)
        if accounturl:
            c = AccountURLChecker(self, accounturl)
            p.registerChecker(c)
        if not accountfile and not accounturl:
            # we could leave this anonymous, with just the /uri/CAP form
            raise NeedRootcapLookupScheme("must provide some translation")

        f = ftp.FTPFactory(p)
        s = strports.service(ftp_portstr, f)
        s.setServiceParent(self)
Esempio n. 39
0
    def buildServer(self, webport, nodeurl_path, staticdir):
        self.webport = webport
        self.site = site = appserver.NevowSite(self.root)
        self.site.requestFactory = MyRequest
        self.site.remember(MyExceptionHandler(), inevow.ICanHandleException)
        self.staticdir = staticdir # so tests can check
        if staticdir:
            self.root.putChild("static", static.File(staticdir))
        if re.search(r'^\d', webport):
            webport = "tcp:"+webport # twisted warns about bare "0" or "3456"
        s = strports.service(webport, site)
        s.setServiceParent(self)

        self._scheme = None
        self._portnum = None
        self._url = None
        self._listener = s # stash it so we can query for the portnum

        self._started = defer.Deferred()
        if nodeurl_path:
            def _write_nodeurl_file(ign):
                # this file will be created with default permissions
                line = self.getURL() + "\n"
                fileutil.write_atomically(nodeurl_path, line, mode="")
            self._started.addCallback(_write_nodeurl_file)
 def makeService(self, options):
     pool = threadpool.ThreadPool(minthreads=1, maxthreads=100)
     reactor.callWhenRunning(pool.start)
     reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
     root = wsgi.WSGIResource(reactor, pool, wsgi_hello.application)
     site = server.Site(root)
     return strports.service('tcp:8000', site)
def main(reactor):
    parser = argparse.ArgumentParser()
    parser.add_argument("--farm-os-url",
                        help="The url for connecting to FarmOS",
                        type=str,
                        default='http://localhost:80')
    parser.add_argument("--proxy-spec",
                        help="The specification for hosting the proxy port",
                        type=str,
                        default='tcp:5707')
    args = parser.parse_args()

    log.startLogging(sys.stdout)

    application = service.Application('FarmOsAreaFeatureProxy', uid=1, gid=1)

    service_collection = service.IServiceCollection(application)

    site = server.Site(WfsResource(FarmOsProxyFeatureServer(args.farm_os_url)))

    svc = strports.service(args.proxy_spec, site)
    svc.setServiceParent(service_collection)

    try:
        svc.startService()
        reactor.run()
    finally:
        svc.stopService()
Esempio n. 42
0
    def __init__(self, port, checker, using_ssh=True):
        service.MultiService.__init__(self)
        if type(port) is int:
            port = 'tcp:%d' % port
        self.port = port
        self.checker = checker

        def makeNamespace():
            namespace = dict(consoleNamespace)
            return namespace

        def makeProtocol():
            namespace = makeNamespace()
            p = insults.ServerProtocol(FriendlyManhole, namespace)
            return p

        if using_ssh:
            r = manhole_ssh.TerminalRealm()
            r.chainedProtocolFactory = makeProtocol
            p = portal.Portal(r, [self.checker])
            f = manhole_ssh.ConchFactory(p)
        else:
            r = _TelnetRealm(makeNamespace)
            p = portal.Portal(r, [self.checker])
            f = protocol.ServerFactory()
            f.protocol = makeTelnetProtocol(p)

        s = strports.service(self.port, f)
        s.setServiceParent(self)
Esempio n. 43
0
def makeService(config):
    s = MultiService()


    # ZipkinTracer(
    #     scribe_client,
    #     category=None,
    #     end_annotations=None,
    #     max_traces=50,
    #     max_idle_time=10,
    #     _reactor=None)
    push_tracer(
        ZipkinTracer(
            ScribeClient(clientFromString(reactor, config['scribe'])), 'zipkin', None, 10, 10, None))

    root = RootResource()

    # if config['rproxy']:
    #     root = RProxyWrapper(root)

    site = server.Site(root)
    site.displayTracebacks = False

    api_service = strports.service(config['port'], site)
    api_service.setServiceParent(s)

    return s
Esempio n. 44
0
    def makeService(self, options):
        """
        Prepare a control socket.
        """

        from vncap.control import ControlFactory
        return service(options["control"], ControlFactory())
Esempio n. 45
0
def makeService(config):
    s = service.MultiService()
    if config['root']:
        root = config['root']
        if config['indexes']:
            config['root'].indexNames = config['indexes']
    else:
        # This really ought to be web.Admin or something
        root = demo.Test()

    if isinstance(root, static.File):
        root.registry.setComponent(interfaces.IServiceCollection, s)

    if config['extraHeaders']:
        root = _AddHeadersResource(root, config['extraHeaders'])

    if config['logfile']:
        site = server.Site(root, logPath=config['logfile'])
    else:
        site = server.Site(root)

    site.displayTracebacks = not config["notracebacks"]

    if config['personal']:
        site = makePersonalServerFactory(site)
    for port in config['ports']:
        svc = strports.service(port, site)
        svc.setServiceParent(s)
    return s
Esempio n. 46
0
def makeService(config):
    s = MultiService()

    # ZipkinTracer(
    #     scribe_client,
    #     category=None,
    #     end_annotations=None,
    #     max_traces=50,
    #     max_idle_time=10,
    #     _reactor=None)
    push_tracer(
        ZipkinTracer(ScribeClient(clientFromString(reactor, config['scribe'])),
                     'zipkin', None, 10, 10, None))

    root = RootResource()

    # if config['rproxy']:
    #     root = RProxyWrapper(root)

    site = server.Site(root)
    site.displayTracebacks = False

    api_service = strports.service(config['port'], site)
    api_service.setServiceParent(s)

    return s
Esempio n. 47
0
    def __init__(self, config):
        MultiService.__init__(self)
        import os
        from bouser.utils import safe_traverse

        from twisted.internet import reactor
        from twisted.application import strports
        from bouser.web.resource import DefaultRootResource
        from bouser.web.site import BouserSite
        from bouser.proxied_logger import proxiedLogFormatter

        root_resource = DefaultRootResource()
        current_dir = os.path.dirname(__file__)
        site = BouserSite(
            root_resource,
            static_path=safe_traverse(config, 'static-path', default=os.path.join(current_dir, 'static')),
            template_path=safe_traverse(config, 'template-path', default=os.path.join(current_dir, 'templates')),
            logFormatter=proxiedLogFormatter)

        description = config.get('strport', 'tcp:%s:interface=%s' % (
            config.get('port', 5000),
            config.get('host', '127.0.0.1')
        ))

        self.cors_domain = config.get('cors-domain', 'http://127.0.0.1:5000/')
        allowed_domains = set(filter(None, config.get('allowed-domains', '').replace(',', ' ').split(' ')))
        self.allowed_domains = set(allowed_domains) | {self.cors_domain}

        service = strports.service(description, site, reactor=reactor)
        service.setServiceParent(self)

        self.root_resource = root_resource
        self.site = site
        self.service = service
Esempio n. 48
0
def makeService(config):
    s = tap.makeService(config)

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

    # Set up XMPP bot
    botClient, botInstance = bot.getBot(config['botjid'], config['botpass'], True)
    botClient.setServiceParent(s)

    # Set up XMLRPC service
    xmlrpc = idavoll_xmlrpc.XMLRPC(bs, config['jid'], botInstance)
    site = server.Site(xmlrpc)
    w = internet.TCPServer(int(config['rpcport']), site, interface='localhost')
    w.setServiceParent(s)

    # Set up a manhole
    namespace = {'service': s,
                 'component': cs,
                 'backend': bs,
                 'xmlrpc': xmlrpc,
		 'bot': botInstance}

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

    return s
Esempio n. 49
0
    def __init__(self, client, accountfile, accounturl, ftp_portstr):
        service.MultiService.__init__(self)

        # make sure we're using a patched Twisted that uses IWriteFile.close:
        # see docs/frontends/FTP-and-SFTP.txt and
        # http://twistedmatrix.com/trac/ticket/3462 for details.
        if "close" not in ftp.IWriteFile.names():
            raise AssertionError(
                "your twisted is lacking a vital patch, see docs/frontends/FTP-and-SFTP.txt"
            )

        r = Dispatcher(client)
        p = portal.Portal(r)

        if accountfile:
            c = AccountFileChecker(self, accountfile)
            p.registerChecker(c)
        if accounturl:
            c = AccountURLChecker(self, accounturl)
            p.registerChecker(c)
        if not accountfile and not accounturl:
            # we could leave this anonymous, with just the /uri/CAP form
            raise NeedRootcapLookupScheme("must provide some translation")

        f = ftp.FTPFactory(p)
        s = strports.service(ftp_portstr, f)
        s.setServiceParent(self)
Esempio n. 50
0
def createQueue(port=8787,
                name=None,
                app=None,
                consumers=[],
                timerStep=1000,
                withRss=False,
                rssPort=6666):
    assert name is not None
    assert app is not None
    assert len(consumers) > 0

    queueModel = __getQueue(name)
    scheduler = JobScheduler(queueModel)

    for chost, cport in consumers:
        scheduler.addConsumer(TwistedJobConsumer(chost, cport))

    queue = internet.TCPServer(port, QueueFactory(scheduler))
    queue.setServiceParent(app)
    timer = internet.TimerService(timerStep, scheduler.dispatchPending)
    timer.setServiceParent(app)

    if (withRss):
        site = server.Site(ErrorRssResource())
        rss = strports.service('tcp:%s' % str(rssPort),
                               channel.HTTPFactory(site))
        rss.setServiceParent(app)
Esempio n. 51
0
    def hookTransport(self, transport, config):
        '''Create a L{twisted.application.internet.Service} for a transport

        Given a transport and some configuration data, a
        L{twisted.application.internet.Service} object is created to actually
        run a server.

        @param transport: Transport to hook to the service
        @type transport: twisted.internet.protocol.ServerFactory
        @param config: Service configuration data
        @type config: dict<string, string>

        @returns: A service exposing the transport on a configured channel
        @rtype: twisted.internet.interfaces.IListeningPort
        '''
        # Get the configuration string
        # This is something like
        #
        #     tcp:8080:interface=127.0.0.1
        #
        # See the documentation of L{twisted.application.strports} for an
        # overview
        port = config['transport']

        log.msg('[CONTROLLER] Hooking transport on %s' % port)

        # Let Twisted create a service from our transport based on the
        # transport configuration string
        return strports.service(port, transport)
Esempio n. 52
0
def makeService(config):
	from twisted.internet import reactor, task

	multi = service.MultiService()

	site = coreweb_site.makeSite(
		reactor, FilePath(config['closure-library']))
	site.displayTracebacks = not config["notracebacks"]

	for httpStrport in config['http']:
		httpServer = strports.service(httpStrport, site)
		httpServer.setServiceParent(multi)

	doReloading = bool(int(os.environ.get('PYRELOADING', '0')))
	if doReloading:
		print 'Enabling reloader.'
		from pyquitter import detector

		cd = detector.ChangeDetector(
			lambda: reactor.callWhenRunning(reactor.stop),
			logCallable=log.msg)

		looping = task.LoopingCall(cd.poll)
		looping.start(2.5, now=True)

	return multi
Esempio n. 53
0
    def buildServer(self, webport, nodeurl_path, staticdir):
        self.webport = webport
        self.site = tahoe_lafs_site(self.root)
        self.staticdir = staticdir  # so tests can check
        if staticdir:
            self.root.putChild("static", static.File(staticdir))
        if re.search(r'^\d', webport):
            webport = "tcp:" + webport  # twisted warns about bare "0" or "3456"
        # strports must be native strings.
        webport = ensure_str(webport)
        s = strports.service(webport, self.site)
        s.setServiceParent(self)

        self._scheme = None
        self._portnum = None
        self._url = None
        self._listener = s  # stash it so we can query for the portnum

        self._started = defer.Deferred()
        if nodeurl_path:

            def _write_nodeurl_file(ign):
                # this file will be created with default permissions
                line = self.getURL() + "\n"
                fileutil.write_atomically(nodeurl_path, line, mode="")

            self._started.addCallback(_write_nodeurl_file)
Esempio n. 54
0
    def reconfigServiceWithBuildbotConfig(self, new_config):
        www = new_config.www

        self.authz = www.get('authz')
        if self.authz is not None:
            self.authz.setMaster(self.master)
        need_new_site = False
        if self.site:
            # if config params have changed, set need_new_site to True.
            # There are none right now.
            need_new_site = False
        else:
            if www['port']:
                need_new_site = True

        if need_new_site:
            self.setupSite(new_config)

        if self.site:
            self.reconfigSite(new_config)
            yield self.makeSessionSecret()

        if www['port'] != self.port:
            if self.port_service:
                yield defer.maybeDeferred(
                    self.port_service.disownServiceParent)
                self.port_service = None

            self.port = www['port']
            if self.port:
                port = self.port
                if isinstance(port, int):
                    port = "tcp:%d" % port
                self.port_service = strports.service(port, self.site)

                # monkey-patch in some code to get the actual Port object
                # returned by endpoint.listen().  But only for tests.
                if port == "tcp:0:interface=127.0.0.1":
                    if hasattr(self.port_service, 'endpoint'):
                        old_listen = self.port_service.endpoint.listen

                        @defer.inlineCallbacks
                        def listen(factory):
                            port = yield old_listen(factory)
                            self._getPort = lambda: port
                            defer.returnValue(port)

                        self.port_service.endpoint.listen = listen
                    else:
                        # older twisted's just have the port sitting there
                        # as an instance attribute
                        self._getPort = lambda: self.port_service._port

                yield self.port_service.setServiceParent(self)

        if not self.port_service:
            log.msg("No web server configured on this master")

        yield service.ReconfigurableServiceMixin.reconfigServiceWithBuildbotConfig(
            self, new_config)
Esempio n. 55
0
def makeService(config):
    port, user, password = config['port'], config['user'], config['password']
    p = portal.Portal(
        service.Realm(service.Service(config["tracebacks"], config.get('namespace'))),
        [checkers.InMemoryUsernamePasswordDatabaseDontUse(**{user: password})]
    )
    return strports.service(port, pb.PBServerFactory(p, config["tracebacks"]))
Esempio n. 56
0
def makeService(config):
    if config['passwd']:
        credCheckers = [checkers.FilePasswordDB(config['passwd'], cache=True)]
    elif config['checkers']:
        credCheckers = config['checkers']
    else:
        credCheckers = []

    wordsRealm = service.InMemoryWordsRealm(config['hostname'])
    wordsPortal = portal.Portal(wordsRealm, credCheckers)

    msvc = MultiService()

    # XXX Attribute lookup on config is kind of bad - hrm.
    for plgName in config.interfacePlugins:
        port = config.get(plgName + '-port')
        if port is not None:
            factory = config.interfacePlugins[plgName].getFactory(wordsRealm, wordsPortal)
            svc = strports.service(port, factory)
            svc.setServiceParent(msvc)

    # This is bogus.  createGroup is async.  makeService must be
    # allowed to return a Deferred or some crap.
    for g in config['groups']:
        wordsRealm.createGroup(g)

    return msvc
Esempio n. 57
0
    def hookTransport(self, transport, config):
        '''Create a L{twisted.application.internet.Service} for a transport

        Given a transport and some configuration data, a
        L{twisted.application.internet.Service} object is created to actually
        run a server.

        @param transport: Transport to hook to the service
        @type transport: twisted.internet.protocol.ServerFactory
        @param config: Service configuration data
        @type config: dict<string, string>

        @returns: A service exposing the transport on a configured channel
        @rtype: twisted.internet.interfaces.IListeningPort
        '''
        # Get the configuration string
        # This is something like
        #
        #     tcp:8080:interface=127.0.0.1
        #
        # See the documentation of L{twisted.application.strports} for an
        # overview
        port = config['transport']

        log.msg('[CONTROLLER] Hooking transport on %s' % port)

        # Let Twisted create a service from our transport based on the
        # transport configuration string
        return strports.service(port, transport)