Ejemplo n.º 1
0
def get_app(args):
    logger = utils.configure_logger("doh-httpproxy", args.level)
    app = DOHApplication(logger=logger, debug=args.debug)
    app.set_upstream_resolver(args.upstream_resolver, args.upstream_port)
    app.set_ecs(args.ecs)
    app.router.add_get(args.uri, doh1handler)
    app.router.add_post(args.uri, doh1handler)

    # Get trusted reverse proxies and format it for aiohttp_remotes setup
    if len(args.trusted) == 0:
        x_forwarded_handling = aiohttp_remotes.XForwardedRelaxed()
    else:
        x_forwarded_handling = aiohttp_remotes.XForwardedStrict([args.trusted])

    asyncio.ensure_future(aiohttp_remotes.setup(app, x_forwarded_handling))
    return app
Ejemplo n.º 2
0
    def __init__(self, loop, syncer, config):
        self.host = config['rpc']['host']
        self.port = config['rpc']['port']
        self.loop = loop
        self.syncer = syncer
        self.global_message_queue = self.syncer.queues['RPCManager']
        #self.allowed_clients
        self.requests = {}
        self.up = True
        self.logger = logging.getLogger("RPCManager")
        default_log_level = logging.INFO
        if "logging" in config:  #debug, info, warning, error, critical
            loglevels = {
                "debug": logging.DEBUG,
                "info": logging.INFO,
                "warning": logging.WARNING,
                "error": logging.ERROR,
                "critical": logging.CRITICAL
            }
            if "base" in config["logging"] and config["logging"][
                    "base"] in loglevels:
                self.logger.setLevel(loglevels[config["logging"]["base"]])
            if "rpc" in config["logging"] and config["logging"][
                    "rpc"] in loglevels:
                #its ok to rewrite
                self.logger.setLevel(loglevels[config["logging"]["rpc"]])

        rpc_manager_location = __file__
        web_wallet_dir = join(
            path_split(rpc_manager_location)[0], "web_wallet")
        self.app = web.Application(loop=self.loop)
        self.loop.run_until_complete(
            setup(
                self.app,
                BasicAuth(config['rpc']['login'],
                          config['rpc']['password'],
                          "realm",
                          white_paths=['/'])))

        self.app.router.add_route('*', '/rpc', self.handle)
        self.app.router.add_route('*', '/', self.handle_root)
        self.app.router.add_static('/', web_wallet_dir)
        self.server = self.loop.create_server(self.app.make_handler(),
                                              self.host, self.port)
        asyncio.ensure_future(self.server, loop=loop)
        asyncio.ensure_future(self.check_queue())

        methods.add(self.ping)
        methods.add(self.getconnectioncount)
        methods.add(self.getheight)
        methods.add(self.getblocktemplate)
        methods.add(self.getwork)
        methods.add(self.submitwork)
        methods.add(self.validatesolution)
        methods.add(self.getbalancestats)
        methods.add(self.getbalancelist)
        methods.add(self.getbalance)
        methods.add(self.sendtoaddress)
        methods.add(self.getnewaddress)
        methods.add(self.dumpprivkey)
        methods.add(self.importprivkey)
        methods.add(self.getsyncstatus)
        methods.add(self.getblock)
        methods.add(self.getnodes)
        methods.add(self.connecttonode)
        methods.add(self.gettransactions)
        methods.add(self.getversion)
        methods.add(self.shutdown)

        methods.add(self.eth_getWork)
        methods.add(self.eth_submitWork)
        methods.add(self.eth_getBlockByNumber)
        self.no_auth_methods = [
            "eth_getWork", "eth_submitWork", "eth_getBlockByNumber"
        ]
Ejemplo n.º 3
0
def create_app(**kwargs):
    ''' Completely initialize the flask application
  '''
    from aiohttp import web
    from aiohttp_wsgi import WSGIHandler
    from aiohttp_remotes import setup, XForwardedRelaxed
    #
    from flask import Flask, Blueprint, current_app, redirect
    from flask_cors import CORS
    #
    from appyter.render.flask_app.socketio import socketio
    from appyter.render.flask_app.core import core
    import appyter.render.flask_app.static
    import appyter.render.flask_app.download
    import appyter.render.flask_app.execution
    if kwargs['debug']:
        import appyter.render.flask_app.livereload
    #
    from appyter.context import get_env, find_blueprints
    from appyter.util import join_routes
    config = get_env(**kwargs)
    #
    if config['DEBUG']:
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(name)s %(message).80s',
        )
    else:
        logging.basicConfig(
            level=logging.WARNING,
            format='%(name)s %(message).80s',
        )
        logging.getLogger(__package__).setLevel(logging.INFO)
    #
    logger.info('Initializing aiohttp...')
    app = web.Application()
    app['config'] = config
    #
    logger.info('Initializing socketio...')
    socketio.attach(app, join_routes(config['PREFIX'], 'socket.io'))
    #
    logger.info('Initializing flask...')
    flask_app = Flask(__name__, static_url_path=None, static_folder=None)
    CORS(flask_app)
    flask_app.config.update(config)
    flask_app.debug = config['DEBUG']
    #
    logger.info('Registering blueprints...')
    flask_app.register_blueprint(core)
    for blueprint_name, blueprint in find_blueprints(
            config=flask_app.config).items():
        if isinstance(blueprint, Blueprint):
            flask_app.register_blueprint(blueprint,
                                         url_prefix='/' +
                                         blueprint_name.strip('/'))
        elif callable(blueprint):
            blueprint(flask_app, url_prefix='/' + blueprint_name.strip('/'))
        else:
            raise Exception('Unrecognized blueprint type: ' + blueprint_name)
    #
    if app['config']['PREFIX'].strip('/'):
        logger.info('Registering prefix redirect')

        async def redirect_to_prefix(request):
            path = request.match_info['path']
            if path == app['config']['PREFIX'].strip('/'): path = ''
            raise web.HTTPFound(
                join_routes(app['config']['PREFIX'], path) + '/')

        app.router.add_get('/{path:[^/]*}', redirect_to_prefix)
    #
    logger.info('Registering flask with aiohttp...')
    wsgi_handler = WSGIHandler(flask_app)
    app.router.add_route(
        '*', join_routes(app['config']['PREFIX'], '{path_info:.*}'),
        wsgi_handler)
    if flask_app.config['PROXY']:
        logger.info('Applying proxy fix middleware...')
        import asyncio
        asyncio.get_event_loop().run_until_complete(
            setup(app, XForwardedRelaxed()))
    return app
Ejemplo n.º 4
0
    result = {}
    if request.match_info['item']:
        if int(request.rel_url.query['per_page']) == 1:
            if request.match_info['item'] == 'fact_values':
                with open('hosts-perpage1-facts.json') as json_file:
                    result = json.load(json_file)
            else:
                with open('hosts-perpage1.json') as json_file:
                    result = json.load(json_file)
        else:
            await asyncio.sleep(randrange(0, 20))
            with open('hosts-perpagefull.json') as json_file:
                result = json.load(json_file)
    #return web.json_response(await time())
    #return web.Response(text=str(result))
    return web.json_response(result)


if __name__ == '__main__':
    app = web.Application()
    app.router.add_route('GET', "/api/v2/{item}", method)
    app.router.add_route('GET', "/api/{item}", method)
    logging.basicConfig(level=logging.DEBUG)
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ssl_context.load_verify_locations('../ssl/foreman_cache-localhost.crt',
                                      '../ssl/foreman_cache-localhost.key')
    ssl_context.load_cert_chain('../ssl/foreman_cache-localhost.crt',
                                '../ssl/foreman_cache-localhost.key')
    setup(app, BasicAuth('foreman', 'foreman', 'fback'))
    web.run_app(app, host='localhost', port=8233, ssl_context=ssl_context)