Esempio n. 1
0
    def set_reactor():
        import platform

        REACTORNAME = DEFAULT_REACTORS.get(platform.system(), "select")
        # get the reactor in here
        if REACTORNAME == "kqueue":
            from twisted.internet import kqreactor

            kqreactor.install()
        elif REACTORNAME == "epoll":
            from twisted.internet import epollreactor

            epollreactor.install()
        elif REACTORNAME == "poll":
            from twisted.internet import pollreactor

            pollreactor.install()
        else:  # select is the default
            from twisted.internet import selectreactor

            selectreactor.install()

        from twisted.internet import reactor

        set_reactor = lambda: reactor
        return reactor
Esempio n. 2
0
def installCommonReactor():
    try:
        from twisted.internet import kqreactor
        kqreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
    try:
        from twisted.internet import epollreactor
        epollreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
    try:
        from twisted.internet import pollreactor
        pollreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
Esempio n. 3
0
def setup(setup_event=None):
    try:
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        print "Failed to install epoll reactor, default reactor will be used instead."
    
    try:
        import settings
    except ImportError:
        print "***** Is configs.py missing? Maybe you want to copy and customize config_default.py?"

    from twisted.application import service
    application = service.Application("stratum-server")

    # Setting up logging
    from twisted.python.log import ILogObserver, FileLogObserver
    from twisted.python.logfile import DailyLogFile

    #logfile = DailyLogFile(settings.LOGFILE, settings.LOGDIR)
    #application.setComponent(ILogObserver, FileLogObserver(logfile).emit)

    if settings.ENABLE_EXAMPLE_SERVICE:
        import stratum.example_service
    
    if setup_event == None:
        setup_finalize(None, application)
    else:
        setup_event.addCallback(setup_finalize, application)
        
    return application
Esempio n. 4
0
def run_twisted(host, port, barrier, profile):

    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
        from twisted.internet import kqreactor
        kqreactor.install()
    elif sys.platform in ['win32']:
        from twisted.internet.iocpreactor import reactor as iocpreactor
        iocpreactor.install()
    elif sys.platform.startswith('linux'):
        from twisted.internet import epollreactor
        epollreactor.install()
    else:
        from twisted.internet import default as defaultreactor
        defaultreactor.install()

    from twisted.web.server import Site
    from twisted.web.resource import Resource
    from twisted.internet import reactor

    class TestResource(Resource):

        def __init__(self, name):
            super().__init__()
            self.name = name
            self.isLeaf = name is not None

        def render_GET(self, request):
            txt = 'Hello, ' + self.name
            request.setHeader(b'Content-Type', b'text/plain; charset=utf-8')
            return txt.encode('utf8')

        def getChild(self, name, request):
            return TestResource(name=name.decode('utf-8'))

    class PrepareResource(Resource):

        isLeaf = True

        def render_GET(self, request):
            gc.collect()
            return b'OK'

    class StopResource(Resource):

        isLeaf = True

        def render_GET(self, request):
            reactor.callLater(0.1, reactor.stop)
            return b'OK'

    root = Resource()
    root.putChild(b'test', TestResource(None))
    root.putChild(b'prepare', PrepareResource())
    root.putChild(b'stop', StopResource())
    site = Site(root)
    reactor.listenTCP(port, site, interface=host)
    barrier.wait()

    reactor.run()
Esempio n. 5
0
def run_twisted(host, port, barrier, profile):

    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
        from twisted.internet import kqreactor
        kqreactor.install()
    elif sys.platform in ['win32']:
        from twisted.internet.iocpreactor import reactor as iocpreactor
        iocpreactor.install()
    elif sys.platform.startswith('linux'):
        from twisted.internet import epollreactor
        epollreactor.install()
    else:
        from twisted.internet import default as defaultreactor
        defaultreactor.install()

    from twisted.web.server import Site
    from twisted.web.resource import Resource
    from twisted.internet import reactor

    class TestResource(Resource):

        def __init__(self, name):
            super().__init__()
            self.name = name
            self.isLeaf = name is not None

        def render_GET(self, request):
            txt = 'Hello, ' + self.name
            request.setHeader(b'Content-Type', b'text/plain; charset=utf-8')
            return txt.encode('utf8')

        def getChild(self, name, request):
            return TestResource(name=name.decode('utf-8'))

    class PrepareResource(Resource):

        isLeaf = True

        def render_GET(self, request):
            gc.collect()
            return b'OK'

    class StopResource(Resource):

        isLeaf = True

        def render_GET(self, request):
            reactor.callLater(0.1, reactor.stop)
            return b'OK'

    root = Resource()
    root.putChild(b'test', TestResource(None))
    root.putChild(b'prepare', PrepareResource())
    root.putChild(b'stop', StopResource())
    site = Site(root)
    reactor.listenTCP(port, site, interface=host)
    barrier.wait()

    reactor.run()
Esempio n. 6
0
File: run.py Progetto: lordsky/hall0
 def install(self):
     try:
         from twisted.internet import epollreactor
         epollreactor.install()
     except:
         pass
     from twisted.internet import reactor
     self.__reactor__ = reactor
Esempio n. 7
0
def install_optimal_reactor():
    """
   Try to install the optimal Twisted reactor for platform.
   """
    import sys

    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
        try:
            v = sys.version_info
            if v[0] == 1 or (v[0] == 2
                             and v[1] < 6) or (v[0] == 2 and v[1] == 6
                                               and v[2] < 5):
                raise Exception("Python version too old (%s)" % sys.version)
            from twisted.internet import kqreactor
            kqreactor.install()
        except Exception as e:
            print("""
   WARNING: Running on BSD or Darwin, but cannot use kqueue Twisted reactor.

    => %s

   To use the kqueue Twisted reactor, you will need:

     1. Python >= 2.6.5 or PyPy > 1.8
     2. Twisted > 12.0

   Note the use of >= and >.

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
            pass

    if sys.platform in ['win32']:
        try:
            from twisted.application.reactors import installReactor
            installReactor("iocp")
        except Exception as e:
            print("""
   WARNING: Running on Windows, but cannot use IOCP Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))

    if sys.platform.startswith('linux'):
        try:
            from twisted.internet import epollreactor
            epollreactor.install()
        except Exception as e:
            print("""
   WARNING: Running on Linux, but cannot use Epoll Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
Esempio n. 8
0
def main():
    print 'logserver has started.'
    logger = logging.getLogger('log_server')
    logger.info('logserver has started.')
     
    from twisted.internet import epollreactor
    epollreactor.install()
    reactor = twisted.internet.reactor
    reactor.listenTCP(settings.PORT, ReceiveFactory())
    reactor.run()
Esempio n. 9
0
def main():
    print 'logserver has started.'
    logger = logging.getLogger('log_server')
    logger.info('logserver has started.')
     
    from twisted.internet import epollreactor
    epollreactor.install()
    reactor = twisted.internet.reactor
    reactor.listenTCP(settings.PORT, ReceiveFactory())
    reactor.run()
Esempio n. 10
0
def install_optimal_reactor():
   """
   Try to install the optimal Twisted reactor for platform.
   """
   import sys

   if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
      try:
         v = sys.version_info
         if v[0] == 1 or (v[0] == 2 and v[1] < 6) or (v[0] == 2 and v[1] == 6 and v[2] < 5):
            raise Exception("Python version too old (%s)" % sys.version)
         from twisted.internet import kqreactor
         kqreactor.install()
      except Exception as e:
         print("""
   WARNING: Running on BSD or Darwin, but cannot use kqueue Twisted reactor.

    => %s

   To use the kqueue Twisted reactor, you will need:

     1. Python >= 2.6.5 or PyPy > 1.8
     2. Twisted > 12.0

   Note the use of >= and >.

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
         pass

   if sys.platform in ['win32']:
      try:
         from twisted.application.reactors import installReactor
         installReactor("iocp")
      except Exception as e:
         print("""
   WARNING: Running on Windows, but cannot use IOCP Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))

   if sys.platform.startswith('linux'):
      try:
         from twisted.internet import epollreactor
         epollreactor.install()
      except Exception as e:
         print("""
   WARNING: Running on Linux, but cannot use Epoll Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
Esempio n. 11
0
def run():
    if platform.system() != "Windows":
        if not sys.modules.has_key('twisted.internet.reactor'):
            print "installing epoll reactor"
            from twisted.internet import epollreactor
            epollreactor.install()
        else:
            print "reactor already installed"
    from twisted.internet import reactor
    application = makeApplication(sys.argv)
    app.startApplication(application, None)
    reactor.run()
Esempio n. 12
0
def run():
    if platform.system() != "Windows":
        if not sys.modules.has_key('twisted.internet.reactor'):
            print "installing epoll reactor"
            from twisted.internet import epollreactor
            epollreactor.install()
        else:
            print "reactor already installed"
    from twisted.internet import reactor
    application = makeApplication(sys.argv)
    app.startApplication(application, None)
    reactor.run()
Esempio n. 13
0
def run():
    twisted_log.startLogging(sys.stdout)
    if platform.system() != "Windows":
        if 'twisted.internet.reactor' not in sys.modules:
            log.debug("installing epoll reactor")
            from twisted.internet import epollreactor
            epollreactor.install()
        else:
            log.debug("reactor already installed")
    from twisted.internet import reactor
    application = makeApplication(sys.argv)
    app.startApplication(application, None)
    reactor.run()
Esempio n. 14
0
def main(http_host='127.0.0.1', http_base_dir='e:\\tmp'):
    if os.name != 'nt':
        from twisted.internet import epollreactor

        epollreactor.install()

    from twisted.internet import reactor

    server = VmFileServer(http_host=http_host, http_base_dir=http_base_dir)
    factory = Factory()
    factory.protocol = lambda: VmFileProtocol(server)
    reactor.listenTCP(4444, factory)
    reactor.run()
Esempio n. 15
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=443, type='int', dest='port', help='This option lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    parser.add_option('-m', '--maxConnections', default=None, type='int', dest='maxConnections', help='You can limit the number of maximum simultaneous connections with that switch')
    parser.add_option('-f', '--forcebuild', default=None, dest='customHostname', help='This option will force rebuild the certificate using the custom hostname and exit.')
    parser.add_option('-n', '--noSSL', action="store_true", default=False, dest='sslDisabled', help='You can switch off SSL with this switch.')
    (options, _) = parser.parse_args()
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    
    if not options.sslDisabled:
        create_self_signed_cert(options.customHostname)
        if options.customHostname != None:
            return
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    
    x.info("Starting server on port {0}".format(options.port))
    if options.sslDisabled:
        x.warning("Starting, as requested, without SSL, connections are not secured and can be altered and eavesdropped on from client to server")
        reactor.listenTCP(options.port, SiriFactory(options.maxConnections))
    else:
        reactor.listenSSL(options.port, SiriFactory(options.maxConnections), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Esempio n. 16
0
def run(argv):
    twisted_log.startLoggingWithObserver(RefloggingObserver())

    if platform.system() != "Windows":
        if 'twisted.internet.reactor' not in sys.modules:
            log.debug("installing epoll reactor")
            from twisted.internet import epollreactor
            epollreactor.install()
        else:
            log.debug("reactor already installed")
    from twisted.internet import reactor
    application = makeApplication(argv)
    app.startApplication(application, None)
    reactor.run()
Esempio n. 17
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    parser.add_option('-m', '--maxConnections', default=None, type='int', dest='maxConnections', help='You can limit the number of maximum simultaneous connections with that switch')
    parser.add_option('-f', '--forcelanguage', action='store_true', default=False, dest='forcelanguage', help='Force the server use language by region of device and ignore the Siri Settings language. Usefull with anyvoice cydia package. Adds functionallity for unsupported languages')
    (options, _) = parser.parse_args()
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    
    if options.forcelanguage != False:
        config.forcelanguage=True
        x.info("Forcing languages to device region and ignoring Siri Languge settings")
    else:
        config.forcelanguage=False
    
    create_self_signed_cert()
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    
    x.info("Starting server on port {0}".format(options.port))
    reactor.listenSSL(options.port, SiriFactory(options.maxConnections), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Esempio n. 18
0
def installReactor():
    # Tries to install epoll first, then poll, and if neither are
    # available, the default select reactor will install when
    # twisted.internet.reactor is imported.
    try:
        from select import epoll
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        try:
            from select import poll
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            pass
Esempio n. 19
0
def installReactor():
    # Tries to install epoll first, then poll, and if neither are
    # available, the default select reactor will install when
    # twisted.internet.reactor is imported.
    try:
        from select import epoll
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        try:
            from select import poll
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            pass
Esempio n. 20
0
def setup(setup_event=None):
    try:
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        log.error("Failed to install epoll reactor, "
                  "default reactor will be used instead.")

    application = service.Application("stratum-server")

    if setup_event is None:
        setup_finalize(None, application)
    else:
        setup_event.addCallback(setup_finalize, application)

    return application
Esempio n. 21
0
def __install_named_reactor(reactor_name, reactor_specific=None):
    """Setup a proper Twisted reactor, given its name.

    @precondition: reactor_name in SUPPORTED_REACTOR_NAMES

    @param reactor_specific: some arguments which are specific
        for a particular reactor (a bit hacky, yes).
        If C{reactor_name} == 'qt4': contains particular C{QCoreApplication}
            subclass to be used for primary application creation.
            May be C{None}.

    @raises ImportError: if the reactor cannot be installed.
    @raises NotImplementedError: if such reactor name is unsupported.
    """
    logger.debug('Attempting to install %s reactor...', reactor_name)

    if reactor_name == 'epoll':
        from twisted.internet import epollreactor
        epollreactor.install()

    elif reactor_name == 'kqueue':
        from txkqr import kqreactor_ex
        kqreactor_ex.install()

    elif reactor_name == 'qt4':
        qapp_class = reactor_specific
        if qapp_class is not None:
            app = qapp_class(sys.argv)

        from contrib.qt4reactor import qt4reactor
        qt4reactor.install()

    elif reactor_name == 'win32':
        from twisted.internet import win32eventreactor
        win32eventreactor.install()

    elif reactor_name == 'zmq':
        from zmqr import zmqreactor
        zmqreactor.install()

    else:
        logger.debug('Cannot install %s reactor, using default', reactor_name)
        raise NotImplementedError('Unsupported reactor {!r}'
                                      .format(reactor_name))

    logger.debug('Installed %s reactor', reactor_name)
Esempio n. 22
0
def set_reactor():
    import platform
    REACTORNAME = DEFAULT_REACTORS.get(platform.system(), 'select')
    #get the reactor in here
    if REACTORNAME == 'kqueue':
        from twisted.internet import kqreactor
        kqreactor.install()
    elif REACTORNAME == 'epoll':
        from twisted.internet import epollreactor
        epollreactor.install()
    elif REACTORNAME == 'poll':
        from twisted.internet import pollreactor
        pollreactor.install()
    else:  #select is the default
        from twisted.internet import selectreactor
        selectreactor.install()

    from twisted.internet import reactor
    set_reactor = lambda: reactor
    return reactor
Esempio n. 23
0
def initepollreactor():
    t1 = time.time()
    ftlog.info('initepollreactor begin')
    try:
        if platform.system() == 'Darwin':
            from twisted.internet import reactor
        else:
            from twisted.internet import epollreactor
            epollreactor.install()
    except:
        ftlog.exception('epoll reactor installed fail, not linux?')
    ftlog.info('initepollreactor done, use time ', time.time() - t1)

    ftlog.info(sys.modules['twisted.internet.reactor'])

    global tybomb, tychannel, tygetcurrent
    tybomb = getattr(stackless, 'bomb')
    tychannel = getattr(stackless, 'channel')
    tygetcurrent = getattr(stackless, 'getcurrent')
    ftlog.tygetcurrent = tygetcurrent
Esempio n. 24
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=4443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    (options, _) = parser.parse_args()
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    
    create_self_signed_cert()
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    
    x.info("Starting server on port {0}".format(options.port))
    reactor.listenSSL(options.port, SiriFactory(), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Esempio n. 25
0
    def set_reactor(self):
        """sets the reactor up"""
        #get the reactor in here
        if self.REACTORNAME == 'kqueue':
            from twisted.internet import kqreactor
            kqreactor.install()
        elif self.REACTORNAME == 'epoll':
            from twisted.internet import epollreactor
            epollreactor.install()
        elif self.REACTORNAME == 'poll':
            from twisted.internet import pollreactor
            pollreactor.install()
        else:  #select is the default
            from twisted.internet import selectreactor
            selectreactor.install()

        from twisted.internet import reactor
        self.reactor = reactor
        #shouldn't have to, but sys.exit is scary
        self.reactor.callWhenRunning(self._protect)
        #prevent this from being called ever again
        self.set_reactor = lambda: None
Esempio n. 26
0
    def set_reactor(self):
        """sets the reactor up"""
        #get the reactor in here
        if self.REACTORNAME == 'kqueue':
            from twisted.internet import kqreactor
            kqreactor.install()
        elif self.REACTORNAME == 'epoll':
            from twisted.internet import epollreactor
            epollreactor.install()
        elif self.REACTORNAME == 'poll':
            from twisted.internet import pollreactor
            pollreactor.install()
        else: #select is the default
            from twisted.internet import selectreactor
            selectreactor.install()

        from twisted.internet import reactor
        self.reactor = reactor
        #shouldn't have to, but sys.exit is scary
        self.reactor.callWhenRunning(self._protect)
        #prevent this from being called ever again
        self.set_reactor = lambda: None
Esempio n. 27
0
def install_twisted_reactor():
    """
    Install the Twisted reactor designed for this platform.
    """

    import sys

    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
         from twisted.internet import kqreactor
         kqreactor.install()
    elif sys.platform in ['win32']:
         from twisted.internet.iocpreactor import reactor as iocpreactor
         iocpreactor.install()
    elif sys.platform.startswith('linux'):
         from twisted.internet import epollreactor
         epollreactor.install()
    else:
         from twisted.internet import default as defaultreactor
         defaultreactor.install()

    from twisted.internet import reactor
    
    return reactor
Esempio n. 28
0
def install_optimal_reactor(require_optimal_reactor=True):
    """
    Try to install the optimal Twisted reactor for this platform:

    - Linux:   epoll
    - BSD/OSX: kqueue
    - Windows: iocp
    - Other:   select

    Notes:

    - This function exists, because the reactor types selected based on platform
      in `twisted.internet.default` are different from here.
    - The imports are inlined, because the Twisted code base is notorious for
      importing the reactor as a side-effect of merely importing. Hence we postpone
      all importing.

    See: http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html#reactor-functionality

    :param require_optimal_reactor: If ``True`` and the desired reactor could not be installed,
        raise ``ReactorAlreadyInstalledError``, else fallback to another reactor.
    :type require_optimal_reactor: bool

    :returns: The Twisted reactor in place (`twisted.internet.reactor`).
    """
    log = txaio.make_logger()

    # determine currently installed reactor, if any
    #
    current_reactor = current_reactor_klass()

    # depending on platform, install optimal reactor
    #
    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):

        # *BSD and MacOSX
        #
        if current_reactor != 'KQueueReactor':
            if current_reactor is None:
                try:
                    from twisted.internet import kqreactor
                    kqreactor.install()
                except:
                    log.warn('Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor: {tb}', tb=traceback.format_exc())
                else:
                    log.debug('Running on *BSD or MacOSX and optimal reactor (kqueue) was installed.')
            else:
                log.warn('Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor, because another reactor ({klass}) is already installed.', klass=current_reactor)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug('Running on *BSD or MacOSX and optimal reactor (kqueue) already installed.')

    elif sys.platform in ['win32']:

        # Windows
        #
        if current_reactor != 'IOCPReactor':
            if current_reactor is None:
                try:
                    from twisted.internet.iocpreactor import reactor as iocpreactor
                    iocpreactor.install()
                except:
                    log.warn('Running on Windows, but cannot install IOCP Twisted reactor: {tb}', tb=traceback.format_exc())
                else:
                    log.debug('Running on Windows and optimal reactor (ICOP) was installed.')
            else:
                log.warn('Running on Windows, but cannot install IOCP Twisted reactor, because another reactor ({klass}) is already installed.', klass=current_reactor)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug('Running on Windows and optimal reactor (ICOP) already installed.')

    elif sys.platform.startswith('linux'):

        # Linux
        #
        if current_reactor != 'EPollReactor':
            if current_reactor is None:
                try:
                    from twisted.internet import epollreactor
                    epollreactor.install()
                except:
                    log.warn('Running on Linux, but cannot install Epoll Twisted reactor: {tb}', tb=traceback.format_exc())
                else:
                    log.debug('Running on Linux and optimal reactor (epoll) was installed.')
            else:
                log.warn('Running on Linux, but cannot install Epoll Twisted reactor, because another reactor ({klass}) is already installed.', klass=current_reactor)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug('Running on Linux and optimal reactor (epoll) already installed.')

    else:

        # Other platform
        #
        if current_reactor != 'SelectReactor':
            if current_reactor is None:
                try:
                    from twisted.internet import selectreactor
                    selectreactor.install()
                    # from twisted.internet import default as defaultreactor
                    # defaultreactor.install()
                except:
                    log.warn('Running on "{platform}", but cannot install Select Twisted reactor: {tb}', tb=traceback.format_exc(), platform=sys.platform)
                else:
                    log.debug('Running on "{platform}" and optimal reactor (Select) was installed.', platform=sys.platform)
            else:
                log.warn('Running on "{platform}", but cannot install Select Twisted reactor, because another reactor ({klass}) is already installed.', klass=current_reactor, platform=sys.platform)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug('Running on "{platform}" and optimal reactor (Select) already installed.', platform=sys.platform)

    from twisted.internet import reactor
    txaio.config.loop = reactor

    return reactor
Esempio n. 29
0
def install_optimal_reactor(verbose=False):
    """
    Try to install the optimal Twisted reactor for this platform.

    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    log = make_logger()

    import sys
    from twisted.python import reflect
    import txaio
    txaio.use_twisted()  # just to be sure...
    # XXX should I configure txaio.config.loop in here too, or just in
    # install_reactor()? (I am: see bottom of function)

    # determine currently installed reactor, if any
    ##
    if 'twisted.internet.reactor' in sys.modules:
        current_reactor = reflect.qual(
            sys.modules['twisted.internet.reactor'].__class__).split('.')[-1]
    else:
        current_reactor = None

    # depending on platform, install optimal reactor
    ##
    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):

        # *BSD and MacOSX
        ##
        if current_reactor != 'KQueueReactor':
            try:
                from twisted.internet import kqreactor
                kqreactor.install()
            except:
                log.critical(
                    "Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor"
                )
                log.debug(traceback.format_exc())
            else:
                log.debug(
                    "Running on *BSD or MacOSX and optimal reactor (kqueue) was installed."
                )
        else:
            log.debug(
                "Running on *BSD or MacOSX and optimal reactor (kqueue) already installed."
            )

    elif sys.platform in ['win32']:

        # Windows
        ##
        if current_reactor != 'IOCPReactor':
            try:
                from twisted.internet.iocpreactor import reactor as iocpreactor
                iocpreactor.install()
            except:
                log.critical(
                    "Running on Windows, but cannot install IOCP Twisted reactor"
                )
                log.debug(traceback.format_exc())
            else:
                log.debug(
                    "Running on Windows and optimal reactor (ICOP) was installed."
                )
        else:
            log.debug(
                "Running on Windows and optimal reactor (ICOP) already installed."
            )

    elif sys.platform.startswith('linux'):

        # Linux
        ##
        if current_reactor != 'EPollReactor':
            try:
                from twisted.internet import epollreactor
                epollreactor.install()
            except:
                log.critical(
                    "Running on Linux, but cannot install Epoll Twisted reactor"
                )
                log.debug(traceback.format_exc())
            else:
                log.debug(
                    "Running on Linux and optimal reactor (epoll) was installed."
                )
        else:
            log.debug(
                "Running on Linux and optimal reactor (epoll) already installed."
            )

    else:
        try:
            from twisted.internet import default as defaultreactor
            defaultreactor.install()
        except:
            log.critical(
                "Could not install default Twisted reactor for this platform")
            log.debug(traceback.format_exc())

    from twisted.internet import reactor
    txaio.config.loop = reactor
Esempio n. 30
0
# Copyright (C) 2008-2014 AG Projects
#

"""Implementation of the MediaProxy relay"""

import cjson
import signal
import resource
from time import time

try:    from twisted.internet import epollreactor; epollreactor.install()
except: raise RuntimeError("mandatory epoll reactor support is missing from the twisted framework")

from application import log
from application.process import process
from gnutls.errors import CertificateError, CertificateSecurityError
from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet.error import ConnectionDone, TCPTimedOutError, DNSLookupError
from twisted.internet.protocol import ClientFactory
from twisted.internet.defer import DeferredList, succeed
from twisted.internet import reactor
from twisted.python import failure
from twisted.names import dns
from twisted.names.client import lookupService
from twisted.names.error import DomainError

from mediaproxy import __version__
from mediaproxy.configuration import RelayConfig
from mediaproxy.headers import DecodingDict, DecodingError
from mediaproxy.mediacontrol import SessionManager, RelayPortsExhaustedError
from mediaproxy.scheduler import RecurrentCall, KeepRunning
def install_optimal_reactor(verbose=False):
    """
    Try to install the optimal Twisted reactor for this platform.

    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    log = make_logger()

    import sys
    from twisted.python import reflect
    import txaio
    txaio.use_twisted()  # just to be sure...
    # XXX should I configure txaio.config.loop in here too, or just in
    # install_reactor()? (I am: see bottom of function)

    # determine currently installed reactor, if any
    ##
    if 'twisted.internet.reactor' in sys.modules:
        current_reactor = reflect.qual(sys.modules['twisted.internet.reactor'].__class__).split('.')[-1]
    else:
        current_reactor = None

    # depending on platform, install optimal reactor
    ##
    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):

        # *BSD and MacOSX
        ##
        if current_reactor != 'KQueueReactor':
            try:
                from twisted.internet import kqreactor
                kqreactor.install()
            except:
                log.critical("Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor")
                log.debug(traceback.format_exc())
            else:
                log.debug("Running on *BSD or MacOSX and optimal reactor (kqueue) was installed.")
        else:
            log.debug("Running on *BSD or MacOSX and optimal reactor (kqueue) already installed.")

    elif sys.platform in ['win32']:

        # Windows
        ##
        if current_reactor != 'IOCPReactor':
            try:
                from twisted.internet.iocpreactor import reactor as iocpreactor
                iocpreactor.install()
            except:
                log.critical("Running on Windows, but cannot install IOCP Twisted reactor")
                log.debug(traceback.format_exc())
            else:
                log.debug("Running on Windows and optimal reactor (ICOP) was installed.")
        else:
            log.debug("Running on Windows and optimal reactor (ICOP) already installed.")

    elif sys.platform.startswith('linux'):

        # Linux
        ##
        if current_reactor != 'EPollReactor':
            try:
                from twisted.internet import epollreactor
                epollreactor.install()
            except:
                log.critical("Running on Linux, but cannot install Epoll Twisted reactor")
                log.debug(traceback.format_exc())
            else:
                log.debug("Running on Linux and optimal reactor (epoll) was installed.")
        else:
            log.debug("Running on Linux and optimal reactor (epoll) already installed.")

    else:
        try:
            from twisted.internet import default as defaultreactor
            defaultreactor.install()
        except:
            log.critical("Could not install default Twisted reactor for this platform")
            log.debug(traceback.format_exc())

    from twisted.internet import reactor
    txaio.config.loop = reactor
Esempio n. 32
0
 def install_epoll(self):
     from twisted.internet import epollreactor
     epollreactor.install()
Esempio n. 33
0
def install_optimal_reactor(require_optimal_reactor=True):
    """
    Try to install the optimal Twisted reactor for this platform:

    - Linux:   epoll
    - BSD/OSX: kqueue
    - Windows: iocp
    - Other:   select

    Notes:

    - This function exists, because the reactor types selected based on platform
      in `twisted.internet.default` are different from here.
    - The imports are inlined, because the Twisted code base is notorious for
      importing the reactor as a side-effect of merely importing. Hence we postpone
      all importing.

    See: http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html#reactor-functionality

    :param require_optimal_reactor: If ``True`` and the desired reactor could not be installed,
        raise ``ReactorAlreadyInstalledError``, else fallback to another reactor.
    :type require_optimal_reactor: bool

    :returns: The Twisted reactor in place (`twisted.internet.reactor`).
    """
    log = txaio.make_logger()

    # determine currently installed reactor, if any
    #
    current_reactor = current_reactor_klass()

    # depending on platform, install optimal reactor
    #
    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):

        # *BSD and MacOSX
        #
        if current_reactor != 'KQueueReactor':
            if current_reactor is None:
                try:
                    from twisted.internet import kqreactor
                    kqreactor.install()
                except:
                    log.warn(
                        'Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor: {tb}',
                        tb=traceback.format_exc())
                else:
                    log.debug(
                        'Running on *BSD or MacOSX and optimal reactor (kqueue) was installed.'
                    )
            else:
                log.warn(
                    'Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor, because another reactor ({klass}) is already installed.',
                    klass=current_reactor)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug(
                'Running on *BSD or MacOSX and optimal reactor (kqueue) already installed.'
            )

    elif sys.platform in ['win32']:

        # Windows
        #
        if current_reactor != 'IOCPReactor':
            if current_reactor is None:
                try:
                    from twisted.internet.iocpreactor import reactor as iocpreactor
                    iocpreactor.install()
                except:
                    log.warn(
                        'Running on Windows, but cannot install IOCP Twisted reactor: {tb}',
                        tb=traceback.format_exc())
                else:
                    log.debug(
                        'Running on Windows and optimal reactor (ICOP) was installed.'
                    )
            else:
                log.warn(
                    'Running on Windows, but cannot install IOCP Twisted reactor, because another reactor ({klass}) is already installed.',
                    klass=current_reactor)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug(
                'Running on Windows and optimal reactor (ICOP) already installed.'
            )

    elif sys.platform.startswith('linux'):

        # Linux
        #
        if current_reactor != 'EPollReactor':
            if current_reactor is None:
                try:
                    from twisted.internet import epollreactor
                    epollreactor.install()
                except:
                    log.warn(
                        'Running on Linux, but cannot install Epoll Twisted reactor: {tb}',
                        tb=traceback.format_exc())
                else:
                    log.debug(
                        'Running on Linux and optimal reactor (epoll) was installed.'
                    )
            else:
                log.warn(
                    'Running on Linux, but cannot install Epoll Twisted reactor, because another reactor ({klass}) is already installed.',
                    klass=current_reactor)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug(
                'Running on Linux and optimal reactor (epoll) already installed.'
            )

    else:

        # Other platform
        #
        if current_reactor != 'SelectReactor':
            if current_reactor is None:
                try:
                    from twisted.internet import selectreactor
                    selectreactor.install()
                    # from twisted.internet import default as defaultreactor
                    # defaultreactor.install()
                except:
                    log.warn(
                        'Running on "{platform}", but cannot install Select Twisted reactor: {tb}',
                        tb=traceback.format_exc(),
                        platform=sys.platform)
                else:
                    log.debug(
                        'Running on "{platform}" and optimal reactor (Select) was installed.',
                        platform=sys.platform)
            else:
                log.warn(
                    'Running on "{platform}", but cannot install Select Twisted reactor, because another reactor ({klass}) is already installed.',
                    klass=current_reactor,
                    platform=sys.platform)
                if require_optimal_reactor:
                    raise ReactorAlreadyInstalledError()
        else:
            log.debug(
                'Running on "{platform}" and optimal reactor (Select) already installed.',
                platform=sys.platform)

    from twisted.internet import reactor
    txaio.config.loop = reactor

    return reactor
Esempio n. 34
0
import sys
import thread

from monocle import launch

# prefer fast reactors
# FIXME: this should optionally refuse to use slow ones
if not "twisted.internet.reactor" in sys.modules:
    try:
        from twisted.internet import epollreactor
        epollreactor.install()
    except:
        try:
            from twisted.internet import kqreactor
            kqreactor.install()
        except:
            try:
                from twisted.internet import pollreactor
                pollreactor.install()
            except:
                pass

from twisted.internet import reactor
try:
    from twisted.internet.error import ReactorNotRunning
except ImportError:
    ReactorNotRunning = RuntimeError


# thanks to Peter Norvig
def singleton(object, message="singleton class already instantiated",
Esempio n. 35
0
def install_optimal_reactor(verbose=False):
    """
    Try to install the optimal Twisted reactor for platform.

    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    import sys
    from twisted.python import reflect
    import txaio
    txaio.use_twisted()  # just to be sure...
    # XXX should I configure txaio.config.loop in here too, or just in
    # install_reactor()? (I am: see bottom of function)

    # determine currently installed reactor, if any
    ##
    if 'twisted.internet.reactor' in sys.modules:
        current_reactor = reflect.qual(sys.modules['twisted.internet.reactor'].__class__).split('.')[-1]
    else:
        current_reactor = None

    # depending on platform, install optimal reactor
    ##
    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):

        # *BSD and MacOSX
        ##
        if current_reactor != 'KQueueReactor':
            try:
                v = sys.version_info
                if v[0] == 1 or (v[0] == 2 and v[1] < 6) or (v[0] == 2 and v[1] == 6 and v[2] < 5):
                    raise Exception("Python version too old ({0}) to use kqueue reactor".format(sys.version))
                from twisted.internet import kqreactor
                kqreactor.install()
            except Exception as e:
                print("WARNING: Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor ({0}).".format(e))
            else:
                if verbose:
                    print("Running on *BSD or MacOSX and optimal reactor (kqueue) was installed.")
        else:
            if verbose:
                print("Running on *BSD or MacOSX and optimal reactor (kqueue) already installed.")

    elif sys.platform in ['win32']:

        # Windows
        ##
        if current_reactor != 'IOCPReactor':
            try:
                from twisted.internet.iocpreactor import reactor as iocpreactor
                iocpreactor.install()
            except Exception as e:
                print("WARNING: Running on Windows, but cannot install IOCP Twisted reactor ({0}).".format(e))
            else:
                if verbose:
                    print("Running on Windows and optimal reactor (ICOP) was installed.")
        else:
            if verbose:
                print("Running on Windows and optimal reactor (ICOP) already installed.")

    elif sys.platform.startswith('linux'):

        # Linux
        ##
        if current_reactor != 'EPollReactor':
            try:
                from twisted.internet import epollreactor
                epollreactor.install()
            except Exception as e:
                print("WARNING: Running on Linux, but cannot install Epoll Twisted reactor ({0}).".format(e))
            else:
                if verbose:
                    print("Running on Linux and optimal reactor (epoll) was installed.")
        else:
            if verbose:
                print("Running on Linux and optimal reactor (epoll) already installed.")

    else:
        try:
            from twisted.internet import default as defaultreactor
            defaultreactor.install()
        except Exception as e:
            print("WARNING: Could not install default Twisted reactor for this platform ({0}).".format(e))

    from twisted.internet import reactor
    txaio.config.loop = reactor
Esempio n. 36
0
def main():

    parser = OptionParser()
    parser.add_option(
        '-l',
        '--loglevel',
        default='info',
        dest='logLevel',
        help=
        'This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info'
    )
    parser.add_option(
        '-p',
        '--port',
        default=443,
        type='int',
        dest='port',
        help=
        'This option lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)'
    )
    parser.add_option('--logfile',
                      default=None,
                      dest='logfile',
                      help='Log to a file instead of stdout.')
    parser.add_option(
        '-m',
        '--maxConnections',
        default=None,
        type='int',
        dest='maxConnections',
        help=
        'You can limit the number of maximum simultaneous connections with that switch'
    )
    parser.add_option(
        '-f',
        '--forcebuild',
        default=None,
        dest='customHostname',
        help=
        'This option will force rebuild the certificate using the custom hostname and exit.'
    )
    parser.add_option('-n',
                      '--noSSL',
                      action="store_true",
                      default=False,
                      dest='sslDisabled',
                      help='You can switch off SSL with this switch.')
    (options, _) = parser.parse_args()

    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])

    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()

    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)

    if not options.sslDisabled:
        create_self_signed_cert(options.customHostname)
        if options.customHostname != None:
            return

    try:
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    x.info("Starting server on port {0}".format(options.port))
    if options.sslDisabled:
        x.warning(
            "Starting, as requested, without SSL, connections are not secured and can be altered and eavesdropped on from client to server"
        )
        reactor.listenTCP(options.port, SiriFactory(options.maxConnections))
    else:
        reactor.listenSSL(
            options.port, SiriFactory(options.maxConnections),
            ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE,
                                             SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Esempio n. 37
0
def install_optimal_reactor(verbose=False):
    """
   Try to install the optimal Twisted reactor for platform.

   :param verbose: If ``True``, print what happens.
   :type verbose: bool
   """
    import sys
    from twisted.python import reflect
    from twisted.python import log

    ## determine currently installed reactor, if any
    ##
    if "twisted.internet.reactor" in sys.modules:
        current_reactor = reflect.qual(sys.modules["twisted.internet.reactor"].__class__).split(".")[-1]
    else:
        current_reactor = None

    ## depending on platform, install optimal reactor
    ##
    if "bsd" in sys.platform or sys.platform.startswith("darwin"):

        ## *BSD and MacOSX
        ##
        if current_reactor != "KQueueReactor":
            try:
                v = sys.version_info
                if v[0] == 1 or (v[0] == 2 and v[1] < 6) or (v[0] == 2 and v[1] == 6 and v[2] < 5):
                    raise Exception("Python version too old ({0}) to use kqueue reactor".format(sys.version))
                from twisted.internet import kqreactor

                kqreactor.install()
            except Exception as e:
                log.err(
                    "WARNING: Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor ({0}).".format(e)
                )
            else:
                if verbose:
                    log.msg("Running on *BSD or MacOSX and optimal reactor (kqueue) was installed.")
        else:
            if verbose:
                log.msg("Running on *BSD or MacOSX and optimal reactor (kqueue) already installed.")

    elif sys.platform in ["win32"]:

        ## Windows
        ##
        if current_reactor != "IOCPReactor":
            try:
                from twisted.internet.iocpreactor import reactor as iocpreactor

                iocpreactor.install()
            except Exception as e:
                log.err("WARNING: Running on Windows, but cannot install IOCP Twisted reactor ({0}).".format(e))
            else:
                if verbose:
                    log.msg("Running on Windows and optimal reactor (ICOP) was installed.")
        else:
            if verbose:
                log.msg("Running on Windows and optimal reactor (ICOP) already installed.")

    elif sys.platform.startswith("linux"):

        ## Linux
        ##
        if current_reactor != "EPollReactor":
            try:
                from twisted.internet import epollreactor

                epollreactor.install()
            except Exception as e:
                log.err("WARNING: Running on Linux, but cannot install Epoll Twisted reactor ({0}).".format(e))
            else:
                if verbose:
                    log.msg("Running on Linux and optimal reactor (epoll) was installed.")
        else:
            if verbose:
                log.msg("Running on Linux and optimal reactor (epoll) already installed.")

    else:
        try:
            from twisted.internet import default as defaultreactor

            defaultreactor.install()
        except Exception as e:
            log.err("WARNING: Could not install default Twisted reactor for this platform ({0}).".format(e))
Esempio n. 38
0
# print(os.name, '000000000000')                      # posix
if os.name != 'nt':
    try:
        if platform.isLinux():
            try:
                from twisted.internet.epollreactor import install
            except ImportError:
                from twisted.internet.pollreactor import install
        elif platform.getType() == 'posix' and not platform.isMacOSX():
            from twisted.internet.pollreactor import install
        else:
            from twisted.internet.selectreactor import install
    except ImportError:
        from twisted.internet.selectreactor import install
    install()

from twisted.internet import reactor
from twisted.python import log
from learn_twist.utils import services
from learn_twist.netconnect.protoc import LiberateFactory

reactor = reactor
service = services.CommandService("loginService",
                                  run_style=services.Service.PARALLEL_STYLE)


def serviceHandle(target):
    '''服务处理
    @param target: func Object
    '''
Esempio n. 39
0
def install_optimal_reactor(verbose=False):
    """
    Try to install the optimal Twisted reactor for this platform.

    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    log = txaio.make_logger()

    import sys
    from twisted.python import reflect

    # determine currently installed reactor, if any
    ##
    if "twisted.internet.reactor" in sys.modules:
        current_reactor = reflect.qual(sys.modules["twisted.internet.reactor"].__class__).split(".")[-1]
    else:
        current_reactor = None

    # depending on platform, install optimal reactor
    ##
    if "bsd" in sys.platform or sys.platform.startswith("darwin"):

        # *BSD and MacOSX
        ##
        if current_reactor != "KQueueReactor":
            try:
                from twisted.internet import kqreactor

                kqreactor.install()
            except:
                log.critical("Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor")
                log.warn("{tb}", tb=traceback.format_exc())
            else:
                log.debug("Running on *BSD or MacOSX and optimal reactor (kqueue) was installed.")
        else:
            log.debug("Running on *BSD or MacOSX and optimal reactor (kqueue) already installed.")

    elif sys.platform in ["win32"]:

        # Windows
        ##
        if current_reactor != "IOCPReactor":
            try:
                from twisted.internet.iocpreactor import reactor as iocpreactor

                iocpreactor.install()
            except:
                log.critical("Running on Windows, but cannot install IOCP Twisted reactor")
                log.warn("{tb}", tb=traceback.format_exc())
            else:
                log.debug("Running on Windows and optimal reactor (ICOP) was installed.")
        else:
            log.debug("Running on Windows and optimal reactor (ICOP) already installed.")

    elif sys.platform.startswith("linux"):

        # Linux
        ##
        if current_reactor != "EPollReactor":
            try:
                from twisted.internet import epollreactor

                epollreactor.install()
            except:
                log.critical("Running on Linux, but cannot install Epoll Twisted reactor")
                log.warn("{tb}", tb=traceback.format_exc())
            else:
                log.debug("Running on Linux and optimal reactor (epoll) was installed.")
        else:
            log.debug("Running on Linux and optimal reactor (epoll) already installed.")

    else:
        try:
            from twisted.internet import default as defaultreactor

            defaultreactor.install()
        except:
            log.critical("Could not install default Twisted reactor for this platform")
            log.warn("{tb}", tb=traceback.format_exc())

    from twisted.internet import reactor

    txaio.config.loop = reactor
Esempio n. 40
0
def install_optimal_reactor(verbose=False):
    """
    Try to install the optimal Twisted reactor for platform.

    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    import sys
    from twisted.python import reflect
    import txaio
    txaio.use_twisted()  # just to be sure...
    # XXX should I configure txaio.config.loop in here too, or just in
    # install_reactor()? (I am: see bottom of function)

    # determine currently installed reactor, if any
    ##
    if 'twisted.internet.reactor' in sys.modules:
        current_reactor = reflect.qual(
            sys.modules['twisted.internet.reactor'].__class__).split('.')[-1]
    else:
        current_reactor = None

    # depending on platform, install optimal reactor
    ##
    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):

        # *BSD and MacOSX
        ##
        if current_reactor != 'KQueueReactor':
            try:
                v = sys.version_info
                if v[0] == 1 or (v[0] == 2
                                 and v[1] < 6) or (v[0] == 2 and v[1] == 6
                                                   and v[2] < 5):
                    raise Exception(
                        "Python version too old ({0}) to use kqueue reactor".
                        format(sys.version))
                from twisted.internet import kqreactor
                kqreactor.install()
            except Exception as e:
                print(
                    "WARNING: Running on *BSD or MacOSX, but cannot install kqueue Twisted reactor ({0})."
                    .format(e))
            else:
                if verbose:
                    print(
                        "Running on *BSD or MacOSX and optimal reactor (kqueue) was installed."
                    )
        else:
            if verbose:
                print(
                    "Running on *BSD or MacOSX and optimal reactor (kqueue) already installed."
                )

    elif sys.platform in ['win32']:

        # Windows
        ##
        if current_reactor != 'IOCPReactor':
            try:
                from twisted.internet.iocpreactor import reactor as iocpreactor
                iocpreactor.install()
            except Exception as e:
                print(
                    "WARNING: Running on Windows, but cannot install IOCP Twisted reactor ({0})."
                    .format(e))
            else:
                if verbose:
                    print(
                        "Running on Windows and optimal reactor (ICOP) was installed."
                    )
        else:
            if verbose:
                print(
                    "Running on Windows and optimal reactor (ICOP) already installed."
                )

    elif sys.platform.startswith('linux'):

        # Linux
        ##
        if current_reactor != 'EPollReactor':
            try:
                from twisted.internet import epollreactor
                epollreactor.install()
            except Exception as e:
                print(
                    "WARNING: Running on Linux, but cannot install Epoll Twisted reactor ({0})."
                    .format(e))
            else:
                if verbose:
                    print(
                        "Running on Linux and optimal reactor (epoll) was installed."
                    )
        else:
            if verbose:
                print(
                    "Running on Linux and optimal reactor (epoll) already installed."
                )

    else:
        try:
            from twisted.internet import default as defaultreactor
            defaultreactor.install()
        except Exception as e:
            print(
                "WARNING: Could not install default Twisted reactor for this platform ({0})."
                .format(e))

    from twisted.internet import reactor
    txaio.config.loop = reactor
Esempio n. 41
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=4443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    parser.add_option('-d', '--daemon', default=None, dest='daemon', action="store_true", help='run SiriServer as a daemon')
    parser.add_option('--kill', default=None, dest='kill', help='kills a running daemon by the provided pidfile')
    (options, _) = parser.parse_args()

    createPID = False
    
    if options.daemon:
        if options.logfile:
            daemonize()        
            reatePID = True
        else:
            options.logfile = "/var/log/SiriServer.log"
            daemonize()
            createPID = True   
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    

    if options.kill != None:
        PIDFILE = options.kill
        if os.path.exists(PIDFILE):
            try:
                pidtokill = open(PIDFILE, 'r').read()
                os.kill(int(pidtokill), signal.SIGTERM)
                os.unlink(PIDFILE)
                x.info("SiriServer successfully killed")
            except:
                x.info("Error trying to Kill " + str(pidtokill))
            exit()
        else:
            x.info("Seems like SiriServer is not running...")
            exit()


    create_self_signed_cert()
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    if createPID:
        PIDFILE = tempfile.mkstemp(suffix=".pid", prefix="SiriServer-", dir="/var/run")
        PIDFILE = PIDFILE[1]
        pid = str(os.getpid())
        x.info(u"Writing PID " + pid + " to " + str(PIDFILE))
        file(PIDFILE, 'w').write(pid)


    x.info("Starting server on port {0}".format(options.port))
    reactor.listenSSL(options.port, SiriFactory(), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Esempio n. 42
0
"""Implementation of the MediaProxy relay"""

import cjson
import signal
import resource
from time import time

try:    from twisted.internet import epollreactor; epollreactor.install()
except: raise RuntimeError("mandatory epoll reactor support is missing from the twisted framework")

from application import log
from application.process import process
from gnutls.errors import CertificateError, CertificateSecurityError
from gnutls.interfaces.twisted import TLSContext
from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet.error import ConnectionDone, TCPTimedOutError, DNSLookupError
from twisted.internet.protocol import ClientFactory
from twisted.internet.defer import DeferredList, succeed
from twisted.internet import reactor
from twisted.python import failure
from twisted.names import dns
from twisted.names.client import lookupService
from twisted.names.error import DomainError

from mediaproxy import __version__
from mediaproxy.configuration import RelayConfig
from mediaproxy.headers import DecodingDict, DecodingError
from mediaproxy.mediacontrol import SessionManager, RelayPortsExhaustedError
from mediaproxy.scheduler import RecurrentCall, KeepRunning
from mediaproxy.tls import X509Credentials
Esempio n. 43
0
from optparse import OptionParser

# Figure out where we're installed
BIN_DIR = dirname(abspath(__file__))
ROOT_DIR = dirname(BIN_DIR)
CONF_DIR = join(ROOT_DIR, 'conf')
default_relayrules = join(CONF_DIR, 'relay-rules.conf')

# Make sure that carbon's 'lib' dir is in the $PYTHONPATH if we're running from
# source.
LIB_DIR = join(ROOT_DIR, 'lib')
sys.path.insert(0, LIB_DIR)

try:
    from twisted.internet import epollreactor
    epollreactor.install()
except ImportError:
    pass

from twisted.internet import stdio, reactor, defer  # noqa
from twisted.protocols.basic import LineReceiver  # noqa
from carbon.routers import ConsistentHashingRouter, RelayRulesRouter  # noqa
from carbon.client import CarbonClientManager  # noqa
from carbon import log, events  # noqa

option_parser = OptionParser(
    usage="%prog [options] <host:port:instance> <host:port:instance> ...")
option_parser.add_option('--debug',
                         action='store_true',
                         help="Log debug info to stdout")
option_parser.add_option(
Esempio n. 44
0
def installReactor(rtype):
    if rtype == 'epoll':
        from twisted.internet import epollreactor
        epollreactor.install()