Python flask.current_app() Examples

The following are 30 code examples of flask.current_app(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: indexd.py    From fence with Apache License 2.0 6 votes vote down vote up
def init_multipart_upload(key, expires_in=None):
        """
        Initilize multipart upload given key

        Args:
            key(str): object key

        Returns:
            uploadId(str)
        """
        try:
            bucket = flask.current_app.config["DATA_UPLOAD_BUCKET"]
        except KeyError:
            raise InternalError(
                "fence not configured with data upload bucket; can't create signed URL"
            )
        s3_url = "s3://{}/{}".format(bucket, key)
        return S3IndexedFileLocation(s3_url).init_multipart_upload(expires_in) 
Example #2
Source File: manage.py    From evesrp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def create(force=False):
    """Create tables if the database has not been configured yet."""
    # Fail if there's an alembic version set
    engine = db.get_engine(flask.current_app)
    conn = engine.connect()
    context = MigrationContext.configure(conn)
    current_rev = context.get_current_revision()
    alembic_config = flask.current_app.extensions['migrate'].migrate.get_config(
            directory=migrate_path)
    script = ScriptDirectory.from_config(alembic_config)
    latest_rev = script.get_current_head()
    if current_rev == latest_rev and not force:
        print(u"You need to run 'evesrp -c config.py db migrate' to "
              u"migrate to the latest database schema.")
    else:
        db.create_all()
        if current_rev is None:
            stamp() 
Example #3
Source File: redis.py    From lemur with Apache License 2.0 6 votes vote down vote up
def redis(self, db=0):
        # The decode_responses flag here directs the client to convert the responses from Redis into Python strings
        # using the default encoding utf-8.  This is client specific.
        function = f"{__name__}.{sys._getframe().f_code.co_name}"
        try:
            red = redis.StrictRedis(host=self.host, port=self.port, db=self.db, encoding="utf-8", decode_responses=True)
            red.set("test", 0)
        except redis.ConnectionError:
            log_data = {
                "function": function,
                "message": "Redis Connection error",
                "host": self.host,
                "port": self.port
            }
            current_app.logger.error(log_data)
            sentry.captureException()
        return red 
Example #4
Source File: tasks.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def harvest(self, ident):
    log.info('Launching harvest job for source "%s"', ident)

    source = HarvestSource.get(ident)
    if source.deleted:
        return  # Ignore deleted sources
    Backend = backends.get(current_app, source.backend)
    backend = Backend(source)
    items = backend.perform_initialization()
    if items > 0:
        finalize = harvest_job_finalize.s(backend.job.id)
        items = [
            harvest_job_item.s(backend.job.id, item.remote_id)
            for item in backend.job.items
        ]
        chord(items)(finalize)
    elif items == 0:
        backend.finalize() 
Example #5
Source File: __init__.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def list_available():
    '''
    List available migrations for udata and enabled plugins

    Each row is a tuple with following signature:

        (plugin, package, filename)
    '''
    migrations = []

    migrations.extend(_iter('udata', 'udata'))

    plugins = entrypoints.get_enabled('udata.models', current_app)
    for plugin, module in plugins.items():
        migrations.extend(_iter(plugin, module))
    return sorted(migrations, key=lambda m: m.filename) 
Example #6
Source File: celery.py    From lemur with Apache License 2.0 6 votes vote down vote up
def report_failed_task(**kwargs):
    """
    Report a generic failure metric as tasks to our metrics broker every time a task fails.
    This metric can be used for alerting.
    https://docs.celeryproject.org/en/latest/userguide/signals.html#task-failure
    """
    with flask_app.app_context():
        log_data = {
            "function": f"{__name__}.{sys._getframe().f_code.co_name}",
            "Message": "Celery Task Failure",
        }

        # Add traceback if exception info is in the kwargs
        einfo = kwargs.get("einfo")
        if einfo:
            log_data["traceback"] = einfo.traceback

        error_tags = get_celery_request_tags(**kwargs)

        log_data.update(error_tags)
        current_app.logger.error(log_data)
        metrics.send("celery.failed_task", "TIMER", 1, metric_tags=error_tags) 
Example #7
Source File: utils.py    From lemur with Apache License 2.0 6 votes vote down vote up
def get_keys():
    """
    Gets the encryption keys.

    This supports multiple keys to facilitate key rotation. The first
    key in the list is used to encrypt. Decryption is attempted with
    each key in succession.

    :return:
    """

    # when running lemur create_config, this code needs to work despite
    # the fact that there is not a current_app with a config at that point
    keys = current_app.config.get("LEMUR_ENCRYPTION_KEYS", [])

    # this function is expected to return a list of keys, but we want
    # to let people just specify a single key
    if not isinstance(keys, list):
        keys = [keys]

    # make sure there is no accidental whitespace
    keys = [key.strip() for key in keys]

    return keys 
Example #8
Source File: celery.py    From lemur with Apache License 2.0 6 votes vote down vote up
def enable_autorotate_for_certs_attached_to_endpoint():
    """
    This celery task automatically enables autorotation for unexpired certificates that are
    attached to an endpoint but do not have autorotate enabled.
    :return:
    """
    function = f"{__name__}.{sys._getframe().f_code.co_name}"
    task_id = None
    if celery.current_task:
        task_id = celery.current_task.request.id

    log_data = {
        "function": function,
        "task_id": task_id,
        "message": "Enabling autorotate to eligible certificates",
    }
    current_app.logger.debug(log_data)

    cli_certificate.automatically_enable_autorotate()
    metrics.send(f"{function}.success", "counter", 1)
    return log_data 
Example #9
Source File: indexd.py    From fence with Apache License 2.0 6 votes vote down vote up
def complete_multipart_upload(key, uploadId, parts, expires_in=None):
        """
        Complete multipart upload

        Args:
            key(str): object key or `GUID/filename`
            uploadId(str): upload id of the current upload
            parts(list(set)): List of part infos
                [{"Etag": "1234567", "PartNumber": 1}, {"Etag": "4321234", "PartNumber": 2}]

        Returns:
            None if success otherwise an exception
        """
        try:
            bucket = flask.current_app.config["DATA_UPLOAD_BUCKET"]
        except KeyError:
            raise InternalError(
                "fence not configured with data upload bucket; can't create signed URL"
            )
        s3_url = "s3://{}/{}".format(bucket, key)
        S3IndexedFileLocation(s3_url).complete_multipart_upload(
            uploadId, parts, expires_in
        ) 
Example #10
Source File: indexd.py    From fence with Apache License 2.0 6 votes vote down vote up
def generate_aws_presigned_url_for_part(key, uploadId, partNumber, expires_in):
        """
        Generate presigned url for each part

        Args:
            key(str): object key of `guid/filename`
            uploadID(str): uploadId of the current upload.
            partNumber(int): the part number

        Returns:
            presigned_url(str)
        """
        try:
            bucket = flask.current_app.config["DATA_UPLOAD_BUCKET"]
        except KeyError:
            raise InternalError(
                "fence not configured with data upload bucket; can't create signed URL"
            )
        s3_url = "s3://{}/{}".format(bucket, key)
        return S3IndexedFileLocation(s3_url).generate_presigne_url_for_part_upload(
            uploadId, partNumber, expires_in
        ) 
Example #11
Source File: indexd.py    From fence with Apache License 2.0 6 votes vote down vote up
def delete_files(self, urls=None, delete_all=True):
        """
        Delete the data files stored at all the locations for this indexed file.

        If a list of URLs is specified, delete only files at those locations;
        otherwise, delete files at all locations.

        Args:
            urls (Optional[List[str]])

        Return:
            None
        """
        locations_to_delete = []
        if urls is None and delete_all:
            locations_to_delete = self.indexed_file_locations
        else:
            locations_to_delete = [
                location for location in locations_to_delete if location.url in urls
            ]
        for location in locations_to_delete:
            bucket = location.bucket_name()
            flask.current_app.boto.delete_data_file(bucket, self.file_id) 
Example #12
Source File: powerdns.py    From lemur with Apache License 2.0 6 votes vote down vote up
def _get(path, params=None):
    """
    Execute a GET request on the given URL (base_uri + path) and return response as JSON object

    :param path: Relative URL path
    :param params: additional parameters
    :return: json response
    """
    base_uri = current_app.config.get("ACME_POWERDNS_DOMAIN")
    verify_value = current_app.config.get("ACME_POWERDNS_VERIFY", True)
    resp = requests.get(
        f"{base_uri}{path}",
        headers=_generate_header(),
        params=params,
        verify=verify_value
    )
    resp.raise_for_status()
    return resp.json() 
Example #13
Source File: powerdns.py    From lemur with Apache License 2.0 6 votes vote down vote up
def _patch(path, payload):
    """
    Execute a Patch request on the given URL (base_uri + path) with given payload

    :param path:
    :param payload:
    :return:
    """
    base_uri = current_app.config.get("ACME_POWERDNS_DOMAIN")
    verify_value = current_app.config.get("ACME_POWERDNS_VERIFY", True)
    resp = requests.patch(
        f"{base_uri}{path}",
        data=json.dumps(payload),
        headers=_generate_header(),
        verify=verify_value
    )
    resp.raise_for_status() 
Example #14
Source File: log_ara.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        super(CallbackModule, self).__init__()

        if not flask.current_app:
            ctx = app.app_context()
            ctx.push()

        self.taskresult = None
        self.task = None
        self.play = None
        self.playbook = None
        self.stats = None
        self.loop_items = []

        self.play_counter = itertools.count()
        self.task_counter = itertools.count()

        if cli:
            self._options = cli.options
        else:
            self._options = None 
Example #15
Source File: powerdns.py    From lemur with Apache License 2.0 5 votes vote down vote up
def _generate_header():
    """
    Generate a PowerDNS API header and return it as a dictionary

    :return: Dict of header parameters
    """
    api_key_name = current_app.config.get("ACME_POWERDNS_APIKEYNAME")
    api_key = current_app.config.get("ACME_POWERDNS_APIKEY")
    headers = {api_key_name: api_key}
    return headers 
Example #16
Source File: ldap.py    From lemur with Apache License 2.0 5 votes vote down vote up
def __init__(self, args):
        self._ldap_validate_conf()
        # setup ldap config
        if not args["username"]:
            raise Exception("missing ldap username")
        if not args["password"]:
            self.error_message = "missing ldap password"
            raise Exception("missing ldap password")
        self.ldap_principal = args["username"]
        self.ldap_email_domain = current_app.config.get("LDAP_EMAIL_DOMAIN", None)
        if "@" not in self.ldap_principal:
            self.ldap_principal = "%s@%s" % (
                self.ldap_principal,
                self.ldap_email_domain,
            )
        self.ldap_username = args["username"]
        if "@" in self.ldap_username:
            self.ldap_username = args["username"].split("@")[0]
        self.ldap_password = args["password"]
        self.ldap_server = current_app.config.get("LDAP_BIND_URI", None)
        self.ldap_base_dn = current_app.config.get("LDAP_BASE_DN", None)
        self.ldap_use_tls = current_app.config.get("LDAP_USE_TLS", False)
        self.ldap_cacert_file = current_app.config.get("LDAP_CACERT_FILE", None)
        self.ldap_default_role = current_app.config.get("LEMUR_DEFAULT_ROLE", None)
        self.ldap_required_group = current_app.config.get("LDAP_REQUIRED_GROUP", None)
        self.ldap_groups_to_roles = current_app.config.get("LDAP_GROUPS_TO_ROLES", None)
        self.ldap_is_active_directory = current_app.config.get(
            "LDAP_IS_ACTIVE_DIRECTORY", False
        )
        self.ldap_attrs = ["memberOf"]
        self.ldap_client = None
        self.ldap_groups = None 
Example #17
Source File: powerdns.py    From lemur with Apache License 2.0 5 votes vote down vote up
def create_txt_record(domain, token, account_number):
    """
    Create a TXT record for the given domain and token and return a change_id tuple

    :param domain: FQDN
    :param token: challenge value
    :param account_number:
    :return: tuple of domain/token
    """
    _check_conf()

    function = sys._getframe().f_code.co_name
    log_data = {
        "function": function,
        "fqdn": domain,
        "token": token,
    }

    # Create new record
    domain_id = domain + "."
    records = [Record({'name': domain_id, 'content': f"\"{token}\"", 'disabled': False})]

    # Get current records
    cur_records = _get_txt_records(domain)
    for record in cur_records:
        if record.content != token:
            records.append(record)

    try:
        _patch_txt_records(domain, account_number, records)
        log_data["message"] = "TXT record(s) successfully created"
        current_app.logger.debug(log_data)
    except Exception as e:
        sentry.captureException()
        log_data["Exception"] = e
        log_data["message"] = "Unable to create TXT record(s)"
        current_app.logger.debug(log_data)

    change_id = (domain, token)
    return change_id 
Example #18
Source File: celery.py    From lemur with Apache License 2.0 5 votes vote down vote up
def fetch_all_pending_acme_certs():
    """Instantiate celery workers to resolve all pending Acme certificates"""

    function = f"{__name__}.{sys._getframe().f_code.co_name}"
    task_id = None
    if celery.current_task:
        task_id = celery.current_task.request.id

    log_data = {
        "function": function,
        "message": "Starting job.",
        "task_id": task_id,
    }

    if task_id and is_task_active(function, task_id, None):
        log_data["message"] = "Skipping task: Task is already active"
        current_app.logger.debug(log_data)
        return

    current_app.logger.debug(log_data)
    pending_certs = pending_certificate_service.get_unresolved_pending_certs()

    # We only care about certs using the acme-issuer plugin
    for cert in pending_certs:
        cert_authority = get_authority(cert.authority_id)
        if cert_authority.plugin_name == "acme-issuer":
            if datetime.now(timezone.utc) - cert.last_updated > timedelta(minutes=5):
                log_data["message"] = "Triggering job for cert {}".format(cert.name)
                log_data["cert_name"] = cert.name
                log_data["cert_id"] = cert.id
                current_app.logger.debug(log_data)
                fetch_acme_cert.delay(cert.id)

    metrics.send(f"{function}.success", "counter", 1)
    return log_data 
Example #19
Source File: powerdns.py    From lemur with Apache License 2.0 5 votes vote down vote up
def wait_for_dns_change(change_id, account_number=None):
    """
    Checks the authoritative DNS Server to see if changes have propagated.

    :param change_id: tuple of domain/token
    :param account_number:
    :return:
    """
    _check_conf()
    domain, token = change_id
    number_of_attempts = current_app.config.get("ACME_POWERDNS_RETRIES", 3)
    zone_name = _get_zone_name(domain, account_number)
    nameserver = dnsutil.get_authoritative_nameserver(zone_name)
    record_found = False
    for attempts in range(0, number_of_attempts):
        txt_records = dnsutil.get_dns_records(domain, "TXT", nameserver)
        for txt_record in txt_records:
            if txt_record == token:
                record_found = True
                break
        if record_found:
            break
        time.sleep(10)

    function = sys._getframe().f_code.co_name
    log_data = {
        "function": function,
        "fqdn": domain,
        "status": record_found,
        "message": "Record status on PowerDNS authoritative server"
    }
    current_app.logger.debug(log_data)

    if record_found:
        metrics.send(f"{function}.success", "counter", 1, metric_tags={"fqdn": domain, "txt_record": token})
    else:
        metrics.send(f"{function}.fail", "counter", 1, metric_tags={"fqdn": domain, "txt_record": token}) 
Example #20
Source File: celery.py    From lemur with Apache License 2.0 5 votes vote down vote up
def report_celery_last_success_metrics():
    """
    For each celery task, this will determine the number of seconds since it has last been successful.

    Celery tasks should be emitting redis stats with a deterministic key (In our case, `f"{task}.last_success"`.
    report_celery_last_success_metrics should be ran periodically to emit metrics on when a task was last successful.
    Admins can then alert when tasks are not ran when intended. Admins should also alert when no metrics are emitted
    from this function.
    """
    function = f"{__name__}.{sys._getframe().f_code.co_name}"
    task_id = None
    if celery.current_task:
        task_id = celery.current_task.request.id

    log_data = {
        "function": function,
        "message": "recurrent task",
        "task_id": task_id,
    }

    if task_id and is_task_active(function, task_id, None):
        log_data["message"] = "Skipping task: Task is already active"
        current_app.logger.debug(log_data)
        return

    current_time = int(time.time())
    schedule = current_app.config.get("CELERYBEAT_SCHEDULE")
    for _, t in schedule.items():
        task = t.get("task")
        last_success = int(red.get(f"{task}.last_success") or 0)
        metrics.send(
            f"{task}.time_since_last_success", "gauge", current_time - last_success
        )
    red.set(
        f"{function}.last_success", int(time.time())
    )  # Alert if this metric is not seen
    metrics.send(f"{function}.success", "counter", 1) 
Example #21
Source File: powerdns.py    From lemur with Apache License 2.0 5 votes vote down vote up
def _get_txt_records(domain):
    """
    Retrieve TXT records for a given domain and return list of Record Objects

    :param domain: FQDN
    :return: list of Record objects
    """
    server_id = current_app.config.get("ACME_POWERDNS_SERVERID", "localhost")

    path = f"/api/v1/servers/{server_id}/search-data?q={domain}&max=100&object_type=record"
    function = sys._getframe().f_code.co_name
    log_data = {
        "function": function
    }
    try:
        records = _get(path)
        log_data["message"] = "Retrieved TXT Records Successfully"
        current_app.logger.debug(log_data)

    except Exception as e:
        sentry.captureException()
        log_data["Exception"] = e
        log_data["message"] = "Failed to Retrieve TXT Records"
        current_app.logger.debug(log_data)
        return []

    txt_records = []
    for record in records:
        cur_record = Record(record)
        txt_records.append(cur_record)
    return txt_records 
Example #22
Source File: powerdns.py    From lemur with Apache License 2.0 5 votes vote down vote up
def get_zones(account_number):
    """
    Retrieve authoritative zones from the PowerDNS API and return a list of zones

    :param account_number:
    :raise: Exception
    :return: list of Zone Objects
    """
    _check_conf()
    server_id = current_app.config.get("ACME_POWERDNS_SERVERID", "localhost")
    path = f"/api/v1/servers/{server_id}/zones"
    zones = []
    function = sys._getframe().f_code.co_name
    log_data = {
        "function": function
    }
    try:
        records = _get(path)
        log_data["message"] = "Retrieved Zones Successfully"
        current_app.logger.debug(log_data)

    except Exception as e:
        sentry.captureException()
        log_data["message"] = "Failed to Retrieve Zone Data"
        current_app.logger.debug(log_data)
        raise

    for record in records:
        zone = Zone(record)
        if zone.kind == 'Master':
            zones.append(zone.name)
    return zones 
Example #23
Source File: manage.py    From lemur with Apache License 2.0 5 votes vote down vote up
def run(self, *args, **kwargs):
        from gunicorn.app.wsgiapp import WSGIApplication

        app = WSGIApplication()

        # run startup tasks on an app like object
        validate_conf(current_app, REQUIRED_VARIABLES)

        app.app_uri = 'lemur:create_app(config_path="{0}")'.format(
            current_app.config.get("CONFIG_PATH")
        )

        return app.run() 
Example #24
Source File: manage.py    From lemur with Apache License 2.0 5 votes vote down vote up
def make_shell_context():
    """
    Creates a python REPL with several default imports
    in the context of the current_app

    :return:
    """
    return dict(current_app=current_app) 
Example #25
Source File: celery.py    From lemur with Apache License 2.0 5 votes vote down vote up
def sync_all_sources():
    """
    This function will sync certificates from all sources. This function triggers one celery task per source.
    """
    function = f"{__name__}.{sys._getframe().f_code.co_name}"
    task_id = None
    if celery.current_task:
        task_id = celery.current_task.request.id

    log_data = {
        "function": function,
        "message": "creating celery task to sync source",
        "task_id": task_id,
    }

    if task_id and is_task_active(function, task_id, None):
        log_data["message"] = "Skipping task: Task is already active"
        current_app.logger.debug(log_data)
        return

    sources = validate_sources("all")
    for source in sources:
        log_data["source"] = source.label
        current_app.logger.debug(log_data)
        sync_source.delay(source.label)

    metrics.send(f"{function}.success", "counter", 1)
    return log_data 
Example #26
Source File: utils.py    From lemur with Apache License 2.0 5 votes vote down vote up
def mktemppath():
    try:
        path = os.path.join(
            tempfile._get_default_tempdir(), next(tempfile._get_candidate_names())
        )
        yield path
    finally:
        try:
            os.unlink(path)
        except OSError as e:
            current_app.logger.debug("No file {0}".format(path)) 
Example #27
Source File: utils.py    From lemur with Apache License 2.0 5 votes vote down vote up
def mktempfile():
    with tempfile.NamedTemporaryFile(delete=False) as f:
        name = f.name

    try:
        yield name
    finally:
        try:
            os.unlink(name)
        except OSError as e:
            current_app.logger.debug("No file {0}".format(name)) 
Example #28
Source File: keys.py    From fence with Apache License 2.0 5 votes vote down vote up
def default_private_key(app=flask.current_app):
    """
    Return the default (first) private key for the given app.
    """
    return app.keypairs[0].private_key 
Example #29
Source File: keys.py    From fence with Apache License 2.0 5 votes vote down vote up
def default_public_key(app=flask.current_app):
    """
    Return the default (first) public key for the given app.
    """
    return app.keypairs[0].public_key 
Example #30
Source File: __init__.py    From fence with Apache License 2.0 5 votes vote down vote up
def get_current_user_info():
    with flask.current_app.db.session as session:
        return get_user_info(session, session.merge(flask.g.user).username)