Example #1
0
    def test_trace_all_requests(self):
        app = Flask('dummy_app')
        tracing = FlaskTracing(app=app)
        assert tracing._trace_all_requests is True

        tracing = FlaskTracing(app=app, trace_all_requests=False)
        assert tracing._trace_all_requests is False
Example #2
0
def create_app(run_mode=os.getenv('FLASK_ENV', 'production')):
    """Return a configured Flask App using the Factory method."""
    app = Flask(__name__)
    app.config.from_object(config.CONFIGURATION[run_mode])

    # start tracer
    tracer = init_tracer(__name__)
    FlaskTracing(tracer)

    from auth_api import models
    from auth_api.resources import API_BLUEPRINT, OPS_BLUEPRINT

    db.init_app(app)
    ma.init_app(app)

    app.register_blueprint(API_BLUEPRINT)
    app.register_blueprint(OPS_BLUEPRINT)

    setup_jwt_manager(app, jwt)

    @app.after_request
    def add_version(response):  # pylint: disable=unused-variable
        version = get_run_version()
        response.headers['API'] = f'auth_api/{version}'
        return response

    register_shellcontext(app)

    return app
Example #3
0
def init_tracer():
    if (jaeger_logging):
        app.logger.info("Report log on {}:{} with app name {}".format(
            jaeger_host, jaeger_port, jaeger_service_name))
    else:
        app.logger.info("Jaeger is not activated")

    config = Config(
        config={  # usually read from some yaml config
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'local_agent': {
                'reporting_host': jaeger_host,
                'reporting_port': jaeger_port,
            },
            'logging': jaeger_logging,
            'propagation': 'b3'
        },
        service_name=jaeger_service_name,
        validate=True)

    opentracing_tracer = config.initialize_tracer()
    tracing = FlaskTracing(opentracing_tracer, True, app)
    return opentracing_tracer
Example #4
0
def create_tracer(service_name,
                  flask_app,
                  jaeger_host="localhost",
                  sample_type="const",
                  sample_param=1):
    """Create global flask trace instance
    :param service_name: current service name
    :param flask_app: flask app instance
    :param jaeger_host: jaeger agent host, default localhost
    :param sample_type: work with sample param
           reference: https://www.jaegertracing.io/docs/1.15/sampling/
    :param sample_param:
    :return:
    """
    config = Config(config={
        'sampler': {
            'type': sample_type,
            'param': sample_param
        },
        'local_agent': {
            'reporting_host': jaeger_host
        }
    },
                    service_name=service_name,
                    validate=True)
    jaeger_tracer = config.initialize_tracer()
    tracer = FlaskTracing(jaeger_tracer, True, flask_app)
    logging.info("Create trace {} on flask_app {} as service_name {}".format(
        tracer, flask_app, service_name))
    return tracer
Example #5
0
def load(env):
    # Flag parsing with wsgi runners is a major pain
    # We identify a flag break '--' and consume only flags after it
    if env != 'dev':
        if '--' in sys.argv:
            separator = sys.argv.index('--')
            args = sys.argv[separator:]
            logging.debug(
                'Prod mode, loading args the hard way: {args}'.format(
                    args=args))
        else:
            args = sys.argv
        FLAGS(args)
    else:
        FLAGS(sys.argv)

    # Init sentry as early as possible to catch as much as possible
    if FLAGS.sentry:
        sentry_sdk.init(dsn=FLAGS.sentry,
                        integrations=[FlaskIntegration()],
                        environment=env,
                        release=__version__)

    app = Flask(__name__)
    app.config.from_object('websiteconfig')

    # gRPC channel init
    global channels
    kwargs = {}
    if FLAGS.consul:
        kwargs['consul'] = True
    if FLAGS.jaeger:
        tracer = init_tracer()
        kwargs['tracer'] = tracer
        flask_tracer = FlaskTracing(tracer, True, app)
        logging.info('Flask tracing enabled')
    channels = Channels(**kwargs)
    channels.refresh_all()

    lm.init_app(app)
    mail.init_app(app)
    bcrypt.init_app(app)
    flask_static_digest.init_app(app)

    from app import user, maintenance, asset, pwa
    app.register_blueprint(user.bp)
    app.register_blueprint(maintenance.bp)
    app.register_blueprint(asset.bp)
    app.register_blueprint(pwa.bp)

    @app.route('/')
    def root():
        return render_template('index.html')

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory('static', 'img/icons/favicon.ico')

    return app
Example #6
0
 def init_tracer(self) -> None:
     """Set attribute in flask `tracer`. See in `pyms.flask.services.tracer` how it works
     :return: None
     """
     if self._exists_service("tracer"):
         client = self.tracer.get_client()
         self.application.tracer = FlaskTracing(client, True,
                                                self.application)
Example #7
0
def init():
    config = Config(service_name='test',
                    config={
                        'trace_id_header': 'Trace_ID',
                        'baggage_header_prefix': 'Trace-Attr-',
                    })
    reporter = InMemoryReporter()
    tracer = config.create_tracer(
        reporter=reporter,
        sampler=ConstSampler(True),
    )
    tracing = FlaskTracing(tracer, True, app)
            def rest_prediction_server():
                app = seldon_microservice.get_rest_microservice(user_object)
                try:
                    user_object.load()
                except (NotImplementedError, AttributeError):
                    pass
                if args.tracing:
                    logger.info("Tracing branch is active")
                    from flask_opentracing import FlaskTracing

                    logger.info("Set JAEGER_EXTRA_TAGS %s", jaeger_extra_tags)
                    tracing = FlaskTracing(tracer, True, app, jaeger_extra_tags)

                app.run(host="0.0.0.0", port=port)
    def test_error(self):
        def start_span_cb(span, request):
            raise RuntimeError('Should not happen')

        tracing = FlaskTracing(MockTracer(),
                               True,
                               app,
                               start_span_cb=start_span_cb)
        rv = test_app.get('/test')
        assert '200' in str(rv.status_code)

        spans = tracing.tracer.finished_spans()
        assert len(spans) == 1
        assert spans[0].tags.get(tags.ERROR, None) is None
    def test_simple(self):
        def start_span_cb(span, request):
            span.set_tag('component', 'not-flask')
            span.set_tag('mytag', 'myvalue')

        tracing = FlaskTracing(MockTracer(),
                               True,
                               app,
                               start_span_cb=start_span_cb)
        rv = test_app.get('/test')
        assert '200' in str(rv.status_code)

        spans = tracing.tracer.finished_spans()
        assert len(spans) == 1
        assert spans[0].tags.get(tags.COMPONENT, None) == 'not-flask'
        assert spans[0].tags.get('mytag', None) == 'myvalue'
Example #11
0
    def load(self):
        if self.jaeger_extra_tags is not None:
            logger.info("Tracing branch is active")
            from flask_opentracing import FlaskTracing

            tracer = setup_tracing(self.interface_name)

            logger.info("Set JAEGER_EXTRA_TAGS %s", self.jaeger_extra_tags)
            FlaskTracing(tracer, True, self.application, self.jaeger_extra_tags)
        logger.debug("LOADING APP %d", os.getpid())
        try:
            logger.debug("Calling user load method")
            self.user_object.load()
        except (NotImplementedError, AttributeError):
            logger.debug("No load method in user model")
        return self.application
Example #12
0
        def rest_prediction_server():
            app = seldon_microservice.get_rest_microservice(user_object, seldon_metrics)
            try:
                user_object.load()
            except (NotImplementedError, AttributeError):
                pass
            if args.tracing:
                logger.info("Tracing branch is active")
                from flask_opentracing import FlaskTracing

                tracer = setup_tracing(args.interface_name)

                logger.info("Set JAEGER_EXTRA_TAGS %s", jaeger_extra_tags)
                FlaskTracing(tracer, True, app, jaeger_extra_tags)

            app.run(
                host="0.0.0.0",
                port=http_port,
                threaded=False if args.single_threaded else True,
            )
Example #13
0
import traceback
from flask import request
from flask_restplus import Resource, Namespace
from auth_api.services.keycloak import KeycloakService
import opentracing
from flask_opentracing import FlaskTracing
from ..utils.trace_tags import TraceTags as tags
from auth_api.utils.util import cors_preflight


API = Namespace('user', description='Keycloak Admin - user')
KEYCLOAK_SERVICE = KeycloakService()

tracer = opentracing.tracer
tracing = FlaskTracing(tracer)


@cors_preflight('GET, POST, DELETE, OPTIONS')
@API.route('', methods=['GET', 'POST', 'DELETE', 'OPTIONS'])
class User(Resource):
    """End point resource to manage users."""

    @staticmethod
    @tracing.trace()
    def post():
        """Add user, return a new/existing user."""

        current_span = tracer.active_span
        data = request.get_json()
        if not data:
Example #14
0
application = Flask(__name__)

config = Config(config={
    'sampler': {
        'type': 'const',
        'param': 1
    },
    'logging': True,
    'local_agent': {
        'reporting_host': getenv('JAEGER_HOST', 'localhost')
    }
},
                service_name=getenv('JAEGER_SERVICE_NAME', __name__))
jaeger_tracer = config.initialize_tracer()
tracing = FlaskTracing(jaeger_tracer, True, application, [])

api = swagger.docs(Api(application),
                   apiVersion='0.1',
                   basePath='http://*****:*****@application.route("/")
def index():
    return render_template('index.html', title='Home')

Example #15
0
                'type': 'const',
                'param': 1,
            },
            'local_agent': {
                'reporting_host': 'jaeger',
                # 'reporting_port': 'your-reporting-port',
            },
            'logging': True,
        },
        service_name=service_name,
        validate=True
    )
    return config.initialize_tracer()


tracer = FlaskTracing(init_jaeger_tracer, True, app)


@api_usuarios.route("/")
class UserList(Resource):
    @api_usuarios.expect(UserModel.model, validate=True)
    def post(self):
        payload = json.loads(request.data)

        with opentracing.tracer.start_span('Adicionando o Usuario') as span:
            span.set_tag("add_user.request_data", payload)

            custom_erros = validate_payload(payload)
            if custom_erros:
                with opentracing.tracer.start_span(
                        'Dados de Telefone Invalido',
Example #16
0
    def __init__(
        self,
        pathfinding_service: PathfindingService,
        one_to_n_address: Address,
        operator: str,
        info_message: str = DEFAULT_INFO_MESSAGE,
        service_fee: TokenAmount = TokenAmount(0),
        debug_mode: bool = False,
        enable_tracing: bool = False,
    ) -> None:
        flask_app = Flask(__name__)

        if enable_tracing:
            FlaskTracing(opentracing.tracer, trace_all_requests=True, app=flask_app)

        self.flask_app = DispatcherMiddleware(
            NotFound(),
            {
                "/metrics": make_wsgi_app(registry=metrics.REGISTRY),
                API_PATH: flask_app.wsgi_app,
            },
        )

        self.api = ApiWithErrorHandler(flask_app)
        self.rest_server: Optional[WSGIServer] = None
        self.one_to_n_address = one_to_n_address
        self.pathfinding_service = pathfinding_service
        self.service_fee = service_fee
        self.operator = operator
        self.info_message = info_message

        # Enable cross origin requests
        @flask_app.after_request
        def after_request(response: Response) -> Response:  # pylint: disable=unused-variable
            response.headers.add("Access-Control-Allow-Origin", "*")
            response.headers.add("Access-Control-Allow-Headers", "Origin, Content-Type, Accept")
            response.headers.add("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
            return response

        resources: List[Tuple[str, Resource, Dict, str]] = [
            (
                "/v1/<token_network_address>/paths",
                PathsResource,
                dict(debug_mode=debug_mode),
                "paths",
            ),
            ("/v1/<token_network_address>/payment/iou", IOUResource, {}, "payments"),
            ("/v1/<token_network_address>/feedback", FeedbackResource, {}, "feedback"),
            (
                "/v1/<token_network_address>/suggest_partner",
                SuggestPartnerResource,
                {},
                "suggest_partner",
            ),
            ("/v1/online_addresses", OnlineAddressesResource, {}, "online_addresses"),
            ("/v1/info", InfoResource, {}, "info"),
            ("/v2/info", InfoResource2, {}, "info2"),
            (
                "/v1/address/<checksummed_address>/metadata",
                AddressMetadataResource,
                {},
                "address_metadata",
            ),
        ]

        if debug_mode:
            log.warning("The debug REST API is enabled. Don't do this on public nodes.")
            resources.extend(
                [
                    (
                        "/v1/_debug/routes/<token_network_address>/<source_address>",
                        cast(Resource, DebugPathResource),
                        {},
                        "debug1",
                    ),
                    (
                        "/v1/_debug/routes/<token_network_address>/<source_address>/<target_address>",  # noqa
                        DebugPathResource,
                        {},
                        "debug2",
                    ),
                    ("/v1/_debug/ious/<source_address>", DebugIOUResource, {}, "debug3"),
                    ("/v1/_debug/stats", DebugStatsResource, {}, "debug4"),
                ]
            )

        for endpoint_url, resource, kwargs, endpoint in resources:
            kwargs.update({"pathfinding_service": pathfinding_service, "api": self})
            self.api.add_resource(
                resource, endpoint_url, resource_class_kwargs=kwargs, endpoint=f"rest-{endpoint}"
            )
})

upload_parser = api.parser()
upload_parser.add_argument('file', location='files',
                           type=FileStorage, required=True)

# Create configuration object with enabled logging and sampling of all requests.
config = Config(config={'sampler': {'type': 'const', 'param': 1},
                        'logging': True,
                        'local_agent':
                        # Also, provide a hostname of Jaeger instance to send traces to.
                            {'reporting_host': app.config['JAEGER_HOST']}},
                # Service name can be arbitrary string describing this particular web service.
                service_name=app.config['APP_NAME'])
jaeger_tracer = config.initialize_tracer()
tracing = FlaskTracing(tracer=jaeger_tracer, app=app)


createPermissions = lambda f: admin_required(f, roles=['ROLE_ADMIN', 'ROLE_PRODUCTS_CREATE', 'SCOPE_openid'])


ALLOWED_EXTENSIONS = app.config['ALLOWED_EXTENSIONS']


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@traced(log)
@logged(log)
Example #18
0
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Endpoints to check and manage payments."""
import opentracing
from flask_opentracing import FlaskTracing
from flask_restplus import Namespace, Resource

API = Namespace('payments', description='Service - Payments')

TRACER = opentracing.tracer
TRACING = FlaskTracing(TRACER)


@API.route('')
class Payment(Resource):
    """Payment endpoint resource."""
    @staticmethod
    @TRACING.trace()
    def get():
        """Get payment."""
        return {'message': 'pay'}, 200
Example #19
0
    },
    "local_agent": {
        "reporting_host": "jaeger-agent",
        "reporting_port": 5775,
    },
    "logging": True,
}

config = jConfig(
    config=tracer_config,
    service_name=f"RDSWebConnexionPlus",
    metrics_factory=PrometheusMetricsFactory(namespace=f"RDSWebConnexionPlus"),
)

tracer_obj = config.initialize_tracer()
tracing = FlaskTracing(tracer_obj, True, app)
install_all_patches()

# add a TracingHandler for Logging
gunicorn_logger = logging.getLogger("gunicorn.error")
app.logger.handlers.extend(gunicorn_logger.handlers)
app.logger.addHandler(TracingHandler(tracer_obj))
app.logger.setLevel(gunicorn_logger.level)
### Tracing end ###

app.config.update(flask_config)

try:
    from prometheus_flask_exporter.multiprocess import GunicornPrometheusMetrics
    metrics = GunicornPrometheusMetrics(app)
except Exception as e:
import mock
import unittest

from flask import (Flask, request)
import opentracing
from opentracing.ext import tags
from opentracing.mocktracer import MockTracer
from flask_opentracing import FlaskTracing

app = Flask(__name__)
test_app = app.test_client()

tracing_all = FlaskTracing(MockTracer(), True, app, ['url'])
tracing = FlaskTracing(MockTracer())
tracing_deferred = FlaskTracing(lambda: MockTracer(), True, app, ['url'])


def flush_spans(tcr):
    for req in tcr._current_scopes:
        tcr._current_scopes[req].close()
    tcr._current_scopes = {}


@app.route('/test')
def check_test_works():
    return 'Success'


@app.route('/another_test')
@tracing.trace('url', 'url_rule')
def decorated_fn():
Example #21
0
host_ip = get_ip()

if __name__ == '__main__':
    debugmode = os.getenv('DEBUG_MODE', False)

    log_level = logging.DEBUG
    logging.getLogger('').handlers = []
    logging.basicConfig(format='%(asctime)s %(message)s', level=log_level)

    # Create configuration object with enabled logging and sampling of all requests.
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1
            },
            'logging': True,
            'local_agent':
            # Also, provide a hostname of Jaeger instance to send traces to.
            {
                'reporting_host': jaeger_host
            }
        },
        # Service name can be arbitrary string describing this particular web service.
        service_name="markf_vmworld_frontend")
    jaeger_tracer = config.initialize_tracer()
    tracing = FlaskTracing(jaeger_tracer, trace_all_requests=True, app=app)
    install_all_patches()

    app.run(host='0.0.0.0', debug=bool(debugmode), port=int(port))
Example #22
0
    def __init__(
        self,
        name,
        use_tracer=None,
        use_metric=False,
        use_logging_level=logging.DEBUG,
        use_optimizer=None,
        use_cors=None,
        use_default_error=None,
        use_scheduler=None,
        all=None,
        flaskName=None,
        *args,
        **kwargs,
    ):
        # TODO: Add more text here for current situation
        """
        Initialize Flask App with multiple microservice-related and usability features.

        None is for deactivating, so it equals to False.

        *use_tracer* must be of type: bool (True for defaults, False for deactivating), 
        opentracing.Tracer (use it for configuration), dict (use default opentracing.Tracer and the given dict as config) or defaults: None

        *use_metric* must be of type: bool (True for defaults, False for deactivating) or defaults: None

        *use_logging_level* must be of type: logging.{INFO, WARNING, ERROR, DEBUG}, defaults: DEBUG
        *use_optimizer* must be of type: bool (True for defaults, False for deactivating) or defaults: None
        *use_cors* must be of type: bool (True for defaults, False for deactivating) or defaults: None
        *use_default_error* must be of type: bool (True for defaults, False for deactivating) or defaults: None
        *use_scheduler* must be of type: bool (True for defaults, False for deactivating) or defaults: None
        *all* must be of type: bool (True for use all functions with defaults, False for deactivating all functions) or defaults: None
        """
        if flaskName is None:
            flaskName = __name__

        super().__init__(flaskName, *args, **kwargs)
        logger = logging.getLogger("")

        self.name = name
        self.metrics = None
        self.tracing = None
        self.optimize = None
        self.cors = None
        self.default_errorhandler = None
        self.scheduler = None

        if all is not None and all is not False:
            use_tracer = True
            use_metric = True
            use_optimizer = True
            use_cors = True
            use_default_error = True
            use_scheduler = True

        logger.info("--- Start Connexion-Plus ---")

        if not isinstance(self.app, (Flask, FlaskApp)):
            logger.warning(
                "Given App is not flask, so it cannot get any functionality added from this lib currently."
            )
            return

        # add default error
        if use_default_error is not None and use_default_error is not False:
            from werkzeug.exceptions import HTTPException
            from werkzeug.exceptions import default_exceptions

            logger.info("Add default error handler to Flask...")

            if callable(use_default_error):
                self.default_errorhandler = use_default_error

                logger.info("use given handler.")

            else:

                def handle_error(e):
                    code = 500
                    if isinstance(e, HTTPException):
                        code = e.code

                    error = {
                        "error": e.__class__.__name__,
                        "http_code": code,
                        "description": str(e),
                    }
                    logger.exception(error)
                    return jsonify(error), code

                self.default_errorhandler = handle_error

                logger.info("use default one")

            # register for all json exceptions
            self.app.register_error_handler(Exception,
                                            self.default_errorhandler)

            # register handler for all http exceptions
            for ex in default_exceptions:
                self.app.register_error_handler(ex, self.default_errorhandler)

        if use_scheduler is not None and use_scheduler is not False:
            logger.info("Add background scheduler to Flask")
            from flask_apscheduler import APScheduler

            self.scheduler = APScheduler()
            self.scheduler.init_app(self.app)
            self.scheduler.start()

        # add optimizer
        if use_optimizer is not None and use_optimizer is not False:
            logger.info("Add optimizer to Flask...")
            from .Optimizer import FlaskOptimize

            config = {"compress": False, "minify": False}
            if isinstance(use_optimizer, dict):
                config.update(use_optimizer)

            if isinstance(use_optimizer, bool) and use_optimizer:
                config.update({"compress": True, "minify": True})

            logger.info("use config {}.".format(config))

            self.optimize = FlaskOptimize(self.app, config)

        # add CORS
        if use_cors is not None and use_cors is not False:
            logger.info("Add cors to Flask...")
            from flask_cors import CORS

            if isinstance(use_cors, dict):
                logger.info("use given settings.")
                self.cors = CORS(self.app, resources=use_cors)
            else:
                logger.info("use default ones.")
                self.cors = CORS(self.app)

            logger.info("CORS added.")

        # add prometheus
        if use_metric is not None and use_metric is not False:
            # TODO: add configuration https://github.com/rycus86/prometheus_flask_exporter#configuration

            from prometheus_flask_exporter import PrometheusMetrics

            self.metrics = PrometheusMetrics(self.app)
            logger.info("Add prometheus to Flask")

        # add tracing
        if use_tracer is not None and use_tracer is not False:
            logger.info("Add opentracing to Flask...")
            # add tracing to all routes in flaskApp
            from flask_opentracing import FlaskTracing
            import opentracing
            from functools import wraps
            from flask import request

            def wrapper(fn):
                @wraps(fn)
                def request_func(*args, **kwargs):
                    if request.path != "/metrics":
                        return fn(*args, **kwargs)

                return request_func

            FlaskTracing._before_request_fn = wrapper(
                FlaskTracing._before_request_fn)
            FlaskTracing._after_request_fn = wrapper(
                FlaskTracing._after_request_fn)

            config = None
            if not isinstance(use_tracer, opentracing.Tracer):
                logger.info("use default one.")
                from jaeger_client import Config as jConfig

                tracer_config = {
                    "sampler": {
                        "type": "const",
                        "param": 1,
                    },
                    "local_agent": {
                        "reporting_host": "jaeger-agent",
                        "reporting_port": 5775,
                    },
                    "logging": True,
                }

                if isinstance(use_tracer, dict):
                    tracer_config = use_tracer

                if isinstance(use_metric, bool) and use_metric is True:
                    logger.info("Use metrics for tracer.")
                    from jaeger_client.metrics.prometheus import (
                        PrometheusMetricsFactory, )

                    config = jConfig(
                        config=tracer_config,
                        service_name=f"{name}ConnexionPlus",
                        metrics_factory=PrometheusMetricsFactory(
                            namespace=f"{name}ConnexionPlus"),
                    )
                else:
                    logger.info("no metrics for tracer configured.")
                    config = jConfig(
                        config=tracer_config,
                        service_name=f"{name}ConnexionPlus",
                    )
            else:
                logger.info("use given tracer config.")

            tracer_obj = use_tracer if config is None else config.initialize_tracer(
            )
            self.tracing = FlaskTracing(tracer_obj, True, self.app)

            # add tracer to everything to support spans through multiple microservices via rpc-calls
            from opentracing_instrumentation.client_hooks import install_all_patches

            install_all_patches()
            logger.info("All tracing relevant libs patched.")

            # add a TracingHandler for Logging
            from .TracingHandler import TracingHandler

            th = TracingHandler(use_tracer)
            th.setLevel(use_logging_level)

            logging.getLogger("").addHandler(th)
            logger.info("Finished Tracer adding.")

        logger.info("--- Finished Connexion-Plus ---")
Example #23
0
import schedule
import time
import threading
from flask import Flask, request
from flask_cors import CORS
from api_management.jaeger import initializejaeger
from flask_opentracing import FlaskTracing
import implementation as implementation

app = Flask(__name__)
CORS(app)

jaeger_tracer = initializejaeger()
tracing = FlaskTracing(jaeger_tracer)


@app.route('/notificationscheduler/')
@tracing.trace()
def test_thread():
    with jaeger_tracer.start_active_span(
            'Notification-scheduler-API endpoint /notificationscheduler/') as scope:
        scope.span.log_kv({'event': 'Calling endpoint /notificationscheduler/', 'request_method': request.method})
        return implementation.getUsersWithFlowers()


def job():
    with app.app_context():
        implementation.getUsersWithFlowers()


sched = schedule
Example #24
0
import jaeger_client
from flask import Flask


def initialize_tracer():
    log_level = logging.DEBUG
    logging.getLogger('').handlers = []
    logging.basicConfig(format='%(asctime)s %(message)s', level=log_level)
    config = jaeger_client.Config(
        config={ # usually read from some yaml config
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
        },
        service_name='flask-tracing-app',
        validate=True,
    )
    # return config.initialize_tracer(io_loop=ioloop.IOLoop.current())
    return config.initialize_tracer()


app = Flask(__name__)
tracing = FlaskTracing(initialize_tracer, True, app)


@app.route('/')
def hello():
    return f'Hello, world!\n'
Example #25
0
import registrator

from JaegerInjectAPI import TestInject

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})

# Connection to models
JaegerInjectAPI_Provider = TestInject()

# Distributed Tracing
import jaegerTracing

tracer = jaegerTracing.getTracerInstance()
from flask_opentracing import FlaskTracing

tracing = FlaskTracing(tracer, True, app)


@app.route('/inject', methods=['GET'])
def testjaegerInject():
    try:
        application_status = JaegerInjectAPI_Provider.injectSpan()
        return str(application_status)
    except Exception as ex:
        return jsonify(str(ex)), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0')
Example #26
0
from interfaces import ViewsStorageBackend
import di

app = Flask(__name__)
tracer = Config(
    config={
        'sampler': {
            'type': 'const',
            'param': 1
        }
    },
    service_name="pixel-tracking",
).initialize_tracer()

redis_opentracing.init_tracing(tracer)
FlaskTracing(tracer, app=app)

PIXEL = (b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00"
         b"\x00\x00\xff\xff\xff!\xf9\x04\x01\x00"
         b"\x00\x00\x00,\x00\x00\x00\x00\x01\x00"
         b"\x01\x00\x00\x02\x01D\x00;")

REQUEST_TIME = Summary("request_processing_seconds",
                       "Time spent processing requests")
AVARAGE_TOP_HITS = Gauge("average_top_hits",
                         "Average number of top-10 page counts ")
TOP_PAGE = Info("top_page", "Most popular referrer")


@app.route("/track")
@REQUEST_TIME.time()
Example #27
0
    },
    'handlers': {
        'wsgi': {
            'class': 'logging.StreamHandler',
            'stream': 'ext://flask.logging.wsgi_errors_stream',
            'formatter': 'default'
        }
    },
    'root': {
        'level': os.getenv('LOG_LEVEL', logging.INFO),
        'handlers': ['wsgi']
    }
})
logging.getLogger('werkzeug').disabled = True
app = Flask(__name__)
FlaskTracing(tracer=init_tracer(), trace_all_requests=True, app=app)


# TODO: 別モジュール化
@app.before_request
def before_request() -> NoReturn:
    app.logger.info(f'[START] {request.method} {request.url}')


# TODO: 別モジュール化
@app.after_request
def after_request(response: flask.Response) -> flask.Response:
    app.logger.info(f'[END] {response.status_code}')
    return response

Example #28
0
 def test_start_span_invalid(self):
     with pytest.raises(ValueError):
         FlaskTracing(start_span_cb=0)
Example #29
0
if JAEGER_AGENT != "":
    config = Config(config={
        'sampler': {
            'type': 'const',
            'param': 1
        },
        'local_agent': {
            'reporting_host': JAEGER_AGENT,
            'reporting_port': 6831
        },
        'logging': True,
        'reporter_batch_size': 1
    },
                    service_name="utilities")
    jaeger_tracer = config.initialize_tracer()
    tracing = FlaskTracing(jaeger_tracer, True, app)
else:
    jaeger_tracer = None
    tracing = None


def get_tracing_headers(req):
    """
    receives a requests object, returns headers suitable for RPC and ID for logging
    """
    new_headers = {}
    if JAEGER_AGENT != "":
        try:
            jaeger_tracer.inject(tracing.get_span(req),
                                 opentracing.Format.TEXT_MAP, new_headers)
        except Exception as e:
Example #30
0
 def init_tracer(self):
     self.application.opentracing_tracer = init_lightstep_tracer(
         self.application.config["APP_NAME"])
     self.application.tracer = FlaskTracing(
         self.application.opentracing_tracer, True, self.application)