Ejemplo n.º 1
0
 def __init__(self, relayport, transitport, advertise_version,
              db_url=":memory:", blur_usage=None):
     service.MultiService.__init__(self)
     self._blur_usage = blur_usage
     self.db = get_db(db_url)
     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 = PrivacyEnhancedSite(self.root)
     if blur_usage:
         site.logRequests = False
     r = endpoints.serverFromString(reactor, relayport)
     self.relayport_service = ServerEndpointService(r, site)
     self.relayport_service.setServiceParent(self)
     self.relay = Relay(self.db, welcome, blur_usage) # accessible from tests
     self.root.putChild(b"wormhole-relay", self.relay)
     if transitport:
         self.transit = Transit(self.db, blur_usage)
         self.transit.setServiceParent(self) # for the timer
         t = endpoints.serverFromString(reactor, transitport)
         self.transport_service = ServerEndpointService(t, self.transit)
         self.transport_service.setServiceParent(self)
Ejemplo n.º 2
0
def main():
    config = ConfigParser.ConfigParser()
    config.read(os.path.expanduser('~/.b07'))
    api = b07.api.API(reactor,
                      config.get('ingress', 'email'),
                      config.get('ingress', 'password'))
    

    http_root = Redirect('https://localhost:{}/'.format(config.get('server', 'https_port')))
    http_factory = Site(http_root)
    http_endpoint = endpoints.serverFromString(reactor,
                                               'tcp:{}'.format(config.get('server', 'http_port')))
    http_endpoint.listen(http_factory)

    https_root = File(os.path.expanduser(config.get('server', 'web_root')))
    https_root.indexNames = ['index.html']
    https_factory = Site(https_root)
    https_endpoint = endpoints.serverFromString(reactor,
                                                'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'https_port'),
                                                                                         os.path.expanduser(config.get('server', 'ssl_key')),
                                                                                         os.path.expanduser(config.get('server', 'ssl_cert'))))
    https_endpoint.listen(https_factory)

    wsfactory = Factory()
    wsfactory.protocol = WebSocketProtocol
    wss_endpoint = endpoints.serverFromString(reactor,
                                              'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'wss_port'),
                                                                                       os.path.expanduser(config.get('server', 'ssl_key')),
                                                                                       os.path.expanduser(config.get('server', 'ssl_cert'))))
    wss_endpoint.listen(txws.WebSocketFactory(wsfactory))



    reactor.run()
Ejemplo n.º 3
0
 def __init__(self, reactor, cap_table, http_endpoint, ws_endpoint, root_cap, title):
     # Constants
     self.__http_endpoint_string = str(http_endpoint)
     self.__http_endpoint = endpoints.serverFromString(reactor, self.__http_endpoint_string)
     self.__ws_endpoint = endpoints.serverFromString(reactor, str(ws_endpoint))
     self.__visit_path = _make_cap_url(root_cap)
     
     wcommon = WebServiceCommon(
         reactor=reactor,
         title=title,
         ws_endpoint_string=ws_endpoint)
     # TODO: Create poller actually for the given reactor w/o redundancy -- perhaps there should be a one-poller-per-reactor map
     subscription_context = SubscriptionContext(reactor=reactor, poller=the_poller)
     
     def resource_factory(entry_point):
         # TODO: If not an IWebEntryPoint, return a generic result
         return IWebEntryPoint(entry_point).get_entry_point_resource(wcommon=wcommon)  # pylint: disable=redundant-keyword-arg
     
     server_root = CapAccessResource(cap_table=cap_table, resource_factory=resource_factory)
     _put_root_static(wcommon, server_root)
     
     if UNIQUE_PUBLIC_CAP in cap_table:
         # TODO: consider factoring out "generate URL for cap"
         server_root.putChild('', Redirect(_make_cap_url(UNIQUE_PUBLIC_CAP)))
         
     self.__ws_protocol = txws.WebSocketFactory(
         FactoryWithArgs.forProtocol(OurStreamProtocol, cap_table, subscription_context))
     self.__site = _SiteWithHeaders(server_root)
     
     self.__ws_port_obj = None
     self.__http_port_obj = None
Ejemplo n.º 4
0
def main():
        
    log.startLogging(sys.stdout)

    startPort = 3000

    lastServerEndpoint = 'tcp:interface=127.0.0.1:%s' % startPort
    torAgent = TorAgent(reactor)
    serverEndpoint = serverFromString(reactor, lastServerEndpoint)
    connectDeferred = serverEndpoint.listen(AgentProxyFactory(torAgent))

    endpoint = []
    agent = []
    for x in range(10):
        endpoint = clientFromString(reactor, "tcp:127.0.0.1:%s" % (startPort + x))
        proxyAgent = ProxyAgent(endpoint)
        serverEndpoint = serverFromString(reactor, "tcp:interface=127.0.0.1:%s" % (startPort + x + 1))
        
        connectDeferred = serverEndpoint.listen(AgentProxyFactory(proxyAgent))


    # XXX
    def clientConnectionFailed(factory, reason):
        log.err(reason)
        log.err("httpTorProxy: clientConnectionFailed")

    connectDeferred.addErrback(clientConnectionFailed)


    reactor.run()
Ejemplo n.º 5
0
def coerce_to_server_endpoint(reactor, ep_descr):
    """Given a string, attempt to produce a server endpoint.

    If the string describes an endpoint directly, we use that; otherwise,
    assume it's an attempt to provide a TCP endpoint and try variations on
    that in the hope that one is parseable.

    Parameters
    ----------
    reactor : `implements twisted.internet.interfaces.IReactorCore`
        Twisted reactor to use in constructing endpoint.
    ep_descr : `str`
        String describing the desired endpoint.
    """
    try:
        # Maybe this already is a valid endpoint.
        return serverFromString(reactor, ep_descr)
    except (ValueError, TypeError):
        pass
    try:
        # Assume it just needs "tcp:" prepended.
        return serverFromString(reactor, f"tcp:{ep_descr}")
    except (ValueError, TypeError):
        # At this point, we'll give up, and go back to the original bad parse.
        serverFromString(reactor, ep_descr)
Ejemplo n.º 6
0
    def postOptions(self):
        strport = self['strport']
        factoryIdentifier = self['factory-identifier']
        if strport is None or factoryIdentifier is None:
            self.opt_help()

        store = self.parent.parent.getStore()
        storeID = int(factoryIdentifier)
        try:
            factory = store.getItemByID(storeID)
        except KeyError:
            print "%d does not identify an item." % (storeID,)
            raise SystemExit(1)
        else:
            if not IProtocolFactoryFactory.providedBy(factory):
                print "%d does not identify a factory." % (storeID,)
                raise SystemExit(1)
            else:
                description = self.decodeCommandLine(strport)
                try:
                    serverFromString(reactor, description.encode('ascii'))
                except ValueError:
                    print "%r is not a valid port description." % (strport,)
                    raise SystemExit(1)
                port = StringEndpointPort(
                    store=store, description=description, factory=factory)
                installOn(port, store)
                print "Created."
        raise SystemExit(0)
Ejemplo n.º 7
0
    def main(self, reactor, options):
        certificates_path = FilePath(options["certificates-directory"])
        ca = Certificate.loadPEM(
            certificates_path.child(b"cluster.crt").getContent())
        # This is a hack; from_path should be more
        # flexible. https://clusterhq.atlassian.net/browse/FLOC-1865
        control_credential = ControlCredential.from_path(
            certificates_path, b"service")

        top_service = MultiService()
        persistence = ConfigurationPersistenceService(
            reactor, options["data-path"])
        persistence.setServiceParent(top_service)
        cluster_state = ClusterStateService(reactor)
        cluster_state.setServiceParent(top_service)
        api_service = create_api_service(
            persistence, cluster_state, serverFromString(
                reactor, options["port"]),
            rest_api_context_factory(ca, control_credential))
        api_service.setServiceParent(top_service)
        amp_service = ControlAMPService(
            reactor, cluster_state, persistence, serverFromString(
                reactor, options["agent-port"]),
            amp_server_context_factory(ca, control_credential))
        amp_service.setServiceParent(top_service)
        return main_for_service(reactor, top_service)
Ejemplo n.º 8
0
 def __init__(self, reactor, cap_table, read_only_dbs, writable_db, http_endpoint, ws_endpoint, root_cap, title, flowgraph_for_debug):
     # Constants
     self.__http_endpoint_string = http_endpoint
     self.__http_endpoint = endpoints.serverFromString(reactor, http_endpoint)
     self.__ws_endpoint = endpoints.serverFromString(reactor, ws_endpoint)
     self.__visit_path = _make_cap_url(root_cap)
     
     wcommon = WebServiceCommon(ws_endpoint_string=ws_endpoint)
     
     def BoundSessionResource(session):
         return SessionResource(session, wcommon, reactor, title, read_only_dbs, writable_db, flowgraph_for_debug)
     
     server_root = CapAccessResource(cap_table=cap_table, resource_ctor=BoundSessionResource)
     _put_root_static(server_root)
     
     if UNIQUE_PUBLIC_CAP in cap_table:
         # TODO: consider factoring out "generate URL for cap"
         server_root.putChild('', Redirect(_make_cap_url(UNIQUE_PUBLIC_CAP)))
         
     self.__ws_protocol = txws.WebSocketFactory(
         FactoryWithArgs.forProtocol(OurStreamProtocol, cap_table))
     self.__site = _SiteWithHeaders(server_root)
     
     self.__ws_port_obj = None
     self.__http_port_obj = None
Ejemplo n.º 9
0
def main():
    options = docopt.docopt(__doc__)
    port = int(options['<port>'])
    rate = float(options['<rate>'])
    label = options['<label>']

    endpoints.serverFromString(reactor, "tcp:%d" % port).listen(SampleFactory(rate, label))
    reactor.run()
Ejemplo n.º 10
0
 def born(self, data):
     """Method initiate TCL and UDP listeners."""
     lc = LoopingCall(get_metrics, None)
     lc.start(2)
     reactor.listenUDP(self.UDP_PORT, NotificationUDPProcessor())
     reactor.listenMulticast(self.MULTICAST_PORT,
                             MunticastNotificationProcessor(self.MULTICAST_IP), # add multicast 'born' processing
                             listenMultiple=True)
     endpoints.serverFromString(reactor, "tcp:21999").listen(EchoFactory())
Ejemplo n.º 11
0
    def do_listen(self, addr):
        if not hasattr(self, "isClient") or not self.isClient:
            self.isClient = False
        else:
            self.error("this is a client, doesn't support listen")
            return

        self._readHistoryFile('.peagunServer')
        serverFromString(reactor, addr).listen(self.connectionManager)
Ejemplo n.º 12
0
def start():
    game = MultisnakeServer()

    server_update = task.LoopingCall(game.update)
    server_update.start(1.0)

    endpoints.serverFromString(reactor, "tcp:1234").listen(PlayerConnectionFactory(game))

    reactor.run()
Ejemplo n.º 13
0
    def __init__(self, rendezvous_web_port, transit_port,
                 advertise_version, db_url=":memory:", blur_usage=None,
                 signal_error=None):
        service.MultiService.__init__(self)
        self._blur_usage = blur_usage

        db = get_db(db_url)
        welcome = {
            # The primary (python CLI) implementation will emit a message if
            # its version does not match this key. If/when we have
            # distributions which include older version, but we still expect
            # them to be compatible, stop sending this key.
            "current_cli_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_cli_version"] = advertise_version
        if signal_error:
            welcome["error"] = signal_error

        rendezvous = Rendezvous(db, welcome, blur_usage)
        rendezvous.setServiceParent(self) # for the pruning timer

        root = Root()
        wsrf = WebSocketRendezvousFactory(None, rendezvous)
        root.putChild(b"v1", WebSocketResource(wsrf))

        site = PrivacyEnhancedSite(root)
        if blur_usage:
            site.logRequests = False

        r = endpoints.serverFromString(reactor, rendezvous_web_port)
        rendezvous_web_service = ServerEndpointService(r, site)
        rendezvous_web_service.setServiceParent(self)

        if transit_port:
            transit = Transit(db, blur_usage)
            transit.setServiceParent(self) # for the timer
            t = endpoints.serverFromString(reactor, transit_port)
            transit_service = ServerEndpointService(t, transit)
            transit_service.setServiceParent(self)

        # make some things accessible for tests
        self._db = db
        self._rendezvous = rendezvous
        self._root = root
        self._rendezvous_web_service = rendezvous_web_service
        self._rendezvous_websocket = wsrf
        if transit_port:
            self._transit = transit
            self._transit_service = transit_service
Ejemplo n.º 14
0
def serve_forever(port=9999):
    """Process incoming requests from the given socket.

    :param port: The port to listen on
    :type port: int
    """
    endpoints.serverFromString(reactor, "tcp:{}".format(port)).listen(
        MemcachedProtocolFactory()
    )
    reactor.run()
Ejemplo n.º 15
0
def start_server():
    factory = KnowledgeFactory()

    endpoints.serverFromString(
        reactor, "tcp:%s" % config.SERVER_PORT).listen(factory)

    logging.info("server started on port %d", config.SERVER_PORT)
    reactor.run()
    reactor.callLater(100, reactor.stop)
    logging.info("server execution ended")
Ejemplo n.º 16
0
def main(amqp_host, max_vms, intf):
	#_install_sig_handlers()

	virt_ip = netifaces.ifaddresses('virbr2')[2][0]['addr']
	endpoints.serverFromString(reactor, "tcp:55555:interface={}".format(virt_ip)).listen(GuestCommsFactory())

	slave = Slave.instance(amqp_host, max_vms, intf)
	reactor.callWhenRunning(slave.start)
	reactor.addSystemEventTrigger("during", "shutdown", Slave.instance().stop)
	reactor.run()
Ejemplo n.º 17
0
def create_endpoint_services(reactor, parent, listen_endpoints, factory):
    for listen_endpoint in listen_endpoints:

        # work around http://twistedmatrix.com/trac/ticket/8422
        if sys.version_info.major < 3:
            endpoint = endpoints.serverFromString(reactor, listen_endpoint.encode('utf-8'))
        else:
            endpoint = endpoints.serverFromString(reactor, listen_endpoint)

        service = internet.StreamServerEndpointService(endpoint, factory)
        # FIXME: Use addService on parent ?
        service.setServiceParent(parent)
Ejemplo n.º 18
0
def start_http():
    #http in reactor
    root = Resource()
    root.putChild("register", RegisterHTTP())
    root.putChild("data", ICBCHTTP())

    endpoints.serverFromString(reactor, "tcp:8000").listen(server.Site(root))
    #tcp in reactor
    ICBCEndpoint = endpoints.serverFromString(reactor, "tcp:8800")
    ICBCEndpoint.listen(ICBCFactory())
    #start the reactor
    reactor.run(installSignalHandlers=0)
Ejemplo n.º 19
0
 def startService(self):
     if self.port_s is not None:
         endpoint = serverFromString(reactor, self.port_s)
         d = endpoint.listen(self.site)
         d.addCallback(self.register_port, 'app')
     if self.authInfoEndpointStr is not None:
         authInfoApp = AuthInfoApp()
         self.authInfoApp = authInfoApp
         authInfoSite = Site(authInfoApp.app.resource())
         endpoint = serverFromString(reactor, self.authInfoEndpointStr)
         d2 = endpoint.listen(authInfoSite)
         d2.addCallback(self.register_port, 'authInfoSite')
Ejemplo n.º 20
0
def main():
    bind_address = "0.0.0.0"
    gateway_port = 5001
    logger.debug("start gateway server(%s:%d)" % (bind_address, gateway_port))

    # reactor.listenTCP(gateway_port, GatewayFactory(), 100, bind_address)
    endpoints.serverFromString(reactor, "tcp:%d" % gateway_port).listen(GatewayFactory())

    try:
        reactor.run()
    except KeyboardInterrupt:
        logger.error("stop gateway server")
Ejemplo n.º 21
0
def start_reactor():
    cp = ConfigParser.SafeConfigParser()
    cp.read('config\config.ini')
    #http in reactor
    root = Resource()
    root.putChild("data", ICBCHTTP())
    endpoints.serverFromString(reactor, "tcp:" + str(cp.get('server', 'http_server_port'))).listen(server.Site(root))
    #tcp in reactor
    ICBCEndpoint = endpoints.serverFromString(reactor, "tcp:" + str(cp.get('server', 'tcp_server_port')))
    ICBCEndpoint.listen(ICBCFactory())
    #start the reactor
    logger.info("Reactor has started.")
    reactor.run(installSignalHandlers=0)
Ejemplo n.º 22
0
    def initialize(self):
        print ('Initializing the world...')

        # Accept new players.
        endpoints.serverFromString(reactor, "tcp:8799").listen(WorldSessionFactory(self))

        # Start the heartbeat
        self.heartbeat.start(self.heartbeat_delay)

        # Call the CLI handler.
        reactor.callInThread(self.CLI)

        print ('World initialized.')
Ejemplo n.º 23
0
 def startService(self):
     debug = self.debug
     factory = Balancer(self.hostports, self.netmap)
     factory.debug = debug
     admin_portal = self.admin_portal
     admin_endpoint = self.admin_endpoint
     if admin_portal is not None and admin_endpoint is not None:
         admin_service, admin_website = make_ws(admin_portal, factory)
         ep = serverFromString(reactor, admin_endpoint)
         d0 = ep.listen(admin_service)
         d0.addCallback(self.set_listening_port, port_type='admin')            
     ep = serverFromString(reactor, self.endpoint)
     d = ep.listen(factory)
     d.addCallback(self.set_listening_port, port_type='proxy')
Ejemplo n.º 24
0
def main(reactor, server_endpoint_string, handoff_endpoint_string):
    logger.globalLogBeginner.beginLoggingTo(
        [logger.textFileLogObserver(sys.stderr)])
    server_endpoint = endpoints.serverFromString(
        reactor, server_endpoint_string)
    server_port = yield server_endpoint.listen(AlwaysAbortFactory())
    handoff_factory = HandoffFactory(server_port,
                                     describe_socket(server_port.socket))
    reactor.removeReader(server_port)

    handoff_endpoint = endpoints.serverFromString(
        reactor, handoff_endpoint_string)
    yield handoff_endpoint.listen(handoff_factory)
    yield defer.Deferred()
Ejemplo n.º 25
0
 def main(self, reactor, options):
     top_service = MultiService()
     persistence = ConfigurationPersistenceService(
         reactor, options["data-path"])
     persistence.setServiceParent(top_service)
     cluster_state = ClusterStateService()
     cluster_state.setServiceParent(top_service)
     create_api_service(persistence, cluster_state, serverFromString(
         reactor, options["port"])).setServiceParent(top_service)
     amp_service = ControlAMPService(
         cluster_state, persistence, serverFromString(
             reactor, options["agent-port"]))
     amp_service.setServiceParent(top_service)
     return main_for_service(reactor, top_service)
def setup_module(module):
    """ setup any state specific to the execution of the given module."""
    
    global b_handler, a_handler, t
    # blueflood server mock
    b_handler = http_server_mock.MockServerHandler()
    # auth server mock
    a_handler = http_server_mock.MockServerHandler()

    endpoints.serverFromString(reactor, "tcp:8000").listen(server.Site(b_handler))
    endpoints.serverFromString(reactor, "tcp:8001").listen(server.Site(a_handler))

    t = threading.Thread(target=reactor.run, args=(0, ))
    t.daemon = True
    t.start()
Ejemplo n.º 27
0
 def run(self):
     logger.info("Twisted " + self.getName() + " Start Running")
     # http in reactor
     root = Resource()
     root.putChild("data", ICBCHTTP())
     root.putChild("register", RegisterHTTP())
     endpoints.serverFromString(reactor, "tcp:" + self.http_port).listen(server.Site(root))
     logger.info("HTTP Server listen on port: " + self.http_port)
     # tcp in reactor
     ICBCEndpoint = endpoints.serverFromString(reactor, "tcp:" + self.tcp_port)
     ICBCEndpoint.listen(ICBCFactory())
     logger.info("TCP Server listen on port: " + self.tcp_port)
     # start the reactor
     logger.info("Reactor has started.")
     reactor.run(installSignalHandlers=0)
Ejemplo n.º 28
0
 def clean(self, value):
     from twisted.internet.endpoints import serverFromString
     from twisted.internet import reactor
     try:
         return serverFromString(reactor, value)
     except ValueError:
         self.raise_config_error('is not a valid server endpoint')
Ejemplo n.º 29
0
    def test_parse_relative_path(self):
        # this makes sure we convert a relative path to absolute
        # hiddenServiceDir args. see Issue #77

        # make sure we have a valid thing from get_global_tor without
        # actually launching tor
        config = TorConfig()
        config.post_bootstrap = defer.succeed(config)
        from txtorcon import torconfig
        torconfig._global_tor_config = None
        get_global_tor(
            self.reactor,
            _tor_launcher=lambda react, config, prog: defer.succeed(config)
        )

        orig = os.path.realpath('.')
        try:
            with util.TempDir() as t:
                t = str(t)
                os.chdir(t)
                os.mkdir(os.path.join(t, 'foo'))
                hsdir = os.path.join(t, 'foo', 'blam')
                os.mkdir(hsdir)

                ep = serverFromString(
                    self.reactor,
                    'onion:88:localPort=1234:hiddenServiceDir=foo/blam'
                )
                self.assertEqual(
                    os.path.realpath(hsdir),
                    ep.hidden_service_dir
                )

        finally:
            os.chdir(orig)
Ejemplo n.º 30
0
    def __init__(self, basedir, reactor):
        service.MultiService.__init__(self)
        self._basedir = basedir
        self._reactor = reactor

        root = Root()
        site = server.Site(root)
        ep = endpoints.serverFromString(reactor, "tcp:8220")
        internet.StreamServerEndpointService(ep, site).setServiceParent(self)

        self._jm = journal.JournalManager(self._save_state)

        root.putChild(b"", static.Data("root", "text/plain"))
        root.putChild(b"list-invitations", Status(self._list_invitations))
        root.putChild(b"invite", Action(self._invite)) # {petname:}
        root.putChild(b"accept", Action(self._accept)) # {petname:, code:}

        self._state_fn = os.path.join(self._basedir, "state.json")
        self._state = State.from_filename(self._state_fn)

        self._wormholes = {}
        for iid, invitation_state in self._state.get_all_invitations().items():
            def _dispatch(event, *args, **kwargs):
                self._dispatch_wormhole_event(iid, event, *args, **kwargs)
            w = wormhole.journaled_from_data(invitation_state["wormhole"],
                                             reactor=self._reactor,
                                             journal=self._jm,
                                             event_handler=self,
                                             event_handler_args=(iid,))
            self._wormholes[iid] = w
            w.setServiceParent(self)
Ejemplo n.º 31
0
    def onJoin(self, details):
        # regs = []
        yield self.register(rpc_bdata, u'ru.bustime.rpc_bdata')
        yield self.register(rpc_passenger, u'ru.bustime.rpc_passenger')
        # mobile support only
        yield self.register(rpc_bootstrap_amounts,
                            u'ru.bustime.rpc_bootstrap_amounts')
        yield self.register(rpc_tcard, u'ru.bustime.rpc_tcard')
        yield self.register(rpc_stop_ids, u'ru.bustime.rpc_stop_ids')


def accept(offers):
    for offer in offers:
        if isinstance(offer, PerMessageDeflateOffer):
            return PerMessageDeflateOfferAccept(offer)


if __name__ == '__main__':
    router_factory = wamp.RouterFactory()
    session_factory = wamp.RouterSessionFactory(router_factory)
    component_config = types.ComponentConfig(realm="realm1")
    component_session = MyBackendComponent(component_config)
    session_factory.add(component_session)

    transport_factory = websocket.WampWebSocketServerFactory(session_factory,
                                                             debug=False,
                                                             debug_wamp=False)
    server = serverFromString(reactor, "tcp:%s" % PORT)
    server.listen(transport_factory)
    reactor.run()
    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        for c in self.factory.clients:
            source = u"<{}> ".format(self.transport.getHost()).encode("ascii")
            c.sendLine(source + line)


class PubFactory(protocol.Factory):
    def __init__(self):
        self.clients = set()

    def buildProtocol(self, addr):
        return PubProtocol(self)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Socket Server Example with Epoll')
    parser.add_argument('--port',
                        action="store",
                        dest="port",
                        type=int,
                        required=True)
    given_args = parser.parse_args()
    port = given_args.port
    endpoints.serverFromString(reactor, "tcp:%s" % port).listen(PubFactory())
    reactor.run()
Ejemplo n.º 33
0
                        action="store_true",
                        help="Enable debug output.")

    parser.add_argument(
        "--endpoint",
        default="tcp:8080",
        help=
        'WebSocket server Twisted endpoint descriptor, e.g. "tcp:127.0.0.1:8080" or "unix:/tmp/mywebsocket".'
    )

    parser.add_argument(
        "--url",
        default=u"ws://localhost:8080/ws",
        help=
        'WebSocket URL (must suit the endpoint), e.g. ws://localhost:8080/ws.')

    args = parser.parse_args()

    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    factory = WebSocketServerFactory(args.url, reactor=reactor)
    factory.protocol = MyServerProtocol

    server = serverFromString(reactor, args.endpoint)
    server.listen(factory)

    reactor.run()
Ejemplo n.º 34
0
    def __init__(self,
                 rendezvous_web_port,
                 transit_port,
                 advertise_version,
                 db_url=":memory:",
                 blur_usage=None,
                 signal_error=None,
                 stats_file=None,
                 allow_list=True):
        service.MultiService.__init__(self)
        self._blur_usage = blur_usage
        self._allow_list = allow_list

        db = get_db(db_url)
        welcome = {
            # The primary (python CLI) implementation will emit a message if
            # its version does not match this key. If/when we have
            # distributions which include older version, but we still expect
            # them to be compatible, stop sending this key.
            "current_cli_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_cli_version"] = advertise_version
        if signal_error:
            welcome["error"] = signal_error

        self._rendezvous = Rendezvous(db, welcome, blur_usage,
                                      self._allow_list)
        self._rendezvous.setServiceParent(self)  # for the pruning timer

        root = Root()
        wsrf = WebSocketRendezvousFactory(None, self._rendezvous)
        root.putChild(b"v1", WebSocketResource(wsrf))

        site = PrivacyEnhancedSite(root)
        if blur_usage:
            site.logRequests = False

        r = endpoints.serverFromString(reactor, rendezvous_web_port)
        rendezvous_web_service = internet.StreamServerEndpointService(r, site)
        rendezvous_web_service.setServiceParent(self)

        if transit_port:
            transit = Transit(db, blur_usage)
            transit.setServiceParent(self)  # for the timer
            t = endpoints.serverFromString(reactor, transit_port)
            transit_service = internet.StreamServerEndpointService(t, transit)
            transit_service.setServiceParent(self)

        self._stats_file = stats_file
        if self._stats_file and os.path.exists(self._stats_file):
            os.unlink(self._stats_file)
            # this will be regenerated immediately, but if something goes
            # wrong in dump_stats(), it's better to have a missing file than
            # a stale one
        t = internet.TimerService(EXPIRATION_CHECK_PERIOD, self.timer)
        t.setServiceParent(self)

        # make some things accessible for tests
        self._db = db
        self._root = root
        self._rendezvous_web_service = rendezvous_web_service
        self._rendezvous_websocket = wsrf
        self._transit = None
        if transit_port:
            self._transit = transit
            self._transit_service = transit_service
Ejemplo n.º 35
0
def create_listening_endpoint_from_config(config, cbdir, reactor, log):
    """
    Create a Twisted stream server endpoint from a Crossbar.io transport configuration.

    See: https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IStreamServerEndpoint.html

    :param config: The transport configuration.
    :type config: dict
    :param cbdir: Crossbar.io node directory (we need this for TLS key/certificates).
    :type cbdir: str
    :param reactor: The reactor to use for endpoint creation.
    :type reactor: obj

    :returns obj -- An instance implementing IStreamServerEndpoint
    """
    endpoint = None

    # a TCP endpoint
    #
    if config['type'] == 'tcp':

        # the TCP protocol version (v4 or v6)
        #
        version = int(config.get('version', 4))

        # the listening port
        if type(config['port']) is six.text_type:
            # read port from environment variable ..
            try:
                port = int(environ[config['port'][1:]])
            except Exception as e:
                log.warn("Could not read listening port from env var: {e}", e=e)
                raise
        else:
            port = config['port']

        # the listening interface
        #
        interface = str(config.get('interface', '').strip())

        # the TCP accept queue depth
        #
        backlog = int(config.get('backlog', 50))

        if 'tls' in config:
            # create a TLS server endpoint
            #
            if _HAS_TLS:
                # TLS server context
                context = _create_tls_server_context(config['tls'], cbdir, log)

                if version == 4:
                    endpoint = SSL4ServerEndpoint(reactor,
                                                  port,
                                                  context,
                                                  backlog=backlog,
                                                  interface=interface)
                elif version == 6:
                    raise Exception("TLS on IPv6 not implemented")
                else:
                    raise Exception("invalid TCP protocol version {}".format(version))
            else:
                raise Exception("TLS transport requested, but TLS packages not available:\n{}".format(_LACKS_TLS_MSG))

        else:
            # create a non-TLS server endpoint
            #
            if version == 4:
                endpoint = TCP4ServerEndpoint(reactor,
                                              port,
                                              backlog=backlog,
                                              interface=interface)
            elif version == 6:
                endpoint = TCP6ServerEndpoint(reactor,
                                              port,
                                              backlog=backlog,
                                              interface=interface)
            else:
                raise Exception("invalid TCP protocol version {}".format(version))

    # a Unix Domain Socket endpoint
    #
    elif config['type'] == 'unix':

        # the accept queue depth
        #
        backlog = int(config.get('backlog', 50))

        # the path
        #
        path = FilePath(join(cbdir, config['path']))

        # if there is already something there, delete it.
        #
        if path.exists():
            log.info(("{path} exists, attempting to remove before using as a "
                     "UNIX socket"), path=path)
            path.remove()

        # create the endpoint
        #
        endpoint = UNIXServerEndpoint(reactor, path.path, backlog=backlog)

    # twisted endpoint-string
    elif config['type'] == 'twisted':
        endpoint = serverFromString(reactor, config['server_string'])

    else:
        raise Exception("invalid endpoint type '{}'".format(config['type']))

    return endpoint
Ejemplo n.º 36
0
from twisted.internet import protocol, reactor, defer, utils, endpoints
from twisted.protocols import basic


class FingerProtocol(basic.LineReceiver):
    def lineReceived(self, user):
        d = self.factory.getUser(user)

        def onError(err):
            return b'Internal error in server'

        d.addErrback(onError)

        def writeResponse(message):
            self.transport.write(b'writeResponse:')
            self.transport.write(message + b'\r\n')
            self.transport.loseConnection()

        d.addCallback(writeResponse)


class FingerFactory(protocol.ServerFactory):
    protocol = FingerProtocol

    def getUser(self, user):
        return utils.getProcessOutput(b"finger", [user])


fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
fingerEndpoint.listen(FingerFactory())
reactor.run()
Ejemplo n.º 37
0
 def start(self):
     self.endpoint = endpoints.serverFromString(reactor,
                                                self.options.endpoint)
     self.endpoint.listen(self.site)
Ejemplo n.º 38
0

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(
        description='Starts a new pubsub broker hub for the ping protocol')
    parser.add_argument('--port',
                        metavar='P',
                        type=int,
                        help='Port to listen',
                        default=1026)
    parser.add_argument('--ip',
                        dest='ip',
                        help='ip to listen',
                        default="127.0.0.1")
    parser.add_argument('--dest_port',
                        type=int,
                        help='Port to connect',
                        default=1025)
    parser.add_argument('--dest_ip',
                        dest='dest_ip',
                        help='ip to connect',
                        default="127.0.0.1")
    args = parser.parse_args()

    endpoints.serverFromString(
        reactor, "tcp:interface=%s:port=%s" % (args.ip, args.port)).listen(
            BrokerPubFactory(args.dest_ip, args.dest_port))
    reactor.run()
Ejemplo n.º 39
0
#! /bin/env python3

from twisted.web import server, resource
from twisted.internet import reactor, endpoints


class Counter(resource.Resource):
    isLeaf = True
    numberRequests = 0

    def render_GET(self, request):
        # self.numberRequests += 1
        # request.setHeader(b"content-type", b"text/plain")
        content = ""
        return content.encode("ascii")


endpoints.serverFromString(reactor, "tcp:5555").listen(server.Site(Counter()))
reactor.run()
Ejemplo n.º 40
0
            #req_args['master'][0], req_args['num_nodes'][0], req_args['cores'][0])

        elif 'explore' in req_args.keys():
            self.start_exploration(req_args['target_cpus'][0])

        elif 'exploit' in req_args.keys():
            self.start_exploitation(req_args['num_jobs'][0])

        else:
            print("not understood")

        return "OK"

    ##################################################

    def render_GET(self, request):
        #    self.numberRequests += 1
        a = request.args
        print(a)
        to_ret = self.parse_handle_req(a)
        request.setHeader(b"content-type", b"text/plain")
        content = to_ret
        return content.encode("ascii")


##################################################

endpoints.serverFromString(reactor, "tcp:7878").listen(server.Site(evlisten()))

reactor.run()
Ejemplo n.º 41
0
from twisted.internet import reactor, protocol, endpoints
from twisted.protocols import basic


class PubProtocol(basic.LineReceiver):
    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.clients.add(self)

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        for c in self.factory.clients:
            source = u"<{}> ".format(self.transport.getHost()).encode("ascii")
            c.sendLine(source + line)


class PubFactory(protocol.Factory):
    def __init__(self):
        self.clients = set()

    def buildProtocol(self, addr):
        return PubProtocol(self)


endpoints.serverFromString(reactor, "tcp:1025").listen(PubFactory())
reactor.run()
Ejemplo n.º 42
0
def main(opts):
    global games
    games = load_games(opts)
    ep = "tcp:%d" % (opts.port, )
    endpoints.serverFromString(reactor, ep).listen(server.Site(root))
    reactor.run()
Ejemplo n.º 43
0
import datetime
import httplib2
from twisted.web import server, resource
from twisted.internet import reactor, endpoints


class Health(resource.Resource):
    isLeaf = True

    def render_GET(self, request):
        request.responseHeaders.addRawHeader("content-type",
                                             "application/json")
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
              ' SideCar健康检查')
        return '{"status":"UP"}'.encode('utf-8')


root = Health()
root.putChild('health', Health())
endpoints.serverFromString(reactor, "tcp:port=5680").listen(server.Site(root))
reactor.run()
Ejemplo n.º 44
0
def main(reactor, listenOn="stdio:"):
    endpoint = serverFromString(reactor, listenOn)
    endpoint.listen(factoryFromFlow(echoFlow))
    return Deferred()
Ejemplo n.º 45
0
        "--web",
        default="tcp:8080",
        help='Web server endpoint descriptor, e.g. "tcp:8080".')

    args = parser.parse_args()

    # start Twisted logging to stdout
    log.startLogging(sys.stdout)

    # we use an Autobahn utility to install the "best" available Twisted reactor
    from autobahn.twisted.choosereactor import install_reactor
    reactor = install_reactor()
    print("Running on reactor {}".format(reactor))

    # start a WebSocket server
    wsfactory = EchoServerFactory(args.wsurl)
    wsserver = serverFromString(reactor, args.websocket)
    wsserver.listen(wsfactory)

    # start a Web server
    if args.web != "":
        from twisted.web.server import Site
        from twisted.web.static import File

        webfactory = Site(File("."))
        webserver = serverFromString(reactor, args.web)
        webserver.listen(webfactory)

    # now enter the Twisted reactor loop
    reactor.run()
Ejemplo n.º 46
0
            res['msg'] = mems
            res['status'] = True

        if isinstance(res, dict):
            request.setHeader("Content-Type", "application/json;charset=UTF-8")
            res = json.dumps(res)
        elif path.startswith('/v1/wxspider/img/'):
            request.setHeader('Content-Type', 'image/jpeg')
        else:
            request.setHeader('Content-Type', 'text/html')
        return res


def cleanup():
    for client in CLIENTS.itervalues():
        client.cleanup()


if __name__ == '__main__':
    from twisted.web.server import Site
    from twisted.internet import endpoints

    endpoints.serverFromString(reactor, "tcp:%s:interface=%s" %
                               (8087, INNER_IP)).listen(Site(TaskManage()))
    init_clients()
    for c in CLIENTS.itervalues():
        c.run()
    task.LoopingCall(check_clients).start(40, now=False)
    reactor.addSystemEventTrigger('before', 'shutdown', cleanup)
    reactor.run()
    def test_minimal(self):

        embedded_components, client_components = [], [
            Case2_Backend, Case2_Frontend
        ]

        ## create a WAMP router factory
        ##
        from autobahn.wamp.router import RouterFactory
        router_factory = RouterFactory()

        ## create a WAMP router session factory
        ##
        from autobahn.twisted.wamp import RouterSessionFactory
        session_factory = RouterSessionFactory(router_factory)

        ## .. and create and add an WAMP application session to
        ## run next to the router
        ##
        from autobahn.wamp import types

        config = types.ComponentConfig(realm=self.realm,
                                       extra={'caselog': 'case1.log'})
        try:
            log = io.open('caselog.log', 'w')
            print "WWW" * 10, log
        except Exception as e:
            print "X" * 10, e


#      log = io.open(config.extra['caselog'], 'w')
        config.log = log
        config.dlog = []
        config.components = []

        config.all_done = []

        for C in embedded_components:
            one_done = Deferred()
            config.all_done.append(one_done)
            c = C(config, one_done)
            config.components.append(c)
            session_factory.add(c)

        print "2" * 10

        if self.transport == "websocket":

            ## create a WAMP-over-WebSocket transport server factory
            ##
            from autobahn.twisted.websocket import WampWebSocketServerFactory
            transport_factory = WampWebSocketServerFactory(
                session_factory, debug_wamp=self.debug)
            transport_factory.setProtocolOptions(failByDrop=False,
                                                 openHandshakeTimeout=0,
                                                 closeHandshakeTimeout=0)

        elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:

            ## create a WAMP-over-RawSocket transport server factory
            ##
            if self.transport == 'rawsocket-msgpack':
                from autobahn.wamp.serializer import MsgPackSerializer
                serializer = MsgPackSerializer()
            elif self.transport == 'rawsocket-json':
                from autobahn.wamp.serializer import JsonSerializer
                serializer = JsonSerializer()
            else:
                raise Exception("should not arrive here")

            from autobahn.twisted.rawsocket import WampRawSocketServerFactory
            transport_factory = WampRawSocketServerFactory(session_factory,
                                                           serializer,
                                                           debug=self.debug)

        else:
            raise Exception("should not arrive here")

        from autobahn.twisted.websocket import WampWebSocketClientFactory, WampWebSocketClientProtocol

        ## start the server from an endpoint
        ##
        from twisted.internet import reactor
        server = serverFromString(reactor, self.server)
        d = server.listen(transport_factory)

        def onlisten(port):
            print "onlisten", port
            config.port = port

        d.addCallback(onlisten)

        print "3" * 10

        clients = []
        clients_d = []
        for C in client_components:
            ## create a WAMP application session factory
            ##
            from autobahn.twisted.wamp import ApplicationSessionFactory
            session_factory = ApplicationSessionFactory(config)

            one_done = Deferred()
            config.all_done.append(one_done)

            def make_make(Klass, done):
                def make(config):
                    c = Klass(config, done)
                    config.components.append(c)
                    return c

                return make

            ## .. and set the session class on the factory
            ##
            session_factory.session = make_make(C, one_done)

            print "4" * 10

            if self.transport == "websocket":

                from autobahn.wamp.serializer import JsonSerializer

                serializers = [JsonSerializer()]

                ## create a WAMP-over-WebSocket transport client factory
                ##
                transport_factory = WampWebSocketClientFactory(
                    session_factory,
                    serializers=serializers,
                    url=self.url,
                    debug_wamp=self.debug)

                print "5" * 10

                if True:

                    def maker(Klass):
                        class TestClientProtocol(WampWebSocketClientProtocol):
                            def onOpen(self):
                                print "onOpen"
                                self.txcnt = 0
                                self.rxcnt = 0
                                WampWebSocketClientProtocol.onOpen(self)

                            def sendMessage(self, bytes, isBinary):
                                self.txcnt += 1
                                print("> : {:>3} : {:<20} : {}".format(
                                    self.txcnt, Klass.__name__, bytes))
                                WampWebSocketClientProtocol.sendMessage(
                                    self, bytes, isBinary)

                            def onMessage(self, bytes, isBinary):
                                self.rxcnt += 1
                                print("< : {:>3} : {:<20} : {}".format(
                                    self.rxcnt, Klass.__name__, bytes))
                                WampWebSocketClientProtocol.onMessage(
                                    self, bytes, isBinary)

                        return TestClientProtocol

                    transport_factory.protocol = maker(C)
                else:
                    transport_factory.protocol = WampWebSocketClientProtocol

                transport_factory.setProtocolOptions(failByDrop=False,
                                                     openHandshakeTimeout=0,
                                                     closeHandshakeTimeout=0)

            elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:

                ## create a WAMP-over-RawSocket transport client factory
                ##
                if self.transport == 'rawsocket-msgpack':
                    from autobahn.wamp.serializer import MsgPackSerializer
                    serializer = MsgPackSerializer()
                elif self.transport == 'rawsocket-json':
                    from autobahn.wamp.serializer import JsonSerializer
                    serializer = JsonSerializer()
                else:
                    raise Exception("should not arrive here")

                from autobahn.twisted.rawsocket import WampRawSocketClientFactory
                transport_factory = WampRawSocketClientFactory(
                    session_factory, serializer, debug=self.debug)

            ## start the client from an endpoint
            ##
            cl = clientFromString(reactor, self.client)
            clients_d.append(cl.connect(transport_factory))

            print "6" * 10

            clients.append(cl)

        print config.all_done

        config.connected_clients = None

        def client_connected(res):
            config.connected_clients = [
                proto for success, proto in res if success
            ]
            print "XXXXXXX", config.connected_clients

        DeferredList(clients_d).addCallback(client_connected)

        d = DeferredList(config.all_done, consumeErrors=True)
        #d = config.components[1]._done

        print "7"

        def done(res):
            print "DOne"
            log.flush()
            log.close()
            if config.port:
                config.port.stopListening()
            if config.connected_clients:
                for proto in config.connected_clients:
                    proto.transport.abortConnection()
            print("Log length: {}".format(len(config.dlog)))
            print(config.dlog)
            #from twisted.internet import reactor
            #reactor.callLater(1, reactor.stop)

        def error(err):
            print err

        d.addCallbacks(done, error)

        print "8", d

        #      d2 = Deferred()

        return d
 def startService(self):
     self.endpoint = endpoints.serverFromString(reactor, self.description)
     self.endpoint.listen(self.site)
Ejemplo n.º 49
0
def main():
    endpoints.serverFromString(reactor, "tcp:179").listen(factory)
    reactor.run()
Ejemplo n.º 50
0
 def __init__(self, reactor, top, endpoint_string):
     self.__top = top
     self.__endpoint = endpoints.serverFromString(reactor, endpoint_string)
     self.__port_obj = None
Ejemplo n.º 51
0
        if enabled == "1":
            hostLog.log(auth, domain, "WXS to Host", "ACKNOWLE", response)
        else:
            print(loggingNotEnabledMsg)
        return response


class Echo(protocol.Protocol):
    def dataReceived(self, data):

        printable = data.decode('ascii')
        print(' wrote ' + printable)

        response = createResponseMessage(data)

        print('response: ' + response.decode('ascii'))

        #self.transport.write(data)
        self.transport.write(response)


class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()


if __name__ == "__main__":

    endpoints.serverFromString(
        reactor, "tcp:65432:interface=127.0.0.1").listen(EchoFactory())
    reactor.run()
Ejemplo n.º 52
0
 def test_stringDescription_default(self):
     from twisted.internet.endpoints import serverFromString
     with mock.patch('txi2p.sam.endpoints.getSession', fakeSession):
         ep = serverFromString(
             MemoryReactor(), "i2p:/tmp/testkeys.foo")
     self.assertIsInstance(ep, SAMI2PStreamServerEndpoint)
Ejemplo n.º 53
0
 def web_server(cls, reactor, engine, description):
     ep = endpoints.serverFromString(reactor, description)
     counter = cls(engine)
     return ep.listen(Site(counter.app.resource()))
Ejemplo n.º 54
0
 def _add_listen(self, description, factory):
     log.info("Start listened %s", description)
     endpoint = endpoints.serverFromString(reactor, description)
     new_listen = endpoint.listen(factory)
     self.__ports[description] = {'listen': new_listen, 'factory': factory, 'number': 1}
Ejemplo n.º 55
0
            print('data from', self.deviceid, data)
            # print('data from', self.deviceid, (wtr, nut))
            self.transport.write(b'\x00')

        elif cmd == 5:
            now = int(time.time() * 1000)
            self.transport.write(bytes([6]) + now.to_bytes(8, 'big'))

        elif cmd == 200:
            devid = int.from_bytes(data[1:5], 'big')
            if devid in self.devices:
                print('command for ', devid, data[5:])
                self.devices[devid].transport.write(data[5:])
            else:
                print('cannot find', devid)

        else:
            print('cmd', cmd)


class HydroFactory(protocol.Factory):
    devices = {}

    def buildProtocol(self, addr):
        return HydroProtocol(self.devices)


factory = HydroFactory()
endpoint = endpoints.serverFromString(reactor, 'tcp:8888')
endpoint.listen(factory)
reactor.run()
Ejemplo n.º 56
0
    def run(self):
        # A dict of protocol: {"application_instance":, "connected":, "disconnected":} dicts
        self.connections = {}
        # Make the factory
        self.http_factory = HTTPFactory(self)
        self.ws_factory = WebSocketFactory(self, server=self.server_name)
        protocol_options = {
            'autoPingTimeout': self.ping_timeout,
            'allowNullOrigin': True,
            'openHandshakeTimeout': self.websocket_handshake_timeout
        }
        if self.ws_compress:
            def ws_accept_compression(offers):
                for offer in offers:
                    if isinstance(offer, PerMessageDeflateOffer):
                        return PerMessageDeflateOfferAccept(offer)
            protocol_options['perMessageCompressionAccept'] = ws_accept_compression
        self.ws_factory.setProtocolOptions(**protocol_options)
        if self.verbosity <= 1:
            # Redirect the Twisted log to nowhere
            globalLogBeginner.beginLoggingTo(
                [lambda _: None], redirectStandardIO=False, discardBuffer=True
            )
        else:
            globalLogBeginner.beginLoggingTo([STDLibLogObserver(__name__)])

        # Detect what Twisted features are enabled
        if http.H2_ENABLED:
            logger.info("HTTP/2 support enabled")
        else:
            logger.info(
                "HTTP/2 support not enabled (install the http2 and tls Twisted extras)"
            )

        # Kick off the timeout loop
        reactor.callLater(1, self.application_checker)
        reactor.callLater(2, self.timeout_checker)

        for socket_description in self.endpoints:
            logger.info("Configuring endpoint %s", socket_description)
            ep = serverFromString(reactor, str(socket_description))
            listener = ep.listen(self.http_factory)
            listener.addCallback(self.listen_success)
            listener.addErrback(self.listen_error)
            self.listeners.append(listener)

        # Set the asyncio reactor's event loop as global
        # TODO: Should we instead pass the global one into the reactor?
        asyncio.set_event_loop(reactor._asyncioEventloop)

        # Verbosity 3 turns on asyncio debug to find those blocking yields
        if self.verbosity >= 3:
            asyncio.get_event_loop().set_debug(True)

        reactor.addSystemEventTrigger("before", "shutdown", self.kill_all_applications)
        if not self.abort_start:
            # Trigger the ready flag if we had one
            if self.ready_callable:
                self.ready_callable()
            # Run the reactor
            reactor.run(installSignalHandlers=self.signal_handlers)
Ejemplo n.º 57
0
def main():
    parser = argparse.ArgumentParser()

    # Network options
    group_network_container = parser.add_argument_group(
        title="Network options")
    group_network = group_network_container.add_mutually_exclusive_group(
        required=True)
    group_network.add_argument("--mainnet",
                               action="store_true",
                               default=False,
                               help="Use MainNet")
    group_network.add_argument("--testnet",
                               action="store_true",
                               default=False,
                               help="Use TestNet")
    group_network.add_argument("--privnet",
                               action="store_true",
                               default=False,
                               help="Use PrivNet")
    group_network.add_argument("--coznet",
                               action="store_true",
                               default=False,
                               help="Use CozNet")
    group_network.add_argument("--config",
                               action="store",
                               help="Use a specific config file")

    # Ports for RPC and REST api
    group_modes = parser.add_argument_group(title="Mode(s)")
    group_modes.add_argument(
        "--port-rpc",
        type=int,
        help="port to use for the json-rpc api (eg. 10332)")
    group_modes.add_argument("--port-rest",
                             type=int,
                             help="port to use for the rest api (eg. 80)")

    # Advanced logging setup
    group_logging = parser.add_argument_group(title="Logging options")
    group_logging.add_argument("--logfile",
                               action="store",
                               type=str,
                               help="Logfile")
    group_logging.add_argument(
        "--syslog",
        action="store_true",
        help=
        "Log to syslog instead of to log file ('user' is the default facility)"
    )
    group_logging.add_argument(
        "--syslog-local",
        action="store",
        type=int,
        choices=range(0, 7),
        metavar="[0-7]",
        help=
        "Log to a local syslog facility instead of 'user'. Value must be between 0 and 7 (e.g. 0 for 'local0')."
    )
    group_logging.add_argument("--disable-stderr",
                               action="store_true",
                               help="Disable stderr logger")

    # Where to store stuff
    parser.add_argument("--datadir",
                        action="store",
                        help="Absolute path to use for database directories")

    # Now parse
    args = parser.parse_args()
    # print(args)

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        return

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        return

    if args.logfile and (args.syslog or args.syslog_local):
        print("Error: Cannot only use logfile or syslog at once")
        parser.print_help()
        return

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    if args.datadir:
        settings.set_data_dir(args.datadir)

    if args.syslog or args.syslog_local is not None:
        # Setup the syslog facility
        if args.syslog_local is not None:
            print("Logging to syslog local%s facility" % args.syslog_local)
            syslog_facility = SysLogHandler.LOG_LOCAL0 + args.syslog_local
        else:
            print("Logging to syslog user facility")
            syslog_facility = SysLogHandler.LOG_USER

        # Setup logzero to only use the syslog handler
        logzero.syslog(facility=syslog_facility)
    else:
        # Setup file logging
        if args.logfile:
            logfile = os.path.abspath(args.logfile)
            if args.disable_stderr:
                print("Logging to logfile: %s" % logfile)
            else:
                print("Logging to stderr and logfile: %s" % logfile)
            logzero.logfile(logfile,
                            maxBytes=LOGFILE_MAX_BYTES,
                            backupCount=LOGFILE_BACKUP_COUNT,
                            disableStderrLogger=args.disable_stderr)

        else:
            print("Logging to stdout and stderr")

    # Disable logging smart contract events
    settings.set_log_smart_contract_events(False)

    # Write a PID file to easily quit the service
    write_pid_file()

    # Setup Twisted and Klein logging to use the logzero setup
    observer = STDLibLogObserver(name=logzero.LOGZERO_DEFAULT_LOGGER)
    globalLogPublisher.addObserver(observer)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)

    # Setup twisted reactor, NodeLeader and start the NotificationDB
    reactor.suggestThreadPoolSize(15)
    NodeLeader.Instance().Start()
    NotificationDB.instance().start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Default host is open for all
    host = "0.0.0.0"

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" %
                    (host, args.port_rpc))
        api_server_rpc = JsonRpcApi(args.port_rpc)
        endpoint_rpc = "tcp:port={0}:interface={1}".format(args.port_rpc, host)
        endpoints.serverFromString(reactor, endpoint_rpc).listen(
            Site(api_server_rpc.app.resource()))

    if args.port_rest:
        logger.info("Starting REST api server on http://%s:%s" %
                    (host, args.port_rest))
        api_server_rest = RestApi()
        endpoint_rest = "tcp:port={0}:interface={1}".format(
            args.port_rest, host)
        endpoints.serverFromString(reactor, endpoint_rest).listen(
            Site(api_server_rest.app.resource()))

    reactor.run()

    # After the reactor is stopped, gracefully shutdown the database.
    logger.info("Closing databases...")
    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
Ejemplo n.º 58
0
 def startService(self):
     self.endpoint = serverFromString(reactor, self.port)
     self.endpoint.listen(AMPFactory(self.responder))
Ejemplo n.º 59
0
    def connectionLost(self, reason):
        self.server.concurrentClientCount -= 1

    def dataReceived(self, data):
        #self - это клиент
        data = data.decode('utf8')
        print("Data received: "+data)
        queries = self.dataForProcessing + data;
        queries = queries.split("\r\n");
        self.dataForProcessing = queries[-1];
        del queries[-1]
        words = queries.split(" ")
        
            #words = query.split(" ")
        i = 33
        answer = str(words[0])
        print("Ok")
        self.transport.write((answer+"\r\n").encode('utf8'))
        print("Answer: "+answer)

class Server(protocol.Factory):
    def __init__(self):
        self.concurrentClientCount = 0

    def buildProtocol(self, addr):
        return ProcessClient(self)

endpoints.serverFromString(reactor, "tcp:12345").listen(Server())
reactor.run()
Ejemplo n.º 60
0
    def startService(self):
        scp = load_config(instance_config=self.instance_config)
        validate_config(scp)
        endpoint = self.endpoint
        if endpoint is None:
            if scp.has_option("Application", "endpoint"):
                endpoint = scp.get("Application", "endpoint")
            else:
                endpoint = "tcp:10389"
        factory = protocol.ServerFactory()
        if scp.has_option("LDAP", "proxy_cert"):
            proxy_cert = scp.get("LDAP", "proxy_cert")
            with open(proxy_cert, "r") as f:
                certData = f.read()
            cert = ssl.PrivateCertificate.loadPEM(certData)
            factory.options = cert.options()
        proxied_endpoints = []
        last_proxied_scheme = None
        for opt in scp.options("LDAP"):
            if opt.startswith("proxied_endpoint"):
                proxied_endpoint = scp.get("LDAP", opt)
                proxied_endpoints.append(proxied_endpoint)
        if len(proxied_endpoints) == 0:
            log.msg("[ERROR] No proxied endpoints specified.")
            sys.exit(1)
        use_tls = scp.getboolean('LDAP', 'use_starttls')
        if scp.has_option('Application', 'debug'):
            debug_app = scp.getboolean('Application', 'debug')
        else:
            debug_app = False
        if scp.has_option('Application', 'debug_cache'):
            debug_cache = scp.getboolean('Application', 'debug_cache')
        else:
            debug_cache = False
        if scp.has_option('Application', 'search_cache_lifetime'):
            searchCacheLifetime = scp.getint('Application', 'search_cache_lifetime')
        else:
            searchCacheLifetime = 600
        if scp.has_option('Application', 'search_cache_size'):
            searchCacheSize = scp.getint('Application', 'search_cache_size')
        else:
            searchCacheSize = 2000
        if scp.has_option('Application', 'bind_cache_lifetime'):
            bindCacheLifetime = scp.getint('Application', 'bind_cache_lifetime')
        else:
            bindCacheLifetime = 600
        if scp.has_option('Application', 'bind_cache_size'):
            bindCacheSize = scp.getint('Application', 'bind_cache_size')
        else:
            bindCacheSize = 2000
        use_cluster = False
        if scp.has_section("Cluster"):
            cluster_endpoint = None
            cluster_peers = []
            if not scp.has_option("Cluster", "endpoint"):
                log.msg("[ERROR] Section 'Cluster' does not define an 'endpoint' option.")
                sys.exit(1)
            cluster_endpoint = scp.get("Cluster", "endpoint")
            options = scp.options("Cluster")
            has_peer = False
            for option in options:
                if option.startswith("peer"):
                    has_peer = True
                    cluster_peers.append(scp.get("Cluster", option))
            if not has_peer:
                log.msg("[ERROR] Section 'Cluster' does not have any 'peerxxx' options.")
                sys.exit(1)
            use_cluster = True
            clusterClient = LRUClusterClient(cluster_peers)
            clusterClient.debug = debug_cache

        def make_protocol():
            proto = BindProxy()
            proto.debug = debug_app
            proto.use_tls = use_tls
            proto.clientConnector = makeClientConnector(reactor, proxied_endpoints)
            proto.searchResponses = {}
            return proto

        factory.protocol = make_protocol
        kwds = {}
        if use_cluster:
            kwds['cluster_func'] = make_cluster_func('bind', clusterClient, debug=debug_cache)
        factory.lastBindCache = LRUTimedCache(lifetime=bindCacheLifetime, capacity=bindCacheSize, **kwds)
        kwds = {}
        if use_cluster:
            kwds['cluster_func'] = make_cluster_func('search', clusterClient, debug=debug_cache)
        factory.searchCache = LRUTimedCache(lifetime=searchCacheLifetime, capacity=searchCacheSize, **kwds)
        ep = serverFromString(reactor, endpoint)
        d = ep.listen(factory)
        d.addCallback(self.set_listening_port, port_type='ldap')
        if use_cluster:
            ep = serverFromString(reactor, cluster_endpoint)
            cache_map = {
                'bind': factory.lastBindCache,
                'search': factory.searchCache,}
            cluster_proto_factory = LRUClusterProtocolFactory(cache_map)
            cluster_proto_factory.protocol.debug = debug_cache
            d = ep.listen(cluster_proto_factory)
            d.addCallback(self.set_listening_port, port_type='cluster')
            d.addErrback(log.err)
        if scp.has_section("WebService") and scp.has_option("WebService", "endpoint"):
            endpoint = scp.get("WebService", "endpoint")
            ws_site = make_ws(bindCache=factory.lastBindCache, portal=self.portal)
            ws_site.displayTracebacks = debug_cache
            ep = serverFromString(reactor, endpoint)
            d = ep.listen(ws_site)
            d.addCallback(self.set_listening_port, port_type='ws')