def config_app(application): try: # Load the default configuration application.config.from_object('prom2teams.config.settings') # Load the configuration from the instance folder instance = os.path.join(os.path.join(root, os.pardir), 'instance') config = os.path.join(instance, 'config.py') if os.path.isdir(instance) and os.path.exists(config): application.config.from_pyfile(config) # Load the file specified by the APP_CONFIG_FILE environment variable # Variables defined here will override those in the default configuration if 'APP_CONFIG_FILE' in os.environ: application.config['APP_CONFIG_FILE'] = os.environ.get( 'APP_CONFIG_FILE') config_provided = _config_provided(os.getenv('APP_CONFIG_FILE')) _update_application_configuration(application, config_provided) # Parse and load command line properties # Variables defined here will override previous configuration command_line_args = _config_command_line() if command_line_args.configpath: application.config[ 'APP_CONFIG_FILE'] = command_line_args.configpath config_provided = _config_provided(command_line_args.configpath) _update_application_configuration(application, config_provided) if command_line_args.loglevel: application.config['LOG_LEVEL'] = command_line_args.loglevel if command_line_args.logfilepath: application.config['LOG_FILE_PATH'] = command_line_args.logfilepath if command_line_args.templatepath: application.config[ 'TEMPLATE_PATH'] = command_line_args.templatepath if command_line_args.groupalertsby: application.config[ 'GROUP_ALERTS_BY'] = command_line_args.groupalertsby if command_line_args.enablemetrics or os.environ.get( 'PROM2TEAMS_PROMETHEUS_METRICS', False): os.environ["DEBUG_METRICS"] = "True" from prometheus_flask_exporter import PrometheusMetrics metrics = PrometheusMetrics(application) if 'MICROSOFT_TEAMS' not in application.config: raise MissingConnectorConfigKeyException( 'missing connector key in config') except MissingConnectorConfigKeyException: sys.exit('No Microsoft Teams connector available')
def setup_prometheus(self, registry=None): """Setup Prometheus.""" kwargs = {} if registry: kwargs["registry"] = registry self.metrics = PrometheusMetrics(self.app, **kwargs) try: version = pkg_resources.require(self.app.name)[0].version except pkg_resources.DistributionNotFound: version = "unknown" self.metrics.info("app_info", "Application info", version=version, appname=self.app.name) self.app.logger.info("Prometheus is enabled.")
def _setup_metrics(self): metrics = PrometheusMetrics(self.app) metrics.info('flask_app_info', 'Application info', version=os.environ.get('GIT_COMMIT') or 'unknown') metrics.info('flask_app_built_at', 'Application build timestamp').set( float(os.environ.get('BUILD_TIMESTAMP') or '0')) action_summary = Summary('webhook_proxy_actions', 'Action invocation metrics', labelnames=('http_route', 'http_method', 'action_type', 'action_index')) return action_summary
def init_prometheus_flask_exporter(self, app): enable_exporter_flask = app.config.get( "PROMETHEUS_ENABLE_EXPORTER_FLASK", False) if not enable_exporter_flask: LOGGER.debug( f"Prometheus Flask exporter is not enabled for {app.name}.") return prefix = app.name metrics_flask = PrometheusMetrics(app=None, defaults_prefix=prefix, group_by=url_rule) metrics_flask.init_app(app) LOGGER.debug( f"Prometheus Flask exporter is initialized with prefix {prefix}.")
def integrate_prometheus_metrics(app: Flask, restful_api: Api): # metrics = RESTfulPrometheusMetrics(app, restful_api) metrics = PrometheusMetrics(app) metrics.info('app_info', 'Application info', version='1.0.3') metrics.register_default( metrics.summary('by_path_method_time_stamp_summary', 'Request summary by request paths, method, timestamp', labels={ 'path': lambda: request.path, 'method': lambda: request.method, 'status': lambda r: r.status_code, 'time_stamp': lambda: time.time() })) return metrics
def create_app(): app = Flask(__name__, instance_relative_config=True) app.config.from_object(Config) app.url_map.converters['oid'] = ObjectIdConverter db.init_app(app) auth.init_app(app) views.init_app(app) metrics = PrometheusMetrics(app) metrics.info('backend_info', 'Backend Information', version='1.0.0') @app.route('/ping') @metrics.do_not_track() def ping(): return 'pong' return app
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) bcrypt.init_app(app) compress.init_app(app) PrometheusMetrics(app) from autochannel.api.routes import mod_api from autochannel.site.routes import mod_site from autochannel.errors.routes import mod_errors app.register_blueprint(mod_api, url_prefix='/api') app.register_blueprint(mod_site) app.register_blueprint(mod_errors) return app
def _setup_metrics(self): metrics = PrometheusMetrics(self.app) metrics.info( "flask_app_info", "Application info", version=os.environ.get("GIT_COMMIT") or "unknown", ) metrics.info("flask_app_built_at", "Application build timestamp").set( float(os.environ.get("BUILD_TIMESTAMP") or "0")) action_summary = Summary( "webhook_proxy_actions", "Action invocation metrics", labelnames=("http_route", "http_method", "action_type", "action_index"), ) return action_summary
def create_app(): """Create Flask App.""" app = Flask(__name__, static_folder="static") # Register blueprints app.register_blueprint(index_blueprint) app.register_blueprint(api) sql_db = os.getenv("SQL_CONNECT", "sqlite://") app.config['SQLALCHEMY_DATABASE_URI'] = sql_db app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Setup Prometheus Metrics metrics = PrometheusMetrics(app) metrics.info('app_info', 'Log Anomaly Detector', version='v0.1.0.beta1') # Initialize db and tables db.init_app(app) with app.app_context(): db.create_all() return app
def create_app(test_config=None): app = Flask(__name__) app.config.from_object("project.config.Config") if test_config is not None: app.config.update(test_config) db.init_app(app) Migrate(app, db) app.register_blueprint(bp_v1) configure_swagger(app) configure_dependencies(app) metrics = PrometheusMetrics(app=app, path='/metrics') config_logging(app) return app
def create_app(): # Construct new Flask core app = Flask(__name__, instance_relative_config=False) # Enable cache app.cache = Cache(app, config={'CACHE_TYPE': 'simple'}) # Enable metrics app.metrics = PrometheusMetrics(app) # Use Configuration object app.config.from_object('config.Config') with app.app_context(): # Import Flask routes from . import routes #Import Dash application from .dash_application import dash_routes app = dash_routes.add_dash(app) return app
def init_flask_metrics(flask_app, export_defaults=True, **kwargs): global flask_metrics, enabled auth_enabled = True try: localconfig = anchore_engine.configuration.localconfig.get_config() metrics_config = localconfig.get("metrics", {}) # Handle typo in config. enabled == enable enabled = bool(metrics_config.get("enable", False)) if not enabled: enabled = bool(metrics_config.get("enabled", False)) auth_enabled = not bool(metrics_config.get("auth_disabled", False)) except Exception as err: logger.warn( "unable to determine if metrics are enabled - exception: " + str(err)) enabled = False if not enabled: flask_metrics = disabled_flask_metrics() return True if not flask_metrics: flask_metrics = PrometheusMetrics(flask_app, export_defaults=export_defaults, group_by_endpoint=True) if auth_enabled: flask_app.before_request(metrics_auth(flask_metrics.path)) flask_metrics.info("anchore_service_info", "Anchore Service Static Information", version=version, **kwargs) return True
def __init__(self,log_level=logging.DEBUG): self.app = Flask(__name__) self.app.logger.setLevel(log_level) self.metrics = PrometheusMetrics(self.app) self.metrics.info('app_info', 'Version info', version=__version__) self.cv = ComputerVision() self.app.register_blueprint(self.cv.blueprint, url_prefix='/v1/') self.app.config['SWAGGER'] = { 'title': 'Corona Medical Monitors Camera Monitoring API', 'uiversion': 3, 'openapi': '3.0.2', 'version': __version__ } self.swagger = Swagger(self.app) @self.app.route('/ping/') def ping() ->str: """ ping --- description: get a pong """ return 'pong'
from flask import Flask, request, jsonify from prometheus_flask_exporter import PrometheusMetrics import mysql.connector import json app = Flask(__name__) app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True metrics = PrometheusMetrics(app) metrics.info('app_info', 'Application info', version='1.0.3') connection = None cursor = None def connect_database(): global connection global cursor connection = mysql.connector.connect(host='database', port='3306', user='******', passwd='1234', database='mydb') cursor = connection.cursor() @app.route('/') def hello_world(): return "hello world"
def metrics(self, **kwargs): registry = kwargs.pop('registry', CollectorRegistry(auto_describe=True)) return PrometheusMetrics(self.app, registry=registry, **kwargs)
if os.path.isfile(full_path): playbook = JsonPlaybookLoader.load_playbook(full_path) if playbook.name not in playbook_name: app.running_context.execution_db.session.add(playbook) app.running_context.execution_db.session.commit() if __name__ == "__main__": args = parse_args() exit_code = 0 walkoff.config.initialize(args.config) compose_api(walkoff.config.Config) app = create_app() if not walkoff.config.Config.SEPARATE_PROMETHEUS: metrics = PrometheusMetrics(app, path='/prometheus_metrics') import_workflows(app) try: run(args, app, *convert_host_port(args)) except KeyboardInterrupt: logger.info( 'Caught KeyboardInterrupt! Please wait a few seconds for WALKOFF to shutdown.' ) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exc() exit_code = 1 finally: app.running_context.executor.shutdown_pool() logger.info('Shutting down server')
from flask import Flask, Response, request from prometheus_client import generate_latest, Gauge, Histogram, Counter, Summary, CONTENT_TYPE_LATEST from prometheus_flask_exporter import PrometheusMetrics import os, time, sys, json, requests VERSION = "0.0.1b" BOTID = 'Robotics' BOTPWD = 'na' OUTPUT_URL = os.environ['REPORT_URL'] app = Flask(__name__) m = PrometheusMetrics(app=app) @app.route('/alert/<string:room>', methods=['POST']) def alert(room): alertinfo = request.json app.logger.debug(alertinfo) c = len(alertinfo['alerts']) app.logger.debug('There are ' + str(c) + ' alerts.') for alert in alertinfo['alerts']: json_data = {} json_data['to'] = room json_data['displayfromname'] = 'AlertManager Bot' json_data['from'] = BOTID json_data['password'] = BOTPWD json_data['type'] = 'meeting' if alert['status'] == "firing": app.logger.info('Firing WARNING Alert to ' + room) app.logger.info('WARNING: ' + alert['annotations']['description'])
tracer_provider.add_span_processor( # BatchSpanProcessor buffers spans and sends them in batches in a # background thread. The default parameters are sensible, but can be # tweaked to optimize your performance BatchSpanProcessor(cloud_trace_exporter)) trace.set_tracer_provider(tracer_provider) tracer = trace.get_tracer(__name__) # flask setup app = Flask(__name__) FlaskInstrumentor().instrument_app(app) RequestsInstrumentor().instrument() # enable tracing for Requests app.config['JSON_AS_ASCII'] = False # otherwise our emojis get hosed CORS(app) # enable CORS metrics = PrometheusMetrics(app) # enable Prom metrics # gRPC setup grpc_serving_port = 9090 grpc_metrics_port = 8080 # prometheus /metrics, same as flask port # define Whereami object whereami_payload = whereami_payload.WhereamiPayload() # create gRPC class class WhereamigRPC(whereami_pb2_grpc.WhereamiServicer): def GetPayload(self, request, context): payload = whereami_payload.build_payload(None) return whereami_pb2.WhereamiReply(**payload)
from flask import Flask, jsonify, request from redis import Redis from flask_limiter import Limiter from flask_limiter.util import get_remote_address from prometheus_flask_exporter import PrometheusMetrics import os import sys app = Flask(__name__) for variable, value in os.environ.items(): if variable.startswith("RATE_LIMIT"): app.config[variable] = value metrics = PrometheusMetrics(app, group_by='endpoint') limiter = Limiter(app, key_func=get_remote_address, default_limits=["1/minute"]) redis = Redis(host='redis', port=6379) @app.route('/') @limiter.limit(app.config["RATE_LIMIT"]) @metrics.counter('client_requests', 'client requests by status code and address', labels={ 'status': lambda resp: resp.status_code, 'address': lambda: request.environ['REMOTE_ADDR'] }) def helloIndex():
from flask import Flask from prometheus_flask_exporter import PrometheusMetrics app = Flask(__name__) metrics = PrometheusMetrics(app=None, path='/metrics') app.debug = True @app.route("/", methods=['GET']) def index(): return "hello world" if __name__ == '__main__': metrics.init_app(app) app.run(host='0.0.0.0', port=80)
app.add_api( "openapi.yaml", options={"swagger_ui": True}, arguments={"title": "User API"}, resolver=RestyResolver(default_module_name="thoth.user_api.api_v1"), strict_validation=True, validate_responses=False, ) application = app.app # create tracer and put it in the application configuration Configuration.tracer = init_jaeger_tracer("user_api") # create metrics and manager metrics = PrometheusMetrics(application, group_by="endpoint") manager = Manager(application) # Needed for session. application.secret_key = Configuration.APP_SECRET_KEY # static information as metric metrics.info("user_api_info", "User API info", version=__version__) _API_GAUGE_METRIC = metrics.info("user_api_schema_up2date", "User API schema up2date") @application.before_request def before_request_callback(): """Callback registered, runs before each request to this service.""" method = request.method
from prometheus_flask_exporter import PrometheusMetrics import base64 import copy import datetime import json import logging import os import re import requests import sys import time app = Flask(__name__) # Setup Prometheus Metrics for Flask app metrics = PrometheusMetrics(app, defaults_prefix="magtape") # Static information as metric metrics.info("app_info", "Application info", version="v2.3.3") # Set logging config log = logging.getLogger("werkzeug") log.disabled = True magtape_log_level = os.environ["MAGTAPE_LOG_LEVEL"] app.logger.setLevel(magtape_log_level) # Set Global variables cluster = os.environ["MAGTAPE_CLUSTER_NAME"] magtape_namespace_name = os.environ["MAGTAPE_NAMESPACE_NAME"] magtape_pod_name = os.environ["MAGTAPE_POD_NAME"]
def create_app(runtime_environment): connexion_options = {"swagger_ui": True} # This feels like a hack but it is needed. The logging configuration # needs to be setup before the flask app is initialized. configure_logging() app_config = Config(runtime_environment) app_config.log_configuration() connexion_app = connexion.App("inventory", specification_dir="./swagger/", options=connexion_options) # Read the swagger.yml file to configure the endpoints parser = ResolvingParser(SPECIFICATION_FILE, resolve_types=RESOLVE_FILES) parser.parse() for api_url in app_config.api_urls: if api_url: connexion_app.add_api( parser.specification, arguments={"title": "RestyResolver Example"}, resolver=RestyResolver("api"), validate_responses=True, strict_validation=True, base_path=api_url, ) logger.info("Listening on API: %s", api_url) # Add an error handler that will convert our top level exceptions # into error responses connexion_app.add_error_handler(InventoryException, render_exception) flask_app = connexion_app.app flask_app.config["SQLALCHEMY_ECHO"] = False flask_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False flask_app.config["SQLALCHEMY_DATABASE_URI"] = app_config.db_uri flask_app.config["SQLALCHEMY_POOL_SIZE"] = app_config.db_pool_size flask_app.config["SQLALCHEMY_POOL_TIMEOUT"] = app_config.db_pool_timeout flask_app.config["INVENTORY_CONFIG"] = app_config db.init_app(flask_app) register_shutdown(db.get_engine(flask_app).dispose, "Closing database") flask_app.register_blueprint(monitoring_blueprint, url_prefix=app_config.mgmt_url_path_prefix) @flask_app.before_request def set_request_id(): threadctx.request_id = request.headers.get(REQUEST_ID_HEADER, UNKNOWN_REQUEST_ID_VALUE) if runtime_environment.event_producer_enabled: flask_app.event_producer = EventProducer(app_config) register_shutdown(flask_app.event_producer.close, "Closing EventProducer") else: logger.warning( "WARNING: The event producer has been disabled. " "The message queue based event notifications have been disabled.") payload_tracker_producer = None if not runtime_environment.payload_tracker_enabled: # If we are running in "testing" mode, then inject the NullProducer. payload_tracker_producer = payload_tracker.NullProducer() logger.warning( "WARNING: Using the NullProducer for the payload tracker producer. " "No payload tracker events will be sent to to payload tracker.") payload_tracker.init_payload_tracker(app_config, producer=payload_tracker_producer) # HTTP request metrics if runtime_environment.metrics_endpoint_enabled: PrometheusMetrics( flask_app, defaults_prefix="inventory", group_by="url_rule", path=None, excluded_paths=[ "^/metrics$", "^/health$", "^/version$", r"^/favicon\.ico$" ], ) # initialize metrics to zero initialize_metrics(app_config) return flask_app
def create_app(config_name, start_tasks=False, start_payload_tracker=False): connexion_options = {"swagger_ui": True} # This feels like a hack but it is needed. The logging configuration # needs to be setup before the flask app is initialized. configure_logging(config_name) app_config = Config(RuntimeEnvironment.server) app_config.log_configuration(config_name) connexion_app = connexion.App("inventory", specification_dir="./swagger/", options=connexion_options) # Read the swagger.yml file to configure the endpoints with open("swagger/api.spec.yaml", "rb") as fp: spec = yaml.safe_load(fp) for api_url in app_config.api_urls: if api_url: connexion_app.add_api( spec, arguments={"title": "RestyResolver Example"}, resolver=RestyResolver("api"), validate_responses=True, strict_validation=True, base_path=api_url, ) logger.info("Listening on API: %s", api_url) # Add an error handler that will convert our top level exceptions # into error responses connexion_app.add_error_handler(InventoryException, render_exception) flask_app = connexion_app.app flask_app.config["SQLALCHEMY_ECHO"] = False flask_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False flask_app.config["SQLALCHEMY_DATABASE_URI"] = app_config.db_uri flask_app.config["SQLALCHEMY_POOL_SIZE"] = app_config.db_pool_size flask_app.config["SQLALCHEMY_POOL_TIMEOUT"] = app_config.db_pool_timeout flask_app.config["INVENTORY_CONFIG"] = app_config db.init_app(flask_app) flask_app.register_blueprint(monitoring_blueprint, url_prefix=app_config.mgmt_url_path_prefix) @flask_app.before_request def set_request_id(): threadctx.request_id = request.headers.get(REQUEST_ID_HEADER, UNKNOWN_REQUEST_ID_VALUE) if start_tasks: init_tasks(app_config, flask_app) else: logger.warning( 'WARNING: The "tasks" subsystem has been disabled. ' "The message queue based system_profile consumer " "and message queue based event notifications have been disabled." ) payload_tracker_producer = None if start_payload_tracker is False: # If we are running in "testing" mode, then inject the NullProducer. payload_tracker_producer = payload_tracker.NullProducer() logger.warning( "WARNING: Using the NullProducer for the payload tracker producer. " "No payload tracker events will be sent to to payload tracker." ) payload_tracker.init_payload_tracker(app_config, producer=payload_tracker_producer) # HTTP request metrics if config_name != "testing": PrometheusMetrics( flask_app, defaults_prefix="inventory", group_by="url_rule", path=None, excluded_paths=["^/metrics$", "^/health$", "^/version$", r"^/favicon\.ico$"], ) return flask_app
from prometheus_flask_exporter import PrometheusMetrics def _env_config(var: str, default: str) -> str: if filename := environ.get(var): with open(filename) as file: return file.read() return default APP = Flask(__name__) MONGO_CLIENT = MongoClient(_env_config("MONGO_URL_FILE", "mongo")) BLABS = MONGO_CLIENT.blabber.blabs METRICS = PrometheusMetrics(APP) @APP.route("/api/blabs", methods=["GET"]) def get_blabs(): """Get all blabs created since the specified timestamp.""" since = int(request.args.get("createdSince", 0)) blabs = list(BLABS.find({"postTime": {"$gte": since}})) for blab in blabs: blab["id"] = str(blab.pop("_id")) return jsonify(blabs)
from flask import Flask from flask_restplus import Api from prometheus_flask_exporter import PrometheusMetrics metrics = PrometheusMetrics(app=None) def create_app(): from users_backend.api_namespace import api_namespace from users_backend.admin_namespace import admin_namespace application = Flask(__name__) # Initialise metrics metrics.init_app(application) api = Api(application, version='0.1', title='Users Backend API', description='A Simple CRUD API') from users_backend.db import db, db_config application.config['RESTPLUS_MASK_SWAGGER'] = False application.config.update(db_config) db.init_app(application) application.db = db api.add_namespace(api_namespace) api.add_namespace(admin_namespace) return application
import jsonpatch import logging import os import re app = Flask(__name__) # Set Global variables imageswap_namespace_name = os.getenv("IMAGESWAP_NAMESPACE_NAME", "imageswap-system") imageswap_pod_name = os.getenv("IMAGESWAP_POD_NAME") imageswap_disable_label = os.getenv("IMAGESWAP_DISABLE_LABEL", "k8s.twr.io/imageswap") # Setup Prometheus Metrics for Flask app metrics = PrometheusMetrics(app, defaults_prefix="imageswap") # Static information as metric metrics.info("app_info", "Application info", version="v1.2.0") # Set logging config log = logging.getLogger("werkzeug") log.disabled = True imageswap_log_level = os.getenv("IMAGESWAP_LOG_LEVEL", "INFO") app.logger.setLevel(imageswap_log_level) ################################################################################ ################################################################################ ################################################################################
from app.services import * from app.custom_log import CustomLog from app.helpers import get_service_version import os from prometheus_flask_exporter import PrometheusMetrics from .services.monit import support_namespace from app.services.v1 import v1_namespace config_name = os.environ.get('ENVIRONMENT') log = CustomLog(get_service_version(), service_name=os.environ.get('SERVICE_NAME')) flask_app = Flask(__name__) flask_app.config.from_object(config[config_name]) flask_app.config['RESTPLUS_VALIDATE'] = True flask_app.config['ERROR_404_HELP'] = False metrics = PrometheusMetrics(flask_app) mongodb = PyMongo(flask_app) flask_app.config.SWAGGER_SUPPORTED_SUBMIT_METHODS = ['get', 'post'] service_api = Api(app=flask_app, doc="/docs", version=get_service_version(), title="Filmes", description="Cadastro de Filmes <style>.models {display: none !important}</style>", validate=True, catch_all_404s=False) service_api.add_namespace(support_namespace.support_namespace, path="/monit") service_api.add_namespace(v1_namespace.v1_namespace, path="/api/v1")
arguments={"title": "User API"}, resolver=RestyResolver(default_module_name="thoth.user_api.api_v1"), strict_validation=True, validate_responses=False, ) application = app.app # create tracer and put it in the application configuration Configuration.tracer = init_jaeger_tracer("user_api") # create metrics and manager metrics = PrometheusMetrics(application, group_by="endpoint", excluded_paths=[ "/liveness", "/readiness", "/api/v1/ui", "/api/v1/openapi", ]) manager = Manager(application) # Needed for session. application.secret_key = Configuration.APP_SECRET_KEY # static information as metric metrics.info("user_api_info", "User API info", version=__service_version__) _API_GAUGE_METRIC = metrics.info("user_api_schema_up2date", "User API schema up2date") class _GraphDatabaseWrapper:
from . import __version__ from .configuration import Configuration # Configure global application logging using Thoth's init_logging. init_logging(logging_env_var_start="AMUN_LOG_") _LOGGER = logging.getLogger("amun") _LOGGER.setLevel( logging.DEBUG if bool(int(os.getenv("AMUN_DEBUG", 0))) else logging.INFO) # Expose for uWSGI. app = connexion.App(__name__) application = app.app app.add_api(Configuration.SWAGGER_YAML_PATH) metrics = PrometheusMetrics(application) manager = Manager(application) # Needed for session. application.secret_key = Configuration.APP_SECRET_KEY # static information as metric metrics.info("amun_api_info", "Amun API info", version=__version__) @app.route("/") @metrics.do_not_track() def base_url(): """Redirect to UI by default.""" return redirect("api/v1/ui")