import sys from twisted.python import log log.startLogging(sys.stdout) from autobahn.twisted import install_reactor # we use an Autobahn utility to import the "best" available Twisted reactor reactor = install_reactor(verbose=False, require_optimal_reactor=False) from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory from twisted.internet.protocol import Factory import json import traceback from buffer import Buffer from player import Player from match import Match class MyServerProtocol(WebSocketServerProtocol): def __init__(self, server): WebSocketServerProtocol.__init__(self) self.server = server self.recv = str() self.stat = str() self.player = None def onConnect(self, request): print("Client connecting: {0}".format(request.peer))
def run(): """ CLI entry point into crossbar. * when called with no arguments, the arguments are read from the command line * when called with an explicit arguments list, use the same arguments in the list as on the command line, leaving out the initial `crossbar` command. twisted.internet.error.ReactorNotRestartable **Examples** To start Crossbar.io programmatically from a given node directory: .. code-block:: python import crossbar crossbar.run(['start', '--cbdir', '/tmp/mynode1/.crossbar']) To start Crossbar.io with log output at level "debug" .. code-block:: console $ crossbar start --loglevel=debug To chose a specific event reactor and print version information .. code-block:: console $ CROSSBAR_REACTOR="kqueue" crossbar version To start from a specified node directory (instead of the default `$CWD/.crossbar`): .. code-block:: console $ CROSSBAR_DIR="/tmp/test/.crossbar" crossbar start which is the same as .. code-block:: console $ crossbar start --cbdir=/tmp/test/.crossbar **Influential command line options and environment variables include:** ================== ======================== ============================================== Command line arg: Environment variable: Description: ================== ======================== ============================================== n.a. **CROSSBAR_REACTOR** Event reactor: * **auto** * **select** * **poll** * **epoll** * **kqueue** * **iocp** n.a. **CROSSBAR_PERSONALITY** Node personality: * **standalone** * **edge** * **master** ``--cbdir`` **CROSSBAR_DIR** Node directory (local directory) ``--config`` **CROSSBAR_CONFIG** Node configuration (local filename) ``--color`` n.a. Enable colored terminal output ``--loglevel`` n.a. Select log level ``--logformat`` n.a. Select log format ``--logdir`` n.a. Log to this local directory ``--logtofile`` n.a. Enable logging to file ================== ======================== ============================================== .. seealso:: `TwistedMatrix: Choosing a Reactor and GUI Toolkit Integration <https://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html>`_ .. note:: The Twisted reactor to use can only be explicitly chosen via an environment variable, not a command line option. """ # # check command line args # argv = sys.argv[:] if len(argv) < 2: print( _HELP_USAGE.format(executable=hl( os.path.basename(argv[0]), bold=True, color='yellow'))) sys.exit(0) # XXX maybe we should Click here, too, since we're already depending on it? executable, command = argv[0:2] args = argv[2:] sys.argv = [executable] + argv[2:] # if no known top-level command was given, fallback to "edge" mode if command not in _TOP_COMMANDS: args = [command] + args command = 'standalone' # redirect a plain "crossbar legal" to "crossbar master legal" if command == 'legal': command = 'master' args = ['legal'] # redirect a plain "crossbar version" to "crossbar master version" if command == 'version': command = 'master' args = ['version'] # shell command (using asyncio) if command == 'shell': from crossbar.shell import main sys.exit(main.run()) elif command == 'quickstart': from crossbar.quickstart import main sys.exit(main.run()) elif command == 'quickstart-venv': from crossbar.quickstart.quickstartvenv import main sys.exit(main.run()) # edge/master commands (using Twisted) elif command in ['standalone', 'edge', 'master', 'network']: # FIXME :: having FX drop out due to lack of entropy makes things a lot # harder from a deployment / monitoring perspective. A retry with reporting # would make life a lot easier. # on Linux, check that we start with sufficient system entropy if sys.platform.startswith('linux'): try: with open('/proc/sys/kernel/random/entropy_avail', 'r') as ent: entropy_avail = int(ent.read()) if entropy_avail < 64: print( 'FATAL: cannot start due to insufficient entropy ({} bytes) available - try installing rng-tools' .format(entropy_avail)) sys.exit(1) except PermissionError: # this happens when packaged as a snap: the code prevented from reading a location # # that is not allowed to a confined snap package entropy_avail = -1 mem_avail = psutil.virtual_memory().available // 2**20 if mem_avail < 100: print( 'FATAL: cannot start due to insufficient available memory ({} MB free)' .format(mem_avail)) sys.exit(1) from autobahn.twisted import install_reactor # IMPORTANT: keep the reactor install as early as possible to avoid importing # any Twisted module that comes with the side effect of installing a default # reactor (which might not be what we want!). reactor = install_reactor(explicit_reactor=os.environ.get( 'CROSSBAR_REACTOR', None), verbose=False, require_optimal_reactor=False) # get chosen personality class if command == 'standalone': from crossbar import personality as standalone personality = standalone.Personality elif command == 'edge': from crossbar import edge personality = edge.Personality elif command == 'network': from crossbar import network personality = network.Personality elif command == 'master': from crossbar import master personality = master.Personality else: # should not arrive here raise Exception('internal error') # do NOT move this import above *** (triggers reactor imports) from crossbar.node.main import main # and now actually enter here .. this never returns! sys.exit(main(executable, args, reactor, personality)) else: assert False, 'should not arrive here'
def run(args=None, reactor=None, personality=None): """ Main entry point into Crossbar.io: * when called with no arguments, the arguments are read from the command line * when called with an explicit arguments list, use the same arguments in the list as on the command line, leaving out the initial `crossbar` command. twisted.internet.error.ReactorNotRestartable **Examples** To start Crossbar.io programmatically from a given node directory: .. code-block:: python import crossbar crossbar.run(['start', '--cbdir', '/tmp/mynode1/.crossbar']) To start Crossbar.io with log output at level "debug" .. code-block:: console $ crossbar start --loglevel=debug To chose a specific event reactor and print version information .. code-block:: console $ CROSSBAR_REACTOR="kqueue" crossbar version To start from a specified node directory (instead of the default `$CWD/.crossbar`): .. code-block:: console $ CROSSBAR_DIR="/tmp/test/.crossbar" crossbar start which is the same as .. code-block:: console $ crossbar start --cbdir=/tmp/test/.crossbar **Influential command line options and environment variables include:** ================== ======================== ============================================== Command line arg: Environment variable: Description: ================== ======================== ============================================== n.a. **CROSSBAR_REACTOR** Event reactor: * **auto** * **select** * **poll** * **epoll** * **kqueue** * **iocp** n.a. **CROSSBAR_PERSONALITY** Node personality: * **standalone** * **edge** * **master** ``--cbdir`` **CROSSBAR_DIR** Node directory (local directory) ``--config`` **CROSSBAR_CONFIG** Node configuration (local filename) ``--color`` n.a. Enable colored terminal output ``--loglevel`` n.a. Select log level ``--logformat`` n.a. Select log format ``--logdir`` n.a. Log to this local directory ``--logtofile`` n.a. Enable logging to file ================== ======================== ============================================== .. seealso:: `TwistedMatrix: Choosing a Reactor and GUI Toolkit Integration <https://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html>`_ .. note:: The Twisted reactor to use can only be explicitly chosen via an environment variable, not a command line option. :param args: The (optional) program name . :type args: List[str] :param reactor: Optional Twisted reactor to use. If none is given, try to load the optimal reactor for Crossbar.io to run on the host platform. :type reactor: :class:`twisted.internet.reactor` """ import sys import os from autobahn.twisted import install_reactor if reactor is not None and reactor not in _DEFINED_REACTORS: raise Exception('illegal value "{}" for reactor'.format(reactor)) if personality is not None and personality not in _DEFINED_PERSONALITIES: raise Exception( 'illegal value "{}" for personality. Valid: {}'.format( personality, ", ".join(_DEFINED_PERSONALITIES), ) ) # use argument list from command line if none is given explicitly if args is None: exename = os.path.basename(sys.argv[0]) args = sys.argv[1:] else: exename = 'crossbar' # IMPORTANT: keep the reactor install as early as possible to avoid importing # any Twisted module that comes with the side effect of installing a default # reactor (which might not be what we want!). if reactor is None: # we use an Autobahn utility to import the "best" available Twisted reactor reactor = install_reactor(explicit_reactor=os.environ.get('CROSSBAR_REACTOR', None), verbose=False, require_optimal_reactor=False) # Twisted reactor installed FROM HERE *** # get installed personalities _personalities = personalities() # set personality if not personality: # choose node personality to run if 'CROSSBAR_PERSONALITY' in os.environ: personality = os.environ['CROSSBAR_PERSONALITY'] if personality not in _DEFINED_PERSONALITIES: raise Exception( 'illegal value "{}" for personality (from CROSSBAR_PERSONALITY environment variable): {}'.format( personality, ", ".join(_DEFINED_PERSONALITIES), ) ) else: personality = 'standalone' if personality not in _personalities: raise Exception('fatal: no personality "{}" [{}]'.format(personality, sorted(_personalities.keys()))) # get chosen personality class personality_klass = _personalities[personality] # do NOT move this import above *** (triggers reactor imports) from crossbar.node.main import main # and now actually enter here .. this never returns! return main(exename, args, reactor, personality_klass)
def run(args=None, reactor=None, personality=None): """ Main entry point into Crossbar.io: * when called with no arguments, the arguments are read from the command line * when called with an explicit arguments list, use the same arguments in the list as on the command line, leaving out the initial `crossbar` command. twisted.internet.error.ReactorNotRestartable **Examples** To start Crossbar.io programmatically from a given node directory: .. code-block:: python import crossbar crossbar.run(['start', '--cbdir', '/tmp/mynode1/.crossbar']) To start Crossbar.io with log output at level "debug" .. code-block:: console $ crossbar start --loglevel=debug To chose a specific event reactor and print version information .. code-block:: console $ CROSSBAR_REACTOR="kqueue" crossbar version To start from a specified node directory (instead of the default `$CWD/.crossbar`): .. code-block:: console $ CROSSBAR_DIR="/tmp/test/.crossbar" crossbar start which is the same as .. code-block:: console $ crossbar start --cbdir=/tmp/test/.crossbar **Influential command line options and environment variables include:** ================== ======================== ============================================== Command line arg: Environment variable: Description: ================== ======================== ============================================== n.a. **CROSSBAR_REACTOR** Event reactor: * **auto** * **select** * **poll** * **epoll** * **kqueue** * **iocp** n.a. **CROSSBAR_PERSONALITY** Node personality: * **standalone** * **fabric** * **fabricenter** ``--cbdir`` **CROSSBAR_DIR** Node directory (local directory) ``--config`` **CROSSBAR_CONFIG** Node configuration (local filename) ``--color`` n.a. Enable colored terminal output ``--loglevel`` n.a. Select log level ``--logformat`` n.a. Select log format ``--logdir`` n.a. Log to this local directory ``--logtofile`` n.a. Enable logging to file ================== ======================== ============================================== .. seealso:: `TwistedMatrix: Choosing a Reactor and GUI Toolkit Integration <https://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html>`_ .. note:: The Twisted reactor to use can only be explicitly chosen via an environment variable, not a command line option. :param args: The (optional) program name . :type args: List[str] :param reactor: Optional Twisted reactor to use. If none is given, try to load the optimal reactor for Crossbar.io to run on the host platform. :type reactor: :class:`twisted.internet.reactor` """ import sys import os from autobahn.twisted import install_reactor if reactor is not None and reactor not in _DEFINED_REACTORS: raise Exception('illegal value "{}" for reactor'.format(reactor)) if personality is not None and personality not in _DEFINED_PERSONALITIES: raise Exception('illegal value "{}" for personality'.format(personality)) # use argument list from command line if none is given explicitly if args is None: exename = os.path.basename(sys.argv[0]) args = sys.argv[1:] else: exename = 'crossbar' # IMPORTANT: keep the reactor install as early as possible to avoid importing # any Twisted module that comes with the side effect of installing a default # reactor (which might not be what we want!). if reactor is None: # we use an Autobahn utility to import the "best" available Twisted reactor reactor = install_reactor(explicit_reactor=os.environ.get('CROSSBAR_REACTOR', None), verbose=False, require_optimal_reactor=False) # Twisted reactor installed FROM HERE *** # get installed personalities _personalities = personalities() # set personality if not personality: # choose node personality to run if 'CROSSBAR_PERSONALITY' in os.environ: personality = os.environ['CROSSBAR_PERSONALITY'] if personality not in _DEFINED_PERSONALITIES: raise Exception('illegal value "{}" for personality (from CROSSBAR_PERSONALITY environment variable)'.format(personality)) else: if _SELECT_MAX_PERSONALITY_AS_DEFAULT: if 'fabriccenter' in _personalities: personality = 'fabriccenter' elif 'fabric' in _personalities: personality = 'fabric' elif 'standalone' in _personalities: personality = 'standalone' else: raise Exception('logic error') else: personality = 'standalone' if personality not in _personalities: raise Exception('fatal: no personality "{}"'.format(personality)) # get chosen personality class personality_klass = _personalities[personality] # do NOT move this import above *** (triggers reactor imports) from crossbar.node.main import main # and now actually enter here .. this never returns! return main(exename, args, reactor, personality_klass)