예제 #1
0
 def __init__(self):
     # Inject environment variables from local file
     load_env()
     self.app_cache_dir = get_path("cache/app_cache").absolute().__str__()
     self.app_cache_default_timeout = 60
     self.tg_host = os.getenv("TG_HOST")
     self.tg_graph = os.getenv("TG_GRAPH")
     self.tg_username = os.getenv("TG_USERNAME")
     self.tg_password = os.getenv("TG_PASSWORD")
     self.tg_api_key = os.getenv("TG_API_KEY")
# -*- coding: utf-8 -*-
#
import sys
from util import load_env
from os import getenv
load_env()
module = sys.modules[__name__]
TRUTHS = {True, 1, '1', 'T', 't', 'true', 'TRUE', 'True'}
CONFIG = module.CONFIG = {}

OVERRIDE_SERVER_NAME = CONFIG['OVERRIDE_SERVER_NAME'] = getenv("SANIC_OVERRIDE_SERVER_NAME", "localhost:9001")
PROXY_ROUTE_BASE = CONFIG['PROXY_ROUTE_BASE'] = getenv("SANIC_PROXY_ROUTE_BASE", "")
SANIC_SERVER_NAME = CONFIG['SANIC_SERVER_NAME'] = getenv("SANIC_SERVER_NAME", "")
INFLUXDB_HOST = CONFIG['INFLUXDB_HOST'] = getenv("INFLUX_DB_HOST", "cosmoz.influxdb")
INFLUXDB_PORT = CONFIG['INFLUXDB_PORT'] = int(getenv("INFLUX_DB_PORT", 8086))
INFLUXDB_USERNAME = CONFIG['INFLUXDB_USERNAME'] = getenv("INFLUX_DB_USERNAME", None)
INFLUXDB_PASSWORD = CONFIG['INFLUXDB_PASSWORD'] = getenv("INFLUX_DB_PASSWORD", None)
INFLUXDB_NAME = CONFIG['INFLUXDB_NAME'] = getenv("INFLUX_DB_NAME", "cosmoz")
MONGODB_HOST = CONFIG['MONGODB_HOST'] = getenv("MONGO_DB_HOST", "cosmoz.mongodb")
MONGODB_PORT = CONFIG['MONGODB_PORT'] = int(getenv("MONGO_DB_PORT", 27017))
MONGODB_NAME = CONFIG['MONGODB_NAME'] = getenv("MONGO_DB_NAME", "cosmoz")
METRICS_DIRECTORY = CONFIG['METRICS_DIRECTORY'] = getenv("METRICS_DIRECTORY", ".")
DEBUG = CONFIG['DEBUG'] = getenv("SANIC_DEBUG", '') in TRUTHS
예제 #3
0
파일: dkr.py 프로젝트: nemac/forwarn2_build
import os, os.path, pwd, grp
import docker
import logging as log

from util import load_env

load_env(ns=globals())


def build_gdal():
    client = docker.from_env()
    user = pwd.getpwnam(DKR_USER)
    group = grp.getgrnam(DKR_GROUP)
    user_id = user[2]
    group_id = group[2]
    gdal_image = client.images.build(path=DKR_BUILD_DIR_HOST,
                                     tag=DKR_IMAGE_TAG,
                                     buildargs={
                                         'DKR_BUILD_DIR': DKR_BUILD_DIR,
                                         'DKR_USER': DKR_USER,
                                         'DKR_GROUP': DKR_GROUP,
                                         'DKR_USER_ID': str(user_id),
                                         'DKR_GROUP_ID': str(group_id)
                                     })


def run_gdal(cmd, volumes=None):
    client = docker.from_env()
    containers = client.containers.list()
    if DKR_CONTAINER_NAME in [c.name for c in containers]:
        log.info("Already running!")
예제 #4
0
    if not sch.signed_off and (curr_time >= NOTIFICATION_START or \
       (curr_time <= RESET_TIME)):
        await _default_channel.send(
            'Reminder that <@{}> is responsible for the kitchen tonight!'.
            format(sch.on_call.id))
    elif sch.signed_off and curr_time >= RESET_TIME:
        sch.signed_off = False
    else:
        logger.info('Notification suppressed.')

    logger.info('{} has been notified.'.format(util.discord_name(sch.on_call)))
    return


@notify.before_loop
async def notifications_init():
    """Sleep so that the notifications start on the hour."""
    next_hour = datetime.datetime.now()
    next_hour = next_hour.replace(minute=0, second=0,
                                  microsecond=0) + datetime.timedelta(hours=1)

    delta = next_hour - datetime.datetime.now()
    logger.info('Sleeping {} seconds before activating notifications'.format(
        delta.total_seconds()))
    await asyncio.sleep(delta.total_seconds())
    return


if __name__ == '__main__':
    util.load_env()
    bot.run(os.getenv('TOKEN'))
예제 #5
0
def add_to_app(app, oauth=None, remote=None):
    load_env()
    if not oauth:
        oauth = add_oauth_plugin(app)
    if not remote:
        remote = create_oauth1_remote(app, oauth)
    spf = SanicPluginsFramework(app)
    try:
        session_interface = FilesystemSessionInterface()
        spf.register_plugin(session_plugin, interface=session_interface)
    except ValueError:
        pass
    try:
        ctx = spf.register_plugin(contextualize)
    except ValueError as v:
        _, ctx = v.args

    # @app.route('/')
    # async def index(request):
    #     if 'csiro-to-ldap_oauth' in session:
    #         ret = await oauth.get('email')
    #         if isinstance(ret.data, dict):
    #             return json(ret.data)
    #         return str(ret.data)
    #     return redirect(app.url_for('login'))

    @app.route('/create_oauth')
    @remote.autoauthorize
    async def create_oauth(request, context):
        override_server_name = getenv("SANIC_OVERRIDE_SERVER_NAME",
                                      "localhost:9001")
        callback = request.app.url_for('authorized',
                                       _external=True,
                                       _scheme='http',
                                       _server=override_server_name)
        proxy_route_base = getenv("SANIC_PROXY_ROUTE_BASE", "")
        if len(proxy_route_base):
            callback = callback.replace(
                "/authorized", "/{}authorized".format(proxy_route_base))
        print("In AutoAuthorize. Asking for request_token using callback: {}".
              format(callback))
        after_this = request.args.get("after_authorized", "/apikey")
        state = {
            "remote_app": 'csiro-to-ldap',
            "oauth_version": "1.0a",
            "after_authorized": after_this
        }
        #Oauth1 cannot put state in the request, we need to put it in the session
        shared_context = context.shared
        shared_request_context = shared_context.request[id(request)]
        session = shared_request_context.get('session', {})
        session['oauth_state'] = state
        return {'callback': callback}

    @ctx.route('/logout')
    def logout(request, context):
        shared_context = context.shared
        shared_request_context = shared_context.request[id(request)]
        session = shared_request_context.get('session', {})
        session.pop('csiro-to-ldap_oauth1', None)
        return redirect(app.url_for('index'))

    @app.route('/authorized')
    @remote.authorized_handler
    async def authorized(request, data, context):
        if data is None:
            return 'Access denied: error=%s' % (request.args['error'])
        resp = {k: v[0] for k, v in data.items()}

        shared_context = context.shared
        shared_request_context = shared_context.request[id(request)]
        session = shared_request_context.get('session', {})
        state = session.get('oauth_state', None)
        after_authorized = state.get('after_authorized',
                                     "/apikey") if state else "/apikey"
        if 'oauth_token' in resp:
            session['csiro-to-ldap_oauth1'] = resp
            if state:
                state['access_token_session_key'] = "csiro-to-ldap_oauth1"
        session['oauth_state'] = state
        return redirect(after_authorized)

    @app.route('/method/<name>')
    async def method(request, name):
        func = getattr(remote, name)
        ret = func('method')
        if isawaitable(ret):
            ret = await ret
        return text(ret.raw_data)

    def make_token_getter(_remote):
        context = oauth.context
        shared_context = context.shared

        @_remote.tokengetter
        async def get_oauth_token():
            nonlocal context, shared_context
            raise NotImplementedError(
                "Out-of-order token getter is not implemented. Pass the token to the requester when its required."
            )
            # if 'dev_oauth' in session:
            #     resp = session['dev_oauth']
            #     return resp['oauth_token'], resp['oauth_token_secret']

    make_token_getter(remote)
    return remote