Пример #1
0
def start_server():
    ''' Main entry point for the application '''
    sockets = netutil.bind_sockets(config.listen_port)
    server = HTTPServer(app)
    server.add_sockets(sockets)
    io_loop = IOLoop.instance()
    scoring = PeriodicCallback(scoring_round,
                               int(5 * 60 * 1000),
                               io_loop=io_loop)
    scoring.start()
    try:
        sys.stdout.write("\r" + INFO + "The game has begun, good hunting!\n")
        if config.debug:
            sys.stdout.write(WARN + "WARNING: Debug mode is enabled.\n")
        sys.stdout.flush()
        game_history = GameHistory.Instance()
        history_callback = PeriodicCallback(game_history.take_snapshot,
                                            int(60 * 1000),
                                            io_loop=io_loop)
        history_callback.start()
        io_loop.start()
    except KeyboardInterrupt:
        print('\r' + WARN + 'Shutdown Everything!')
    except:
        logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        if config.debug and \
                raw_input(PROMPT + "Flush Memcache? [Y/n]: ").lower() == 'y':
            print(INFO + 'Flushing cache ...'),
            FileCache.flush()
            print('OK')
        _exit(0)
Пример #2
0
def start_server():
    ''' Main entry point for the application '''
    sockets = netutil.bind_sockets(config.listen_port)
    server = HTTPServer(app)
    server.add_sockets(sockets)
    io_loop = IOLoop.instance()
    scoring = PeriodicCallback(
        scoring_round, int(5 * 60 * 1000), io_loop=io_loop
    )
    scoring.start()
    try:
        sys.stdout.write("\r" + INFO + "The game has begun, good hunting!\n")
        if config.debug:
            sys.stdout.write(WARN + "WARNING: Debug mode is enabled.\n")
        sys.stdout.flush()
        game_history = GameHistory.Instance()
        history_callback = PeriodicCallback(
            game_history.take_snapshot, int(60 * 1000), io_loop=io_loop
        )
        history_callback.start()
        io_loop.start()
    except KeyboardInterrupt:
        print('\r' + WARN + 'Shutdown Everything!')
    except:
      logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        if config.debug and \
                raw_input(PROMPT + "Flush Memcache? [Y/n]: ").lower() == 'y':
            print(INFO + 'Flushing cache ...'),
            FileCache.flush()
            print('OK')
        _exit(0)
Пример #3
0
def start_game():
    try:
        print("\r" + INFO + "Starting web server; binding to port %d" % config.listen_port)
        application.listen(config.listen_port)
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        FileCache.flush()
        print("\r" + WARN + "Shutting everything!")
Пример #4
0
def start_server():
    ''' Main entry point for the application '''
    
    if config.debug:
        sys.stdout.write(WARN+"WARNING: Debug mode is enabled in "+config.filename)
        sys.stdout.flush()
        logging.warn("Debug mode is enabled; some security measures will be ignored")
    
    # Setup server object
    if config.use_ssl:
        server = HTTPServer(app, 
            ssl_options={
                "certfile": config.certfile,
                "keyfile": config.keyfile,
            }, 
            xheaders=config.x_headers
        )
    else:
        server = HTTPServer(app, xheaders=config.x_headers)

    # Bind to a socket
    sockets = netutil.bind_sockets(config.listen_port)
    server.add_sockets(sockets)
    
    # Start the i/o loop, and callbacks
    try:
        io_loop = IOLoop.instance()
        game_history = GameHistory.Instance()
        history_callback = PeriodicCallback(
            game_history.take_snapshot, 
            config.history_snapshot_interval, 
            io_loop=io_loop
        )
        if config.use_bots:
            scoring_callback = PeriodicCallback(
                score_bots, 
                config.bot_reward_interval, 
                io_loop=io_loop
            )
            bot_ping_callback = PeriodicCallback(
                ping_bots, 30000, io_loop=io_loop
            )
            bot_ping_callback.start()
            scoring_callback.start()
        history_callback.start()
        io_loop.start()
    except KeyboardInterrupt:
        sys.stdout.write('\r'+WARN+'Shutdown Everything!\n')
    except:
        logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        if config.debug and raw_input(PROMPT+"Flush Memcache? [Y/n]: ").lower() == 'y':
            sys.stdout.write(INFO+'Flushing cache ... '),
            FileCache.flush()
            sys.stdout.write('okay\n')
        _exit(0)
Пример #5
0
    def get_version(cls, settings, path):
        '''
        Generate the version string to be used in static URLs.

        This method may be overridden in subclasses (but note that it
        is a class method rather than a static method).  The default
        implementation uses a hash of the file's contents.

        ``settings`` is the `Application.settings` dictionary and ``path``
        is the relative location of the requested asset on the filesystem.
        The returned value should be a string, or ``None`` if no version
        could be determined.
        '''
        abs_path = os.path.join(settings["static_path"], path)
        with cls._lock:
            hashes = cls._static_hashes
            if abs_path not in hashes:
                try:
                    data = FileCache.get(abs_path)
                    hashes[abs_path] = hashlib.md5(data).hexdigest()
                except Exception:
                    logging.error("Could not open static file %r", path)
                    hashes[abs_path] = None
            hsh = hashes.get(abs_path)
            if hsh:
                return hsh[:5]
        return None
Пример #6
0
    def get_version(cls, settings, path):
        '''
        Generate the version string to be used in static URLs.

        This method may be overridden in subclasses (but note that it
        is a class method rather than a static method).  The default
        implementation uses a hash of the file's contents.

        ``settings`` is the `Application.settings` dictionary and ``path``
        is the relative location of the requested asset on the filesystem.
        The returned value should be a string, or ``None`` if no version
        could be determined.
        '''
        abs_path = os.path.join(settings["static_path"], path)
        with cls._lock:
            hashes = cls._static_hashes
            if abs_path not in hashes:
                try:
                    data = FileCache.get(abs_path)
                    hashes[abs_path] = hashlib.md5(data).hexdigest()
                except Exception:
                    logging.error("Could not open static file %r", path)
                    hashes[abs_path] = None
            hsh = hashes.get(abs_path)
            if hsh:
                return hsh[:5]
        return None
Пример #7
0
    def get(self, path, include_body=True):
        path = self.parse_url_path(path)
        abspath = os.path.abspath(os.path.join(self.root, path))
        # os.path.abspath strips a trailing /
        # it needs to be temporarily added back for requests to root/
        if not (abspath + os.path.sep).startswith(self.root):
            raise HTTPError(403, "%s is not in root static directory", path)
        if os.path.isdir(abspath) and self.default_filename is not None:
            # need to look at the request.path here for when path is empty
            # but there is some prefix to the path that was already
            # trimmed by the routing
            if not self.request.path.endswith("/"):
                self.redirect(self.request.path + "/")
                return
            abspath = os.path.join(abspath, self.default_filename)
        if not os.path.exists(abspath):
            raise HTTPError(404)
        if not os.path.isfile(abspath):
            raise HTTPError(403, "%s is not a file", path)

        stat_result = os.stat(abspath)
        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])

        self.set_header("Last-Modified", modified)

        mime_type, encoding = mimetypes.guess_type(abspath)
        if mime_type:
            self.set_header("Content-Type", mime_type)

        cache_time = self.get_cache_time(path, modified, mime_type)

        if cache_time > 0:
            self.set_header("Expires", datetime.datetime.utcnow() +
                            datetime.timedelta(seconds=cache_time))
            self.set_header("Cache-Control", "max-age=" + str(cache_time))
        else:
            self.set_header("Cache-Control", "public")

        self.set_extra_headers(path)

        # Check the If-Modified-Since, and don't send the result if the
        # content has not been modified
        ims_value = self.request.headers.get("If-Modified-Since")
        if ims_value is not None:
            date_tuple = email.utils.parsedate(ims_value)
            if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
            if if_since >= modified:
                self.set_status(304)
                return

        data = FileCache.get(abspath)
        hasher = hashlib.sha1()
        hasher.update(data)
        self.set_header("Etag", '"%s"' % hasher.hexdigest())
        if include_body:
            self.write(data)
        else:
            assert self.request.method == "HEAD"
            self.set_header("Content-Length", len(data))
Пример #8
0
def start_server():
    ''' Main entry point for the application '''
    server = HTTPServer(app)
    sockets = netutil.bind_sockets(config.listen_port)
    server.add_sockets(sockets)
    io_loop = IOLoop.instance()
    try:
        if config.debug:
            # Print a nice verbose warning
            sys.stdout.write(WARN + "WARNING: Debug mode is enabled in " +
                             config.filename)
            sys.stdout.write(
                bold +
                "\n\n\t>>> Debug Mode Disables Some Security Measures <<<" +
                W + "\n\n")
        sys.stdout.flush()
        game_history = GameHistory.Instance()
        history_callback = PeriodicCallback(game_history.take_snapshot,
                                            config.history_snapshot_interval,
                                            io_loop=io_loop)
        scoring_callback = PeriodicCallback(score_bots,
                                            config.bot_reward_interval,
                                            io_loop=io_loop)
        bot_ping_callback = PeriodicCallback(ping_bots, 30000, io_loop=io_loop)
        # Start ALL THE THINGS!
        bot_ping_callback.start()
        history_callback.start()
        scoring_callback.start()
        io_loop.start()
    except KeyboardInterrupt:
        sys.stdout.write('\r' + WARN + 'Shutdown Everything!\n')
    except:
        logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        if config.debug and raw_input(
                PROMPT + "Flush Memcache? [Y/n]: ").lower() == 'y':
            sys.stdout.write(INFO + 'Flushing cache ... '),
            FileCache.flush()
            sys.stdout.write('okay\n')
        _exit(0)
Пример #9
0
    def get(self, path, include_body=True):
        path = self.parse_url_path(path)
        abspath = os.path.abspath(os.path.join(self.root, path))
        # os.path.abspath strips a trailing /
        # it needs to be temporarily added back for requests to root/
        if not (abspath + os.path.sep).startswith(self.root):
            raise HTTPError(403, "%s is not in root static directory", path)
        if os.path.isdir(abspath) and self.default_filename is not None:
            # need to look at the request.path here for when path is empty
            # but there is some prefix to the path that was already
            # trimmed by the routing
            if not self.request.path.endswith("/"):
                self.redirect(self.request.path + "/")
                return
            abspath = os.path.join(abspath, self.default_filename)
        if not os.path.exists(abspath):
            raise HTTPError(404)
        if not os.path.isfile(abspath):
            raise HTTPError(403, "%s is not a file", path)

        stat_result = os.stat(abspath)
        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])

        self.set_header("Last-Modified", modified)

        mime_type, encoding = mimetypes.guess_type(abspath)
        if mime_type:
            self.set_header("Content-Type", mime_type)

        cache_time = self.get_cache_time(path, modified, mime_type)

        if cache_time > 0:
            self.set_header(
                "Expires",
                datetime.datetime.utcnow() +
                datetime.timedelta(seconds=cache_time))
            self.set_header("Cache-Control", "max-age=" + str(cache_time))
        else:
            self.set_header("Cache-Control", "public")

        self.set_extra_headers(path)

        # Check the If-Modified-Since, and don't send the result if the
        # content has not been modified
        ims_value = self.request.headers.get("If-Modified-Since")
        if ims_value is not None:
            date_tuple = email.utils.parsedate(ims_value)
            if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
            if if_since >= modified:
                self.set_status(304)
                return

        data = FileCache.get(abspath)
        hasher = hashlib.sha1()
        hasher.update(data)
        self.set_header("Etag", '"%s"' % hasher.hexdigest())
        if include_body:
            self.write(data)
        else:
            assert self.request.method == "HEAD"
            self.set_header("Content-Length", len(data))