Exemple #1
0
def main():
    from optparse import OptionParser
    parser = OptionParser(usage="usage: %prog [options] channels")

    # IRC connection options
    parser.add_option("-s", "--server",
                      action="store", dest="server",
                      default="irc.freenode.net",
                      help="IRC server to connect to")
    parser.add_option("-p", "--port",
                      action="store", type="int", dest="port", default=None,
                      help="IRC server to connect to")
    parser.add_option("--ssl",
                      action="store_true", dest="ssl", default=False,
                      help="use SSL")
    parser.add_option("--password",
                      action="store", dest="password", default=None,
                      help="server password")
    parser.add_option("-n", "--nick",
                      action="store", dest="nick", default="karmabot",
                      help="nickname to use")
    # Bot options
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="enable verbose output")
    parser.add_option("-d", "--data",
                      action="store", dest="filename", default="karma.json",
                      help="karma data file name")
    parser.add_option("-t", "--trust",
                      action="append", dest="trusted", default=[],
                      help="trusted hostmasks")
    parser.add_option("-f", "--facets",
                      action="append", dest="facets", default=[],
                      help="additional facets to load")

    (options, channels) = parser.parse_args()

    if not channels:
        parser.error("You must supply some channels to join.")
    else:
        log.msg("Channels to join: %s" % channels)

    if options.verbose:
        log.startLogging(sys.stdout)

    if not options.port:
        options.port = 6667 if not options.ssl else 9999
    
    # FIXME: this needs to be replaced with a real facet manager
    for facet_path in options.facets:
        execfile(facet_path, globals())

    factory = KarmaBotFactory(options.filename, options.nick,
                              channels, options.trusted, options.password)
    if not options.ssl:
        reactor.connectTCP(options.server, options.port, factory)
    else:
        reactor.connectSSL(options.server, options.port,
                           factory, ssl.ClientContextFactory())
    reactor.run()
Exemple #2
0
 def run(self):
     log.msg("Running bot as %r" % self.name)
     self.irc = BottuClientFactory(self)
     self.join_passive_channel.ready()
     reactor.connectTCP(self.network, self.port, self.irc)
     reactor.run()
     log.msg("Stopping bot")
Exemple #3
0
 def __init__(self, lm, port=12346, n=0):
     """n indicates the n-gram size, if set to 0 (which is default), the server will expect to only receive whole sentence, if set to a particular value, it will only expect n-grams of that value"""
     if n == 0:
         reactor.listenTCP(port, LMSentenceFactory(lm))
     else:
         reactor.listenTCP(port, LMNGramFactory(lm))
     reactor.run()
Exemple #4
0
 def run():
     with LoggingContext("run"):
         logger.info("Running")
         change_resource_limit(config.soft_file_limit)
         if config.gc_thresholds:
             gc.set_threshold(*config.gc_thresholds)
         reactor.run()
 def run(self):
     framelog = os.path.join(self.basedir, "driver.log")
     log.startLogging(open(framelog, "a"), setStdout=False)
     log.msg("CHECK_MEMORY(mode=%s) STARTING" % self.mode)
     #logfile = open(os.path.join(self.testdir, "log"), "w")
     #flo = log.FileLogObserver(logfile)
     #log.startLoggingWithObserver(flo.emit, setStdout=False)
     d = fireEventually()
     d.addCallback(lambda res: self.setUp())
     d.addCallback(lambda res: self.record_initial_memusage())
     d.addCallback(lambda res: self.make_nodes())
     d.addCallback(lambda res: self.wait_for_client_connected())
     d.addCallback(lambda res: self.do_test())
     d.addBoth(self.tearDown)
     def _err(err):
         self.failed = err
         log.err(err)
         print err
     d.addErrback(_err)
     def _done(res):
         reactor.stop()
         return res
     d.addBoth(_done)
     reactor.run()
     if self.failed:
         # raiseException doesn't work for CopiedFailures
         self.failed.raiseException()
Exemple #6
0
def run(port, hostname, interface, verbosity):
    if verbosity == 0: # -q
        level = logging.CRITICAL
    elif verbosity == 1: # default
        level = logging.WARNING
    elif verbosity == 2: # -v
        level = logging.INFO
    else: # -v -v
        level = logging.DEBUG
    logging.basicConfig(level=level)

    if hostname:
        if not hostname.startswith('http://'):
            hostname = 'http://%s' % (hostname,)
        sep = hostname.find('/')
        if sep != -1:
            hostname = hostname[:sep]
        if port != 80 and not ':' in hostname:
            hostname = "http://%s:%d/" % (hostname, port)
        else:
            hostname = "http://%s/" % hostname
        logging.info('Hostname set to %s' % hostname)

    pong = PongGame()

    reactor.listenTCP(port, HttpFactory(hostname, pong), interface=interface)
    reactor.run()
Exemple #7
0
 def run(self):
     """
     Start serving webpages from the local web server
     """
     log.debug("start web server running")
     webDir = self.config.webDir
     self.root.putChild("images",      static.File(webDir+"/images"))
     self.root.putChild("previews",      static.File(webDir+"/previews"))
     self.root.putChild("css",         static.File(webDir+"/css"))   
     self.root.putChild("scripts",     static.File(webDir+"/scripts"))
     self.root.putChild("style",       static.File(webDir+"/style"))
     self.root.putChild("docs",        static.File(webDir+"/docs"))
     self.root.putChild("temp_print_dirs",
                                       static.File(webDir+"/temp_print_dirs"))
     xulDir = self.config.xulDir
     self.root.putChild("xulscripts",  static.File(xulDir+"/scripts"))
     self.root.putChild("xultemplates",  static.File(xulDir+"/templates"))
     self.root.putChild("templates",   static.File(webDir+"/templates"))
     self.root.putChild("editor",      self.editor)
     self.root.putChild("preferences", self.preferences)
     self.root.putChild("about",       self.about)
     if self.config.port >= 0:
         log.info("run() using eXe port# %d", self.config.port)
         reactor.run()
     else:
         log.error("ERROR: webserver's run() called, but a valid port was not available.")
Exemple #8
0
    def next_step(self):
        # We already sent the details, but may still be on the same step.
        # Also, if the user didn't choose to "register now", respect his
        # decision
        if not self.model.register_now or self.wizard.link_request_done:
            return FinishInstallationStep(self.wizard)

        webapi = WebService()
        response = webapi.link_registration(
            self.model.name, self.model.email, self.model.phone)
        response.addCallback(self._on_response_done)
        response.addErrback(self._on_response_error)

        # FIXME: This is a hack, remove it when we can avoid
        #        calling dialog.run()
        if not reactor.running:
            reactor.run()

        self.send_progress.show()
        self.send_progress.set_text(_('Sending...'))
        self.send_progress.set_pulse_step(0.05)
        self.wizard.next_button.set_sensitive(False)
        glib.timeout_add(50, self._pulse)

        # Cancel the request after 30 seconds without a reply
        glib.timeout_add(30000, self._cancel_request)

        # Stay on the same step while sending the details
        return self
def main():
	factory = protocol.ServerFactory()      # 实例化一个ServerFactory对象
	factory.protocol = Echo     # 重写protocol

	# reactor(反应堆)就是twisted的事件驱动,是twisted的核心.
	reactor.listenTCP(1234, factory)  # 将factory回调函数注册到reactor中,reactor监听指定端口,根据状态来触发factory中不同的方法
	reactor.run()   # 启动一个TCP服务器, 监听1234端口,reactor则开始监听。
Exemple #10
0
def main():
    boots = (('router.bittorrent.com', 6881),)
    p = BittorrentProtocol(boots)
    # lc = LoopingCall(monitor, p)
    # lc.start(5)
    reactor.listenUDP(6881, p)
    reactor.run()
Exemple #11
0
    def run(self):
        self.factory = HTTPFactory(
            self.channel_layer,
            self.action_logger,
            timeout=self.http_timeout,
            websocket_timeout=self.websocket_timeout,
            ping_interval=self.ping_interval,
            ws_protocols=self.ws_protocols,
            root_path=self.root_path,
        )
        # Redirect the Twisted log to nowhere
        globalLogBeginner.beginLoggingTo([lambda _: None], redirectStandardIO=False, discardBuffer=True)
        # Listen on a socket
        if self.unix_socket:
            reactor.listenUNIX(self.unix_socket, self.factory)
        elif self.file_descriptor:
            # socket returns the same socket if supplied with a fileno
            sock = socket.socket(fileno=self.file_descriptor)
            reactor.adoptStreamPort(self.file_descriptor, sock.family, self.factory)
        else:
            reactor.listenTCP(self.port, self.factory, interface=self.host)

        if "twisted" in self.channel_layer.extensions:
            logging.info("Using native Twisted mode on channel layer")
            reactor.callLater(0, self.backend_reader_twisted)
        else:
            logging.info("Using busy-loop synchronous mode on channel layer")
            reactor.callLater(0, self.backend_reader_sync)
        reactor.callLater(2, self.timeout_checker)
        reactor.run(installSignalHandlers=self.signal_handlers)
Exemple #12
0
 def wrapper(*args, **kwds):
     # Ignore SIGINT to avoid it being captured in the child process
     # when pressing ctrl+c on the terminal to close the server
     signal.signal(signal.SIGINT, signal.SIG_IGN)
     signal.signal(signal.SIGTERM, _sigterm_handler)
     f(*args, **kwds)
     reactor.run(False)
Exemple #13
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--port')
  parser.add_argument('--store')
  parser.add_argument('--retrieve')
  parser.add_argument('--connect', default=None)

  args = parser.parse_args()
  port = int(args.port)

  service = ChordService()

  if (args.connect):
    dst = args.connect.split(':')
    service.AddToRoutingTable(IPv4Address('TCP', dst[0], int(dst[1])))

  if (args.store):
    key, value = args.store.split(':')
    service.StoreValue(key, value)
    
  if (args.retrieve):
    def EchoValue(value):
      print('Retrieved value: {}.'.format(value))
    d = service.GetValue(args.retrieve)
    d.addCallback(EchoValue)

  f = pb.PBServerFactory(service)
  reactor.listenTCP(port, f)
    
  reactor.run()
Exemple #14
0
    def run(self, *args, **kw):
	""""""
	log.info("broker.run")
        from twisted.internet import reactor
        reactor.exitcode = 0
        reactor.run()
        return reactor.exitcode
    def test_priorization(self):
        webdriver = Mock()
        settings = self.settings(WEBDRIVER_BROWSER=webdriver)
        webdriver.get.side_effect = self._wait
        webdriver.page_source = u''

        dispatcher.connect(self._stop_reactor, signal=signals.spider_closed)

        crawler = Crawler(Settings(values=settings))
        crawler.configure()
        spider = self.Spider(name='test', domain='testdomain')
        crawler.crawl(spider)
        crawler.start()
        log.start(loglevel='ERROR')
        reactor.run()

        assert webdriver.get.mock_calls == [
            call('http://testdomain/path?wr=0'),
            call('http://testdomain/path?wr=0&wa=0'),
            call('http://testdomain/path?wr=0&wa=1'),
            call('http://testdomain/path?wr=1'),
            call('http://testdomain/path?wr=1&wa=0'),
            call('http://testdomain/path?wr=1&wa=1'),
            call('http://testdomain/path?wr=0&wa=0&wr=0'),
            call('http://testdomain/path?wr=0&wa=1&wr=0'),
            call('http://testdomain/path?wr=1&wa=0&wr=0'),
            call('http://testdomain/path?wr=1&wa=1&wr=0')]
Exemple #16
0
def main():
#    app=QApplication(sys.argv)
    app.setStyle("cleanlooks")
    d = im(app)
    client_twisted.clientUi=d
    #pylint: disable=E1101 
    reactor.run()
Exemple #17
0
    def run(self):
        # If umask = 0077, created files will be rw for effective user only
        # If umask = 0007, they will be rw for effective user and group only
        os.umask(self.config.umask)
        os.setegid(self.config.egid)
        os.seteuid(self.config.euid)

        # Daemonize early
        if self.daemon:
            self.lock.acquire()
            self.daemonize()

        # Do all kind of initialization
        try:
            ret = self.initialize()
        finally:
            # Tell the father how to return, and let him return (release)
            if self.daemon:
                self.state = ret
                self.lock.release()

        if ret:
            return ret

        reactor.run()
Exemple #18
0
def start(host='localhost', port=61613, username='******', password='******'):
    """Start twisted event loop and the fun should begin...
    """
    StompClientFactory.username = username
    StompClientFactory.password = password
    reactor.connectTCP(host, port, StompClientFactory())
    reactor.run()
Exemple #19
0
def main():
    config = hamper.config.load()
    hamper.log.setup_logging()

    reactor.connectTCP(config['server'], config['port'],
            CommanderFactory(config))
    reactor.run()
Exemple #20
0
 def add_bank(self):
     task = Administration(self.creds, "add bank", self.details)
     task.runEngine()
     try:
         reactor.run()
     except:
         pass
Exemple #21
0
 def add_settings(self):
     task = Administration(self.creds, "add settings", self.details)
     task.runEngine()
     try:
         reactor.run()
     except:
         pass
Exemple #22
0
def launch_stdout_downloader():

    from twisted.internet import reactor

    logging.basicConfig(level=logging.WARNING, filename="dl.log")
    if len(sys.argv) == 3:
        downloader = StdoutDownloader(int(sys.argv[2]), [])
    elif len(sys.argv) == 5:
        downloader = StdoutDownloader(int(sys.argv[2]), [(sys.argv[3], int(sys.argv[4]))])
    else:
        print "Usage: lbrynet-stdout-downloader <sd_hash> <peer_port> <dht_node_port>" \
              " [<dht_bootstrap_host> <dht_bootstrap port>]"
        sys.exit(1)

    def start_stdout_downloader():
        return downloader.start_download(sys.argv[1])

    def print_error(err):
        logging.warning(err.getErrorMessage())

    def shut_down():
        reactor.stop()

    d = task.deferLater(reactor, 0, downloader.start)
    d.addCallback(lambda _: start_stdout_downloader())
    d.addErrback(print_error)
    d.addCallback(lambda _: shut_down())
    reactor.addSystemEventTrigger('before', 'shutdown', downloader.shut_down)
    reactor.run()
Exemple #23
0
def main():
  #64bit machine builds innomitor and bitblinder
#  reactor.connectTCP('192.168.1.121', 12900, SSHFactory(LinuxInnomitorBuild()))
  reactor.connectTCP('192.168.1.121', 12900, SSHFactory(LinuxBitBlinderBuild(Globals.VERSION)))
  #32bit machine just builds innomitor
#  reactor.connectTCP('192.168.1.121', 13200, SSHFactory(LinuxInnomitorBuild()))
  reactor.run()
Exemple #24
0
def main():
    from twisted.internet import reactor
    from twisted.python import log
    import logging
    log.PythonLoggingObserver().start()
    logging.getLogger().setLevel(level=logging.DEBUG)
    LOG.setLevel(level=logging.DEBUG)

    api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    api_secret = "XXXXXXXXXXXX"

    flickr = TwistedFlickrAPI(api_key, api_secret)

    #flickr.authenticate_console("write"
    #    ).addCallback(log.msg, "<- got token"
    #    ).addBoth(lambda _: reactor.callLater(0, reactor.stop)
    #    )

    #flickr.upload("test.jpg", is_public="0"
    #    ).addBoth(log.msg
    #    ).addBoth(lambda _: reactor.callLater(0, reactor.stop)
    #    )

    flickr.photos_search(user_id='73509078@N00', per_page='10'
        ).addBoth(log.msg
        ).addBoth(lambda _: reactor.callLater(0, reactor.stop)
        )
    
    reactor.run()
Exemple #25
0
def poetry_main():
    addresses = parse_args()

    from twisted.internet import reactor

    poems = []
    errors = []

    def got_poem(poem):
        poems.append(poem)

    def poem_failed(err):
        print >>sys.stderr, 'Poem failed:', err
        errors.append(err)

    def poem_done(_):
        if len(poems) + len(errors) == len(addresses):
            reactor.stop()

    for address in addresses:
        host, port = address
        d = get_poetry(host, port)
        d.addCallbacks(got_poem, poem_failed)
        d.addBoth(poem_done)

    reactor.run()

    for poem in poems:
        print poem
Exemple #26
0
def getList():
    # For the sample client, below:
    from twisted.internet import reactor
    from twisted.internet.protocol import ClientCreator

    creator = ClientCreator(reactor, amp.AMP)
    host = '127.0.0.1'
    import sys
    if len(sys.argv) > 1:
        host = sys.argv[1]
    d = creator.connectTCP(host, 62308)

    def connected(ampProto):
        return ampProto.callRemote(GatewayAMPCommand, command=command)
    d.addCallback(connected)

    def resulted(result):
        return result['result']
    d.addCallback(resulted)

    def done(result):
        print('Done: %s' % (result,))
        reactor.stop()
    d.addCallback(done)
    reactor.run()
Exemple #27
0
def main():
    # command line processing
    process_commandline()

    call_list_server = None
    # run the call list providing web server in listening mode
    if CONFIG["LISTEN"]:
        call_list_server = CallListServer()
        site = http_server.Site(call_list_server)
        try:
            reactor.listenTCP(CONFIG["HTTP_PORT"], site, interface=CONFIG["HTTP_HOST"])
        except:
            # port could not be bound
            # (already in use, permission denied, ...)
            call_list_server = None
        else:
            dprint("running call list web server on 'http://{HTTP_HOST}:{HTTP_PORT}'".format(**CONFIG))

    # configure notifications
    enable_notifcations(
        not CONFIG["DISABLE_NOTIFICATIONS"],
        # 'All recent calls...' link only when the call list webserver
        # is running
        call_list_server,
    )

    # start the client
    reactor.connectTCP(
        CONFIG["NCID_HOST"], CONFIG["NCID_PORT"], NCIDClientFactory(reactor, CONFIG["LISTEN"], call_list_server)
    )

    # run the event dispatcher
    reactor.run()

    dprint("done.")
Exemple #28
0
def run(create_publisher, host='', port=80):
    """Runs a Twisted HTTP server server that publishes a Quixote
    application."""
    publisher = create_publisher()
    factory = QuixoteFactory(publisher)
    reactor.listenTCP(port, factory, interface=host)
    reactor.run()
Exemple #29
0
def nda_loop():
	ndutil.setTimezone()

	ndlCom = NdlCom('nDroid-Executer', '127.0.0.1', 12322)
	ndlCom.doCom('Initiating')

	ndlCom.doCom('Loading Config')
	cnfManager = CnfManager()
	cnfManager.load('./nde.cnf')
	cnfData = cnfManager.getCnfData()

	nsQueue = Queue()
	nsLock = threading.Lock()

	netManager = NetManager()
	netManager.setNdlCom(ndlCom)
	netManager.setNsQueue(nsQueue, nsLock)

	ndlCom.doCom('Starting Threads')
	scheduler = Scheduler([ndlCom, nsQueue, nsLock], 'Scheduler')

	scheduler.start()

	reactor.listenUDP(cnfData['comPort'], netManager)
	ndlCom.doCom('Listening Com Port')
	reactor.run()

	scheduler.join()
def main():
    global cbUrls, tsunamiUrl
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option(
        "-t",
        "--tsunami",
        dest="tsunami",
        type="string",
        default="http://127.0.0.1:9000",
        help="tsunami announce url. default: http://127.0.0.1:9000"
    )
    parser.add_option(
        "-p",
        "--port",
        dest="port",
        type="int",
        default=5000,
        help="port the RestQ demonstration resource should bind to. default: 5000"
    )
    options = parser.parse_args()[0]
    cbUrls = {
        'connect':'http://localhost:%s/connect'%options.port,
        'disconnect':'http://localhost:%s/disconnect'%options.port,
        'subscribe':'http://localhost:%s/subscribe'%options.port,
        'unsubscribe':'http://localhost:%s/unsubscribe'%options.port,
        'send':'http://localhost:%s/send'%options.port
    }
    tsunamiUrl = options.tsunami
    site = server.Site(RestQDummyResource())
    print 'running on %s'%options.port
    reactor.listenTCP(options.port, site)
    reactor.run()
def exec_test(fun, params=None, protocol=None, timeout=None,
        make_conn=True):
  reactor.callWhenRunning (exec_test_deferred, fun, params, protocol, timeout,
          make_conn)
  reactor.run()
Exemple #32
0
    def destroy(self, widget, data=None):
        reactor.stop()


class PprzUDPProtocol(DatagramProtocol):
    cb_recv_data = False

    def __init__(self, in_port, out_port, cb_recv_data):
        self.port = in_port
        self.out_port = out_port
        self.cb_recv_data = cb_recv_data

    def startProtocol(self):
        self.transport.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, True)

    def sendData(self, data):
        self.transport.write(data, ('127.255.255.255', self.out_port))

    def datagramReceived(self, datagram, addr):
        if self.cb_recv_data is not None:
            self.cb_recv_data(datagram)


if __name__ == "__main__":
    from twisted.internet import reactor
    from twisted.internet.serialport import SerialPort

    IridiumCtrl()
    reactor.run()
Exemple #33
0
def main():
    f = EchoFactory()
    reactor.connectTCP("172.20.20.85", 11000, f)
    reactor.run()
Exemple #34
0
def main():
    foo = Foo()
    factory = pb.PBClientFactory()
    reactor.connectTCP("localhost", 8800, factory)
    factory.getRootObject().addCallback(foo.step1)
    reactor.run()
Exemple #35
0
 def reactor_runner(self):
     reactor.run()
Exemple #36
0
def run():
    configure_logging()
    runner = CrawlerRunner(get_project_settings())
    d = runner.crawl(HMSpider)
    d.addBoth(lambda _: reactor.stop())
    reactor.run() # the script will block here until the crawling is finished
def main():
    protocol = EchoClientDatagramProtocol()
    t = reactor.listenUDP(0, protocol)
    reactor.run()
def run_in_scheduled_mode():
    logger.info('Running in scheduled mode')
    signal.signal(signal.SIGINT, handle_sigint)
    crawl()
    reactor.run()
Exemple #39
0
def start_webserver(options,
                    protocol=vtk_wamp.ServerProtocol,
                    disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.host : the interface for the web-server to listen on
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    contextFactory = None

    use_SSL = False
    if options.sslKey and options.sslCert:
        use_SSL = True
        wsProtocol = "wss"
        from twisted.internet import ssl
        contextFactory = ssl.DefaultOpenSSLContextFactory(
            options.sslKey, options.sslCert)
    else:
        wsProtocol = "ws"

    # Create WAMP router factory
    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()

    # create a user DB
    authdb = vtk_wamp.AuthDb()

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

    # Create ApplicationSession and register protocols
    appSession = protocol(types.ComponentConfig(realm="vtkweb"))
    appSession.setAuthDB(authdb)
    session_factory.add(appSession)

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = vtk_wamp.TimeoutWampWebSocketServerFactory(session_factory, \
           url        = "%s://%s:%d" % (wsProtocol, options.host, options.port),    \
           debug      = options.debug,                                              \
           debug_wamp = options.debug,                                              \
           timeout    = options.timeout )

    root = Resource()

    # Do we serve static content or just websocket ?
    if len(options.content) > 0:
        # Static HTTP + WebSocket
        root = File(options.content)

    # Handle possibly complex ws endpoint
    if not options.nows:
        wsResource = WebSocketResource(transport_factory)
        handle_complex_resource_path(options.ws, root, wsResource)

    # Handle binary push WebSocket for images
    if not options.nobws:
        wsbFactory = WebSocketServerFactory( \
            url   = "%s://%s:%d" % (wsProtocol, options.host, options.port), \
            debug = options.debug)
        wsbFactory.protocol = vtk_wamp.ImagePushBinaryWebSocketServerProtocol
        wsbResource = WebSocketResource(wsbFactory)
        handle_complex_resource_path('wsb', root, wsbResource)

    # Handle possibly complex lp endpoint
    if not options.nolp:
        lpResource = WampLongPollResource(session_factory,
                                          timeout=options.timeout,
                                          debug=options.debug)
        #killAfter = 30000,
        #queueLimitBytes = 1024 * 1024,
        #queueLimitMessages = 1000,
        #debug=True,
        #reactor=reactor)
        handle_complex_resource_path(options.lp, root, lpResource)

    if options.uploadPath != None:
        from upload import UploadPage
        uploadResource = UploadPage(options.uploadPath)
        root.putChild("upload", uploadResource)

    if len(options.fsEndpoints) > 3:
        for fsResourceInfo in options.fsEndpoints.split('|'):
            infoSplit = fsResourceInfo.split('=')
            handle_complex_resource_path(infoSplit[0], root,
                                         File(infoSplit[1]))

    site = Site(root)

    if use_SSL:
        reactor.listenSSL(options.port, site, contextFactory)
    else:
        reactor.listenTCP(options.port, site)

    # flush ready line
    sys.stdout.flush()

    # Work around to force the output buffer to be flushed
    # This allow the process launcher to parse the output and
    # wait for "Start factory" to know that the WebServer
    # is running.
    if options.forceFlush:
        for i in range(200):
            log.msg("+" * 80, logLevel=logging.CRITICAL)

    # Initialize testing: checks if we're doing a test and sets it up
    testing.initialize(options, reactor, stop_webserver)

    # Start the reactor
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()

    # Give the testing module a chance to finalize, if necessary
    testing.finalize()
def run_in_single_run_mode():
    logger.info('Running in single run mode')
    runner.crawl(OlxSpider)
    d: Deferred = runner.join()
    d.addBoth(lambda _: reactor.stop())
    reactor.run()
 def requesthandler(self,dynamic=True, sych= False):
     reactor.listenTCP(self.port, MyHTTPFactory())
     reactor.run()
Exemple #42
0
def prepare_twisted_service():
    LOG.info('Prepare twisted services')
    # check all peers
    all_peers = {}

    # check running mode
    if not CONF.standalone:
        # rabbitmq factory
        rabbit_mq_factory = PikaFactory(url=CONF.rabbit_mq.rabbit_url)
        rabbit_mq_factory.peer_list = CONF.bgp.running_config.keys()
        rabbit_mq_factory.connect()
        # mongodb connection
        if CONF.database.use_replica:
            mongo_connection = MongoApi(
                connection_url=CONF.database.connection,
                db_name=CONF.database.dbname,
                use_replica=CONF.database.use_replica,
                replica_name=CONF.database.replica_name,
                read_preference=CONF.database.read_preference,
                write_concern=CONF.database.write_concern,
                w_timeout=CONF.database.write_concern_timeout)
        else:
            mongo_connection = MongoApi(
                connection_url=CONF.database.connection,
                db_name=CONF.database.dbname)
        # check api bind host
        if CONF.rest.bind_host == '0.0.0.0':
            LOG.error(
                'please use the exactly rest host ip address when not running in standalone mode'
            )
            sys.exit()
        # TODO load channel filter and peer policy
    else:
        rabbit_mq_factory = None
        mongo_connection = None
    for peer in CONF.bgp.running_config:
        LOG.info('Get peer %s configuration', peer)
        if not CONF.standalone:
            if CONF.bgp.running_config[peer]['local_addr'] == '0.0.0.0':
                LOG.error(
                    'please use the exactly local bgp ip address when not running in standalone mode'
                )
                sys.exit()
        if CONF.message.write_disk:
            msg_file_path_for_peer = os.path.join(CONF.message.write_dir,
                                                  peer.lower())
            if not os.path.exists(msg_file_path_for_peer):
                os.makedirs(msg_file_path_for_peer)
                LOG.info('Create dir %s for peer %s', msg_file_path_for_peer,
                         peer)
            LOG.info('BGP message file path is %s', msg_file_path_for_peer)
        else:
            msg_file_path_for_peer = None
        LOG.info('Create BGPPeering instance')
        afi_safi_list = [
            bgp_cons.AFI_SAFI_STR_DICT[afi_safi]
            for afi_safi in CONF.bgp.running_config[peer]['afi_safi']
        ]
        CONF.bgp.running_config[peer]['afi_safi'] = afi_safi_list
        CONF.bgp.running_config[peer]['capability']['local'][
            'afi_safi'] = afi_safi_list
        bgp_peering = BGPPeering(
            myasn=CONF.bgp.running_config[peer]['local_as'],
            myaddr=CONF.bgp.running_config[peer]['local_addr'],
            peerasn=CONF.bgp.running_config[peer]['remote_as'],
            peeraddr=CONF.bgp.running_config[peer]['remote_addr'],
            tag=CONF.bgp.running_config[peer]['tag'],
            afisafi=CONF.bgp.running_config[peer]['afi_safi'],
            msgpath=msg_file_path_for_peer,
            md5=CONF.bgp.running_config[peer]['md5'],
            channel=rabbit_mq_factory,
            mongo_conn=mongo_connection)
        all_peers[peer] = bgp_peering
        CONF.bgp.running_config[peer]['factory'] = bgp_peering

        # register to database and check agent role
        if not CONF.standalone:
            register_to_db(peer_ip=peer, mongo_api=mongo_connection)
            if not CONF.bgp.running_config[peer]['tag']:
                LOG.error(
                    'Please point out the role tag(SRC,DST or BOTH)for not running in standalone mode'
                )
                sys.exit()
            load_channel_filter_from_db(peer_ip=peer,
                                        mongo_api=mongo_connection)

    # Starting api server
    if sys.version_info[0] == 2:
        from twisted.web.wsgi import WSGIResource
        LOG.info("Prepare RESTAPI service")
        resource = WSGIResource(reactor, reactor.getThreadPool(), app)
        site = Site(resource)
        try:
            reactor.listenTCP(CONF.rest.bind_port,
                              site,
                              interface=CONF.rest.bind_host)
            LOG.info("serving RESTAPI on http://%s:%s", CONF.rest.bind_host,
                     CONF.rest.bind_port)
        except Exception as e:
            LOG.error(e, exc_info=True)
            sys.exit()

    for peer in all_peers:
        LOG.info('start peer, peer address=%s', peer)
        all_peers[peer].automatic_start()
    reactor.run()
Exemple #43
0
 def run(self, reactor):
     reactor.run(installSignalHandlers=ServerConfig.backend.installSignalHandlers)
Exemple #44
0
'''
Created on 12/set/2014

@author: riccardo
'''
from twisted.cred import checkers, portal
from twisted.internet import reactor
from twisted.words import service

wordsRealm = service.InMemoryWordsRealm("example.com")
wordsRealm.createGroupOnRequest = True
checker = checkers.FilePasswordDB("passwords.txt")
portal = portal.Portal(wordsRealm, [checker])

reactor.listenTCP(6667, service.IRCFactory(wordsRealm,
                                           portal))  # @UndefinedVariable
reactor.run()  # @UndefinedVariable
Exemple #45
0
 def run(self):
     # Starts listening for client to connect
     reactor.listenTCP(self.commandPort1,
                       ServerCommandConnectionFactory(self))
     reactor.run()
 def createserver(self):
 #pConnect to the server
     factory = MyClientFactory()            
     reactor.connectTCP(self.host, self.port, factory)
     reactor.run()
Exemple #47
0
 def in_thread():
     # Uncomment to enable tracing of log context changes.
     # sys.settrace(logcontext_tracer)
     with LoggingContext("run"):
         change_resource_limit(hs.config.soft_file_limit)
         reactor.run()
Exemple #48
0
def download_from_sitemap(enlaces,ruta_d):
	runner= CrawlerRunner({'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'})
	d=runner.crawl(MySpider,url=enlaces,ruta=ruta_d,a=(),kw={})
	d.addBoth(lambda _: reactor.stop())
	reactor.run()
Exemple #49
0
    def _wait(self, d, running=_wait_is_running):
        """Take a Deferred that only ever callbacks. Block until it happens."""
        if running:
            raise RuntimeError("_wait is not reentrant")

        from twisted.internet import reactor

        results = []

        def append(any):
            if results is not None:
                results.append(any)

        def crash(ign):
            if results is not None:
                reactor.crash()

        crash = utils.suppressWarnings(
            crash,
            util.suppress(message=r"reactor\.crash cannot be used.*",
                          category=DeprecationWarning),
        )

        def stop():
            reactor.crash()

        stop = utils.suppressWarnings(
            stop,
            util.suppress(message=r"reactor\.crash cannot be used.*",
                          category=DeprecationWarning),
        )

        running.append(None)
        try:
            d.addBoth(append)
            if results:
                # d might have already been fired, in which case append is
                # called synchronously. Avoid any reactor stuff.
                return
            d.addBoth(crash)
            reactor.stop = stop
            try:
                reactor.run()
            finally:
                del reactor.stop

            # If the reactor was crashed elsewhere due to a timeout, hopefully
            # that crasher also reported an error. Just return.
            # _timedOut is most likely to be set when d has fired but hasn't
            # completed its callback chain (see self._run)
            if results or self._timedOut:  # defined in run() and _run()
                return

            # If the timeout didn't happen, and we didn't get a result or
            # a failure, then the user probably aborted the test, so let's
            # just raise KeyboardInterrupt.

            # FIXME: imagine this:
            # web/test/test_webclient.py:
            # exc = self.assertRaises(error.Error, wait, method(url))
            #
            # wait() will raise KeyboardInterrupt, and assertRaises will
            # swallow it. Therefore, wait() raising KeyboardInterrupt is
            # insufficient to stop trial. A suggested solution is to have
            # this code set a "stop trial" flag, or otherwise notify trial
            # that it should really try to stop as soon as possible.
            raise KeyboardInterrupt()
        finally:
            results = None
            running.pop()
Exemple #50
0
 def runReactor():
     reactor.run(installSignalHandlers=False)
Exemple #51
0
    def run(self):
        def signal_handler(*args):
            logger.info('Received SIGTERM, shutting down.')
            logger.info("Stopping threads, please wait...")
            # teardown()
            if self.raw_report_processor.isAlive():
                self.raw_report_processor.stop()
            self.timer.stop()

        log_path = os.path.join(CONST_FARADAY_HOME_PATH, 'logs',
                                'access-logging.log')
        site = twisted.web.server.Site(self.__root_resource,
                                       logPath=log_path,
                                       logFormatter=proxiedLogFormatter)
        site.displayTracebacks = False
        if self.__ssl_enabled:
            ssl_context = self.__load_ssl_certs()
            self.__listen_func = functools.partial(reactor.listenSSL,
                                                   contextFactory=ssl_context)
        else:
            self.__listen_func = reactor.listenTCP

        try:
            self.install_signal()
            # start threads and processes
            self.raw_report_processor = ReportsManager(
                REPORTS_QUEUE, name="ReportsManager-Thread", daemon=True)
            self.raw_report_processor.start()
            self.timer = TimerClass()
            self.timer.start()
            # web and static content
            self.__listen_func(self.__listen_port,
                               site,
                               interface=self.__bind_address)
            # websockets
            if faraday.server.config.websocket_ssl.enabled:

                try:
                    contextFactory = ssl.DefaultOpenSSLContextFactory(
                        faraday.server.config.websocket_ssl.keyfile.strip(
                            '\''),
                        faraday.server.config.websocket_ssl.certificate.strip(
                            '\''))

                    listenWS(self.__build_websockets_resource(),
                             interface=self.__bind_address,
                             contextFactory=contextFactory)

                except SSLError as e:
                    logger.error(
                        'Could not start websockets due to a SSL Config error. Some web functionality will not be available'
                    )
                except error.CannotListenError:
                    logger.warn(
                        'Could not start websockets, address already open. This is ok is you wan to run multiple instances.'
                    )
                except Exception as ex:
                    logger.warn(
                        'Could not start websocket, error: {}'.format(ex))
            else:
                try:
                    listenWS(self.__build_websockets_resource(),
                             interface=self.__bind_address)
                except error.CannotListenError:
                    logger.warn(
                        'Could not start websockets, address already open. This is ok is you wan to run multiple instances.'
                    )
                except Exception as ex:
                    logger.warn(
                        'Could not start websocket, error: {}'.format(ex))
            logger.info('Faraday Server is ready')
            reactor.addSystemEventTrigger('before', 'shutdown', signal_handler)
            reactor.run()

        except error.CannotListenError as e:
            logger.error(e)
            sys.exit(1)

        except Exception as e:
            logger.error(
                'Something went wrong when trying to setup the Web UI')
            logger.exception(e)
            sys.exit(1)
Exemple #52
0
        # Create new session
        os.setsid()
        if os.fork() != 0:
            os._exit(0)
        os.chdir('/')
        fd = os.open('/dev/null', os.O_RDONLY)
        os.dup2(fd, sys.__stdin__.fileno())
        os.close(fd)
        fd = os.open('/var/log/sippy.log',
                     os.O_WRONLY | os.O_CREAT | os.O_APPEND)
        os.dup2(fd, sys.__stdout__.fileno())
        os.dup2(fd, sys.__stderr__.fileno())
        os.close(fd)

    SipConf.my_uaname = 'Sippy B2BUA (Simple)'
    SipConf.allow_formats = (0, 8, 18, 100, 101)
    global_config['_sip_address'] = SipConf.my_address
    global_config['_sip_port'] = SipConf.my_port
    if laddr != None:
        global_config['_sip_address'] = laddr
    if lport != None:
        global_config['_sip_port'] = lport
    global_config['_sip_logger'] = SipLogger('b2bua')

    cmap = CallMap(global_config)

    global_config['_sip_tm'] = SipTransactionManager(global_config,
                                                     cmap.recvRequest)

    reactor.run(installSignalHandlers=True)
Exemple #53
0
def start():
    """The primary entry point for launching the daemon."""

    # postpone loading the config file to after the CLI arguments
    # have been parsed, as they may contain an alternate config file location
    conf.initialize_settings(load_conf_file=False)

    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument(
        "--conf",
        help="specify an alternative configuration file",
        type=str,
        default=None
    )
    parser.add_argument(
        "--wallet",
        help="lbryum or ptc for testing, default lbryum",
        type=str,
        default=conf.settings['wallet']
    )
    parser.add_argument(
        "--http-auth", dest="useauth", action="store_true", default=conf.settings['use_auth_http']
    )
    parser.add_argument(
        '--quiet', dest='quiet', action="store_true",
        help='Disable all console output.'
    )
    parser.add_argument(
        '--verbose', nargs="*",
        help=('Enable debug output. Optionally specify loggers for which debug output '
              'should selectively be applied.')
    )
    parser.add_argument(
        '--version', action="store_true",
        help='Show daemon version and quit'
    )

    args = parser.parse_args()
    update_settings_from_args(args)

    conf.settings.load_conf_file_settings()

    if args.version:
        version = system_info.get_platform(get_ip=False)
        version['installation_id'] = conf.settings.installation_id
        print utils.json_dumps_pretty(version)
        return

    lbrynet_log = conf.settings.get_log_filename()
    log_support.configure_logging(lbrynet_log, not args.quiet, args.verbose)
    log.debug('Final Settings: %s', conf.settings.get_current_settings_dict())

    try:
        log.debug('Checking for an existing lbrynet daemon instance')
        JSONRPCProxy.from_url(conf.settings.get_api_connection_string()).status()
        log.info("lbrynet-daemon is already running")
        return
    except Exception:
        log.debug('No lbrynet instance found, continuing to start')

    log.info("Starting lbrynet-daemon from command line")

    if test_internet_connection():
        analytics_manager = analytics.Manager.new_instance()
        start_server_and_listen(args.useauth, analytics_manager)
        reactor.run()
    else:
        log.info("Not connected to internet, unable to start")
Exemple #54
0
 def start(self) -> None:
     self.server.start()
     self.https_server.start()
     self.thread = threading.Thread(
         target=lambda: reactor.run(installSignalHandlers=0))
     self.thread.start()
Exemple #55
0
def start():
    parser = argparse.ArgumentParser(description="Launch lbrynet-daemon")
    parser.add_argument("--wallet",
                        help="lbrycrd or lbryum, default lbryum",
                        type=str,
                        default='')
    parser.add_argument("--ui", help="path to custom UI folder", default=None)
    parser.add_argument(
        "--branch",
        help="Branch of lbry-web-ui repo to use, defaults on master")
    parser.add_argument('--no-launch', dest='launchui', action="store_false")
    parser.add_argument('--log-to-console',
                        dest='logtoconsole',
                        action="store_true")
    parser.add_argument('--quiet', dest='quiet', action="store_true")
    parser.set_defaults(branch=False,
                        launchui=True,
                        logtoconsole=False,
                        quiet=False)
    args = parser.parse_args()

    log_support.configure_file_handler(lbrynet_log)
    log_support.configure_loggly_handler()
    if args.logtoconsole:
        log_support.configure_console(level='DEBUG')
    log_support.disable_third_party_loggers()
    log_support.disable_noisy_loggers()

    try:
        JSONRPCProxy.from_url(API_CONNECTION_STRING).is_running()
        log.info("lbrynet-daemon is already running")
        if not args.logtoconsole:
            print "lbrynet-daemon is already running"
        if args.launchui:
            webbrowser.open(UI_ADDRESS)
        return
    except:
        pass

    log.info("Starting lbrynet-daemon from command line")

    if not args.logtoconsole and not args.quiet:
        print "Starting lbrynet-daemon from command line"
        print "To view activity, view the log file here: " + lbrynet_log
        print "Web UI is available at http://%s:%i" % (API_INTERFACE, API_PORT)
        print "JSONRPC API is available at " + API_CONNECTION_STRING
        print "To quit press ctrl-c or call 'stop' via the API"

    if test_internet_connection():
        lbry = LBRYDaemonServer()

        d = lbry.start(
            branch=args.branch if args.branch else DEFAULT_UI_BRANCH,
            user_specified=args.ui,
            wallet=args.wallet,
            branch_specified=True if args.branch else False)
        if args.launchui:
            d.addCallback(lambda _: webbrowser.open(UI_ADDRESS))

        lbrynet_server = server.Site(lbry.root)
        lbrynet_server.requestFactory = LBRYDaemonRequest
        reactor.listenTCP(API_PORT, lbrynet_server, interface=API_INTERFACE)
        reactor.run()

        if not args.logtoconsole and not args.quiet:
            print "\nClosing lbrynet-daemon"
    else:
        log.info("Not connected to internet, unable to start")
        if not args.logtoconsole:
            print "Not connected to internet, unable to start"
        return
Exemple #56
0
def portthread():
    while 1:
        if win.zhuangtai == 1:
            reactor.listenTCP(int(win.port), ChatFactory())
            reactor.run()
        time.sleep(1)
            continue
        if o == '-S':
            sippy_path = a.strip()
            continue
        if o == '-o':
            fname = a.strip()
            if fname == '-':
                file_out = sys.stdout
            else:
                file_out = file(fname, 'w')
        if o == '-t':
            timeout = float(a.strip())
            continue

    if sippy_path != None:
        sys.path.insert(0, sippy_path)

    from sippy.Cli_server_local import Cli_server_local
    from sippy.Cli_server_tcp import Cli_server_tcp
    from sippy.Timeout import Timeout

    ch = cli_handler(file_out)
    if stype == 'unix':
        cs = Cli_server_local(ch.command_received, spath)
    else:
        cs = Cli_server_tcp(ch.command_received, spath)
    if timeout != None:
        Timeout(ch.done, timeout)
    reactor.run(installSignalHandlers=1)
    sys.exit(ch.rval)
def main():
    global f
    f = EchoFactory()
    reactor.connectTCP("localhost", 8000, f)
    reactor.callInThread(promp_metod)
    reactor.run()
 def start(self):
     _transport = self.make_control_transport()
     reactor.run()  # < ------ Blocking Call (Reactor)
Exemple #60
0
def main():
    import argparse,json
    from twisted.python.logfile import DailyLogFile
    parser = argparse.ArgumentParser()
    parser.add_argument('-dict','--dictfile', type=str,default=None,dest='dictfile',help='dict file')
    parser.add_argument('-auth','--authport', type=int,default=0,dest='authport',help='auth port')
    parser.add_argument('-acct','--acctport', type=int,default=0,dest='acctport',help='acct port')
    parser.add_argument('-admin','--adminport', type=int,default=0,dest='adminport',help='admin port')
    parser.add_argument('-c','--conf', type=str,default=None,dest='conf',help='conf file')
    parser.add_argument('-d','--debug', nargs='?',type=bool,default=False,dest='debug',help='debug')
    args =  parser.parse_args(sys.argv[1:])

    if not args.conf or not os.path.exists(args.conf):
        print 'no config file user -c or --conf cfgfile'
        return

    _config = json.loads(open(args.conf).read())
    _database = _config['database']
    _radiusd = _config['radiusd']  

    # init args
    if args.authport:_radiusd['authport'] = args.authport
    if args.acctport:_radiusd['acctport'] = args.acctport
    if args.adminport:_radiusd['adminport'] = args.adminport
    if args.dictfile:_radiusd['dictfile'] = args.dictfile
    if args.debug:_radiusd['debug'] = bool(args.debug)   

    #init dbconfig
    settings.db_config.update(**_config)
    store.__cache_timeout__ = _radiusd['cache_timeout']

    # start logging
    log.startLogging(sys.stdout)

    _trace = UserTrace()
    _runstat = statistics.RunStat()
    _middleware = middleware.Middleware()
    _debug = _radiusd['debug'] or settings.debug

    # init coa clients
    _coa_clients = {}
    for bas in store.list_bas():
        _coa_clients[bas['ip_addr']] = CoAClient(
            bas,dictionary.Dictionary(_radiusd['dictfile']),debug=_debug)

    def start_servers():
        auth_protocol = RADIUSAccess(
            dict=_radiusd['dictfile'],trace=_trace,midware=_middleware,
            runstat=_runstat,debug=_debug
        )
        acct_protocol = RADIUSAccounting(
            dict=_radiusd['dictfile'],trace=_trace,midware=_middleware,
            runstat=_runstat,debug=_debug
        )
        reactor.listenUDP(_radiusd['authport'], auth_protocol)
        reactor.listenUDP(_radiusd['acctport'], acct_protocol)
        _task = task.LoopingCall(auth_protocol.process_delay)
        _task.start(2.7)

        from autobahn.twisted.websocket import WebSocketServerFactory
        factory = WebSocketServerFactory("ws://0.0.0.0:%s"%args.adminport, debug = False)
        factory.protocol = AdminServerProtocol
        factory.protocol.user_trace = _trace
        factory.protocol.midware = _middleware
        factory.protocol.runstat = _runstat
        factory.protocol.coa_clients = _coa_clients
        reactor.listenTCP(_radiusd['adminport'], factory)

    start_servers()
    reactor.run()