Beispiel #1
0
    def serve(self, port=None, host=None, root=None, debug=True, open_url=False):
        """Start serve the server with the given port.

        :param port: serve on this port, default is 5500
        :param host: serve on this hostname, default is 0.0.0.0
        :param root: serve static on this root directory
        :param open_url: open system browser
        """
        if root:
            self.root = root
        if port:
            self.port = port
        if host is None:
            host = ''

        self.application(debug=debug).listen(self.port, address=host)
        logging.getLogger().setLevel(logging.INFO)

        host = host or '127.0.0.1'
        print('Serving on %s:%s' % (host, self.port))

        # Async open web browser after 5 sec timeout
        if open_url:
            def opener():
                time.sleep(5)
                webbrowser.open('http://%s:%s' % (host, self.port))
            threading.Thread(target=opener).start()

        try:
            IOLoop.instance().start()
        except KeyboardInterrupt:
            print('Shutting down...')
Beispiel #2
0
  def respond(self, result=None, error=None, batch_results=None, allow_async=True):
    '''Respond to the request with the given result or error object (the ``batch_results`` and
    ``allow_async`` parameters are for internal use only and not intended to be supplied manually).
    Responses will be serialized according to the ``response_type`` propery. The default
    serialization is "application/json". Other supported protocols are:

    * application/bson - requires pymongo
    * application/msgpack - requires msgpack-python

    The response will also contain any available session information.

    To help with error handling in asynchronous methods, calling ``handler.respond(error=<your_error>)`` with a caught
    exception will trigger a normal Toto error response, log the error and finish the request. This is the same basic
    flow that is used internally when exceptions are raised from synchronous method calls.

    The "error" property of the response is derived from the ``error`` parameter in the following ways:

    1. If ``error`` is an instance of ``TotoException``, "error" will be a dictionary with "value" and "code" keys matching those of the ``TotoException``.
    2. In all other cases, ``error`` is first converted to a ``TotoException`` with ``code = <ERROR_SERVER>`` and ``value = str(error)`` before following (1.).

    To send custom error information, pass an instance of ``TotoException`` with ``value = <some_json_serializable_object>``.
    '''
    #if the handler is processing an async method, schedule the response on the main runloop
    if self.async and allow_async:
      IOLoop.instance().add_callback(lambda: self.respond(result, error, batch_results, False))
      return
Beispiel #3
0
def _go(args):
    app = create_app(args)
    port = app.app.config['PORT']
    app.setup()

    mode = app.app.config['SERVER']
    if args.mode == 'dev':
        mode = 'development'
        app.app.config['DEBUG'] = True
    elif args.mode == 'prd':
        mode = 'production'

    if mode == 'development':
        print("Starting development server on port %d..." % port)
        app.app.run(port=port)
    elif mode == 'production':
        appl = WSGIContainer(app.app)
        if 'SSL_KEY' in app.app.config:
            http_server = HTTPServer(appl, ssl_options={
                "certfile": app.app.config['SSL_CRT'],
                "keyfile": app.app.config['SSL_KEY'],
            })
        else:
            http_server = HTTPServer(appl)
        http_server.listen(port)
        print("Starting production server on port %d..." % port)
        IOLoop.instance().start()
    else:
        sys.stderr.write("Invalid SERVER setting '%s', aborting.\n" % args.mode)
        sys.exit(1)
Beispiel #4
0
    def run(self):
        # 
        # 启动 Tornado HTTP server。
        # 
        # 当 DEBUG = False 时,启动多进程模式。
        # 当 DEBUG = True 时,修改的模块自动重载。
        # 
        from os import getpid
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop

        app = Application(self._get_handlers(), **self._get_settings())
        server = HTTPServer(app)
        port = settings.PORT

        if settings.DEBUG:
            server.listen(port)
            IOLoop.instance().start()
        else:
            # 多进程模式
            server.bind(port)
            server.start(0)
            print " * Sub Process: {0}".format(getpid())

        IOLoop.instance().start()            
Beispiel #5
0
def main() -> None:
    '''Runs server'''

    # Parse options
    define('production',
               default = False,
               help = 'run in production mode',
               type = bool)
    options.parse_command_line()

    # Set server name
    pname = settings.process_name if settings.process_name else None
    if pname:
        setproctitle(pname)

    # Register IRC server
    server = IRCServer(settings = ircdsettings)
    for address, port in ircdsettings['listen']:
        server.listen(port, address = address)

    # Start profiling
    if settings.profiling:
        import yappi
        yappi.start()

    # Setup autoreload
    autoreload.start()

    # Run application
    IOLoop.instance().start()
Beispiel #6
0
    def connection(self, callback):
        """Get a connection from pool

        :Parameters:
          - `callback` : method which will be called when connection is ready

        """
        self._condition.acquire()

        try:
            conn = self._idle_connections.pop(0)

        except IndexError:
            if self._maxconnections and self._connections >= self._maxconnections:

                retry_connection = partial(self.connection, callback)
                IOLoop.instance().add_callback(retry_connection)

                return

            conn = self._create_connection()
            self._connections += 1

        finally:
            self._condition.release()

        return callback(conn)
def test_send_email_single_blacklisted_domain(smtp_sendmail, options):
    options = add_options(options)

    func = partial(accounts.utils.send_email, '*****@*****.**', 'test subject', 'test message')
    IOLoop.instance().run_sync(func)

    assert not smtp_sendmail.called
Beispiel #8
0
 def save(self, data):
     if data != '':
         self.fd.write(data)
     else:
         self.fd.close()
         print "File is saved to " + self.store_path
         IOLoop.instance().stop()
Beispiel #9
0
	def run(self):
		# Global as I can't work out a way to get it into PrinterStateConnection
		global printer
		global gcodeManager

		from tornado.wsgi import WSGIContainer
		from tornado.httpserver import HTTPServer
		from tornado.ioloop import IOLoop
		from tornado.web import Application, FallbackHandler

		# first initialize the settings singleton and make sure it uses given configfile and basedir if available
		self._initSettings(self._configfile, self._basedir)

		# then initialize logging
		self._initLogging(self._debug)

		gcodeManager = gcodefiles.GcodeManager()
		printer = Printer(gcodeManager)

		if self._host is None:
			self._host = settings().get(["server", "host"])
		if self._port is None:
			self._port = settings().getInt(["server", "port"])

		logging.getLogger(__name__).info("Listening on http://%s:%d" % (self._host, self._port))
		app.debug = self._debug

		self._router = tornadio2.TornadioRouter(PrinterStateConnection)

		self._tornado_app = Application(self._router.urls + [
			(".*", FallbackHandler, {"fallback": WSGIContainer(app)})
		])
		self._server = HTTPServer(self._tornado_app)
		self._server.listen(self._port, address=self._host)
		IOLoop.instance().start()
Beispiel #10
0
def main():
    root_dir = os.path.abspath(os.path.split(__file__)[0])
    print(root_dir)
    app = Application([(r'/gfxtablet', GfxTabletHandler),
                       #(r'/(index.js|src/.*\.js|node_modules/.*\.js)', StaticFileHandler, {}),
                       (r'/', MainHandler)],
                      debug=config.get('DEBUG', False), static_path=root_dir, static_url_prefix='/static/')

    _logger.info("app.settings:\n%s" % '\n'.join(['%s: %s' % (k, str(v))
                                                  for k, v in sorted(app.settings.items(),
                                                                     key=itemgetter(0))]))

    port = config.get('PORT', 5000)

    app.listen(port)
    _logger.info("listening on port %d" % port)
    _logger.info("press CTRL-C to terminate the server")
    _logger.info("""
           -----------
        G f x T a b l e t
    *************************
*********************************
STARTING TORNADO APP!!!!!!!!!!!!!
*********************************
    *************************
        G f x T a b l e t
           -----------
""")
    IOLoop.instance().start()
Beispiel #11
0
def main():
  """ Main. """

  logging_level = logging.INFO
  if hermes_constants.DEBUG:
    logging_level = logging.DEBUG
  logging.getLogger().setLevel(logging_level)

  signal.signal(signal.SIGTERM, signal_handler)
  signal.signal(signal.SIGINT, signal_handler)

  parse_command_line()

  app = tornado.web.Application([
    (MainHandler.PATH, MainHandler),
    (TaskHandler.PATH, TaskHandler),
  ], debug=False)

  try:
    app.listen(options.port)
  except socket.error:
    logging.error("ERROR on Hermes initialization: Port {0} already in use.".
      format(options.port))
    shutdown()
    return

  logging.info("Hermes is up and listening on port: {0}.".
    format(options.port))

  # Start loop for accepting http requests.
  IOLoop.instance().start()
Beispiel #12
0
	def access_token_for_id(cls, id, callback):
		"""Returns the access token for an id, acquiring a new one if necessary."""
		token = Cache.get(cls.auth_cache_key_template % id)
		if token:
			return IOLoop.instance().add_callback(lambda: callback(token))

		# If we don't have an access token cached, see if we have a refresh token
		token = TokenIdMapping.lookup_refresh_token(id)
		if token:
			post_body = urllib.urlencode({
				'client_id': Config.get('oauth', 'client-id'),
				'client_secret': Config.get('oauth', 'client-secret'),
				'refresh_token': token,
				'grant_type': 'refresh_token',
			})
			http_client = AsyncHTTPClient()
			return http_client.fetch(
				'https://accounts.google.com/o/oauth2/token',
				lambda response: cls.on_refresh_complete(response, id, callback),
				method='POST',
				body=post_body,
				request_timeout=20.0,
				connect_timeout=15.0,
			)
		else:
			logging.error("Unable to update access token for %s, no refresh token stored.", id)
			return IOLoop.instance().add_callback(lambda: callback(None))
Beispiel #13
0
	def on_refresh_complete(cls, response, id, callback):
		"""Callback for request to get a new access token based on refresh token."""

		if response.code in (400, 401):

			if 'invalid_grant' in response.body:
				# Our refresh token is invalid, which means that we don't have
				# permission to access this user's content anymore. Forget them.
				Cache.delete(cls.auth_cache_key_template % id)
				Cache.delete(cls.profile_cache_key_template % id)
				TokenIdMapping.remove_id(id)
				logging.error("Access was revoked for %s; cached data deleted.", id)

			logging.error("HTTP %s while trying to refresh access token for %s.", response.code, id)
			return IOLoop.instance().add_callback(lambda: callback(None))

		elif response.code != 200:
			logging.error("Non-200 response to refresh token request (%s, id=%s): %r" % (response.code, id, response.body))
			return IOLoop.instance().add_callback(lambda: callback(None))

		results = json.loads(response.body)

		# sanity check
		if results['token_type'] != "Bearer":
			logging.error('Unknown token type received: %s' % results['token_type'])
			return IOLoop.instance().add_callback(lambda: callback(None))

		token = results['access_token']
		Cache.set(cls.auth_cache_key_template % id, token, time=results['expires_in'])

		IOLoop.instance().add_callback(lambda: callback(token))
Beispiel #14
0
def main():
	define('listen', metavar='IP', default='127.0.0.1', help='listen on IP address (default 127.0.0.1)')
	define('port', metavar='PORT', default=8888, type=int, help='listen on PORT (default 8888)')
	define('debug', metavar='True|False', default=False, type=bool, 
			help='enable Tornado debug mode: templates will not be cached '
			'and the app will watch for changes to its source files '
			'and reload itself when anything changes')

	options.parse_command_line()

	settings = dict(
			template_path=rel('templates'),
			static_path=rel('static'),
			debug=options.debug
			)

	application = Application([
		(r'/', MainHandler),
		(r'/ws', EchoWebSocket),
		(r'/websocket', SignallingHandler),
		(r'/webrtc', WebRTCHandler)
		], **settings)

	#application.listen(address=options.listen, port=options.port)
	application.listen(7080)
	IOLoop.instance().start()
Beispiel #15
0
def main():
    parser = OptionParser()
    parser.add_option('-p', '--port', type='int', default=11001,
                      help='Port to serve from (default: 11001)')
    parser.add_option('-u', '--user', type='string', default=None,
                      help='Only track a single user')
    parser.add_option('--constraint', type='string', default=None,
                      help='HTCondor constraint expression')
    parser.add_option('--delay', type='int', default=300,
                      help='delay between calls to condor_q (default: 300 seconds)')
    parser.add_option('--debug', action='store_true', default=False,
                      help='Enable debug logging')
    (options, args) = parser.parse_args()

    if options.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    if options.delay < 0 or options.delay > 1000:
        raise Exception('delay out of range')

    cfg = {'options':options, 'condor_q':False, 'state':[], 'monitoring':{}}

    # load condor_q
    IOLoop.instance().call_later(5, partial(condor_q_helper, cfg))

    # setup server
    s = server(cfg)
    s.start()
Beispiel #16
0
    def test_stepdown_triggers_refresh(self, done):
        c_find_one = motor.MotorReplicaSetClient(
            self.seed, replicaSet=self.name).open_sync()

        # We've started the primary and one secondary
        primary = ha_tools.get_primary()
        secondary = ha_tools.get_secondaries()[0]
        self.assertEqual(
            one(c_find_one.secondaries), _partition_node(secondary))

        ha_tools.stepdown_primary()

        # Make sure the stepdown completes
        yield gen.Task(IOLoop.instance().add_timeout, time.time() + 1)

        # Trigger a refresh
        yield AssertRaises(AutoReconnect, c_find_one.test.test.find_one)

        # Wait for the immediate refresh to complete - we're not waiting for
        # the periodic refresh, which has been disabled
        yield gen.Task(IOLoop.instance().add_timeout, time.time() + 1)

        # We've detected the stepdown
        self.assertTrue(
            not c_find_one.primary
            or primary != _partition_node(c_find_one.primary))

        done()
Beispiel #17
0
 def _on_finish():
     try:
         zs_response = self.zsle_request(data['sim'])
         zlp = ZsLeParser(zs_response.replace('GBK', 'UTF-8'))
         if zlp.success == "0":
              ret.success = ErrorCode.SUCCESS
              ret.position = zlp.get_position()
              ret.info = ErrorCode.ERROR_MESSAGE[ret.success]
              logging.info("[LE] Zsle response position: %s, sim:%s", ret.position, data['sim'])
         else:
             if zlp.success == "9999228":
                 callback = partial(self.re_subscription, data['sim'])
                 IOLoop.instance().add_timeout(int(time.time()) + 5, callback)
             logging.info("[LE] Zsle request failed, errorcode: %s, info: %s, sim:%s",
                          zlp.success, zlp.info, data['sim'])
             # logging.info('[LE] Google request:\n %s', request)
             # response = self.send(ConfHelper.LBMP_CONF.le_host, 
             #                      ConfHelper.LBMP_CONF.le_url, 
             #                      request,
             #                      HTTP.METHOD.POST)
             # logging.info('[LE] Google response:\n %s', response.decode('utf8'))
             # json_data = json_decode(response)
             # if json_data.get("location"):
             #     ret.position.lat = int(json_data["location"]["latitude"] * 3600000)
             #     ret.position.lon = int(json_data["location"]["longitude"] * 3600000)
             #     ret.success = ErrorCode.SUCCESS 
             #     ret.info = ErrorCode.ERROR_MESSAGE[ret.success]
     except Exception as e:
         logging.exception("[LE] Get latlon failed. Exception: %s, sim:%s", e.args, data['sim'])
     self.write(ret)
     IOLoop.instance().add_callback(self.finish)
Beispiel #18
0
def main():
    global http_server

    try:
        signal(SIGTERM, on_signal)

        parse_command_line()
        if options.config != None:
            parse_config_file(options.config)

        path = join(dirname(__file__), "templates")

        application = Application(
            [(r"/", IndexHandler), (r"/stock", StockHandler)],
            template_path=path,
            static_path=join(dirname(__file__), "static"),
        )

        application.db = motor.MotorClient(options.db_host, options.db_port).open_sync()[options.db_name]

        http_server = HTTPServer(application)
        http_server.listen(options.port, options.address)
        log().info("server listening on port %s:%d" % (options.address, options.port))
        if log().isEnabledFor(DEBUG):
            log().debug("autoreload enabled")
            tornado.autoreload.start()
        IOLoop.instance().start()

    except KeyboardInterrupt:
        log().info("exiting...")

    except BaseException as ex:
        log().error("exiting due: [%s][%s]" % (str(ex), str(format_exc().splitlines())))
        exit(1)
def main():
    '''Create server, begin IOLoop 
    '''
    tornado.options.parse_command_line()
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    IOLoop.instance().start()
Beispiel #20
0
def main():
    port = int(os.environ['CTPLOT_PORT']) if 'CTPLOT_PORT' in os.environ else 8080
    print 'listening on', port

    http_server = HTTPServer(WSGIContainer(application))
    http_server.listen(port)
    IOLoop.instance().start()
def run_tornado(addr, port, reload=False):
    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Print listening address and port to command line
    if addr == '0.0.0.0':
        url_string = _("the machine's local ip address")
    else:
        url_string = 'http://%s:%s' % (addr, port)
    print _("Starting OpenSlides' tornado webserver listening to %(url_string)s") % {'url_string': url_string}

    socket_js_router = SockJSRouter(ProjectorSocketHandler, '/projector/socket')

    # Start the application
    app = WSGIContainer(Django_WSGIHandler())
    tornado_app = Application(socket_js_router.urls + [
        (r"%s(.*)" % settings.STATIC_URL, DjangoStaticFileHandler),
        (r'%s(.*)' % settings.MEDIA_URL, StaticFileHandler, {'path': settings.MEDIA_ROOT}),
        ('.*', FallbackHandler, dict(fallback=app))
    ], debug=reload)

    server = HTTPServer(tornado_app)
    server.listen(port=port,
                  address=addr)
    IOLoop.instance().start()
Beispiel #22
0
def start(current_info):
    '''
    Start an instance of the server. 
    '''
    io_utilities.safe_make_dirs(os.path.dirname(TORNADO_LOG_FILE_PREFIX))
    tornado.options.options.log_file_prefix = TORNADO_LOG_FILE_PREFIX
    tornado.options.parse_command_line()
    
    logging.info("Starting up server on machine %s and port %s at %s." % 
                 (current_info[MACHINE], current_info[PORT_HEADER], 
                  time.strftime("%I:%M:%S")))
    
    tr = WSGIContainer(app)
    application = Application([ (r"/tornado", MainHandler),
                                (r".*", FallbackHandler, dict(fallback=tr)),
                              ])
    application.listen(PORT)
    
    # Gracefully handle server shutdown.
    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGQUIT, sig_handler)
    
    # Add the current info to the running info file.
    write_running_info([current_info])
    
    IOLoop.instance().start()
Beispiel #23
0
def run_tornado(addr, port, *args, **kwargs):
    """
    Starts the tornado webserver as wsgi server for OpenSlides.

    It runs in one thread.
    """
    # Save the port and the addr in a global var
    global RUNNING_HOST, RUNNING_PORT
    RUNNING_HOST = addr
    RUNNING_PORT = port

    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Setup WSGIContainer
    app = WSGIContainer(get_wsgi_application())

    # Collect urls
    sock_js_router = SockJSRouter(OpenSlidesSockJSConnection, '/sockjs')
    other_urls = [
        (r'%s(.*)' % settings.STATIC_URL, DjangoStaticFileHandler),
        (r'%s(.*)' % settings.MEDIA_URL, StaticFileHandler, {'path': settings.MEDIA_ROOT}),
        ('.*', FallbackHandler, dict(fallback=app))]

    # Start the application
    debug = settings.DEBUG
    tornado_app = Application(sock_js_router.urls + other_urls, autoreload=debug, debug=debug)
    server = HTTPServer(tornado_app)
    server.listen(port=port, address=addr)
    IOLoop.instance().start()

    # Reset the global vars
    RUNNING_HOST = None
    RUNNING_PORT = None
Beispiel #24
0
def start_tornado():
	myCookie = Hash.MD5(Dict['SharedSecret'] + NAME)

	settings = {"cookie_secret": "__" + myCookie + "__",
							"login_url": "/login"}

	application = Application(httpHandlers, **settings)
	applicationTLS = Application(httpsHandlers, **settings)
	http_server = HTTPServer(application)
	# Use our own certificate for TLS
	http_serverTLS = HTTPServer(applicationTLS, 
													ssl_options={
																			"certfile": os.path.join(Core.bundle_path, 'Contents', 'Code', 'Certificate', 'WebTools.crt'),
																			"keyfile": os.path.join(Core.bundle_path, 'Contents', 'Code', 'Certificate', 'WebTools.key')})


	# Set web server port to the setting in the channel prefs
	port = int(Prefs['WEB_Port_http'])
	ports = int(Prefs['WEB_Port_https'])	
	http_server.listen(port)
	http_serverTLS.listen(ports)

	Log.Debug('Starting tornado on ports %s and %s' %(port, ports))
	IOLoop.instance().start()
	Log.Debug('Shutting down tornado')
Beispiel #25
0
def tornado_start():  # pragma: no cover
    """Just start tornado ioloop

    :return: None
    """
    from tornado.ioloop import IOLoop
    IOLoop.instance().start()
Beispiel #26
0
  def _update_assignment_watch(self, children):
    """ Watches for new or lost groomers.

    Args:
      children: A list of strings specifying registered groomers.
    """
    IOLoop.instance().add_callback(self._update_assignment, children)
Beispiel #27
0
 def run(self, *args, **kwargs):
     super(Service, self).run(*args, **kwargs)
     self.periodicalCb = PeriodicCallback(
         partial(super(Service, self).run, *args, **kwargs),
         self.interval, IOLoop.instance())
     self.periodicalCb.start()
     IOLoop.instance().start()
Beispiel #28
0
def main():
    application = Application([
        (r"/", MainHandler),
        (r"/login", LoginHandler),
        (r"/logout", LogoutHandler),
        (r"/events", EventHandler),
        (r"/translations/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)", TranslationHandler),
        (r"/translations/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/button", ButtonHandler),
        (r"/selections/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)", SelectionHandler),
        (r"/flags/([A-Za-z0-9_]+)", ImageHandler, {
            'location': os.path.join(os.path.dirname(__file__), 'flags', '%s'),
            'fallback': os.path.join(os.path.dirname(__file__), 'static', 'flag.png')
        }),
        ], **{
        "login_url": "/",
        "template_path": os.path.join(os.path.dirname(__file__), "templates"),
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
        "cookie_secret": base64.b64encode("000000000000000000000"),
        })
    application.listen(8891)

    try:
        IOLoop.instance().start()
    except KeyboardInterrupt:
        # Exit cleanly.
        return
Beispiel #29
0
def start_tornado():
    myCookie = Hash.MD5(Dict['SharedSecret'] + NAME)
    login_url = BASEURL + '/login'
    settings = {"cookie_secret": "__" + myCookie + "__",
                "login_url": login_url}
    try:
        application = Application(httpHandlers, **settings)
        applicationTLS = Application(httpsHandlers, **settings)
        http_server = HTTPServer(application)
        # Use our own certificate for TLS
        CRTFile = os.path.join(Core.bundle_path, 'Contents',
                               'Code', 'Certificate', Prefs['Cert_CRT'])
        Log.Info('Certificate crt file is %s' % CRTFile)
        KEYFile = os.path.join(Core.bundle_path, 'Contents',
                               'Code', 'Certificate', Prefs['Cert_KEY'])
        Log.Info('Certificate key file is %s' % KEYFile)
        http_serverTLS = HTTPServer(applicationTLS,
                                    ssl_options={
                                        "certfile": os.path.join(Core.bundle_path, 'Contents', 'Code', 'Certificate', CRTFile),
                                        "keyfile": KEYFile})
        # Set web server port to the setting in the channel prefs
        port = int(Prefs['WEB_Port_http'])
        ports = int(Prefs['WEB_Port_https'])
        http_server.listen(port)
        http_serverTLS.listen(ports)
        Log.Debug('Starting tornado on ports %s and %s' % (port, ports))
        IOLoop.instance().start()
    except Exception, e:
        Log.Exception('Problem starting Tornado: ' + str(e))
Beispiel #30
0
 def inner_run(self, *args, **options):    
     wsgi_app = WSGIContainer(WSGIHandler())
     tornado_app = Application([(r'/static/(.*)',
         DjangoStaticFilesHandler, {'default_filename': 'none.img'}),
         (r'/media/(.*)', StaticFileHandler, {'path': settings.MEDIA_ROOT}),
         ('/hello-tornado', HelloHandler), 
         ('/ws/doc/(\w+)', DocumentWS), 
         ('.*', FallbackHandler, dict(fallback=wsgi_app))])
     quit_command = (platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
     
     self.stdout.write("Validating models...\n\n")
     self.validate(display_num_errors=True)
     self.stdout.write((
         "%(started_at)s\n"
         "Django version %(version)s, using settings %(settings)r\n"
         "Django tornado server is running at http://%(addr)s:%(port)s/\n"
         "Quit the server with %(quit_command)s.\n"
     ) % {
         "started_at": datetime.now().strftime('%B %d, %Y - %X'),
         "version": self.get_version(),
         "settings": settings.SETTINGS_MODULE,
         "addr": '127.0.0.1',
         "port": self.port,
         "quit_command": quit_command,
     })
     # django.core.management.base forces the locale to en-us. We should
     # set it up correctly for the first request (particularly important
     # in the "--noreload" case).
     translation.activate(settings.LANGUAGE_CODE)
     
     server = HTTPServer(tornado_app)
     server.listen(int(self.port))
     IOLoop.instance().start()
Beispiel #31
0
    nginx_proc = Subprocess(
        shlex.split("""nginx -p "%s" -c example/nginx.conf""" %
                    os.path.curdir),
        stdout=Subprocess.STREAM,
        stderr=Subprocess.STREAM,
    )
    out = partial(out_fn, name='rolld')
    nginx_proc.stdout.read_until_close(exit_callback, streaming_callback=out)
    nginx_proc.stderr.read_until_close(exit_callback, streaming_callback=out)

    # now we restart everything
    def send_hub_to_rolld():
        print "sending SIGHUP to rolld"
        os.kill(rolld_proc.pid, signal.SIGHUP)

    def start_ping():
        global periodic_checker
        periodic_checker = PeriodicCallback(
            partial(periodic_callback, proc_pid=rolld_proc.pid), 1000)
        periodic_checker.start()

    IOLoop.instance().add_timeout(time.time() + 5, start_ping)
    IOLoop.instance().add_timeout(time.time() + 15, send_hub_to_rolld)
    IOLoop.instance().add_timeout(time.time() + 55, exit_test)


if __name__ == '__main__':
    ioloop = IOLoop.instance()
    ioloop.add_callback(main)
    ioloop.start()
Beispiel #32
0
    settings = {
        'session': {
            'driver': 'file',
            'driver_settings': {
                'host': options.session_path
            },
            'cookie_config': {
                'expires_days': 365
            },
            'force_persistence': True,
            'cache_driver': True
        }
    }

    mongo_connection.connect(host=options.mongo_uri)

    if options.periodic_process:
        PeriodicCallback(currency_updater(True),
                         options.exchange_update_interval).start()
        PeriodicCallback(send_fails, 20 * 1000).start()
        PeriodicCallback(rating_request_send, 20 * 1000).start()

        IOLoop.instance().start()
    else:
        server = RobomanServer(bots=bots,
                               mode=options.mode,
                               handlers=handlers,
                               settings=settings)
        server.start()
Beispiel #33
0
def link_package(path, app_dir=None, logger=None):
    """Link a package against the JupyterLab build."""
    func = partial(link_package_async, path, app_dir=app_dir, logger=logger)
    return IOLoop.instance().run_sync(func)
Beispiel #34
0
def watch(cwd, logger=None):
    """Run watch mode in a given directory"""
    loop = IOLoop.instance()
    loop.add_callback(run, [get_npm_name(), 'run', 'watch'],
                      cwd=cwd,
                      logger=logger)
Beispiel #35
0
def ensure_dev_build(logger=None):
    """Ensure that the dev build assets are there"""
    cmd = [get_npm_name(), 'run', 'build']
    func = partial(run, cmd, cwd=os.path.dirname(here), logger=logger)
    loop = IOLoop.instance()
    loop.instance().run_sync(func)
 def terminate(self):
     if hasattr(self, 'httpd'):
         self.httpd.stop()
         IOLoop.instance().stop()
Beispiel #37
0
def handle_request(response):
    if response.error:
        print "Error:", response.error
    else:
        print response.body
    IOLoop.instance().stop()
Beispiel #38
0
def shutdown():
    """ Shuts down the server. """
    logging.warning("Hermes is shutting down.")
    IOLoop.instance().stop()
Beispiel #39
0
def main():
    app = Application()
    app.listen(80)
    IOLoop.instance().start()
Beispiel #40
0
 def stop_tornado(signum, frame):
     # Stop the loop.
     IOLoop.instance().stop()
Beispiel #41
0
 def terminate(*_):
     """Trigger shutdown."""
     IOLoop.instance().add_callback_from_signal(app.stop)
Beispiel #42
0
def signal_handler(signal, frame):
    """ Signal handler for graceful shutdown. """
    logging.warning("Caught signal: {0}".format(signal))
    IOLoop.instance().add_callback(shutdown)
Beispiel #43
0
 def stop():
     """Stop the application"""
     if SyncTask.is_running():
         SyncTask.cancel()
     IOLoop.instance().stop()
Beispiel #44
0
def main():
    """Main entrypoint."""
    init_logging()
    create_app()
    IOLoop.instance().start()
Beispiel #45
0
 def emit_in_loop(self, evtname, evtsrc, *data, **kwargs):
     loop = IOLoop.instance()
     src = copy.deepcopy(evtsrc)
     loop.add_callback(self.emit, evtname, src, *data, **kwargs)
Beispiel #46
0
 def stop():
     """Stop the websocket"""
     IOLoop.instance().stop()
Beispiel #47
0
    def get_new_ioloop(self):

        return IOLoop.instance()
Beispiel #48
0
 def emit_system_notify(self, evtname, evtsrc):
     loop = IOLoop.instance()
     src = copy.deepcopy(evtsrc)
     loop.add_callback(self.emit, evtname, src)
def shutdown_hook():
    IOLoop.instance().stop()
Beispiel #50
0
def handle_signal(sig, frame):
    IOLoop.instance().add_callback(IOLoop.instance().stop)
Beispiel #51
0
def run_one():
    IOLoop.instance().add_callback(lambda: IOLoop.instance().stop())
    IOLoop.instance().start()
Beispiel #52
0
def _sync_frontend_all_timed_stop(sid):
    if sid in front_sched_sync_timers and front_sched_sync_timers[sid]:
        IOLoop.instance().remove_timeout(front_sched_sync_timers[sid])
    front_sched_sync_timers[sid] = None
Beispiel #53
0
def convert_scratch_project(job_ID, host, port, verbose):
    logging.basicConfig(
        filename=None,
        level=logging.DEBUG,
        format='%(asctime)s: %(levelname)7s: [%(name)s]: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')

    #     job = get_current_job()
    #     job.meta['handled_by'] = socket.gethostname()
    #     job.save()

    # validate URL
    if job_ID == None or not isinstance(job_ID, int):
        _logger.error(
            "No or invalid Scratch project ID given: {}".format(job_ID))
        return

    if not os.path.isfile(CERTIFICATE_PATH):
        _logger.error("Cannot find server certificate: %s", CERTIFICATE_PATH)
        return

    retries = int(helpers.config.get("SCRATCH_API", "http_retries"))
    timeout_in_secs = int(helpers.config.get("SCRATCH_API",
                                             "http_timeout")) / 1000
    backoff = int(helpers.config.get("SCRATCH_API", "http_backoff"))
    delay = int(helpers.config.get("SCRATCH_API", "http_delay"))
    user_agent = helpers.config.get("SCRATCH_API", "user_agent")

    # preprocessing: fetch project title and project image URL via web API
    def retry_hook(exc, tries, delay):
        _logger.warning("  Exception: {}\nRetrying after {}:'{}' in {} secs (remaining trys: {})" \
                        .format(sys.exc_info()[0], type(exc).__name__, exc, delay, tries))

    @helpers.retry((urllib2.URLError, socket.timeout, IOError, BadStatusLine),
                   delay=delay,
                   backoff=backoff,
                   tries=retries,
                   hook=retry_hook)
    def read_content_of_url(url):
        _logger.info(
            "Fetching project title from: {}".format(scratch_project_url))
        req = urllib2.Request(url, headers={"User-Agent": user_agent})
        return urllib2.urlopen(req, timeout=timeout_in_secs).read()

    title = None
    image_URL = None
    scratch_project_url = "%s%d" % (SCRATCH_PROJECT_BASE_URL, job_ID)
    try:
        html_content = read_content_of_url(scratch_project_url)
        if html_content == None or not isinstance(html_content, str):
            raise Warning("Unable to set title of project from the project's " \
                          "website! Reason: Invalid or empty html content!")

        document = webhelpers.ResponseBeautifulSoupDocumentWrapper(
            BeautifulSoup(html_content.decode('utf-8', 'ignore'), b'html5lib'))
        title = scratchwebapi.extract_project_title_from_document(document)
        image_URL = scratchwebapi.extract_project_image_url_from_document(
            document)
        if title == None:
            raise Warning("Unable to set title of project from the project's website!" \
                          " Reason: Cannot parse title from returned html content!")
        if image_URL == None:
            raise Warning("Unable to extract image url of project from the project's website!" \
                          " Reason: Cannot parse image url from returned html content!")
    except:
        # log error and continue without updating title and/or image URL!
        _logger.error("Unexpected error for URL: {}, {}".format(scratch_project_url, \
                                                                sys.exc_info()[0]))

    _logger.info("Project title is: {}".format(title))

    args = {
        "url": scratch_project_url,
        "jobID": job_ID,
        "title": title,
        "imageURL": image_URL,
        "outputDir": helpers.config.get("PATHS", "web_output")
    }

    # set up signal handler
    #signal.signal(signal.SIGTERM, sig_handler)
    #signal.signal(signal.SIGINT, sig_handler)

    ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)  #@UndefinedVariable
    ssl_ctx.verify_mode = ssl.CERT_REQUIRED
    # check only hostnames for non-local servers
    ssl_ctx.check_hostname = (host != "localhost")
    ssl_ctx.load_verify_locations(cafile=CERTIFICATE_PATH)

    handler = ConverterJobHandler(host,
                                  port,
                                  verbose,
                                  AUTH_KEY,
                                  ssl_options=ssl_ctx)
    handler.run(args)
    IOLoop.instance().start()
def start_hook():
    IOLoop.instance().start()
Beispiel #55
0
def shutdown_server():
    ioloop = IOLoop.instance()
    ioloop.add_callback(ioloop.stop)
    print("Asked Server to shut down.")
def main():
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(80)
    IOLoop.instance().start()
Beispiel #57
0
    handlers = [
        (r'/ws', WSHandler),
        (r'/zip', ZipHandler),
        (r'/del', DelHandler),
        (r'/(.*)', StaticFileHandler, {'path': static_path, 'default_filename': 'index.html'}),
    ]
    options = {
        'debug': False,
        'gzip': True
    }
    http_server = HTTPServer(Application(handlers, **options))
    http_server.listen(port, address)
    logging.basicConfig(level=logging.DEBUG)

    settings['cameras'] = get_cameras()
    tasks = Tasks()
    main = IOLoop.instance()

    def shutdown():
        global is_running
        is_running = False
        tasks.join()
    signal.signal(signal.SIGTERM, shutdown)
    if address == '127.0.0.1':
        webbrowser.open_new_tab('http://%s:%s' % (address, port))
    try:
        main.start()
    except:
        print('shutting down...')
    shutdown()
 def run(self):
     while True:
         app = Application()
         app.listen(options.port, options.address)
         IOLoop.instance().start()
Beispiel #59
0
from cps import web
try:
    from gevent.wsgi import WSGIServer
    gevent_present = True
except ImportError:
    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop
    gevent_present = False

if __name__ == '__main__':
    if web.ub.DEVELOPMENT:
        web.app.run(host="0.0.0.0", port=web.ub.config.config_port, debug=True)
    else:
        if gevent_present:
            web.app.logger.info('Attempting to start gevent')
            web.start_gevent()
        else:
            web.app.logger.info('Falling back to Tornado')
            http_server = HTTPServer(WSGIContainer(web.app))
            http_server.listen(web.ub.config.config_port)
            IOLoop.instance().start()
            IOLoop.instance().close(True)

    if web.helper.global_task == 0:
        web.app.logger.info("Performing restart of Calibre-web")
        os.execl(sys.executable, sys.executable, *sys.argv)
    else:
        web.app.logger.info("Performing shutdown of Calibre-web")
    sys.exit(0)
Beispiel #60
0
def serve_http():
    http_server.listen(PORT)
    IOLoop.instance().start()