code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from __future__ import absolute_import import logging import sys import warnings from django.apps import apps from django.conf import settings as django_settings from zuqa.handlers.logging import LoggingHandler as BaseLoggingHandler from zuqa.utils.logging import get_logger logger = get_logger("zuqa.logging") class LoggingHandler(BaseLoggingHandler): def __init__(self, level=logging.NOTSET): # skip initialization of BaseLoggingHandler logging.Handler.__init__(self, level=level) @property def client(self): try: app = apps.get_app_config("zuqa.contrib.django") if not app.client: logger.warning("Can't send log message to APM server, Django apps not initialized yet") return app.client except LookupError: logger.warning("Can't send log message to APM server, zuqa.contrib.django not in INSTALLED_APPS") def _emit(self, record, **kwargs): from zuqa.contrib.django.middleware import LogMiddleware # Fetch the request from a threadlocal variable, if available request = getattr(LogMiddleware.thread, "request", None) request = getattr(record, "request", request) return super(LoggingHandler, self)._emit(record, request=request, **kwargs) def exception_handler(client, request=None, **kwargs): def actually_do_stuff(request=None, **kwargs): exc_info = sys.exc_info() try: if (django_settings.DEBUG and not client.config.debug) or getattr(exc_info[1], "skip_zuqa", False): return client.capture("Exception", exc_info=exc_info, request=request, handled=False) except Exception as exc: try: client.error_logger.exception(u"Unable to process log entry: %s" % (exc,)) except Exception as exc: warnings.warn(u"Unable to process log entry: %s" % (exc,)) finally: try: del exc_info except Exception as e: client.error_logger.exception(e) return actually_do_stuff(request, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/handlers.py
handlers.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/celery/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from django.conf import settings from django.core.exceptions import ImproperlyConfigured if "djcelery" not in settings.INSTALLED_APPS: raise ImproperlyConfigured( "Put 'djcelery' in your INSTALLED_APPS setting in order to use the sentry celery client." )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/celery/models.py
models.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/management/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import import sys from django.conf import settings from django.core.management.base import BaseCommand from django.core.management.color import color_style from django.utils import termcolors from zuqa.contrib.django.client import DjangoClient from zuqa.utils.compat import urlparse try: from django.core.management.base import OutputWrapper except ImportError: OutputWrapper = None blue = termcolors.make_style(opts=("bold",), fg="blue") cyan = termcolors.make_style(opts=("bold",), fg="cyan") green = termcolors.make_style(fg="green") magenta = termcolors.make_style(opts=("bold",), fg="magenta") red = termcolors.make_style(opts=("bold",), fg="red") white = termcolors.make_style(opts=("bold",), fg="white") yellow = termcolors.make_style(opts=("bold",), fg="yellow") class TestException(Exception): pass class ColoredLogger(object): def __init__(self, stream): self.stream = stream self.errors = [] self.color = color_style() def log(self, level, *args, **kwargs): style = kwargs.pop("style", self.color.NOTICE) msg = " ".join((level.upper(), args[0] % args[1:], "\n")) if OutputWrapper is None: self.stream.write(msg) else: self.stream.write(msg, style_func=style) def error(self, *args, **kwargs): kwargs["style"] = red self.log("error", *args, **kwargs) self.errors.append((args,)) def warning(self, *args, **kwargs): kwargs["style"] = yellow self.log("warning", *args, **kwargs) def info(self, *args, **kwargs): kwargs["style"] = green self.log("info", *args, **kwargs) CONFIG_EXAMPLE = """ You can set it in your settings file: ZUQA = { 'SERVICE_NAME': '<YOUR-SERVICE-NAME>', 'SECRET_TOKEN': '<YOUR-SECRET-TOKEN>', } or with environment variables: $ export ZUQA_SERVICE_NAME="<YOUR-SERVICE-NAME>" $ export ZUQA_SECRET_TOKEN="<YOUR-SECRET-TOKEN>" $ python manage.py zuqa check """ class Command(BaseCommand): arguments = ( (("-s", "--service-name"), {"default": None, "dest": "service_name", "help": "Specifies the service name."}), (("-t", "--token"), {"default": None, "dest": "secret_token", "help": "Specifies the secret token."}), ) args = "test check" def add_arguments(self, parser): parser.add_argument("subcommand") for args, kwargs in self.arguments: parser.add_argument(*args, **kwargs) def handle(self, *args, **options): if "subcommand" in options: subcommand = options["subcommand"] else: return self.handle_command_not_found("No command specified.") if subcommand not in self.dispatch: self.handle_command_not_found('No such command "%s".' % subcommand) else: self.dispatch.get(subcommand, self.handle_command_not_found)(self, subcommand, **options) def handle_test(self, command, **options): """Send a test error to APM Server""" # can't be async for testing config = {"async_mode": False} for key in ("service_name", "secret_token"): if options.get(key): config[key] = options[key] client = DjangoClient(**config) client.error_logger = ColoredLogger(self.stderr) client.logger = ColoredLogger(self.stderr) self.write( "Trying to send a test error to APM Server using these settings:\n\n" "SERVICE_NAME:\t%s\n" "SECRET_TOKEN:\t%s\n" "SERVER:\t\t%s\n\n" % (client.config.service_name, client.config.secret_token, client.config.server_url) ) try: raise TestException("Hi there!") except TestException: client.capture_exception() if not client.error_logger.errors: self.write( "Success! We tracked the error successfully! \n" "You should see it in the APM app in Kibana momentarily. \n" 'Look for "TestException: Hi there!" in the Errors tab of the %s app' % client.config.service_name ) finally: client.close() def handle_check(self, command, **options): """Check your settings for common misconfigurations""" passed = True client = DjangoClient(metrics_interval="0ms") def is_set(x): return x and x != "None" # check if org/app is set: if is_set(client.config.service_name): self.write("Service name is set, good job!", green) else: passed = False self.write("Configuration errors detected!", red, ending="\n\n") self.write(" * SERVICE_NAME not set! ", red, ending="\n") self.write(CONFIG_EXAMPLE) # secret token is optional but recommended if not is_set(client.config.secret_token): self.write(" * optional SECRET_TOKEN not set", yellow, ending="\n") self.write("") server_url = client.config.server_url if server_url: parsed_url = urlparse.urlparse(server_url) if parsed_url.scheme.lower() in ("http", "https"): # parse netloc, making sure people did not supply basic auth if "@" in parsed_url.netloc: credentials, _, path = parsed_url.netloc.rpartition("@") passed = False self.write("Configuration errors detected!", red, ending="\n\n") if ":" in credentials: self.write(" * SERVER_URL cannot contain authentication " "credentials", red, ending="\n") else: self.write( " * SERVER_URL contains an unexpected at-sign!" " This is usually used for basic authentication, " "but the colon is left out", red, ending="\n", ) else: self.write("SERVER_URL {0} looks fine".format(server_url), green) # secret token in the clear not recommended if is_set(client.config.secret_token) and parsed_url.scheme.lower() == "http": self.write(" * SECRET_TOKEN set but server not using https", yellow, ending="\n") else: self.write( " * SERVER_URL has scheme {0} and we require " "http or https!".format(parsed_url.scheme), red, ending="\n", ) passed = False else: self.write("Configuration errors detected!", red, ending="\n\n") self.write(" * SERVER_URL appears to be empty", red, ending="\n") passed = False self.write("") # check if we're disabled due to DEBUG: if settings.DEBUG: if getattr(settings, "ZUQA", {}).get("DEBUG"): self.write( "Note: even though you are running in DEBUG mode, we will " 'send data to the APM Server, because you set ZUQA["DEBUG"] to ' "True. You can disable ZUQA while in DEBUG mode like this" "\n\n", yellow, ) self.write( " ZUQA = {\n" ' "DEBUG": False,\n' " # your other ZUQA settings\n" " }" ) else: self.write( "Looks like you're running in DEBUG mode. ZUQA will NOT " "gather any data while DEBUG is set to True.\n\n", red, ) self.write( "If you want to test ZUQA while DEBUG is set to True, you" " can force ZUQA to gather data by setting" ' ZUQA["DEBUG"] to True, like this\n\n' " ZUQA = {\n" ' "DEBUG": True,\n' " # your other ZUQA settings\n" " }" ) passed = False else: self.write("DEBUG mode is disabled! Looking good!", green) self.write("") # check if middleware is set, and if it is at the first position middleware_attr = "MIDDLEWARE" if getattr(settings, "MIDDLEWARE", None) is not None else "MIDDLEWARE_CLASSES" middleware = list(getattr(settings, middleware_attr)) try: pos = middleware.index("zuqa.contrib.django.middleware.TracingMiddleware") if pos == 0: self.write("Tracing middleware is configured! Awesome!", green) else: self.write("Tracing middleware is configured, but not at the first position\n", yellow) self.write("ZUQA works best if you add it at the top of your %s setting" % middleware_attr) except ValueError: self.write("Tracing middleware not configured!", red) self.write( "\n" "Add it to your %(name)s setting like this:\n\n" " %(name)s = (\n" ' "zuqa.contrib.django.middleware.TracingMiddleware",\n' " # your other middleware classes\n" " )\n" % {"name": middleware_attr} ) self.write("") if passed: self.write("Looks like everything should be ready!", green) else: self.write("Please fix the above errors.", red) self.write("") client.close() return passed def handle_command_not_found(self, message): self.write(message, red, ending="") self.write(" Please use one of the following commands:\n\n", red) self.write("".join(" * %s\t%s\n" % (k.ljust(8), v.__doc__) for k, v in self.dispatch.items())) self.write("\n") argv = self._get_argv() self.write("Usage:\n\t%s zuqa <command>" % (" ".join(argv[: argv.index("zuqa")]))) def write(self, msg, style_func=None, ending=None, stream=None): """ wrapper around self.stdout/stderr to ensure Django 1.4 compatibility """ if stream is None: stream = self.stdout if OutputWrapper is None: ending = "\n" if ending is None else ending msg += ending stream.write(msg) else: stream.write(msg, style_func=style_func, ending=ending) def _get_argv(self): """allow cleaner mocking of sys.argv""" return sys.argv dispatch = {"test": handle_test, "check": handle_check}
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/management/commands/elasticapm.py
elasticapm.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/management/commands/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from django.apps import apps from zuqa.contrib.django.client import get_client from zuqa.middleware import ZUQA as ZuqaBase class ZUQA(ZuqaBase): """ Identical to the default WSGI middleware except that the client comes dynamically via ``get_client >>> from zuqa.contrib.django.middleware.wsgi import ZUQA >>> application = ZUQA(application) """ def __init__(self, application): self.application = application @property def client(self): try: app = apps.get_app_config("zuqa.contrib.django") return app.client except LookupError: return get_client()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/middleware/wsgi.py
wsgi.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from __future__ import absolute_import import logging import threading from django.apps import apps from django.conf import settings as django_settings import zuqa from zuqa.conf import constants from zuqa.contrib.django.client import client, get_client from zuqa.utils import build_name_with_http_method_prefix, get_name_from_func, wrapt try: from importlib import import_module except ImportError: from django.utils.importlib import import_module try: from django.utils.deprecation import MiddlewareMixin except ImportError: # no-op class for Django < 1.10 class MiddlewareMixin(object): pass def _is_ignorable_404(uri): """ Returns True if the given request *shouldn't* notify the site managers. """ urls = getattr(django_settings, "IGNORABLE_404_URLS", ()) return any(pattern.search(uri) for pattern in urls) class ZuqaClientMiddlewareMixin(object): @property def client(self): try: app = apps.get_app_config("zuqa.contrib.django") return app.client except LookupError: return get_client() class Catch404Middleware(MiddlewareMixin, ZuqaClientMiddlewareMixin): def process_response(self, request, response): if response.status_code != 404 or _is_ignorable_404(request.get_full_path()): return response if django_settings.DEBUG and not self.client.config.debug: return response data = {"level": logging.INFO, "logger": "http404"} result = self.client.capture( "Message", request=request, param_message={"message": "Page Not Found: %s", "params": [request.build_absolute_uri()]}, logger_name="http404", level=logging.INFO, ) request._zuqa = {"service_name": data.get("service_name", self.client.config.service_name), "id": result} return response def get_name_from_middleware(wrapped, instance): name = [type(instance).__name__, wrapped.__name__] if type(instance).__module__: name = [type(instance).__module__] + name return ".".join(name) def process_request_wrapper(wrapped, instance, args, kwargs): response = wrapped(*args, **kwargs) try: if response is not None: request = args[0] zuqa.set_transaction_name( build_name_with_http_method_prefix(get_name_from_middleware(wrapped, instance), request) ) finally: return response def process_response_wrapper(wrapped, instance, args, kwargs): response = wrapped(*args, **kwargs) try: request, original_response = args # if there's no view_func on the request, and this middleware created # a new response object, it's logged as the responsible transaction # name if not hasattr(request, "_zuqa_view_func") and response is not original_response: zuqa.set_transaction_name( build_name_with_http_method_prefix(get_name_from_middleware(wrapped, instance), request) ) finally: return response class TracingMiddleware(MiddlewareMixin, ZuqaClientMiddlewareMixin): _zuqa_instrumented = False _instrumenting_lock = threading.Lock() def __init__(self, *args, **kwargs): super(TracingMiddleware, self).__init__(*args, **kwargs) if not self._zuqa_instrumented: with self._instrumenting_lock: if not self._zuqa_instrumented: if self.client.config.instrument_django_middleware: self.instrument_middlewares() TracingMiddleware._zuqa_instrumented = True def instrument_middlewares(self): middlewares = getattr(django_settings, "MIDDLEWARE", None) or getattr( django_settings, "MIDDLEWARE_CLASSES", None ) if middlewares: for middleware_path in middlewares: module_path, class_name = middleware_path.rsplit(".", 1) try: module = import_module(module_path) middleware_class = getattr(module, class_name) if middleware_class == type(self): # don't instrument ourselves continue if hasattr(middleware_class, "process_request"): wrapt.wrap_function_wrapper(middleware_class, "process_request", process_request_wrapper) if hasattr(middleware_class, "process_response"): wrapt.wrap_function_wrapper(middleware_class, "process_response", process_response_wrapper) except ImportError: client.logger.info("Can't instrument middleware %s", middleware_path) def process_view(self, request, view_func, view_args, view_kwargs): request._zuqa_view_func = view_func def process_response(self, request, response): if django_settings.DEBUG and not self.client.config.debug: return response try: if hasattr(response, "status_code"): transaction_name = None if self.client.config.django_transaction_name_from_route and hasattr(request.resolver_match, "route"): transaction_name = request.resolver_match.route elif getattr(request, "_zuqa_view_func", False): transaction_name = get_name_from_func(request._zuqa_view_func) if transaction_name: transaction_name = build_name_with_http_method_prefix(transaction_name, request) zuqa.set_transaction_name(transaction_name, override=False) zuqa.set_context( lambda: self.client.get_data_from_request(request, constants.TRANSACTION), "request" ) zuqa.set_context( lambda: self.client.get_data_from_response(response, constants.TRANSACTION), "response" ) zuqa.set_context(lambda: self.client.get_user_info(request), "user") zuqa.set_transaction_result("HTTP {}xx".format(response.status_code // 100), override=False) except Exception: self.client.error_logger.error("Exception during timing of request", exc_info=True) return response class ErrorIdMiddleware(MiddlewareMixin): """ Appends the X-ZUQA-ErrorId response header for referencing a message within the ZUQA datastore. """ def process_response(self, request, response): if not getattr(request, "_zuqa", None): return response response["X-ZUQA-ErrorId"] = request._zuqa["id"] return response class LogMiddleware(MiddlewareMixin): # Create a thread local variable to store the session in for logging thread = threading.local() def process_request(self, request): self.thread.request = request
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/django/middleware/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import functools from zuqa.conf.constants import LABEL_RE from zuqa.traces import DroppedSpan, capture_span, error_logger, execution_context from zuqa.utils import get_name_from_func class async_capture_span(capture_span): def __call__(self, func): self.name = self.name or get_name_from_func(func) @functools.wraps(func) async def decorated(*args, **kwds): async with self: return await func(*args, **kwds) return decorated async def __aenter__(self): transaction = execution_context.get_transaction() if transaction and transaction.is_sampled: return transaction.begin_span( self.name, self.type, context=self.extra, leaf=self.leaf, labels=self.labels, span_subtype=self.subtype, span_action=self.action, sync=False, start=self.start, ) async def __aexit__(self, exc_type, exc_val, exc_tb): transaction = execution_context.get_transaction() if transaction and transaction.is_sampled: try: span = transaction.end_span(self.skip_frames) if exc_val and not isinstance(span, DroppedSpan): try: exc_val._zuqa_span_id = span.id except AttributeError: # could happen if the exception has __slots__ pass except LookupError: error_logger.info("ended non-existing span %s of type %s", self.name, self.type) async def set_context(data, key="custom"): """ Asynchronous copy of zuqa.traces.set_context(). Attach contextual data to the current transaction and errors that happen during the current transaction. If the transaction is not sampled, this function becomes a no-op. :param data: a dictionary, or a callable that returns a dictionary :param key: the namespace for this data """ transaction = execution_context.get_transaction() if not (transaction and transaction.is_sampled): return if callable(data): data = await data() # remove invalid characters from key names for k in list(data.keys()): if LABEL_RE.search(k): data[LABEL_RE.sub("_", k)] = data.pop(k) if key in transaction.context: transaction.context[key].update(data) else: transaction.context[key] = data
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/asyncio/traces.py
traces.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/asyncio/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def register_zuqa(client, worker): """Given an ZUQA client and an RQ worker, registers exception handlers with the worker so exceptions are logged to the apm server. E.g.: from zuqa.contrib.django.models import client from zuqa.contrib.rq import register_zuqa worker = Worker(map(Queue, listen)) register_zuqa(client, worker) worker.work() """ def send_to_server(job, *exc_info): client.capture_exception( exc_info=exc_info, extra={ "job_id": job.id, "func": job.func_name, "args": job.args, "kwargs": job.kwargs, "description": job.description, }, ) worker.push_exc_handler(send_to_server)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/rq/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import json from starlette.requests import Request from starlette.responses import Response from starlette.types import Message from zuqa.conf import Config, constants from zuqa.utils import compat, get_url_dict async def get_data_from_request(request: Request, config: Config, event_type: str) -> dict: """Loads data from incoming request for APM capturing. Args: request (Request) config (Config) event_type (str) Returns: dict """ result = { "method": request.method, "socket": {"remote_address": _get_client_ip(request), "encrypted": request.url.is_secure}, "cookies": request.cookies, } if config.capture_headers: result["headers"] = dict(request.headers) if request.method in constants.HTTP_WITH_BODY: if config.capture_body not in ("all", event_type): result["body"] = "[REDACTED]" else: body = None try: body = await get_body(request) if request.headers.get("content-type") == "application/x-www-form-urlencoded": body = await query_params_to_dict(body) else: body = json.loads(body) except Exception: pass if body is not None: result["body"] = body result["url"] = get_url_dict(str(request.url)) return result async def get_data_from_response(response: Response, config: Config, event_type: str) -> dict: """Loads data from response for APM capturing. Args: response (Response) config (Config) event_type (str) Returns: dict """ result = {} if isinstance(getattr(response, "status_code", None), compat.integer_types): result["status_code"] = response.status_code if config.capture_headers and getattr(response, "headers", None): headers = response.headers result["headers"] = {key: ";".join(headers.getlist(key)) for key in compat.iterkeys(headers)} if config.capture_body in ("all", event_type) and hasattr(response, "body"): result["body"] = response.body.decode("utf-8") return result async def set_body(request: Request, body: bytes): """Overwrites body in Starlette. Args: request (Request) body (bytes) """ async def receive() -> Message: return {"type": "http.request", "body": body} request._receive = receive async def get_body(request: Request) -> str: """Gets body from the request. todo: This is not very pretty however it is not usual to get request body out of the target method (business logic). Args: request (Request) Returns: str """ body = await request.body() await set_body(request, body) request._stream_consumed = False return body.decode("utf-8") async def query_params_to_dict(query_params: str) -> dict: """Transforms query params from URL to dictionary Args: query_params (str) Returns: dict Examples: >>> print(query_params_to_dict(b"key=val&key2=val2")) {"key": "val", "key2": "val2"} """ query_params = query_params.split("&") res = {} for param in query_params: key, val = param.split("=") res[key] = val return res def _get_client_ip(request: Request): x_forwarded_for = request.headers.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[0] else: ip = request.headers.get("REMOTE_ADDR") return ip
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/starlette/utils.py
utils.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from __future__ import absolute_import import starlette from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp import zuqa import zuqa.instrumentation.control from zuqa.base import Client from zuqa.conf import constants from zuqa.contrib.asyncio.traces import set_context from zuqa.contrib.starlette.utils import get_data_from_request, get_data_from_response from zuqa.utils.disttracing import TraceParent from zuqa.utils.logging import get_logger logger = get_logger("zuqa.errors.client") def make_apm_client(config: dict, client_cls=Client, **defaults) -> Client: """Builds ZUQA client. Args: config (dict): Dictionary of Client configuration. All keys must be uppercase. See `zuqa.conf.Config`. client_cls (Client): Must be Client or its child. **defaults: Additional parameters for Client. See `zuqa.base.Client` Returns: Client """ if "framework_name" not in defaults: defaults["framework_name"] = "starlette" defaults["framework_version"] = starlette.__version__ return client_cls(config, **defaults) class ZUQA(BaseHTTPMiddleware): """ Starlette / FastAPI middleware for ZUQA capturing. >>> zuqa = make_apm_client({ >>> 'SERVICE_NAME': 'myapp', >>> 'DEBUG': True, >>> 'SERVER_URL': 'http://localhost:32140', >>> 'CAPTURE_HEADERS': True, >>> 'CAPTURE_BODY': 'all' >>> }) >>> app.add_middleware(ZUQA, client=zuqa) Pass an arbitrary APP_NAME and SECRET_TOKEN:: >>> zuqa = ZUQA(app, service_name='myapp', secret_token='asdasdasd') Pass an explicit client:: >>> zuqa = ZUQA(app, client=client) Automatically configure logging:: >>> zuqa = ZUQA(app, logging=True) Capture an exception:: >>> try: >>> 1 / 0 >>> except ZeroDivisionError: >>> zuqa.capture_exception() Capture a message:: >>> zuqa.capture_message('hello, world!') """ def __init__(self, app: ASGIApp, client: Client): """ Args: app (ASGIApp): Starlette app client (Client): ZUQA Client """ self.client = client if self.client.config.instrument: zuqa.instrumentation.control.instrument() super().__init__(app) async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: """Processes the whole request APM capturing. Args: request (Request) call_next (RequestResponseEndpoint): Next request process in Starlette. Returns: Response """ await self._request_started(request) try: response = await call_next(request) except Exception: await self.capture_exception( context={"request": await get_data_from_request(request, self.client.config, constants.ERROR)} ) zuqa.set_transaction_result("HTTP 5xx", override=False) zuqa.set_context({"status_code": 500}, "response") raise else: await self._request_finished(response) finally: self.client.end_transaction() return response async def capture_exception(self, *args, **kwargs): """Captures your exception. Args: *args: **kwargs: """ self.client.capture_exception(*args, **kwargs) async def capture_message(self, *args, **kwargs): """Captures your message. Args: *args: Whatever **kwargs: Whatever """ self.client.capture_message(*args, **kwargs) async def _request_started(self, request: Request): """Captures the begin of the request processing to APM. Args: request (Request) """ trace_parent = TraceParent.from_headers(dict(request.headers)) self.client.begin_transaction("request", trace_parent=trace_parent) await set_context(lambda: get_data_from_request(request, self.client.config, constants.TRANSACTION), "request") zuqa.set_transaction_name("{} {}".format(request.method, request.url.path), override=False) async def _request_finished(self, response: Response): """Captures the end of the request processing to APM. Args: response (Response) """ await set_context( lambda: get_data_from_response(response, self.client.config, constants.TRANSACTION), "response" ) result = "HTTP {}xx".format(response.status_code // 100) zuqa.set_transaction_result(result, override=False)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/starlette/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import warnings from opentracing import Format, InvalidCarrierException, SpanContextCorruptedException, UnsupportedFormatException from opentracing.scope_managers import ThreadLocalScopeManager from opentracing.tracer import ReferenceType from opentracing.tracer import Tracer as TracerBase import zuqa from zuqa import instrument, traces from zuqa.conf import constants from zuqa.contrib.opentracing.span import OTSpan, OTSpanContext from zuqa.utils import compat, disttracing class Tracer(TracerBase): _zuqa_client_class = zuqa.Client def __init__(self, client_instance=None, config=None, scope_manager=None): self._agent = client_instance or self._zuqa_client_class(config=config) if scope_manager and not isinstance(scope_manager, ThreadLocalScopeManager): warnings.warn( "Currently, the ZUQA opentracing bridge only supports the ThreadLocalScopeManager. " "Usage of other scope managers will lead to unpredictable results." ) self._scope_manager = scope_manager or ThreadLocalScopeManager() if self._agent.config.instrument and self._agent.config.enabled: instrument() def start_active_span( self, operation_name, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False, finish_on_close=True, ): ot_span = self.start_span( operation_name, child_of=child_of, references=references, tags=tags, start_time=start_time, ignore_active_span=ignore_active_span, ) scope = self._scope_manager.activate(ot_span, finish_on_close) return scope def start_span( self, operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False ): if isinstance(child_of, OTSpanContext): parent_context = child_of elif isinstance(child_of, OTSpan): parent_context = child_of.context elif references and references[0].type == ReferenceType.CHILD_OF: parent_context = references[0].referenced_context else: parent_context = None transaction = traces.execution_context.get_transaction() if not transaction: trace_parent = parent_context.trace_parent if parent_context else None transaction = self._agent.begin_transaction("custom", trace_parent=trace_parent) transaction.name = operation_name span_context = OTSpanContext(trace_parent=transaction.trace_parent) ot_span = OTSpan(self, span_context, transaction) else: # to allow setting an explicit parent span, we check if the parent_context is set # and if it is a span. In all other cases, the parent is found implicitly through the # execution context. parent_span_id = ( parent_context.span.zuqa_ref.id if parent_context and parent_context.span and not parent_context.span.is_transaction else None ) span = transaction._begin_span(operation_name, None, parent_span_id=parent_span_id) trace_parent = parent_context.trace_parent if parent_context else transaction.trace_parent span_context = OTSpanContext(trace_parent=trace_parent.copy_from(span_id=span.id)) ot_span = OTSpan(self, span_context, span) if tags: for k, v in compat.iteritems(tags): ot_span.set_tag(k, v) return ot_span def extract(self, format, carrier): if format in (Format.HTTP_HEADERS, Format.TEXT_MAP): trace_parent = disttracing.TraceParent.from_headers(carrier) if not trace_parent: raise SpanContextCorruptedException("could not extract span context from carrier") return OTSpanContext(trace_parent=trace_parent) raise UnsupportedFormatException def inject(self, span_context, format, carrier): if format in (Format.HTTP_HEADERS, Format.TEXT_MAP): if not isinstance(carrier, dict): raise InvalidCarrierException("carrier for {} format should be dict-like".format(format)) val = span_context.trace_parent.to_ascii() carrier[constants.TRACEPARENT_HEADER_NAME] = val if self._agent.config.use_elastic_traceparent_header: carrier[constants.TRACEPARENT_LEGACY_HEADER_NAME] = val return raise UnsupportedFormatException
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/opentracing/tracer.py
tracer.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from opentracing.span import Span as OTSpanBase from opentracing.span import SpanContext as OTSpanContextBase from zuqa import traces from zuqa.utils import compat, get_url_dict from zuqa.utils.logging import get_logger try: # opentracing-python 2.1+ from opentracing import tags from opentracing import logs as ot_logs except ImportError: # opentracing-python <2.1 from opentracing.ext import tags ot_logs = None logger = get_logger("zuqa.contrib.opentracing") class OTSpan(OTSpanBase): def __init__(self, tracer, context, zuqa_ref): super(OTSpan, self).__init__(tracer, context) self.zuqa_ref = zuqa_ref self.is_transaction = isinstance(zuqa_ref, traces.Transaction) self.is_dropped = isinstance(zuqa_ref, traces.DroppedSpan) if not context.span: context.span = self def log_kv(self, key_values, timestamp=None): exc_type, exc_val, exc_tb = None, None, None if "python.exception.type" in key_values: exc_type = key_values["python.exception.type"] exc_val = key_values.get("python.exception.val") exc_tb = key_values.get("python.exception.tb") elif ot_logs and key_values.get(ot_logs.EVENT) == tags.ERROR: exc_type = key_values[ot_logs.ERROR_KIND] exc_val = key_values.get(ot_logs.ERROR_OBJECT) exc_tb = key_values.get(ot_logs.STACK) else: logger.debug("Can't handle non-exception type opentracing logs") if exc_type: agent = self.tracer._agent agent.capture_exception(exc_info=(exc_type, exc_val, exc_tb)) return self def set_operation_name(self, operation_name): self.zuqa_ref.name = operation_name return self def set_tag(self, key, value): if self.is_transaction: if key == "type": self.zuqa_ref.transaction_type = value elif key == "result": self.zuqa_ref.result = value elif key == tags.HTTP_STATUS_CODE: self.zuqa_ref.result = "HTTP {}xx".format(compat.text_type(value)[0]) traces.set_context({"status_code": value}, "response") elif key == "user.id": traces.set_user_context(user_id=value) elif key == "user.username": traces.set_user_context(username=value) elif key == "user.email": traces.set_user_context(email=value) elif key == tags.HTTP_URL: traces.set_context({"url": get_url_dict(value)}, "request") elif key == tags.HTTP_METHOD: traces.set_context({"method": value}, "request") elif key == tags.COMPONENT: traces.set_context({"framework": {"name": value}}, "service") else: self.zuqa_ref.label(**{key: value}) elif not self.is_dropped: if key.startswith("db."): span_context = self.zuqa_ref.context or {} if "db" not in span_context: span_context["db"] = {} if key == tags.DATABASE_STATEMENT: span_context["db"]["statement"] = value elif key == tags.DATABASE_USER: span_context["db"]["user"] = value elif key == tags.DATABASE_TYPE: span_context["db"]["type"] = value self.zuqa_ref.type = "db." + value else: self.zuqa_ref.label(**{key: value}) self.zuqa_ref.context = span_context elif key == tags.SPAN_KIND: self.zuqa_ref.type = value else: self.zuqa_ref.label(**{key: value}) return self def finish(self, finish_time=None): if self.is_transaction: self.tracer._agent.end_transaction() elif not self.is_dropped: self.zuqa_ref.transaction.end_span() class OTSpanContext(OTSpanContextBase): def __init__(self, trace_parent, span=None): self.trace_parent = trace_parent self.span = span
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/opentracing/span.py
span.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from .span import OTSpan # noqa: F401 from .tracer import Tracer # noqa: F401
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/opentracing/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from twisted.logger import ILogObserver from zope.interface import implementer from zuqa.base import Client @implementer(ILogObserver) class LogObserver(object): """ A twisted log observer for ZUQA. Eg.: from zuqa.base import Client from twisted.logger import Logger client = Client(...) observer = LogObserver(client=client) log = Logger(observer=observer) try: 1 / 0 except: log.failure("Math is hard!") """ def __init__(self, client=None, **kwargs): self.client = client or Client(**kwargs) def __call__(self, event): failure = event.get("log_failure") if failure is not None: self.client.capture_exception( exc_info=(failure.type, failure.value, failure.getTracebackObject()), handled=False, extra=event )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/twisted/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import zuqa from zuqa.conf import constants from zuqa.utils import compat try: import tornado except ImportError: pass def get_data_from_request(request_handler, request, config, event_type): """ Capture relevant data from a tornado.httputil.HTTPServerRequest """ result = { "method": request.method, "socket": {"remote_address": request.remote_ip, "encrypted": request.protocol == "https"}, "cookies": request.cookies, "http_version": request.version, } if config.capture_headers: result["headers"] = dict(request.headers) if request.method in constants.HTTP_WITH_BODY: if tornado.web._has_stream_request_body(request_handler.__class__): # Body is a future and streaming is expected to be handled by # the user in the RequestHandler.data_received function. # Currently not sure of a safe way to get the body in this case. result["body"] = "[STREAMING]" if config.capture_body in ("all", event_type) else "[REDACTED]" else: body = None try: body = tornado.escape.json_decode(request.body) except Exception: body = request.body if body is not None: result["body"] = body if config.capture_body in ("all", event_type) else "[REDACTED]" result["url"] = zuqa.utils.get_url_dict(request.full_url()) return result def get_data_from_response(request_handler, config, event_type): result = {} result["status_code"] = request_handler.get_status() if config.capture_headers and request_handler._headers: headers = request_handler._headers result["headers"] = {key: ";".join(headers.get_list(key)) for key in compat.iterkeys(headers)} pass return result
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/tornado/utils.py
utils.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Framework integration for Tornado Note that transaction creation is actually done in the tornado instrumentation. This module only creates the client for later use by the that instrumentation, and triggers the global instrumentation itself. """ import tornado import zuqa from zuqa import Client class ZUQA: def __init__(self, app, client=None, **config): """ Create the zuqa Client object and store in the app for later use. ZUQA configuration is sent in via the **config kwargs, or optionally can be added to the application via the Application object (as a dictionary under the "ZUQA" key in the settings). """ if "ZUQA" in app.settings and isinstance(app.settings["ZUQA"], dict): settings = app.settings["ZUQA"] settings.update(config) config = settings if not client: config.setdefault("framework_name", "tornado") config.setdefault("framework_version", tornado.version) client = Client(config) self.app = app self.client = client app.zuqa_client = client # Don't instrument if debug=True in tornado, unless client.config.debug is True if ( (not self.app.settings.get("debug") or client.config.debug) and client.config.instrument and client.config.enabled ): zuqa.instrument()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/contrib/tornado/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from __future__ import absolute_import import logging import sys import traceback from zuqa.base import Client from zuqa.traces import execution_context from zuqa.utils import compat, wrapt from zuqa.utils.encoding import to_unicode from zuqa.utils.stacks import iter_stack_frames class LoggingHandler(logging.Handler): def __init__(self, *args, **kwargs): client = kwargs.pop("client_cls", Client) if len(args) == 1: arg = args[0] args = args[1:] if isinstance(arg, Client): self.client = arg else: raise ValueError( "The first argument to %s must be a Client instance, " "got %r instead." % (self.__class__.__name__, arg) ) elif "client" in kwargs: self.client = kwargs.pop("client") else: self.client = client(*args, **kwargs) logging.Handler.__init__(self, level=kwargs.get("level", logging.NOTSET)) def emit(self, record): self.format(record) # Avoid typical config issues by overriding loggers behavior if record.name.startswith(("zuqa.errors",)): sys.stderr.write(to_unicode(record.message) + "\n") return try: return self._emit(record) except Exception: sys.stderr.write("Top level ZUQA exception caught - failed creating log record.\n") sys.stderr.write(to_unicode(record.msg + "\n")) sys.stderr.write(to_unicode(traceback.format_exc() + "\n")) try: self.client.capture("Exception") except Exception: pass def _emit(self, record, **kwargs): data = {} for k, v in compat.iteritems(record.__dict__): if "." not in k and k not in ("culprit",): continue data[k] = v stack = getattr(record, "stack", None) if stack is True: stack = iter_stack_frames(config=self.client.config) if stack: frames = [] started = False last_mod = "" for item in stack: if isinstance(item, (list, tuple)): frame, lineno = item else: frame, lineno = item, item.f_lineno if not started: f_globals = getattr(frame, "f_globals", {}) module_name = f_globals.get("__name__", "") if last_mod.startswith("logging") and not module_name.startswith("logging"): started = True else: last_mod = module_name continue frames.append((frame, lineno)) stack = frames custom = getattr(record, "data", {}) # Add in all of the data from the record that we aren't already capturing for k in record.__dict__.keys(): if k in ( "stack", "name", "args", "msg", "levelno", "exc_text", "exc_info", "data", "created", "levelname", "msecs", "relativeCreated", ): continue if k.startswith("_"): continue custom[k] = record.__dict__[k] # If there's no exception being processed, # exc_info may be a 3-tuple of None # http://docs.python.org/library/sys.html#sys.exc_info if record.exc_info and all(record.exc_info): handler = self.client.get_handler("zuqa.events.Exception") exception = handler.capture(self.client, exc_info=record.exc_info) else: exception = None return self.client.capture( "Message", param_message={"message": compat.text_type(record.msg), "params": record.args}, stack=stack, custom=custom, exception=exception, level=record.levelno, logger_name=record.name, **kwargs ) class LoggingFilter(logging.Filter): """ This filter doesn't actually do any "filtering" -- rather, it just adds three new attributes to any "filtered" LogRecord objects: * zuqa_transaction_id * zuqa_trace_id * zuqa_span_id These attributes can then be incorporated into your handlers and formatters, so that you can tie log messages to transactions in elasticsearch. This filter also adds these fields to a dictionary attribute, `zuqa_labels`, using the official tracing fields names as documented here: https://www.elastic.co/guide/en/ecs/current/ecs-tracing.html Note that if you're using Python 3.2+, by default we will add a LogRecordFactory to your root logger which will add these attributes automatically. """ def filter(self, record): """ Add zuqa attributes to `record`. """ _add_attributes_to_log_record(record) return True @wrapt.decorator def log_record_factory(wrapped, instance, args, kwargs): """ Decorator, designed to wrap the python log record factory (fetched by logging.getLogRecordFactory), adding the same custom attributes as in the LoggingFilter provided above. :return: LogRecord object, with custom attributes for APM tracing fields """ record = wrapped(*args, **kwargs) return _add_attributes_to_log_record(record) def _add_attributes_to_log_record(record): """ Add custom attributes for APM tracing fields to a LogRecord object :param record: LogRecord object :return: Updated LogRecord object with new APM tracing fields """ transaction = execution_context.get_transaction() transaction_id = transaction.id if transaction else None record.zuqa_transaction_id = transaction_id trace_id = transaction.trace_parent.trace_id if transaction and transaction.trace_parent else None record.zuqa_trace_id = trace_id span = execution_context.get_span() span_id = span.id if span else None record.zuqa_span_id = span_id record.zuqa_labels = {"transaction.id": transaction_id, "trace.id": trace_id, "span.id": span_id} return record class Formatter(logging.Formatter): """ Custom formatter to automatically append the zuqa format string, as well as ensure that LogRecord objects actually have the required fields (so as to avoid errors which could occur for logs before we override the LogRecordFactory): formatstring = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" formatstring = formatstring + " | zuqa " \ "transaction.id=%(zuqa_transaction_id)s " \ "trace.id=%(zuqa_trace_id)s " \ "span.id=%(zuqa_span_id)s" """ def __init__(self, fmt=None, datefmt=None, style="%"): if fmt is None: fmt = "%(message)s" fmt = ( fmt + " | zuqa " "transaction.id=%(zuqa_transaction_id)s " "trace.id=%(zuqa_trace_id)s " "span.id=%(zuqa_span_id)s" ) if compat.PY3: super(Formatter, self).__init__(fmt=fmt, datefmt=datefmt, style=style) else: super(Formatter, self).__init__(fmt=fmt, datefmt=datefmt) def format(self, record): if not hasattr(record, "zuqa_transaction_id"): record.zuqa_transaction_id = None record.zuqa_trace_id = None record.zuqa_span_id = None return super(Formatter, self).format(record=record) def formatTime(self, record, datefmt=None): if not hasattr(record, "zuqa_transaction_id"): record.zuqa_transaction_id = None record.zuqa_trace_id = None record.zuqa_span_id = None return super(Formatter, self).formatTime(record=record, datefmt=datefmt)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/handlers/logging.py
logging.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from __future__ import absolute_import import sys import traceback import logbook from zuqa.base import Client from zuqa.utils import compat from zuqa.utils.encoding import to_unicode LOOKBOOK_LEVELS = { logbook.DEBUG: "debug", logbook.INFO: "info", logbook.NOTICE: "info", logbook.WARNING: "warning", logbook.ERROR: "error", logbook.CRITICAL: "fatal", } class LogbookHandler(logbook.Handler): def __init__(self, *args, **kwargs): if len(args) == 1: arg = args[0] # if isinstance(arg, compat.string_types): # self.client = kwargs.pop('client_cls', Client)(dsn=arg) if isinstance(arg, Client): self.client = arg else: raise ValueError( "The first argument to %s must be a Client instance, " "got %r instead." % (self.__class__.__name__, arg) ) args = [] else: try: self.client = kwargs.pop("client") except KeyError: raise TypeError("Expected keyword argument for LoggingHandler: client") super(LogbookHandler, self).__init__(*args, **kwargs) def emit(self, record): self.format(record) # Avoid typical config issues by overriding loggers behavior if record.channel.startswith("zuqa.errors"): sys.stderr.write(to_unicode(record.message + "\n")) return try: return self._emit(record) except Exception: sys.stderr.write("Top level ZUQA exception caught - failed creating log record.\n") sys.stderr.write(to_unicode(record.msg + "\n")) sys.stderr.write(to_unicode(traceback.format_exc() + "\n")) try: self.client.capture("Exception") except Exception: pass def _emit(self, record): # If there's no exception being processed, # exc_info may be a 3-tuple of None # http://docs.python.org/library/sys.html#sys.exc_info if record.exc_info is True or (record.exc_info and all(record.exc_info)): handler = self.client.get_handler("zuqa.events.Exception") exception = handler.capture(self.client, exc_info=record.exc_info) else: exception = None return self.client.capture_message( param_message={"message": compat.text_type(record.msg), "params": record.args}, exception=exception, level=LOOKBOOK_LEVELS[record.level], logger_name=record.channel, custom=record.extra, stack=record.kwargs.get("stack"), )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/handlers/logbook.py
logbook.py
# Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from __future__ import absolute_import from zuqa.traces import execution_context def structlog_processor(logger, method_name, event_dict): """ Add three new entries to the event_dict for any processed events: * transaction.id * trace.id * span.id Only adds non-None IDs. :param logger: Unused (logger instance in structlog) :param method_name: Unused (wrapped method_name) :param event_dict: Event dictionary for the event we're processing :return: `event_dict`, with three new entries. """ transaction = execution_context.get_transaction() if transaction: event_dict["transaction.id"] = transaction.id if transaction and transaction.trace_parent: event_dict["trace.id"] = transaction.trace_parent.trace_id span = execution_context.get_span() if span and span.id: event_dict["span.id"] = span.id return event_dict
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/handlers/structlog.py
structlog.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/handlers/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import threading from zuqa.instrumentation import register _lock = threading.Lock() def instrument(): """ Instruments all registered methods/functions with a wrapper """ with _lock: for obj in register.get_instrumentation_objects(): obj.instrument() def uninstrument(): """ If present, removes instrumentation and replaces it with the original method/function """ with _lock: for obj in register.get_instrumentation_objects(): obj.uninstrument()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/control.py
control.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys from zuqa.utils.module_import import import_string _cls_register = { "zuqa.instrumentation.packages.botocore.BotocoreInstrumentation", "zuqa.instrumentation.packages.jinja2.Jinja2Instrumentation", "zuqa.instrumentation.packages.psycopg2.Psycopg2Instrumentation", "zuqa.instrumentation.packages.psycopg2.Psycopg2ExtensionsInstrumentation", "zuqa.instrumentation.packages.mysql.MySQLInstrumentation", "zuqa.instrumentation.packages.mysql_connector.MySQLConnectorInstrumentation", "zuqa.instrumentation.packages.pymysql.PyMySQLConnectorInstrumentation", "zuqa.instrumentation.packages.pylibmc.PyLibMcInstrumentation", "zuqa.instrumentation.packages.pymongo.PyMongoInstrumentation", "zuqa.instrumentation.packages.pymongo.PyMongoBulkInstrumentation", "zuqa.instrumentation.packages.pymongo.PyMongoCursorInstrumentation", "zuqa.instrumentation.packages.python_memcached.PythonMemcachedInstrumentation", "zuqa.instrumentation.packages.pymemcache.PyMemcacheInstrumentation", "zuqa.instrumentation.packages.redis.RedisInstrumentation", "zuqa.instrumentation.packages.redis.RedisPipelineInstrumentation", "zuqa.instrumentation.packages.redis.RedisConnectionInstrumentation", "zuqa.instrumentation.packages.requests.RequestsInstrumentation", "zuqa.instrumentation.packages.sqlite.SQLiteInstrumentation", "zuqa.instrumentation.packages.urllib3.Urllib3Instrumentation", "zuqa.instrumentation.packages.elasticsearch.ElasticsearchConnectionInstrumentation", "zuqa.instrumentation.packages.elasticsearch.ElasticsearchInstrumentation", "zuqa.instrumentation.packages.cassandra.CassandraInstrumentation", "zuqa.instrumentation.packages.pymssql.PyMSSQLInstrumentation", "zuqa.instrumentation.packages.pyodbc.PyODBCInstrumentation", "zuqa.instrumentation.packages.django.template.DjangoTemplateInstrumentation", "zuqa.instrumentation.packages.django.template.DjangoTemplateSourceInstrumentation", "zuqa.instrumentation.packages.urllib.UrllibInstrumentation", } if sys.version_info >= (3, 5): _cls_register.update( [ "zuqa.instrumentation.packages.asyncio.sleep.AsyncIOSleepInstrumentation", "zuqa.instrumentation.packages.asyncio.aiohttp_client.AioHttpClientInstrumentation", "zuqa.instrumentation.packages.asyncio.elasticsearch.ElasticSearchAsyncConnection", "zuqa.instrumentation.packages.asyncio.aiopg.AioPGInstrumentation", "zuqa.instrumentation.packages.tornado.TornadoRequestExecuteInstrumentation", "zuqa.instrumentation.packages.tornado.TornadoHandleRequestExceptionInstrumentation", "zuqa.instrumentation.packages.tornado.TornadoRenderInstrumentation", ] ) def register(cls): _cls_register.add(cls) _instrumentation_singletons = {} def get_instrumentation_objects(): for cls_str in _cls_register: if cls_str not in _instrumentation_singletons: cls = import_string(cls_str) _instrumentation_singletons[cls_str] = cls() obj = _instrumentation_singletons[cls_str] yield obj
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/register.py
register.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Instrumentation for Tornado """ import zuqa from zuqa.conf import constants from zuqa.instrumentation.packages.asyncio.base import AbstractInstrumentedModule, AsyncAbstractInstrumentedModule from zuqa.traces import capture_span from zuqa.utils.disttracing import TraceParent class TornadoRequestExecuteInstrumentation(AsyncAbstractInstrumentedModule): name = "tornado_request_execute" creates_transactions = True instrument_list = [("tornado.web", "RequestHandler._execute")] async def call(self, module, method, wrapped, instance, args, kwargs): if not hasattr(instance.application, "zuqa_client"): # If tornado was instrumented but not as the main framework # (i.e. in Flower), we should skip it. return await wrapped(*args, **kwargs) # Late import to avoid ImportErrors from zuqa.contrib.tornado.utils import get_data_from_request, get_data_from_response request = instance.request trace_parent = TraceParent.from_headers(request.headers) client = instance.application.zuqa_client client.begin_transaction("request", trace_parent=trace_parent) zuqa.set_context( lambda: get_data_from_request(instance, request, client.config, constants.TRANSACTION), "request" ) # TODO: Can we somehow incorporate the routing rule itself here? zuqa.set_transaction_name("{} {}".format(request.method, type(instance).__name__), override=False) ret = await wrapped(*args, **kwargs) zuqa.set_context( lambda: get_data_from_response(instance, client.config, constants.TRANSACTION), "response" ) result = "HTTP {}xx".format(instance.get_status() // 100) zuqa.set_transaction_result(result, override=False) client.end_transaction() return ret class TornadoHandleRequestExceptionInstrumentation(AbstractInstrumentedModule): name = "tornado_handle_request_exception" instrument_list = [("tornado.web", "RequestHandler._handle_request_exception")] def call(self, module, method, wrapped, instance, args, kwargs): if not hasattr(instance.application, "zuqa_client"): # If tornado was instrumented but not as the main framework # (i.e. in Flower), we should skip it. return wrapped(*args, **kwargs) # Late import to avoid ImportErrors from tornado.web import Finish, HTTPError from zuqa.contrib.tornado.utils import get_data_from_request e = args[0] if isinstance(e, Finish): # Not an error; Finish is an exception that ends a request without an error response return wrapped(*args, **kwargs) client = instance.application.zuqa_client request = instance.request client.capture_exception( context={"request": get_data_from_request(instance, request, client.config, constants.ERROR)} ) if isinstance(e, HTTPError): zuqa.set_transaction_result("HTTP {}xx".format(int(e.status_code / 100)), override=False) zuqa.set_context({"status_code": e.status_code}, "response") else: zuqa.set_transaction_result("HTTP 5xx", override=False) zuqa.set_context({"status_code": 500}, "response") return wrapped(*args, **kwargs) class TornadoRenderInstrumentation(AbstractInstrumentedModule): name = "tornado_render" instrument_list = [("tornado.web", "RequestHandler.render")] def call(self, module, method, wrapped, instance, args, kwargs): if "template_name" in kwargs: name = kwargs["template_name"] else: name = args[0] with capture_span(name, span_type="template", span_subtype="tornado", span_action="render"): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/tornado.py
tornado.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.instrumentation.packages.dbapi2 import extract_signature from zuqa.traces import capture_span from zuqa.utils import compat class CassandraInstrumentation(AbstractInstrumentedModule): name = "cassandra" instrument_list = [("cassandra.cluster", "Session.execute"), ("cassandra.cluster", "Cluster.connect")] def call(self, module, method, wrapped, instance, args, kwargs): name = self.get_wrapped_name(wrapped, instance, method) context = {} if method == "Cluster.connect": span_action = "connect" if hasattr(instance, "contact_points_resolved"): # < cassandra-driver 3.18 host = instance.contact_points_resolved[0] port = instance.port else: host = instance.endpoints_resolved[0].address port = instance.endpoints_resolved[0].port else: hosts = list(instance.hosts) if hasattr(hosts[0], "endpoint"): host = hosts[0].endpoint.address port = hosts[0].endpoint.port else: # < cassandra-driver 3.18 host = hosts[0].address port = instance.cluster.port span_action = "query" query = args[0] if args else kwargs.get("query") if hasattr(query, "query_string"): query_str = query.query_string elif hasattr(query, "prepared_statement") and hasattr(query.prepared_statement, "query"): query_str = query.prepared_statement.query elif isinstance(query, compat.string_types): query_str = query else: query_str = None if query_str: name = extract_signature(query_str) context["db"] = {"type": "sql", "statement": query_str} context["destination"] = { "address": host, "port": port, "service": {"name": "cassandra", "resource": "cassandra", "type": "db"}, } with capture_span(name, span_type="db", span_subtype="cassandra", span_action=span_action, extra=context): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/cassandra.py
cassandra.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span, execution_context class Redis3CheckMixin(object): instrument_list_3 = [] instrument_list = [] def get_instrument_list(self): try: from redis import VERSION if VERSION[0] >= 3: return self.instrument_list_3 return self.instrument_list except ImportError: return self.instrument_list class RedisInstrumentation(Redis3CheckMixin, AbstractInstrumentedModule): name = "redis" # no need to instrument StrictRedis in redis-py >= 3.0 instrument_list_3 = [("redis.client", "Redis.execute_command")] instrument_list = [("redis.client", "Redis.execute_command"), ("redis.client", "StrictRedis.execute_command")] def call(self, module, method, wrapped, instance, args, kwargs): if len(args) > 0: wrapped_name = str(args[0]) else: wrapped_name = self.get_wrapped_name(wrapped, instance, method) with capture_span(wrapped_name, span_type="db", span_subtype="redis", span_action="query", leaf=True): return wrapped(*args, **kwargs) class RedisPipelineInstrumentation(Redis3CheckMixin, AbstractInstrumentedModule): name = "redis" # BasePipeline has been renamed to Pipeline in redis-py 3 instrument_list_3 = [("redis.client", "Pipeline.execute")] instrument_list = [("redis.client", "BasePipeline.execute")] def call(self, module, method, wrapped, instance, args, kwargs): wrapped_name = self.get_wrapped_name(wrapped, instance, method) with capture_span(wrapped_name, span_type="db", span_subtype="redis", span_action="query", leaf=True): return wrapped(*args, **kwargs) class RedisConnectionInstrumentation(AbstractInstrumentedModule): name = "redis" instrument_list = (("redis.connection", "Connection.send_packed_command"),) def call(self, module, method, wrapped, instance, args, kwargs): span = execution_context.get_span() if span and span.subtype == "redis": span.context["destination"] = get_destination_info(instance) return wrapped(*args, **kwargs) def get_destination_info(connection): destination_info = {"service": {"name": "redis", "resource": "redis", "type": "db"}} if hasattr(connection, "port"): destination_info["port"] = connection.port destination_info["address"] = connection.host elif hasattr(connection, "path"): destination_info["port"] = None destination_info["address"] = "unix://" + connection.path return destination_info
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/redis.py
redis.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span from zuqa.utils.compat import urlparse class BotocoreInstrumentation(AbstractInstrumentedModule): name = "botocore" instrument_list = [("botocore.client", "BaseClient._make_api_call")] def call(self, module, method, wrapped, instance, args, kwargs): if "operation_name" in kwargs: operation_name = kwargs["operation_name"] else: operation_name = args[0] target_endpoint = instance._endpoint.host parsed_url = urlparse.urlparse(target_endpoint) if "." in parsed_url.hostname: service = parsed_url.hostname.split(".", 2)[0] else: service = parsed_url.hostname signature = "{}:{}".format(service, operation_name) with capture_span(signature, "aws", leaf=True, span_subtype=service, span_action=operation_name): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/botocore.py
botocore.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) from zuqa.utils import default_ports class PyMSSQLCursorProxy(CursorProxy): provider_name = "pymssql" def extract_signature(self, sql): return extract_signature(sql) class PyMSSQLConnectionProxy(ConnectionProxy): cursor_proxy = PyMSSQLCursorProxy class PyMSSQLInstrumentation(DbApi2Instrumentation): name = "pymssql" instrument_list = [("pymssql", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): host, port = get_host_port(args, kwargs) destination_info = { "address": host, "port": port, "service": {"name": "mssql", "resource": "mssql", "type": "db"}, } return PyMSSQLConnectionProxy(wrapped(*args, **kwargs), destination_info=destination_info) def get_host_port(args, kwargs): host = args[0] if args else kwargs.get("server") port = None if not host: host = kwargs.get("host", "localhost") for sep in (",", ":"): if sep in host: host, port = host.rsplit(sep, 1) port = int(port) break if not port: port = int(kwargs.get("port", default_ports.get("mssql"))) return host, port
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pymssql.py
pymssql.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import import json import zuqa from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.utils import compat from zuqa.utils.logging import get_logger logger = get_logger("zuqa.instrument") API_METHOD_KEY_NAME = "__zuqa_api_method_name" BODY_REF_NAME = "__zuqa_body_ref" class ElasticSearchConnectionMixin(object): query_methods = ("Elasticsearch.search", "Elasticsearch.count", "Elasticsearch.delete_by_query") def get_signature(self, args, kwargs): args_len = len(args) http_method = args[0] if args_len else kwargs.get("method") http_path = args[1] if args_len > 1 else kwargs.get("url") return "ES %s %s" % (http_method, http_path) def get_context(self, instance, args, kwargs): args_len = len(args) params = args[2] if args_len > 2 else kwargs.get("params") body = params.pop(BODY_REF_NAME, None) if params else None api_method = params.pop(API_METHOD_KEY_NAME, None) if params else None context = {"db": {"type": "elasticsearch"}} if api_method in self.query_methods: query = [] # using both q AND body is allowed in some API endpoints / ES versions, # but not in others. We simply capture both if they are there so the # user can see it. if params and "q" in params: # 'q' is already encoded to a byte string at this point # we assume utf8, which is the default query.append("q=" + params["q"].decode("utf-8", errors="replace")) if isinstance(body, dict) and "query" in body: query.append(json.dumps(body["query"], default=compat.text_type)) if query: context["db"]["statement"] = "\n\n".join(query) elif api_method == "Elasticsearch.update": if isinstance(body, dict) and "script" in body: # only get the `script` field from the body context["db"]["statement"] = json.dumps({"script": body["script"]}) context["destination"] = { "address": instance.host, "service": {"name": "elasticsearch", "resource": "elasticsearch", "type": "db"}, } return context class ElasticsearchConnectionInstrumentation(ElasticSearchConnectionMixin, AbstractInstrumentedModule): name = "elasticsearch_connection" instrument_list = [ ("elasticsearch.connection.http_urllib3", "Urllib3HttpConnection.perform_request"), ("elasticsearch.connection.http_requests", "RequestsHttpConnection.perform_request"), ] def call(self, module, method, wrapped, instance, args, kwargs): signature = self.get_signature(args, kwargs) context = self.get_context(instance, args, kwargs) with zuqa.capture_span( signature, span_type="db", span_subtype="elasticsearch", span_action="query", extra=context, skip_frames=2, leaf=True, ): return wrapped(*args, **kwargs) class ElasticsearchInstrumentation(AbstractInstrumentedModule): name = "elasticsearch" instrument_list = [ ("elasticsearch.client", "Elasticsearch.delete_by_query"), ("elasticsearch.client", "Elasticsearch.search"), ("elasticsearch.client", "Elasticsearch.count"), ("elasticsearch.client", "Elasticsearch.update"), ] def __init__(self): super(ElasticsearchInstrumentation, self).__init__() try: from elasticsearch import VERSION self.version = VERSION[0] except ImportError: self.version = None def instrument(self): if self.version and not 2 <= self.version < 8: logger.debug("Instrumenting version %s of Elasticsearch is not supported by ZUQA", self.version) return super(ElasticsearchInstrumentation, self).instrument() def call(self, module, method, wrapped, instance, args, kwargs): params = kwargs.pop("params", {}) # make a copy of params in case the caller reuses them for some reason params = params.copy() if params is not None else {} cls_name, method_name = method.split(".", 1) # store a reference to the non-serialized body so we can use it in the connection layer body = kwargs.get("body") params[BODY_REF_NAME] = body params[API_METHOD_KEY_NAME] = method kwargs["params"] = params return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/elasticsearch.py
elasticsearch.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import functools import os from zuqa.traces import execution_context from zuqa.utils import wrapt from zuqa.utils.logging import get_logger logger = get_logger("zuqa.instrument") class ZuqaFunctionWrapper(wrapt.FunctionWrapper): # used to differentiate between our own function wrappers and 1st/3rd party wrappers pass class AbstractInstrumentedModule(object): """ This class is designed to reduce the amount of code required to instrument library functions using wrapt. Instrumentation modules inherit from this class and override pieces as needed. Only `name`, `instrumented_list`, and `call` are required in the inheriting class. The `instrument_list` is a list of (module, method) pairs that will be instrumented. The module/method need not be imported -- in fact, because instrumentation modules are all processed during the instrumentation process, lazy imports should be used in order to avoid ImportError exceptions. The `instrument()` method will be called for each InstrumentedModule listed in the instrument register (zuqa.instrumentation.register), and each method in the `instrument_list` will be wrapped (using wrapt) with the `call_if_sampling()` function, which (by default) will either call the wrapped function by itself, or pass it into `call()` to be called if there is a transaction active. For simple span-wrapping of instrumented libraries, a very simple InstrumentedModule might look like this:: from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class Jinja2Instrumentation(AbstractInstrumentedModule): name = "jinja2" instrument_list = [("jinja2", "Template.render")] def call(self, module, method, wrapped, instance, args, kwargs): signature = instance.name or instance.filename with capture_span(signature, span_type="template", span_subtype="jinja2", span_action="render"): return wrapped(*args, **kwargs) This class can also be used to instrument callables which are expected to create their own transactions (rather than spans within a transaction). In this case, set `creates_transaction = True` next to your `name` and `instrument_list`. This tells the instrumenting code to always wrap the method with `call()`, even if there is no transaction active. It is expected in this case that a new transaction will be created as part of your `call()` method. """ name = None mutates_unsampled_arguments = False creates_transactions = False instrument_list = [ # List of (module, method) pairs to instrument. E.g.: # ("requests.sessions", "Session.send"), ] def __init__(self): self.originals = {} self.instrumented = False assert self.name is not None def get_wrapped_name(self, wrapped, instance, fallback_method=None): wrapped_name = [] if hasattr(instance, "__class__") and hasattr(instance.__class__, "__name__"): wrapped_name.append(instance.__class__.__name__) if hasattr(wrapped, "__name__"): wrapped_name.append(wrapped.__name__) elif fallback_method: attribute = fallback_method.split(".") if len(attribute) == 2: wrapped_name.append(attribute[1]) return ".".join(wrapped_name) def get_instrument_list(self): return self.instrument_list def instrument(self): if self.instrumented: return skip_env_var = "SKIP_INSTRUMENT_" + str(self.name.upper()) if skip_env_var in os.environ: logger.debug("Skipping instrumentation of %s. %s is set.", self.name, skip_env_var) return try: instrument_list = self.get_instrument_list() skipped_modules = set() instrumented_methods = [] for module, method in instrument_list: try: # Skip modules we already failed to load if module in skipped_modules: continue # We jump through hoop here to get the original # `module`/`method` in the call to `call_if_sampling` parent, attribute, original = wrapt.resolve_path(module, method) if isinstance(original, ZuqaFunctionWrapper): logger.debug("%s.%s already instrumented, skipping", module, method) continue self.originals[(module, method)] = original wrapper = ZuqaFunctionWrapper( original, functools.partial(self.call_if_sampling, module, method) ) wrapt.apply_patch(parent, attribute, wrapper) instrumented_methods.append((module, method)) except ImportError: # Could not import module logger.debug("Skipping instrumentation of %s. Module %s not found", self.name, module) # Keep track of modules we couldn't load so we don't # try to instrument anything in that module again skipped_modules.add(module) except AttributeError as ex: # Could not find thing in module logger.debug("Skipping instrumentation of %s.%s: %s", module, method, ex) if instrumented_methods: logger.debug("Instrumented %s, %s", self.name, ", ".join(".".join(m) for m in instrumented_methods)) except ImportError as ex: logger.debug("Skipping instrumentation of %s. %s", self.name, ex) self.instrumented = True def uninstrument(self): if not self.instrumented or not self.originals: return uninstrumented_methods = [] for module, method in self.get_instrument_list(): if (module, method) in self.originals: parent, attribute, wrapper = wrapt.resolve_path(module, method) wrapt.apply_patch(parent, attribute, self.originals[(module, method)]) uninstrumented_methods.append((module, method)) if uninstrumented_methods: logger.debug("Uninstrumented %s, %s", self.name, ", ".join(".".join(m) for m in uninstrumented_methods)) self.instrumented = False self.originals = {} def call_if_sampling(self, module, method, wrapped, instance, args, kwargs): """ This is the function which will wrap the instrumented method/function. By default, will call the instrumented method/function, via `call()`, only if a transaction is active and sampled. This behavior can be overridden by setting `creates_transactions = True` at the class level. If `creates_transactions == False` and there's an active transaction with `transaction.is_sampled == False`, then the `mutate_unsampled_call_args()` method is called, and the resulting args and kwargs are passed into the wrapped function directly, not via `call()`. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations, even if we're not sampling the transaction. """ if self.creates_transactions: return self.call(module, method, wrapped, instance, args, kwargs) transaction = execution_context.get_transaction() if not transaction: return wrapped(*args, **kwargs) elif not transaction.is_sampled: args, kwargs = self.mutate_unsampled_call_args(module, method, wrapped, instance, args, kwargs, transaction) return wrapped(*args, **kwargs) else: return self.call(module, method, wrapped, instance, args, kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): """ Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations. :param module: :param method: :param wrapped: :param instance: :param args: :param kwargs: :param transaction: :return: """ return args, kwargs def call(self, module, method, wrapped, instance, args, kwargs): """ Wrapped call. This method should gather all necessary data, then call `wrapped` in a `capture_span` context manager. Note that by default this wrapper will only be used if a transaction is currently active. If you want the ability to create a transaction in your `call()` method, set `create_transactions = True` at the class level. :param module: Name of the wrapped module :param method: Name of the wrapped method/function :param wrapped: the wrapped method/function object :param instance: the wrapped instance :param args: arguments to the wrapped method/function :param kwargs: keyword arguments to the wrapped method/function :return: the result of calling the wrapped method/function """ raise NotImplementedError
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/base.py
base.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class PyMemcacheInstrumentation(AbstractInstrumentedModule): name = "pymemcache" method_list = [ "add", "append", "cas", "decr", "delete", "delete_many", "delete_multi", "flush_all", "get", "get_many", "get_multi", "gets", "gets_many", "incr", "prepend", "quit", "replace", "set", "set_many", "set_multi", "stats", "touch", ] def get_instrument_list(self): return ( [("pymemcache.client.base", "Client." + method) for method in self.method_list] + [("pymemcache.client.base", "PooledClient." + method) for method in self.method_list] + [("pymemcache.client.hash", "HashClient." + method) for method in self.method_list] ) def call(self, module, method, wrapped, instance, args, kwargs): name = self.get_wrapped_name(wrapped, instance, method) # Since HashClient uses Client/PooledClient for the actual calls, we # don't need to get address/port info for that class address, port = None, None if getattr(instance, "server", None): if isinstance(instance.server, (list, tuple)): # Address/port are a tuple address, port = instance.server else: # Server is a UNIX domain socket address = instance.server destination = { "address": address, "port": port, "service": {"name": "memcached", "resource": "memcached", "type": "cache"}, } if "PooledClient" in name: # PooledClient calls out to Client for the "work", but only once, # so we don't care about the "duplicate" spans from Client in that # case with capture_span( name, span_type="cache", span_subtype="memcached", span_action="query", extra={"destination": destination}, leaf=True, ): return wrapped(*args, **kwargs) else: with capture_span( name, span_type="cache", span_subtype="memcached", span_action="query", extra={"destination": destination}, ): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pymemcache.py
pymemcache.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) class PyMySQLCursorProxy(CursorProxy): provider_name = "mysql" def extract_signature(self, sql): return extract_signature(sql) class PyMySQLConnectionProxy(ConnectionProxy): cursor_proxy = PyMySQLCursorProxy class PyMySQLConnectorInstrumentation(DbApi2Instrumentation): name = "pymysql" instrument_list = [("pymysql", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): return PyMySQLConnectionProxy(wrapped(*args, **kwargs))
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pymysql.py
pymysql.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class Jinja2Instrumentation(AbstractInstrumentedModule): name = "jinja2" instrument_list = [("jinja2", "Template.render")] def call(self, module, method, wrapped, instance, args, kwargs): signature = instance.name or instance.filename with capture_span(signature, span_type="template", span_subtype="jinja2", span_action="render"): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/jinja2.py
jinja2.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) class PyODBCCursorProxy(CursorProxy): provider_name = "pyodbc" def extract_signature(self, sql): return extract_signature(sql) class PyODBCConnectionProxy(ConnectionProxy): cursor_proxy = PyODBCCursorProxy class PyODBCInstrumentation(DbApi2Instrumentation): name = "pyodbc" instrument_list = [("pyodbc", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): return PyODBCConnectionProxy(wrapped(*args, **kwargs))
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pyodbc.py
pyodbc.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span from zuqa.utils import get_host_from_url, sanitize_url, url_to_destination class RequestsInstrumentation(AbstractInstrumentedModule): name = "requests" instrument_list = [("requests.sessions", "Session.send")] def call(self, module, method, wrapped, instance, args, kwargs): if "request" in kwargs: request = kwargs["request"] else: request = args[0] signature = request.method.upper() signature += " " + get_host_from_url(request.url) url = sanitize_url(request.url) destination = url_to_destination(url) with capture_span( signature, span_type="external", span_subtype="http", extra={"http": {"url": url}, "destination": destination}, leaf=True, ): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/requests.py
requests.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Provides classes to instrument dbapi2 providers https://www.python.org/dev/peps/pep-0249/ """ import re from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span from zuqa.utils import compat, wrapt from zuqa.utils.encoding import force_text class Literal(object): def __init__(self, literal_type, content): self.literal_type = literal_type self.content = content def __eq__(self, other): return isinstance(other, Literal) and self.literal_type == other.literal_type and self.content == other.content def __repr__(self): return "<Literal {}{}{}>".format(self.literal_type, self.content, self.literal_type) def skip_to(start, tokens, value_sequence): i = start while i < len(tokens): for idx, token in enumerate(value_sequence): if tokens[i + idx] != token: break else: # Match return tokens[start : i + len(value_sequence)] i += 1 # Not found return None def look_for_table(sql, keyword): tokens = tokenize(sql) table_name = _scan_for_table_with_tokens(tokens, keyword) if isinstance(table_name, Literal): table_name = table_name.content.strip(table_name.literal_type) return table_name def _scan_for_table_with_tokens(tokens, keyword): seen_keyword = False for idx, lexeme in scan(tokens): if seen_keyword: if lexeme == "(": return _scan_for_table_with_tokens(tokens[idx:], keyword) else: return lexeme if isinstance(lexeme, compat.string_types) and lexeme.upper() == keyword: seen_keyword = True def tokenize(sql): # split on anything that is not a word character, excluding dots return [t for t in re.split(r"([^\w.])", sql) if t != ""] def scan(tokens): literal_start_idx = None literal_started = None prev_was_escape = False lexeme = [] i = 0 while i < len(tokens): token = tokens[i] if literal_start_idx: if prev_was_escape: prev_was_escape = False lexeme.append(token) else: if token == literal_started: if literal_started == "'" and len(tokens) > i + 1 and tokens[i + 1] == "'": # double quotes i += 1 lexeme.append("'") else: yield i, Literal(literal_started, "".join(lexeme)) literal_start_idx = None literal_started = None lexeme = [] else: if token == "\\": prev_was_escape = token else: prev_was_escape = False lexeme.append(token) elif literal_start_idx is None: if token in ["'", '"', "`"]: literal_start_idx = i literal_started = token elif token == "$": # Postgres can use arbitrary characters between two $'s as a # literal separation token, e.g.: $fish$ literal $fish$ # This part will detect that and skip over the literal. skipped_token = skip_to(i + 1, tokens, "$") if skipped_token is not None: dollar_token = ["$"] + skipped_token skipped = skip_to(i + len(dollar_token), tokens, dollar_token) if skipped: # end wasn't found. yield i, Literal("".join(dollar_token), "".join(skipped[: -len(dollar_token)])) i = i + len(skipped) + len(dollar_token) else: if token != " ": yield i, token i += 1 if lexeme: yield i, lexeme def extract_signature(sql): """ Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature """ sql = force_text(sql) sql = sql.strip() first_space = sql.find(" ") if first_space < 0: return sql second_space = sql.find(" ", first_space + 1) sql_type = sql[0:first_space].upper() if sql_type in ["INSERT", "DELETE"]: keyword = "INTO" if sql_type == "INSERT" else "FROM" sql_type = sql_type + " " + keyword table_name = look_for_table(sql, keyword) elif sql_type in ["CREATE", "DROP"]: # 2nd word is part of SQL type sql_type = sql_type + sql[first_space:second_space] table_name = "" elif sql_type == "UPDATE": table_name = look_for_table(sql, "UPDATE") elif sql_type == "SELECT": # Name is first table try: sql_type = "SELECT FROM" table_name = look_for_table(sql, "FROM") except Exception: table_name = "" else: # No name table_name = "" signature = " ".join(filter(bool, [sql_type, table_name])) return signature QUERY_ACTION = "query" EXEC_ACTION = "exec" class CursorProxy(wrapt.ObjectProxy): provider_name = None DML_QUERIES = ("INSERT", "DELETE", "UPDATE") def __init__(self, wrapped, destination_info=None): super(CursorProxy, self).__init__(wrapped) self._self_destination_info = destination_info def callproc(self, procname, params=None): return self._trace_sql(self.__wrapped__.callproc, procname, params, action=EXEC_ACTION) def execute(self, sql, params=None): return self._trace_sql(self.__wrapped__.execute, sql, params) def executemany(self, sql, param_list): return self._trace_sql(self.__wrapped__.executemany, sql, param_list) def _bake_sql(self, sql): """ Method to turn the "sql" argument into a string. Most database backends simply return the given object, as it is already a string """ return sql def _trace_sql(self, method, sql, params, action=QUERY_ACTION): sql_string = self._bake_sql(sql) if action == EXEC_ACTION: signature = sql_string + "()" else: signature = self.extract_signature(sql_string) with capture_span( signature, span_type="db", span_subtype=self.provider_name, span_action=action, extra={"db": {"type": "sql", "statement": sql_string}, "destination": self._self_destination_info}, skip_frames=1, ) as span: if params is None: result = method(sql) else: result = method(sql, params) # store "rows affected", but only for DML queries like insert/update/delete if span and self.rowcount not in (-1, None) and signature.startswith(self.DML_QUERIES): span.update_context("db", {"rows_affected": self.rowcount}) return result def extract_signature(self, sql): raise NotImplementedError() class ConnectionProxy(wrapt.ObjectProxy): cursor_proxy = CursorProxy def __init__(self, wrapped, destination_info=None): super(ConnectionProxy, self).__init__(wrapped) self._self_destination_info = destination_info def cursor(self, *args, **kwargs): return self.cursor_proxy(self.__wrapped__.cursor(*args, **kwargs), self._self_destination_info) class DbApi2Instrumentation(AbstractInstrumentedModule): connect_method = None def call(self, module, method, wrapped, instance, args, kwargs): return ConnectionProxy(wrapped(*args, **kwargs)) def call_if_sampling(self, module, method, wrapped, instance, args, kwargs): # Contrasting to the superclass implementation, we *always* want to # return a proxied connection, even if there is no ongoing zuqa # transaction yet. This ensures that we instrument the cursor once # the transaction started. return self.call(module, method, wrapped, instance, args, kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/dbapi2.py
dbapi2.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.conf import constants from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import DroppedSpan, capture_span, execution_context from zuqa.utils import default_ports, url_to_destination from zuqa.utils.disttracing import TracingOptions class Urllib3Instrumentation(AbstractInstrumentedModule): name = "urllib3" instrument_list = [ ("urllib3.connectionpool", "HTTPConnectionPool.urlopen"), # packages that vendor or vendored urllib3 in the past ("requests.packages.urllib3.connectionpool", "HTTPConnectionPool.urlopen"), ("botocore.vendored.requests.packages.urllib3.connectionpool", "HTTPConnectionPool.urlopen"), ] def call(self, module, method, wrapped, instance, args, kwargs): if "method" in kwargs: method = kwargs["method"] else: method = args[0] headers = None if "headers" in kwargs: headers = kwargs["headers"] if headers is None: headers = {} kwargs["headers"] = headers host = instance.host if instance.port != default_ports.get(instance.scheme): host += ":" + str(instance.port) if "url" in kwargs: url = kwargs["url"] else: url = args[1] signature = method.upper() + " " + host url = "%s://%s%s" % (instance.scheme, host, url) destination = url_to_destination(url) transaction = execution_context.get_transaction() with capture_span( signature, span_type="external", span_subtype="http", extra={"http": {"url": url}, "destination": destination}, leaf=True, ) as span: # if urllib3 has been called in a leaf span, this span might be a DroppedSpan. leaf_span = span while isinstance(leaf_span, DroppedSpan): leaf_span = leaf_span.parent if headers is not None: # It's possible that there are only dropped spans, e.g. if we started dropping spans. # In this case, the transaction.id is used parent_id = leaf_span.id if leaf_span else transaction.id trace_parent = transaction.trace_parent.copy_from( span_id=parent_id, trace_options=TracingOptions(recorded=True) ) self._set_disttracing_headers(headers, trace_parent, transaction) return wrapped(*args, **kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): # since we don't have a span, we set the span id to the transaction id trace_parent = transaction.trace_parent.copy_from( span_id=transaction.id, trace_options=TracingOptions(recorded=False) ) if "headers" in kwargs: headers = kwargs["headers"] if headers is None: headers = {} kwargs["headers"] = headers self._set_disttracing_headers(headers, trace_parent, transaction) return args, kwargs def _set_disttracing_headers(self, headers, trace_parent, transaction): trace_parent_str = trace_parent.to_string() headers[constants.TRACEPARENT_HEADER_NAME] = trace_parent_str if transaction.tracer.config.use_elastic_traceparent_header: headers[constants.TRACEPARENT_LEGACY_HEADER_NAME] = trace_parent_str if trace_parent.tracestate: headers[constants.TRACESTATE_HEADER_NAME] = trace_parent.tracestate
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/urllib3.py
urllib3.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) from zuqa.utils import default_ports class MySQLCursorProxy(CursorProxy): provider_name = "mysql" def extract_signature(self, sql): return extract_signature(sql) class MySQLConnectionProxy(ConnectionProxy): cursor_proxy = MySQLCursorProxy class MySQLConnectorInstrumentation(DbApi2Instrumentation): name = "mysql_connector" instrument_list = [("mysql.connector", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): destination_info = { "address": kwargs.get("host", "localhost"), "port": int(kwargs.get("port", default_ports.get("mysql"))), "service": {"name": "mysql", "resource": "mysql", "type": "db"}, } return MySQLConnectionProxy(wrapped(*args, **kwargs), destination_info=destination_info)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/mysql_connector.py
mysql_connector.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) from zuqa.traces import capture_span from zuqa.utils import compat, default_ports class PGCursorProxy(CursorProxy): provider_name = "postgresql" def _bake_sql(self, sql): # if this is a Composable object, use its `as_string` method # see http://initd.org/psycopg/docs/sql.html if hasattr(sql, "as_string"): return sql.as_string(self.__wrapped__) return sql def extract_signature(self, sql): return extract_signature(sql) def __enter__(self): return PGCursorProxy(self.__wrapped__.__enter__(), destination_info=self._self_destination_info) class PGConnectionProxy(ConnectionProxy): cursor_proxy = PGCursorProxy def __enter__(self): return PGConnectionProxy(self.__wrapped__.__enter__(), destination_info=self._self_destination_info) class Psycopg2Instrumentation(DbApi2Instrumentation): name = "psycopg2" instrument_list = [("psycopg2", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): signature = "psycopg2.connect" host = kwargs.get("host") if host: signature += " " + compat.text_type(host) port = kwargs.get("port") if port: port = str(port) if int(port) != default_ports.get("postgresql"): host += ":" + port signature += " " + compat.text_type(host) else: # Parse connection string and extract host/port pass destination_info = { "address": kwargs.get("host", "localhost"), "port": int(kwargs.get("port", default_ports.get("postgresql"))), "service": {"name": "postgresql", "resource": "postgresql", "type": "db"}, } with capture_span( signature, span_type="db", span_subtype="postgresql", span_action="connect", extra={"destination": destination_info}, ): return PGConnectionProxy(wrapped(*args, **kwargs), destination_info=destination_info) class Psycopg2ExtensionsInstrumentation(DbApi2Instrumentation): """ Some extensions do a type check on the Connection/Cursor in C-code, which our proxy fails. For these extensions, we need to ensure that the unwrapped Connection/Cursor is passed. """ name = "psycopg2" instrument_list = [ ("psycopg2.extensions", "register_type"), # specifically instrument `register_json` as it bypasses `register_type` ("psycopg2._json", "register_json"), ("psycopg2.extensions", "quote_ident"), ("psycopg2.extensions", "encrypt_password"), ] def call(self, module, method, wrapped, instance, args, kwargs): if "conn_or_curs" in kwargs and hasattr(kwargs["conn_or_curs"], "__wrapped__"): kwargs["conn_or_curs"] = kwargs["conn_or_curs"].__wrapped__ # register_type takes the connection as second argument elif len(args) == 2 and hasattr(args[1], "__wrapped__"): args = (args[0], args[1].__wrapped__) # register_json takes the connection as first argument, and can have # several more arguments elif method == "register_json": if args and hasattr(args[0], "__wrapped__"): args = (args[0].__wrapped__,) + args[1:] elif method == "encrypt_password": # connection/cursor is either 3rd argument, or "scope" keyword argument if len(args) >= 3 and hasattr(args[2], "__wrapped__"): args = args[:2] + (args[2].__wrapped__,) + args[3:] elif "scope" in kwargs and hasattr(kwargs["scope"], "__wrapped__"): kwargs["scope"] = kwargs["scope"].__wrapped__ return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/psycopg2.py
psycopg2.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.conf import constants from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import DroppedSpan, capture_span, execution_context from zuqa.utils import compat, default_ports, sanitize_url, url_to_destination from zuqa.utils.disttracing import TracingOptions # copied and adapted from urllib.request def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() parse_result = compat.urlparse.urlparse(url) scheme, host, port = parse_result.scheme, parse_result.hostname, parse_result.port try: port = int(port) except (ValueError, TypeError): pass if host == "": host = request.get_header("Host", "") if port and port != default_ports.get(scheme): host = "%s:%s" % (host, port) return host class UrllibInstrumentation(AbstractInstrumentedModule): name = "urllib" if compat.PY2: instrument_list = [("urllib2", "AbstractHTTPHandler.do_open")] else: instrument_list = [("urllib.request", "AbstractHTTPHandler.do_open")] def call(self, module, method, wrapped, instance, args, kwargs): request_object = args[1] if len(args) > 1 else kwargs["req"] method = request_object.get_method() host = request_host(request_object) url = sanitize_url(request_object.get_full_url()) destination = url_to_destination(url) signature = method.upper() + " " + host transaction = execution_context.get_transaction() with capture_span( signature, span_type="external", span_subtype="http", extra={"http": {"url": url}, "destination": destination}, leaf=True, ) as span: # if urllib has been called in a leaf span, this span might be a DroppedSpan. leaf_span = span while isinstance(leaf_span, DroppedSpan): leaf_span = leaf_span.parent parent_id = leaf_span.id if leaf_span else transaction.id trace_parent = transaction.trace_parent.copy_from( span_id=parent_id, trace_options=TracingOptions(recorded=True) ) self._set_disttracing_headers(request_object, trace_parent, transaction) return wrapped(*args, **kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): request_object = args[1] if len(args) > 1 else kwargs["req"] # since we don't have a span, we set the span id to the transaction id trace_parent = transaction.trace_parent.copy_from( span_id=transaction.id, trace_options=TracingOptions(recorded=False) ) self._set_disttracing_headers(request_object, trace_parent, transaction) return args, kwargs def _set_disttracing_headers(self, request_object, trace_parent, transaction): trace_parent_str = trace_parent.to_string() request_object.add_header(constants.TRACEPARENT_HEADER_NAME, trace_parent_str) if transaction.tracer.config.use_elastic_traceparent_header: request_object.add_header(constants.TRACEPARENT_LEGACY_HEADER_NAME, trace_parent_str) if trace_parent.tracestate: request_object.add_header(constants.TRACESTATE_HEADER_NAME, trace_parent.tracestate)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/urllib.py
urllib.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class ZLibInstrumentation(AbstractInstrumentedModule): name = "zlib" instrument_list = [("zlib", "compress"), ("zlib", "decompress")] def call(self, module, method, wrapped, instance, args, kwargs): wrapped_name = module + "." + method with capture_span(wrapped_name, span_type="compression", span_subtype="zlib"): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/zlib.py
zlib.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class PythonMemcachedInstrumentation(AbstractInstrumentedModule): name = "python_memcached" method_list = [ "add", "append", "cas", "decr", "delete", "delete_multi", "disconnect_all", "flush_all", "get", "get_multi", "get_slabs", "get_stats", "gets", "incr", "prepend", "replace", "set", "set_multi", "touch", ] # Took out 'set_servers', 'reset_cas', 'debuglog', 'check_key' and # 'forget_dead_hosts' because they involve no communication. def get_instrument_list(self): return [("memcache", "Client." + method) for method in self.method_list] def call(self, module, method, wrapped, instance, args, kwargs): name = self.get_wrapped_name(wrapped, instance, method) address, port = None, None if instance.servers: address, port = instance.servers[0].address destination = { "address": address, "port": port, "service": {"name": "memcached", "resource": "memcached", "type": "cache"}, } with capture_span( name, span_type="cache", span_subtype="memcached", span_action="query", extra={"destination": destination} ): return wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/python_memcached.py
python_memcached.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span try: from functools import lru_cache except ImportError: from cachetools.func import lru_cache class PyLibMcInstrumentation(AbstractInstrumentedModule): name = "pylibmc" instrument_list = [ ("pylibmc", "Client.get"), ("pylibmc", "Client.get_multi"), ("pylibmc", "Client.set"), ("pylibmc", "Client.set_multi"), ("pylibmc", "Client.add"), ("pylibmc", "Client.replace"), ("pylibmc", "Client.append"), ("pylibmc", "Client.prepend"), ("pylibmc", "Client.incr"), ("pylibmc", "Client.decr"), ("pylibmc", "Client.gets"), ("pylibmc", "Client.cas"), ("pylibmc", "Client.delete"), ("pylibmc", "Client.delete_multi"), ("pylibmc", "Client.touch"), ("pylibmc", "Client.get_stats"), ] def call(self, module, method, wrapped, instance, args, kwargs): wrapped_name = self.get_wrapped_name(wrapped, instance, method) address, port = get_address_port_from_instance(instance) destination = { "address": address, "port": port, "service": {"name": "memcached", "resource": "memcached", "type": "cache"}, } with capture_span( wrapped_name, span_type="cache", span_subtype="memcached", span_action="query", extra={"destination": destination}, ): return wrapped(*args, **kwargs) @lru_cache(10) def get_address_port_from_instance(instance): address, port = None, None if instance.addresses: first_address = instance.addresses[0] if ":" in first_address: address, port = first_address.split(":", 1) try: port = int(port) except ValueError: port = None return address, port
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pylibmc.py
pylibmc.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) from zuqa.traces import capture_span class SQLiteCursorProxy(CursorProxy): provider_name = "sqlite" def extract_signature(self, sql): return extract_signature(sql) class SQLiteConnectionProxy(ConnectionProxy): cursor_proxy = SQLiteCursorProxy # we need to implement wrappers for the non-standard Connection.execute and # Connection.executemany methods def _trace_sql(self, method, sql, params): signature = extract_signature(sql) with capture_span( signature, span_type="db", span_subtype="sqlite", span_action="query", extra={"db": {"type": "sql", "statement": sql}}, ): if params is None: return method(sql) else: return method(sql, params) def execute(self, sql, params=None): return self._trace_sql(self.__wrapped__.execute, sql, params) def executemany(self, sql, params=None): return self._trace_sql(self.__wrapped__.executemany, sql, params) class SQLiteInstrumentation(DbApi2Instrumentation): name = "sqlite" instrument_list = [("sqlite3", "connect"), ("sqlite3.dbapi2", "connect"), ("pysqlite2.dbapi2", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): signature = ".".join([module, method]) if len(args) == 1: signature += " " + str(args[0]) with capture_span(signature, span_type="db", span_subtype="sqlite", span_action="connect"): return SQLiteConnectionProxy(wrapped(*args, **kwargs))
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/sqlite.py
sqlite.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class PyMongoInstrumentation(AbstractInstrumentedModule): name = "pymongo" instrument_list = [ ("pymongo.collection", "Collection.aggregate"), ("pymongo.collection", "Collection.bulk_write"), ("pymongo.collection", "Collection.count"), ("pymongo.collection", "Collection.create_index"), ("pymongo.collection", "Collection.create_indexes"), ("pymongo.collection", "Collection.delete_many"), ("pymongo.collection", "Collection.delete_one"), ("pymongo.collection", "Collection.distinct"), ("pymongo.collection", "Collection.drop"), ("pymongo.collection", "Collection.drop_index"), ("pymongo.collection", "Collection.drop_indexes"), ("pymongo.collection", "Collection.ensure_index"), ("pymongo.collection", "Collection.find_and_modify"), ("pymongo.collection", "Collection.find_one"), ("pymongo.collection", "Collection.find_one_and_delete"), ("pymongo.collection", "Collection.find_one_and_replace"), ("pymongo.collection", "Collection.find_one_and_update"), ("pymongo.collection", "Collection.group"), ("pymongo.collection", "Collection.inline_map_reduce"), ("pymongo.collection", "Collection.insert"), ("pymongo.collection", "Collection.insert_many"), ("pymongo.collection", "Collection.insert_one"), ("pymongo.collection", "Collection.map_reduce"), ("pymongo.collection", "Collection.reindex"), ("pymongo.collection", "Collection.remove"), ("pymongo.collection", "Collection.rename"), ("pymongo.collection", "Collection.replace_one"), ("pymongo.collection", "Collection.save"), ("pymongo.collection", "Collection.update"), ("pymongo.collection", "Collection.update_many"), ("pymongo.collection", "Collection.update_one"), ] def call(self, module, method, wrapped, instance, args, kwargs): cls_name, method_name = method.split(".", 1) signature = ".".join([instance.full_name, method_name]) nodes = instance.database.client.nodes if nodes: host, port = list(nodes)[0] else: host, port = None, None destination_info = { "address": host, "port": port, "service": {"name": "mongodb", "resource": "mongodb", "type": "db"}, } with capture_span( signature, span_type="db", span_subtype="mongodb", span_action="query", leaf=True, extra={"destination": destination_info}, ): return wrapped(*args, **kwargs) class PyMongoBulkInstrumentation(AbstractInstrumentedModule): name = "pymongo" instrument_list = [("pymongo.bulk", "BulkOperationBuilder.execute")] def call(self, module, method, wrapped, instance, args, kwargs): collection = instance._BulkOperationBuilder__bulk.collection signature = ".".join([collection.full_name, "bulk.execute"]) with capture_span( signature, span_type="db", span_subtype="mongodb", span_action="query", extra={"destination": {"service": {"name": "mongodb", "resource": "mongodb", "type": "db"}}}, ): return wrapped(*args, **kwargs) class PyMongoCursorInstrumentation(AbstractInstrumentedModule): name = "pymongo" instrument_list = [("pymongo.cursor", "Cursor._refresh")] def call(self, module, method, wrapped, instance, args, kwargs): collection = instance.collection signature = ".".join([collection.full_name, "cursor.refresh"]) with capture_span( signature, span_type="db", span_subtype="mongodb", span_action="query", extra={"destination": {"service": {"name": "mongodb", "resource": "mongodb", "type": "db"}}}, ) as span: response = wrapped(*args, **kwargs) if span.context and instance.address: host, port = instance.address span.context["destination"]["address"] = host span.context["destination"]["port"] = port else: pass return response
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/pymongo.py
pymongo.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.dbapi2 import ( ConnectionProxy, CursorProxy, DbApi2Instrumentation, extract_signature, ) from zuqa.utils import default_ports class MySQLCursorProxy(CursorProxy): provider_name = "mysql" def extract_signature(self, sql): return extract_signature(sql) class MySQLConnectionProxy(ConnectionProxy): cursor_proxy = MySQLCursorProxy class MySQLInstrumentation(DbApi2Instrumentation): name = "mysql" instrument_list = [("MySQLdb", "connect")] def call(self, module, method, wrapped, instance, args, kwargs): destination_info = { "address": args[0] if len(args) else kwargs.get("host", "localhost"), "port": args[4] if len(args) > 4 else int(kwargs.get("port", default_ports.get("mysql"))), "service": {"name": "mysql", "resource": "mysql", "type": "db"}, } return MySQLConnectionProxy(wrapped(*args, **kwargs), destination_info=destination_info)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/mysql.py
mysql.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule from zuqa.traces import capture_span class DjangoTemplateInstrumentation(AbstractInstrumentedModule): name = "django_template" instrument_list = [("django.template", "Template.render")] def call(self, module, method, wrapped, instance, args, kwargs): name = getattr(instance, "name", None) if not name: name = "<template string>" with capture_span(name, span_type="template", span_subtype="django", span_action="render"): return wrapped(*args, **kwargs) class DjangoTemplateSourceInstrumentation(AbstractInstrumentedModule): name = "django_template_source" instrument_list = [("django.template.base", "Parser.extend_nodelist")] def call(self, module, method, wrapped, instance, args, kwargs): ret = wrapped(*args, **kwargs) if len(args) > 1: node = args[1] elif "node" in kwargs: node = kwargs["node"] else: return ret if len(args) > 2: token = args[2] elif "token" in kwargs: token = kwargs["token"] else: return ret if not hasattr(node, "token") and hasattr(token, "lineno"): node.token = token return ret
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/django/template.py
template.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/django/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.contrib.asyncio.traces import async_capture_span from zuqa.instrumentation.packages.asyncio.base import AsyncAbstractInstrumentedModule class AsyncIOSleepInstrumentation(AsyncAbstractInstrumentedModule): name = "asyncio_sleep" instrument_list = [("asyncio.tasks", "sleep")] async def call(self, module, method, wrapped, instance, args, kwargs): async with async_capture_span("asyncio.sleep", leaf=True, span_type="task", span_subtype="sleep"): return await wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/asyncio/sleep.py
sleep.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import zuqa from zuqa.instrumentation.packages.asyncio.base import AsyncAbstractInstrumentedModule from zuqa.instrumentation.packages.elasticsearch import ElasticSearchConnectionMixin class ElasticSearchAsyncConnection(ElasticSearchConnectionMixin, AsyncAbstractInstrumentedModule): name = "elasticsearch_connection" instrument_list = [("elasticsearch_async.connection", "AIOHttpConnection.perform_request")] async def call(self, module, method, wrapped, instance, args, kwargs): signature = self.get_signature(args, kwargs) context = self.get_context(instance, args, kwargs) async with zuqa.async_capture_span( signature, span_type="db", span_subtype="elasticsearch", span_action="query", extra=context, skip_frames=2, leaf=True, ): return await wrapped(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/asyncio/elasticsearch.py
elasticsearch.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.instrumentation.packages.base import AbstractInstrumentedModule class AsyncAbstractInstrumentedModule(AbstractInstrumentedModule): async def call(self, module, method, wrapped, instance, args, kwargs): raise NotImplementedError()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/asyncio/base.py
base.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.contrib.asyncio.traces import async_capture_span from zuqa.instrumentation.packages.asyncio.base import AsyncAbstractInstrumentedModule from zuqa.instrumentation.packages.dbapi2 import extract_signature class AioPGInstrumentation(AsyncAbstractInstrumentedModule): name = "aiopg" instrument_list = [("aiopg.cursor", "Cursor.execute"), ("aiopg.cursor", "Cursor.callproc")] async def call(self, module, method, wrapped, instance, args, kwargs): if method == "Cursor.execute": query = args[0] if len(args) else kwargs["operation"] query = _bake_sql(instance.raw, query) name = extract_signature(query) context = {"db": {"type": "sql", "statement": query}} action = "query" elif method == "Cursor.callproc": func = args[0] if len(args) else kwargs["procname"] name = func + "()" context = None action = "exec" else: raise AssertionError("call from uninstrumented method") async with async_capture_span( name, leaf=True, span_type="db", span_subtype="postgres", span_action=action, extra=context ): return await wrapped(*args, **kwargs) def _bake_sql(cursor, sql): # if this is a Composable object, use its `as_string` method # see http://initd.org/psycopg/docs/sql.html if hasattr(sql, "as_string"): return sql.as_string(cursor) return sql
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/asyncio/aiopg.py
aiopg.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa import async_capture_span from zuqa.conf import constants from zuqa.instrumentation.packages.asyncio.base import AsyncAbstractInstrumentedModule from zuqa.traces import DroppedSpan, execution_context from zuqa.utils import get_host_from_url, sanitize_url, url_to_destination from zuqa.utils.disttracing import TracingOptions class AioHttpClientInstrumentation(AsyncAbstractInstrumentedModule): name = "aiohttp_client" instrument_list = [("aiohttp.client", "ClientSession._request")] async def call(self, module, method, wrapped, instance, args, kwargs): method = kwargs["method"] if "method" in kwargs else args[0] url = kwargs["url"] if "url" in kwargs else args[1] url = str(url) destination = url_to_destination(url) signature = " ".join([method.upper(), get_host_from_url(url)]) url = sanitize_url(url) transaction = execution_context.get_transaction() async with async_capture_span( signature, span_type="external", span_subtype="http", extra={"http": {"url": url}, "destination": destination}, leaf=True, ) as span: leaf_span = span while isinstance(leaf_span, DroppedSpan): leaf_span = leaf_span.parent parent_id = leaf_span.id if leaf_span else transaction.id trace_parent = transaction.trace_parent.copy_from( span_id=parent_id, trace_options=TracingOptions(recorded=True) ) headers = kwargs.get("headers") or {} self._set_disttracing_headers(headers, trace_parent, transaction) kwargs["headers"] = headers return await wrapped(*args, **kwargs) def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): # since we don't have a span, we set the span id to the transaction id trace_parent = transaction.trace_parent.copy_from( span_id=transaction.id, trace_options=TracingOptions(recorded=False) ) headers = kwargs.get("headers") or {} self._set_disttracing_headers(headers, trace_parent, transaction) kwargs["headers"] = headers return args, kwargs def _set_disttracing_headers(self, headers, trace_parent, transaction): trace_parent_str = trace_parent.to_string() headers[constants.TRACEPARENT_HEADER_NAME] = trace_parent_str if transaction.tracer.config.use_elastic_traceparent_header: headers[constants.TRACEPARENT_LEGACY_HEADER_NAME] = trace_parent_str if trace_parent.tracestate: headers[constants.TRACESTATE_HEADER_NAME] = trace_parent.tracestate
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/asyncio/aiohttp_client.py
aiohttp_client.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/instrumentation/packages/asyncio/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import warnings from zuqa.transport.http import AsyncTransport as AsyncUrllib3Transport # noqa F401 from zuqa.transport.http import Transport as Urllib3Transport # noqa F401 warnings.warn( "The zuqa.transport.http_urllib3 module has been renamed to zuqa.transport.http", DeprecationWarning )
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/http_urllib3.py
http_urllib3.py
# -*- coding: utf-8 -*- # BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import hashlib import re import ssl import certifi import urllib3 from urllib3.exceptions import MaxRetryError, TimeoutError from zuqa.transport.base import TransportException from zuqa.transport.http_base import HTTPTransportBase from zuqa.utils import compat, json_encoder, read_pem_file from zuqa.utils.logging import get_logger logger = get_logger("zuqa.transport.http") class Transport(HTTPTransportBase): def __init__(self, url, *args, **kwargs): super(Transport, self).__init__(url, *args, **kwargs) url_parts = compat.urlparse.urlparse(url) pool_kwargs = {"cert_reqs": "CERT_REQUIRED", "ca_certs": certifi.where(), "block": True} if self._server_cert and url_parts.scheme != "http": pool_kwargs.update( {"assert_fingerprint": self.cert_fingerprint, "assert_hostname": False, "cert_reqs": ssl.CERT_NONE} ) del pool_kwargs["ca_certs"] elif not self._verify_server_cert and url_parts.scheme != "http": pool_kwargs["cert_reqs"] = ssl.CERT_NONE pool_kwargs["assert_hostname"] = False proxies = compat.getproxies_environment() proxy_url = proxies.get("https", proxies.get("http", None)) if proxy_url and not compat.proxy_bypass_environment(url_parts.netloc): self.http = urllib3.ProxyManager(proxy_url, **pool_kwargs) else: self.http = urllib3.PoolManager(**pool_kwargs) def send(self, data): response = None headers = self._headers.copy() if self._headers else {} headers.update(self.auth_headers) if compat.PY2 and isinstance(self._url, compat.text_type): url = self._url.encode("utf-8") else: url = self._url try: try: response = self.http.urlopen( "POST", url, body=data, headers=headers, timeout=self._timeout, preload_content=False ) logger.debug("Sent request, url=%s size=%.2fkb status=%s", url, len(data) / 1024.0, response.status) except Exception as e: print_trace = True if isinstance(e, MaxRetryError) and isinstance(e.reason, TimeoutError): message = "Connection to APM Server timed out " "(url: %s, timeout: %s seconds)" % ( self._url, self._timeout, ) print_trace = False else: message = "Unable to reach APM Server: %s (url: %s)" % (e, self._url) raise TransportException(message, data, print_trace=print_trace) body = response.read() if response.status >= 400: if response.status == 429: # rate-limited message = "Temporarily rate limited: " print_trace = False else: message = "HTTP %s: " % response.status print_trace = True message += body.decode("utf8", errors="replace") raise TransportException(message, data, print_trace=print_trace) return response.getheader("Location") finally: if response: response.close() def get_config(self, current_version=None, keys=None): """ Gets configuration from a remote APM Server :param current_version: version of the current configuration :param keys: a JSON-serializable dict to identify this instance, e.g. { "service": { "name": "foo", "environment": "bar" } } :return: a three-tuple of new version, config dictionary and validity in seconds. Any element of the tuple can be None. """ url = self._config_url data = json_encoder.dumps(keys).encode("utf-8") headers = self._headers.copy() headers[b"Content-Type"] = "application/json" headers.pop(b"Content-Encoding", None) # remove gzip content-encoding header headers.update(self.auth_headers) max_age = 300 if current_version: headers["If-None-Match"] = current_version try: response = self.http.urlopen( "POST", url, body=data, headers=headers, timeout=self._timeout, preload_content=False ) except (urllib3.exceptions.RequestError, urllib3.exceptions.HTTPError) as e: logger.debug("HTTP error while fetching remote config: %s", compat.text_type(e)) return current_version, None, max_age body = response.read() if "Cache-Control" in response.headers: try: max_age = int(next(re.finditer(r"max-age=(\d+)", response.headers["Cache-Control"])).groups()[0]) except StopIteration: logger.debug("Could not parse Cache-Control header: %s", response.headers["Cache-Control"]) if response.status == 304: # config is unchanged, return logger.debug("Configuration unchanged") return current_version, None, max_age elif response.status >= 400: return None, None, max_age if not body: logger.debug("APM Server answered with empty body and status code %s", response.status) return current_version, None, max_age return response.headers.get("Etag"), json_encoder.loads(body.decode("utf-8")), max_age @property def cert_fingerprint(self): if self._server_cert: with open(self._server_cert, "rb") as f: cert_data = read_pem_file(f) digest = hashlib.sha256() digest.update(cert_data) return digest.hexdigest() return None @property def auth_headers(self): headers = super(Transport, self).auth_headers return {k.encode("ascii"): v.encode("ascii") for k, v in compat.iteritems(headers)} # left for backwards compatibility AsyncTransport = Transport
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/http.py
http.py
# -*- coding: utf-8 -*- # BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.conf import constants from zuqa.transport.base import Transport from zuqa.utils import compat class HTTPTransportBase(Transport): def __init__( self, url, client, verify_server_cert=True, compress_level=5, metadata=None, headers=None, timeout=None, server_cert=None, **kwargs ): self._url = url self._verify_server_cert = verify_server_cert self._server_cert = server_cert self._timeout = timeout self._headers = { k.encode("ascii") if isinstance(k, compat.text_type) else k: v.encode("ascii") if isinstance(v, compat.text_type) else v for k, v in (headers if headers is not None else {}).items() } base, sep, tail = self._url.rpartition(constants.EVENTS_API_PATH) self._config_url = "".join((base, constants.AGENT_CONFIG_PATH, tail)) super(HTTPTransportBase, self).__init__(client, metadata=metadata, compress_level=compress_level, **kwargs) def send(self, data): """ Sends a request to a remote APM Server using HTTP POST. Returns the shortcut URL of the recorded error on ZUQA """ raise NotImplementedError() def get_config(self, current_version=None, keys=None): """ Gets configuration from a remote APM Server :param current_version: version of the current configuration :param keys: a JSON-serializable dict to identify this instance, e.g. { "service": { "name": "foo", "environment": "bar" } } :return: a three-tuple of new version, config dictionary and validity in seconds. Any element of the tuple can be None. """ raise NotImplementedError() @property def auth_headers(self): if self.client.config.api_key: return {"Authorization": "ApiKey " + self.client.config.api_key} elif self.client.config.secret_token: return {"Authorization": "Bearer " + self.client.config.secret_token} return {} # left for backwards compatibility AsyncHTTPTransportBase = HTTPTransportBase
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/http_base.py
http_base.py
# -*- coding: utf-8 -*- # BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import gzip import os import random import threading import time import timeit from collections import defaultdict from zuqa.utils import compat, json_encoder from zuqa.utils.logging import get_logger from zuqa.utils.threading import ThreadManager logger = get_logger("zuqa.transport") class TransportException(Exception): def __init__(self, message, data=None, print_trace=True): super(TransportException, self).__init__(message) self.data = data self.print_trace = print_trace class Transport(ThreadManager): """ All transport implementations need to subclass this class You must implement a send method.. """ async_mode = False def __init__( self, client, metadata=None, compress_level=5, json_serializer=json_encoder.dumps, queue_chill_count=500, queue_chill_time=1.0, processors=None, **kwargs ): """ Create a new Transport instance :param metadata: Metadata object to prepend to every queue :param compress_level: GZip compress level. If zero, no GZip compression will be used :param json_serializer: serializer to use for JSON encoding :param kwargs: """ self.client = client self.state = TransportState() self._metadata = metadata if metadata is not None else {} self._compress_level = min(9, max(0, compress_level if compress_level is not None else 0)) self._json_serializer = json_serializer self._queued_data = None self._event_queue = self._init_event_queue(chill_until=queue_chill_count, max_chill_time=queue_chill_time) self._is_chilled_queue = isinstance(self._event_queue, ChilledQueue) self._thread = None self._last_flush = timeit.default_timer() self._counts = defaultdict(int) self._flushed = threading.Event() self._closed = False self._processors = processors if processors is not None else [] super(Transport, self).__init__() @property def _max_flush_time(self): return self.client.config.api_request_time / 1000.0 if self.client else None @property def _max_buffer_size(self): return self.client.config.api_request_size if self.client else None def queue(self, event_type, data, flush=False): try: self._flushed.clear() kwargs = {"chill": not (event_type == "close" or flush)} if self._is_chilled_queue else {} self._event_queue.put((event_type, data, flush), block=False, **kwargs) except compat.queue.Full: logger.debug("Event of type %s dropped due to full event queue", event_type) def _process_queue(self): buffer = self._init_buffer() buffer_written = False # add some randomness to timeout to avoid stampedes of several workers that are booted at the same time max_flush_time = self._max_flush_time * random.uniform(0.9, 1.1) if self._max_flush_time else None while True: since_last_flush = timeit.default_timer() - self._last_flush # take max flush time into account to calculate timeout timeout = max(0, max_flush_time - since_last_flush) if max_flush_time else None timed_out = False try: event_type, data, flush = self._event_queue.get(block=True, timeout=timeout) except compat.queue.Empty: event_type, data, flush = None, None, None timed_out = True if event_type == "close": if buffer_written: self._flush(buffer) self._flushed.set() return # time to go home! if data is not None: data = self._process_event(event_type, data) if data is not None: buffer.write((self._json_serializer({event_type: data}) + "\n").encode("utf-8")) buffer_written = True self._counts[event_type] += 1 queue_size = 0 if buffer.fileobj is None else buffer.fileobj.tell() if flush: logger.debug("forced flush") elif timed_out or timeout == 0: # update last flush time, as we might have waited for a non trivial amount of time in # _event_queue.get() since_last_flush = timeit.default_timer() - self._last_flush logger.debug( "flushing due to time since last flush %.3fs > max_flush_time %.3fs", since_last_flush, max_flush_time, ) flush = True elif self._max_buffer_size and queue_size > self._max_buffer_size: logger.debug( "flushing since queue size %d bytes > max_queue_size %d bytes", queue_size, self._max_buffer_size ) flush = True if flush: if buffer_written: self._flush(buffer) self._last_flush = timeit.default_timer() buffer = self._init_buffer() buffer_written = False max_flush_time = self._max_flush_time * random.uniform(0.9, 1.1) if self._max_flush_time else None self._flushed.set() def _process_event(self, event_type, data): # Run the data through processors for processor in self._processors: if not hasattr(processor, "event_types") or event_type in processor.event_types: data = processor(self, data) if not data: logger.debug( "Dropped event of type %s due to processor %s.%s", event_type, getattr(processor, "__module__"), getattr(processor, "__name__"), ) return None return data def _init_buffer(self): buffer = gzip.GzipFile(fileobj=compat.BytesIO(), mode="w", compresslevel=self._compress_level) data = (self._json_serializer({"metadata": self._metadata}) + "\n").encode("utf-8") buffer.write(data) return buffer def _init_event_queue(self, chill_until, max_chill_time): # some libraries like eventlet monkeypatch queue.Queue and switch out the implementation. # In those cases we can't rely on internals of queue.Queue to be there, so we simply use # their queue and forgo the optimizations of ChilledQueue. In the case of eventlet, this # isn't really a loss, because the main reason for ChilledQueue (avoiding context switches # due to the event processor thread being woken up all the time) is not an issue. if all( ( hasattr(compat.queue.Queue, "not_full"), hasattr(compat.queue.Queue, "not_empty"), hasattr(compat.queue.Queue, "unfinished_tasks"), ) ): return ChilledQueue(maxsize=10000, chill_until=chill_until, max_chill_time=max_chill_time) else: return compat.queue.Queue(maxsize=10000) def _flush(self, buffer): """ Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None """ if not self.state.should_try(): logger.error("dropping flushed data due to transport failure back-off") else: fileobj = buffer.fileobj # get a reference to the fileobj before closing the gzip file buffer.close() # StringIO on Python 2 does not have getbuffer, so we need to fall back to getvalue data = fileobj.getbuffer() if hasattr(fileobj, "getbuffer") else fileobj.getvalue() try: self.send(data) self.handle_transport_success() except Exception as e: self.handle_transport_fail(e) def start_thread(self, pid=None): super(Transport, self).start_thread(pid=pid) if (not self._thread or self.pid != self._thread.pid) and not self._closed: try: self._thread = threading.Thread(target=self._process_queue, name="eapm event processor thread") self._thread.daemon = True self._thread.pid = self.pid self._thread.start() except RuntimeError: pass def send(self, data): """ You need to override this to do something with the actual data. Usually - this is sending to a server """ raise NotImplementedError def close(self): """ Cleans up resources and closes connection :return: """ if self._closed or (not self._thread or self._thread.pid != os.getpid()): return self._closed = True self.queue("close", None) if not self._flushed.wait(timeout=self._max_flush_time): raise ValueError("close timed out") stop_thread = close def flush(self): """ Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed. """ self.queue(None, None, flush=True) if not self._flushed.wait(timeout=self._max_flush_time): raise ValueError("flush timed out") def handle_transport_success(self, **kwargs): """ Success handler called by the transport on successful send """ self.state.set_success() def handle_transport_fail(self, exception=None, **kwargs): """ Failure handler called by the transport on send failure """ message = str(exception) logger.error("Failed to submit message: %r", message, exc_info=getattr(exception, "print_trace", True)) self.state.set_fail() # left for backwards compatibility AsyncTransport = Transport class TransportState(object): ONLINE = 1 ERROR = 0 def __init__(self): self.status = self.ONLINE self.last_check = None self.retry_number = -1 def should_try(self): if self.status == self.ONLINE: return True interval = min(self.retry_number, 6) ** 2 return timeit.default_timer() - self.last_check > interval def set_fail(self): self.status = self.ERROR self.retry_number += 1 self.last_check = timeit.default_timer() def set_success(self): self.status = self.ONLINE self.last_check = None self.retry_number = -1 def did_fail(self): return self.status == self.ERROR class ChilledQueue(compat.queue.Queue, object): """ A queue subclass that is a bit more chill about how often it notifies the not empty event Note: we inherit from object because queue.Queue is an old-style class in Python 2. This can be removed once we stop support for Python 2 """ def __init__(self, maxsize=0, chill_until=100, max_chill_time=1.0): self._chill_until = chill_until self._max_chill_time = max_chill_time self._last_unchill = time.time() super(ChilledQueue, self).__init__(maxsize=maxsize) def put(self, item, block=True, timeout=None, chill=True): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). """ with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise compat.queue.Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time.time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time.time() if remaining <= 0.0: raise compat.queue.Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 if ( not chill or self._qsize() > self._chill_until or (time.time() - self._last_unchill) > self._max_chill_time ): self.not_empty.notify() self._last_unchill = time.time()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/base.py
base.py
# -*- coding: utf-8 -*- # BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/__init__.py
__init__.py
# -*- coding: utf-8 -*- # BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class InvalidScheme(ValueError): """ Raised when a transport is constructed using a URI which is not handled by the transport """ class DuplicateScheme(Exception): """ Raised when registering a handler for a particular scheme which is already registered """ pass
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/transport/exceptions.py
exceptions.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import import contextvars from zuqa.context.base import BaseContext class ContextVarsContext(BaseContext): zuqa_transaction_var = contextvars.ContextVar("zuqa_transaction_var") zuqa_span_var = contextvars.ContextVar("zuqa_span_var") def get_transaction(self, clear=False): try: transaction = self.zuqa_transaction_var.get() if clear: self.set_transaction(None) return transaction except LookupError: return None def set_transaction(self, transaction): self.zuqa_transaction_var.set(transaction) def get_span(self): try: return self.zuqa_span_var.get() except LookupError: return None def set_span(self, span): self.zuqa_span_var.set(span) execution_context = ContextVarsContext()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/context/contextvars.py
contextvars.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import threading from zuqa.context.base import BaseContext class ThreadLocalContext(BaseContext): thread_local = threading.local() thread_local.transaction = None thread_local.span = None def get_transaction(self, clear=False): """ Get the transaction registered for the current thread. :return: :rtype: Transaction """ transaction = getattr(self.thread_local, "transaction", None) if clear: self.thread_local.transaction = None return transaction def set_transaction(self, transaction): self.thread_local.transaction = transaction def get_span(self): return getattr(self.thread_local, "span", None) def set_span(self, span): self.thread_local.span = span execution_context = ThreadLocalContext()
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/context/threadlocal.py
threadlocal.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class BaseContext(object): def set_transaction(self, transaction): raise NotImplementedError def get_transaction(self, clear=False): raise NotImplementedError def set_span(self, span): raise NotImplementedError def get_span(self): raise NotImplementedError
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/context/base.py
base.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def init_execution_context(): # If _threading_local has been monkeypatched (by gevent or eventlet), then # we should assume it's use as this will be the most "green-thread safe" if threading_local_monkey_patched(): from zuqa.context.threadlocal import execution_context return execution_context try: from zuqa.context.contextvars import execution_context except ImportError: from zuqa.context.threadlocal import execution_context return execution_context def threading_local_monkey_patched(): # Returns True if thread locals have been patched by either gevent of # eventlet try: from gevent.monkey import is_object_patched except ImportError: pass else: if is_object_patched("threading", "local"): return True try: from eventlet.patcher import is_monkey_patched except ImportError: pass else: if is_monkey_patched("thread"): return True return False
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/context/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import import logging import os get_logger = logging.getLogger if os.environ.get("ZUQA_USE_STRUCTLOG", "").lower() == "true": try: import structlog get_logger = structlog.get_logger except ImportError: # use stdlib logger to log warning logger = get_logger("zuqa") logger.warning("ZUQA_USE_STRUCTLOG is set, but structlog is not installed")
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/logging.py
logging.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ This module implements WSGI related helpers adapted from ``werkzeug.wsgi`` :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from zuqa.utils import compat try: from urllib import quote except ImportError: from urllib.parse import quote # `get_headers` comes from `werkzeug.datastructures.EnvironHeaders` def get_headers(environ): """ Returns only proper HTTP headers. """ for key, value in compat.iteritems(environ): key = str(key) if key.startswith("HTTP_") and key not in ("HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"): yield key[5:].replace("_", "-").lower(), value elif key in ("CONTENT_TYPE", "CONTENT_LENGTH"): yield key.replace("_", "-").lower(), value def get_environ(environ): """ Returns our whitelisted environment variables. """ for key in ("REMOTE_ADDR", "SERVER_NAME", "SERVER_PORT"): if key in environ: yield key, environ[key] # `get_host` comes from `werkzeug.wsgi` def get_host(environ): """Return the real host for the given WSGI environment. This takes care of the `X-Forwarded-Host` header. :param environ: the WSGI environment to get the host of. """ scheme = environ.get("wsgi.url_scheme") if "HTTP_X_FORWARDED_HOST" in environ: result = environ["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in environ: result = environ["HTTP_HOST"] else: result = environ["SERVER_NAME"] if (scheme, str(environ["SERVER_PORT"])) not in (("https", "443"), ("http", "80")): result += ":" + environ["SERVER_PORT"] if result.endswith(":80") and scheme == "http": result = result[:-3] elif result.endswith(":443") and scheme == "https": result = result[:-4] return result # `get_current_url` comes from `werkzeug.wsgi` def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False): """A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_url(env, root_only=True) 'http://localhost/script/' >>> get_current_url(env, host_only=True) 'http://localhost/' >>> get_current_url(env, strip_querystring=True) 'http://localhost/script/' :param environ: the WSGI environment to get the current URL from. :param root_only: set `True` if you only want the root URL. :param strip_querystring: set to `True` if you don't want the querystring. :param host_only: set to `True` if the host URL should be returned. """ tmp = [environ["wsgi.url_scheme"], "://", get_host(environ)] cat = tmp.append if host_only: return "".join(tmp) + "/" cat(quote(environ.get("SCRIPT_NAME", "").rstrip("/"))) if root_only: cat("/") else: cat(quote("/" + environ.get("PATH_INFO", "").lstrip("/"))) if not strip_querystring: qs = environ.get("QUERY_STRING") if qs: cat("?" + qs) return "".join(tmp)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wsgi.py
wsgi.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE import fnmatch import inspect import itertools import os import re import sys from zuqa.utils import compat from zuqa.utils.encoding import transform try: from functools import lru_cache except ImportError: from cachetools.func import lru_cache _coding_re = re.compile(r"coding[:=]\s*([-\w.]+)") @lru_cache(512) def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ lineno = lineno - 1 lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines source = None if loader is not None and hasattr(loader, "get_source"): result = get_source_lines_from_loader(loader, module_name, lineno, lower_bound, upper_bound) if result is not None: return result if source is None: try: with open(filename, "rb") as file_obj: encoding = "utf8" # try to find encoding of source file by "coding" header # if none is found, utf8 is used as a fallback for line in itertools.islice(file_obj, 0, 2): match = _coding_re.search(line.decode("utf8")) if match: encoding = match.group(1) break file_obj.seek(0) lines = [ compat.text_type(line, encoding, "replace") for line in itertools.islice(file_obj, lower_bound, upper_bound + 1) ] offset = lineno - lower_bound return ( [l.strip("\r\n") for l in lines[0:offset]], lines[offset].strip("\r\n"), [l.strip("\r\n") for l in lines[offset + 1 :]] if len(lines) > offset else [], ) except (OSError, IOError, IndexError): pass return None, None, None def get_source_lines_from_loader(loader, module_name, lineno, lower_bound, upper_bound): try: source = loader.get_source(module_name) except ImportError: # ImportError: Loader for module cProfile cannot handle module __main__ return None if source is not None: source = source.splitlines() else: return None, None, None try: pre_context = [line.strip("\r\n") for line in source[lower_bound:lineno]] context_line = source[lineno].strip("\r\n") post_context = [line.strip("\r\n") for line in source[(lineno + 1) : upper_bound + 1]] except IndexError: # the file may have changed since it was loaded into memory return None, None, None return pre_context, context_line, post_context def get_culprit(frames, include_paths=None, exclude_paths=None): # We iterate through each frame looking for a deterministic culprit # When one is found, we mark it as last "best guess" (best_guess) and then # check it against ``exclude_paths``. If it isnt listed, then we # use this option. If nothing is found, we use the "best guess". if include_paths is None: include_paths = [] if exclude_paths is None: exclude_paths = [] best_guess = None culprit = None for frame in frames: try: culprit = ".".join((f or "<unknown>" for f in [frame.get("module"), frame.get("function")])) except KeyError: continue if any((culprit.startswith(k) for k in include_paths)): if not (best_guess and any((culprit.startswith(k) for k in exclude_paths))): best_guess = culprit elif best_guess: break # Return either the best guess or the last frames call return best_guess or culprit def _getitem_from_frame(f_locals, key, default=None): """ f_locals is not guaranteed to have .get(), but it will always support __getitem__. Even if it doesnt, we return ``default``. """ try: return f_locals[key] except Exception: return default def to_dict(dictish): """ Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary. """ if hasattr(dictish, "iterkeys"): m = dictish.iterkeys elif hasattr(dictish, "keys"): m = dictish.keys else: raise ValueError(dictish) return dict((k, dictish[k]) for k in m()) def iter_traceback_frames(tb, config=None): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ max_frames = config.stack_trace_limit if config else -1 if not max_frames: return frames = [] while tb: # support for __traceback_hide__ which is used by a few libraries # to hide internal frames. frame = tb.tb_frame f_locals = getattr(frame, "f_locals", None) if f_locals is None or not _getitem_from_frame(f_locals, "__traceback_hide__"): frames.append((frame, getattr(tb, "tb_lineno", None))) tb = tb.tb_next if max_frames != -1: frames = frames[-max_frames:] for frame in frames: yield frame def iter_stack_frames(frames=None, start_frame=None, skip=0, skip_top_modules=(), config=None): """ Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. Frames can be skipped by either providing a number, or a tuple of module names. If the module of a frame matches one of the names (using `.startswith`, that frame will be skipped. This matching will only be done until the first frame doesn't match. This is useful to filter out frames that are caused by frame collection itself. :param frames: a list of frames, or None :param start_frame: a Frame object or None :param skip: number of frames to skip from the beginning :param skip_top_modules: tuple of strings :param config: agent configuration """ if not frames: frame = start_frame if start_frame is not None else inspect.currentframe().f_back frames = _walk_stack(frame) max_frames = config.stack_trace_limit if config else -1 stop_ignoring = False frames_count = 0 # can't use i, as we don't want to count skipped and ignored frames for i, frame in enumerate(frames): if max_frames != -1 and frames_count == max_frames: break if i < skip: continue f_globals = getattr(frame, "f_globals", {}) if not stop_ignoring and f_globals.get("__name__", "").startswith(skip_top_modules): continue stop_ignoring = True f_locals = getattr(frame, "f_locals", {}) if not _getitem_from_frame(f_locals, "__traceback_hide__"): frames_count += 1 yield frame, frame.f_lineno def get_frame_info( frame, lineno, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None, ): # Support hidden frames f_locals = getattr(frame, "f_locals", {}) if _getitem_from_frame(f_locals, "__traceback_hide__"): return None f_globals = getattr(frame, "f_globals", {}) loader = f_globals.get("__loader__") module_name = f_globals.get("__name__") f_code = getattr(frame, "f_code", None) if f_code: abs_path = frame.f_code.co_filename function = frame.f_code.co_name else: abs_path = None function = None # Try to pull a relative file path # This changes /foo/site-packages/baz/bar.py into baz/bar.py try: base_filename = sys.modules[module_name.split(".", 1)[0]].__file__ filename = abs_path.split(base_filename.rsplit(os.path.sep, 2)[0], 1)[-1].lstrip(os.path.sep) except Exception: filename = abs_path if not filename: filename = abs_path frame_result = { "abs_path": abs_path, "filename": filename, "module": module_name, "function": function, "lineno": lineno, "library_frame": is_library_frame(abs_path, include_paths_re, exclude_paths_re), } context_lines = library_frame_context_lines if frame_result["library_frame"] else in_app_frame_context_lines if context_lines and lineno is not None and abs_path: # context_metadata will be processed by zuqa.processors.add_context_lines_to_frames. # This ensures that blocking operations (reading from source files) happens on the background # processing thread. frame_result["context_metadata"] = (abs_path, lineno, int(context_lines / 2), loader, module_name) if with_locals: if f_locals is not None and not isinstance(f_locals, dict): # XXX: Genshi (and maybe others) have broken implementations of # f_locals that are not actually dictionaries try: f_locals = to_dict(f_locals) except Exception: f_locals = "<invalid local scope>" if locals_processor_func: f_locals = {varname: locals_processor_func(var) for varname, var in compat.iteritems(f_locals)} frame_result["vars"] = transform(f_locals) return frame_result def get_stack_info( frames, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None, ): """ Given a list of frames, returns a list of stack information dictionary objects that are JSON-ready. We have to be careful here as certain implementations of the _Frame class do not contain the necessary data to lookup all of the information we want. :param frames: a list of (Frame, lineno) tuples :param with_locals: boolean to indicate if local variables should be collected :param include_paths_re: a regex to determine if a frame is not a library frame :param exclude_paths_re: a regex to exclude frames from not being library frames :param locals_processor_func: a function to call on all local variables :return: """ results = [] for frame, lineno in frames: result = get_frame_info( frame, lineno, library_frame_context_lines=library_frame_context_lines, in_app_frame_context_lines=in_app_frame_context_lines, with_locals=with_locals, include_paths_re=include_paths_re, exclude_paths_re=exclude_paths_re, locals_processor_func=locals_processor_func, ) if result: results.append(result) return results def _walk_stack(frame): while frame: yield frame frame = frame.f_back @lru_cache(512) def is_library_frame(abs_file_path, include_paths_re, exclude_paths_re): if not abs_file_path: return True if include_paths_re and include_paths_re.match(abs_file_path): # frame is in-app, return False return False elif exclude_paths_re and exclude_paths_re.match(abs_file_path): return True # if neither excluded nor included, assume it's an in-app frame return False def get_path_regex(paths): """ compiles a list of path globs into a single pattern that matches any of the given paths :param paths: a list of strings representing fnmatch path globs :return: a compiled regex """ return re.compile("|".join(map(fnmatch.translate, paths)))
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/stacks.py
stacks.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE import datetime import decimal import uuid try: import json except ImportError: import simplejson as json class BetterJSONEncoder(json.JSONEncoder): ENCODERS = { set: list, frozenset: list, datetime.datetime: lambda obj: obj.strftime("%Y-%m-%dT%H:%M:%S.%fZ"), uuid.UUID: lambda obj: obj.hex, bytes: lambda obj: obj.decode("utf-8", errors="replace"), decimal.Decimal: lambda obj: float(obj), } def default(self, obj): if type(obj) in self.ENCODERS: return self.ENCODERS[type(obj)](obj) return super(BetterJSONEncoder, self).default(obj) def better_decoder(data): return data def dumps(value, **kwargs): return json.dumps(value, cls=BetterJSONEncoder, **kwargs) def loads(value, **kwargs): return json.loads(value, object_hook=better_decoder)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/json_encoder.py
json_encoder.py
# -*- coding: utf-8 -*- # BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import atexit import functools import operator import platform import sys import types def noop_decorator(func): @functools.wraps(func) def wrapped(*args, **kwargs): return func(*args, **kwargs) return wrapped def atexit_register(func): """ Uses either uwsgi's atexit mechanism, or atexit from the stdlib. When running under uwsgi, using their atexit handler is more reliable, especially when using gevent :param func: the function to call at exit """ try: import uwsgi orig = getattr(uwsgi, "atexit", None) def uwsgi_atexit(): if callable(orig): orig() func() uwsgi.atexit = uwsgi_atexit except ImportError: atexit.register(func) # Compatibility layer for Python2/Python3, partly inspired by /modified from six, https://github.com/benjaminp/six # Remainder of this file: Copyright Benjamin Peterson, MIT License https://github.com/benjaminp/six/blob/master/LICENSE PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY2: import StringIO import Queue as queue # noqa F401 import urlparse # noqa F401 from urllib2 import HTTPError # noqa F401 from urllib import proxy_bypass_environment, getproxies_environment # noqa F401 StringIO = BytesIO = StringIO.StringIO string_types = (basestring,) # noqa F821 integer_types = (int, long) # noqa F821 class_types = (type, types.ClassType) text_type = unicode # noqa F821 binary_type = str irange = xrange # noqa F821 def b(s): return s get_function_code = operator.attrgetter("func_code") def iterkeys(d, **kwargs): return d.iterkeys(**kwargs) def iteritems(d, **kwargs): return d.iteritems(**kwargs) # for django.utils.datastructures.MultiValueDict def iterlists(d, **kw): return d.iterlists(**kw) else: import io import queue # noqa F401 from urllib import parse as urlparse # noqa F401 from urllib.error import HTTPError # noqa F401 from urllib.request import proxy_bypass_environment, getproxies_environment # noqa F401 StringIO = io.StringIO BytesIO = io.BytesIO string_types = (str,) integer_types = (int,) class_types = (type,) text_type = str binary_type = bytes irange = range def b(s): return s.encode("latin-1") get_function_code = operator.attrgetter("__code__") def iterkeys(d, **kwargs): return iter(d.keys(**kwargs)) def iteritems(d, **kwargs): return iter(d.items(**kwargs)) # for django.utils.datastructures.MultiValueDict def iterlists(d, **kw): return iter(d.lists(**kw)) def get_default_library_patters(): """ Returns library paths depending on the used platform. :return: a list of glob paths """ python_version = platform.python_version_tuple() python_implementation = platform.python_implementation() system = platform.system() if python_implementation == "PyPy": if python_version[0] == "2": return ["*/lib-python/%s.%s/*" % python_version[:2], "*/site-packages/*"] else: return ["*/lib-python/%s/*" % python_version[0], "*/site-packages/*"] else: if system == "Windows": return [r"*\lib\*"] return ["*/lib/python%s.%s/*" % python_version[:2], "*/lib64/python%s.%s/*" % python_version[:2]] def multidict_to_dict(d): """ Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or MultiValueDict instance :return: a dict instance """ return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d)) try: import uwsgi # check if a master is running before importing postfork if uwsgi.masterpid() != 0: from uwsgidecorators import postfork else: def postfork(f): return f except ImportError: def postfork(f): return f
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/compat.py
compat.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE from __future__ import absolute_import import os import threading from timeit import default_timer class IntervalTimer(threading.Thread): """ A timer that runs a function repeatedly. In contrast to threading.Timer, IntervalTimer runs the given function in perpetuity or until it is cancelled. When run, it will wait `interval` seconds until the first execution. """ def __init__( self, function, interval, name=None, args=(), kwargs=None, daemon=None, evaluate_function_interval=False ): """ :param function: the function to run :param interval: the interval in-between invocations of the function, in milliseconds :param name: name of the thread :param args: arguments to call the function with :param kwargs: keyword arguments to call the function with :param daemon: should the thread run as a daemon :param evaluate_function_interval: if set to True, and the function returns a number, it will be used as the next interval """ super(IntervalTimer, self).__init__(name=name) self.daemon = daemon self._args = args self._kwargs = kwargs if kwargs is not None else {} self._function = function self._interval = interval self._interval_done = threading.Event() self._evaluate_function_interval = evaluate_function_interval def run(self): execution_time = 0 interval_override = None while True: real_interval = (interval_override if interval_override is not None else self._interval) - execution_time interval_completed = True if real_interval: interval_completed = not self._interval_done.wait(real_interval) if not interval_completed: # we've been cancelled, time to go home return start = default_timer() rval = self._function(*self._args, **self._kwargs) if self._evaluate_function_interval and isinstance(rval, (int, float)): interval_override = rval else: interval_override = None execution_time = default_timer() - start def cancel(self): self._interval_done.set() class ThreadManager(object): def __init__(self): self.pid = None def start_thread(self, pid=None): if not pid: pid = os.getpid() self.pid = pid def stop_thread(self): raise NotImplementedError() def is_started(self, current_pid=None): if not current_pid: current_pid = os.getpid() return self.pid == current_pid
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/threading.py
threading.py
# -*- coding: utf-8 -*- # # BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE import datetime import itertools import uuid from decimal import Decimal from zuqa.conf.constants import KEYWORD_MAX_LENGTH, LABEL_RE, LABEL_TYPES from zuqa.utils import compat PROTECTED_TYPES = compat.integer_types + (type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, PROTECTED_TYPES) def force_text(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first, saves 30-40% when s is an instance of # compat.text_type. This function gets called often in that setting. # # Adapted from Django if isinstance(s, compat.text_type): return s if strings_only and is_protected_type(s): return s try: if not isinstance(s, compat.string_types): if hasattr(s, "__unicode__"): s = s.__unicode__() else: if compat.PY3: if isinstance(s, bytes): s = compat.text_type(s, encoding, errors) else: s = compat.text_type(s) else: s = compat.text_type(bytes(s), encoding, errors) else: # Note: We use .decode() here, instead of compat.text_type(s, encoding, # errors), so that if s is a SafeBytes, it ends up being a # SafeText at the end. s = s.decode(encoding, errors) except UnicodeDecodeError as e: if not isinstance(s, Exception): raise UnicodeDecodeError(*e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = " ".join([force_text(arg, encoding, strings_only, errors) for arg in s]) return s def _has_zuqa_metadata(value): try: return callable(value.__getattribute__("__zuqa__")) except Exception: return False def transform(value, stack=None, context=None): # TODO: make this extendable if context is None: context = {} if stack is None: stack = [] objid = id(value) if objid in context: return "<...>" context[objid] = 1 transform_rec = lambda o: transform(o, stack + [value], context) if any(value is s for s in stack): ret = "cycle" elif isinstance(value, (tuple, list, set, frozenset)): try: ret = type(value)(transform_rec(o) for o in value) except Exception: # We may be dealing with a namedtuple class value_type(list): __name__ = type(value).__name__ ret = value_type(transform_rec(o) for o in value) elif isinstance(value, uuid.UUID): ret = repr(value) elif isinstance(value, dict): ret = dict((to_unicode(k), transform_rec(v)) for k, v in compat.iteritems(value)) elif isinstance(value, compat.text_type): ret = to_unicode(value) elif isinstance(value, compat.binary_type): ret = to_string(value) elif not isinstance(value, compat.class_types) and _has_zuqa_metadata(value): ret = transform_rec(value.__zuqa__()) elif isinstance(value, bool): ret = bool(value) elif isinstance(value, float): ret = float(value) elif isinstance(value, int): ret = int(value) elif compat.PY2 and isinstance(value, long): # noqa F821 ret = long(value) # noqa F821 elif value is not None: try: ret = transform(repr(value)) except Exception: # It's common case that a model's __unicode__ definition may try to query the database # which if it was not cleaned up correctly, would hit a transaction aborted exception ret = u"<BadRepr: %s>" % type(value) else: ret = None del context[objid] return ret def to_unicode(value): try: value = compat.text_type(force_text(value)) except (UnicodeEncodeError, UnicodeDecodeError): value = "(Error decoding value)" except Exception: # in some cases we get a different exception try: value = compat.binary_type(repr(type(value))) except Exception: value = "(Error decoding value)" return value def to_string(value): try: return compat.binary_type(value.decode("utf-8").encode("utf-8")) except Exception: return to_unicode(value).encode("utf-8") def shorten(var, list_length=50, string_length=200, dict_length=50): """ Shorten a given variable based on configurable maximum lengths, leaving breadcrumbs in the object to show that it was shortened. For strings, truncate the string to the max length, and append "..." so the user knows data was lost. For lists, truncate the list to the max length, and append two new strings to the list: "..." and "(<x> more elements)" where <x> is the number of elements removed. For dicts, truncate the dict to the max length (based on number of key/value pairs) and add a new (key, value) pair to the dict: ("...", "(<x> more elements)") where <x> is the number of key/value pairs removed. :param var: Variable to be shortened :param list_length: Max length (in items) of lists :param string_length: Max length (in characters) of strings :param dict_length: Max length (in key/value pairs) of dicts :return: Shortened variable """ var = transform(var) if isinstance(var, compat.string_types) and len(var) > string_length: var = var[: string_length - 3] + "..." elif isinstance(var, (list, tuple, set, frozenset)) and len(var) > list_length: # TODO: we should write a real API for storing some metadata with vars when # we get around to doing ref storage var = list(var)[:list_length] + ["...", "(%d more elements)" % (len(var) - list_length,)] elif isinstance(var, dict) and len(var) > dict_length: trimmed_tuples = [(k, v) for (k, v) in itertools.islice(compat.iteritems(var), dict_length)] if "<truncated>" not in var: trimmed_tuples += [("<truncated>", "(%d more elements)" % (len(var) - dict_length))] var = dict(trimmed_tuples) return var def keyword_field(string): if not isinstance(string, compat.string_types) or len(string) <= KEYWORD_MAX_LENGTH: return string return string[: KEYWORD_MAX_LENGTH - 1] + u"…" def enforce_label_format(labels): """ Enforces label format: * dots, double quotes or stars in keys are replaced by underscores * string values are limited to a length of 1024 characters * values can only be of a limited set of types :param labels: a dictionary of labels :return: a new dictionary with sanitized keys/values """ new = {} for key, value in compat.iteritems(labels): if not isinstance(value, LABEL_TYPES): value = keyword_field(compat.text_type(value)) new[LABEL_RE.sub("_", compat.text_type(key))] = value return new
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/encoding.py
encoding.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from importlib import import_module def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. From https://github.com/django/django/blob/master/django/utils/module_loading.py """ try: module_path, class_name = dotted_path.rsplit(".", 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path raise ImportError(msg) module = import_module(module_path) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % (module_path, class_name) raise ImportError(msg)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/module_import.py
module_import.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import ctypes from zuqa.conf import constants from zuqa.utils.logging import get_logger logger = get_logger("zuqa.utils") class TraceParent(object): __slots__ = ("version", "trace_id", "span_id", "trace_options", "tracestate", "is_legacy") def __init__(self, version, trace_id, span_id, trace_options, tracestate=None, is_legacy=False): self.version = version self.trace_id = trace_id self.span_id = span_id self.trace_options = trace_options self.is_legacy = is_legacy self.tracestate = tracestate def copy_from(self, version=None, trace_id=None, span_id=None, trace_options=None, tracestate=None): return TraceParent( version or self.version, trace_id or self.trace_id, span_id or self.span_id, trace_options or self.trace_options, tracestate or self.tracestate, ) def to_string(self): return "{:02x}-{}-{}-{:02x}".format(self.version, self.trace_id, self.span_id, self.trace_options.asByte) def to_ascii(self): return self.to_string().encode("ascii") @classmethod def from_string(cls, traceparent_string, tracestate_string=None, is_legacy=False): try: parts = traceparent_string.split("-") version, trace_id, span_id, trace_flags = parts[:4] except ValueError: logger.debug("Invalid traceparent header format, value %s", traceparent_string) return try: version = int(version, 16) if version == 255: raise ValueError() except ValueError: logger.debug("Invalid version field, value %s", version) return try: tracing_options = TracingOptions() tracing_options.asByte = int(trace_flags, 16) except ValueError: logger.debug("Invalid trace-options field, value %s", trace_flags) return return TraceParent(version, trace_id, span_id, tracing_options, tracestate_string, is_legacy) @classmethod def from_headers( cls, headers, header_name=constants.TRACEPARENT_HEADER_NAME, legacy_header_name=constants.TRACEPARENT_LEGACY_HEADER_NAME, tracestate_header_name=constants.TRACESTATE_HEADER_NAME, ): tracestate = cls.merge_duplicate_headers(headers, tracestate_header_name) if header_name in headers: return TraceParent.from_string(headers[header_name], tracestate, is_legacy=False) elif legacy_header_name in headers: return TraceParent.from_string(headers[legacy_header_name], tracestate, is_legacy=False) else: return None @classmethod def merge_duplicate_headers(cls, headers, key): """ HTTP allows multiple values for the same header name. Most WSGI implementations merge these values using a comma as separator (this has been confirmed for wsgiref, werkzeug, gunicorn and uwsgi). Other implementations may use containers like multidict to store headers and have APIs to iterate over all values for a given key. This method is provided as a hook for framework integrations to provide their own TraceParent implementation. The implementation should return a single string. Multiple values for the same key should be merged using a comma as separator. :param headers: a dict-like header object :param key: header name :return: a single string value or None """ # this works for all known WSGI implementations return headers.get(key) class TracingOptions_bits(ctypes.LittleEndianStructure): _fields_ = [("recorded", ctypes.c_uint8, 1)] class TracingOptions(ctypes.Union): _anonymous_ = ("bit",) _fields_ = [("bit", TracingOptions_bits), ("asByte", ctypes.c_uint8)] def __init__(self, **kwargs): super(TracingOptions, self).__init__() for k, v in kwargs.items(): setattr(self, k, v) def trace_parent_from_string(traceparent_string, tracestate_string=None, is_legacy=False): """ This is a wrapper function so we can add traceparent generation to the public API. """ return TraceParent.from_string(traceparent_string, tracestate_string=tracestate_string, is_legacy=is_legacy) def trace_parent_from_headers(headers): """ This is a wrapper function so we can add traceparent generation to the public API. """ return TraceParent.from_headers(headers)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/disttracing.py
disttracing.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import re CGROUP_PATH = "/proc/self/cgroup" SYSTEMD_SCOPE_SUFFIX = ".scope" kubepods_regexp = re.compile( r"(?:^/kubepods/[^/]+/pod([^/]+)$)|(?:^/kubepods\.slice/kubepods-[^/]+\.slice/kubepods-[^/]+-pod([^/]+)\.slice$)" ) container_id_regexp = re.compile( "^(?:[0-9a-f]{64}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4,})$", re.IGNORECASE ) def get_cgroup_container_metadata(): """ Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup The result is a nested dictionary with the detected IDs, e.g. { "container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"}, "pod": {"uid": "90d81341_92de_11e7_8cf2_507b9d4141fa"} } :return: a dictionary with the detected ids or {} """ if not os.path.exists(CGROUP_PATH): return {} with open(CGROUP_PATH) as f: return parse_cgroups(f) or {} def parse_cgroups(filehandle): """ Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs. See tests.utils.docker_tests.test_cgroup_parsing for a set of test cases :param filehandle: :return: nested dictionary or None """ for line in filehandle: parts = line.strip().split(":") if len(parts) != 3: continue cgroup_path = parts[2] # Depending on the filesystem driver used for cgroup # management, the paths in /proc/pid/cgroup will have # one of the following formats in a Docker container: # # systemd: /system.slice/docker-<container-ID>.scope # cgroupfs: /docker/<container-ID> # # In a Kubernetes pod, the cgroup path will look like: # # systemd:/kubepods.slice/kubepods-<QoS-class>.slice/kubepods-<QoS-class>-pod<pod-UID>.slice/<container-iD>.scope # cgroupfs:/kubepods/<QoS-class>/pod<pod-UID>/<container-iD> directory, container_id = os.path.split(cgroup_path) if container_id.endswith(SYSTEMD_SCOPE_SUFFIX): container_id = container_id[: -len(SYSTEMD_SCOPE_SUFFIX)] if "-" in container_id: container_id = container_id.split("-", 1)[1] kubepods_match = kubepods_regexp.match(directory) if kubepods_match: pod_id = kubepods_match.group(1) if not pod_id: pod_id = kubepods_match.group(2) if pod_id: pod_id = pod_id.replace("_", "-") return {"container": {"id": container_id}, "kubernetes": {"pod": {"uid": pod_id}}} elif container_id_regexp.match(container_id): return {"container": {"id": container_id}}
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/cgroup.py
cgroup.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import functools import warnings # https://wiki.python.org/moin/PythonDecoratorLibrary#Smart_deprecation_warnings_.28with_valid_filenames.2C_line_numbers.2C_etc..29 # Updated to work with 2.6 and 3+. from zuqa.utils import compat def deprecated(alternative=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def real_decorator(func): @functools.wraps(func) def new_func(*args, **kwargs): msg = "Call to deprecated function {0}.".format(func.__name__) if alternative: msg += " Use {0} instead".format(alternative) warnings.warn_explicit( msg, category=DeprecationWarning, filename=compat.get_function_code(func).co_filename, lineno=compat.get_function_code(func).co_firstlineno + 1, ) return func(*args, **kwargs) return new_func return real_decorator
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/deprecation.py
deprecation.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE import base64 import os import re from functools import partial from zuqa.conf import constants from zuqa.utils import compat, encoding try: from functools import partialmethod partial_types = (partial, partialmethod) except ImportError: # Python 2 partial_types = (partial,) default_ports = {"https": 443, "http": 80, "postgresql": 5432, "mysql": 3306, "mssql": 1433} def varmap(func, var, context=None, name=None): """ Executes ``func(key_name, value)`` on all values, recursively discovering dict and list scoped values. """ if context is None: context = set() objid = id(var) if objid in context: return func(name, "<...>") context.add(objid) if isinstance(var, dict): ret = func(name, dict((k, varmap(func, v, context, k)) for k, v in compat.iteritems(var))) elif isinstance(var, (list, tuple)): ret = func(name, [varmap(func, f, context, name) for f in var]) else: ret = func(name, var) context.remove(objid) return ret def get_name_from_func(func): # partials don't have `__module__` or `__name__`, so we use the values from the "inner" function if isinstance(func, partial_types): return "partial({})".format(get_name_from_func(func.func)) elif hasattr(func, "_partialmethod") and hasattr(func._partialmethod, "func"): return "partial({})".format(get_name_from_func(func._partialmethod.func)) module = func.__module__ if hasattr(func, "__name__"): view_name = func.__name__ else: # Fall back if there's no __name__ view_name = func.__class__.__name__ return "{0}.{1}".format(module, view_name) def build_name_with_http_method_prefix(name, request): return " ".join((request.method, name)) if name else name def is_master_process(): # currently only recognizes uwsgi master process try: import uwsgi return os.getpid() == uwsgi.masterpid() except ImportError: return False def get_url_dict(url): parse_result = compat.urlparse.urlparse(url) url_dict = { "full": encoding.keyword_field(url), "protocol": parse_result.scheme + ":", "hostname": encoding.keyword_field(parse_result.hostname), "pathname": encoding.keyword_field(parse_result.path), } port = None if parse_result.port is None else str(parse_result.port) if port: url_dict["port"] = port if parse_result.query: url_dict["search"] = encoding.keyword_field("?" + parse_result.query) return url_dict def sanitize_url(url): if "@" not in url: return url parts = compat.urlparse.urlparse(url) return url.replace("%s:%s" % (parts.username, parts.password), "%s:%s" % (parts.username, constants.MASK)) def get_host_from_url(url): parsed_url = compat.urlparse.urlparse(url) host = parsed_url.hostname or " " if parsed_url.port and default_ports.get(parsed_url.scheme) != parsed_url.port: host += ":" + str(parsed_url.port) return host def url_to_destination(url, service_type="external"): parts = compat.urlparse.urlsplit(url) hostname = parts.hostname # preserve brackets for IPv6 URLs if "://[" in url: hostname = "[%s]" % hostname try: port = parts.port except ValueError: # Malformed port, just use None rather than raising an exception port = None default_port = default_ports.get(parts.scheme, None) name = "%s://%s" % (parts.scheme, hostname) resource = hostname if not port and parts.scheme in default_ports: port = default_ports[parts.scheme] if port: if port != default_port: name += ":%d" % port resource += ":%d" % port return {"service": {"name": name, "resource": resource, "type": service_type}} def read_pem_file(file_obj): cert = b"" for line in file_obj: if line.startswith(b"-----BEGIN CERTIFICATE-----"): break # scan until we find the first END CERTIFICATE marker for line in file_obj: if line.startswith(b"-----END CERTIFICATE-----"): break cert += line.strip() return base64.b64decode(cert) def starmatch_to_regex(pattern): i, n = 0, len(pattern) res = [] while i < n: c = pattern[i] i = i + 1 if c == "*": res.append(".*") else: res.append(re.escape(c)) return re.compile(r"(?:%s)\Z" % "".join(res), re.IGNORECASE | re.DOTALL)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/__init__.py
__init__.py
"""This module implements decorators for implementing other decorators as well as some commonly used decorators. """ import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, import builtins exec_ = getattr(builtins, "exec") del builtins else: string_types = basestring, def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") from functools import partial from inspect import ismethod, isclass, formatargspec from collections import namedtuple from threading import Lock, RLock try: from inspect import signature except ImportError: pass from .wrappers import (FunctionWrapper, BoundFunctionWrapper, ObjectProxy, CallableObjectProxy) # Adapter wrapper for the wrapped function which will overlay certain # properties from the adapter function onto the wrapped function so that # functions such as inspect.getargspec(), inspect.getfullargspec(), # inspect.signature() and inspect.getsource() return the correct results # one would expect. class _AdapterFunctionCode(CallableObjectProxy): def __init__(self, wrapped_code, adapter_code): super(_AdapterFunctionCode, self).__init__(wrapped_code) self._self_adapter_code = adapter_code @property def co_argcount(self): return self._self_adapter_code.co_argcount @property def co_code(self): return self._self_adapter_code.co_code @property def co_flags(self): return self._self_adapter_code.co_flags @property def co_kwonlyargcount(self): return self._self_adapter_code.co_kwonlyargcount @property def co_varnames(self): return self._self_adapter_code.co_varnames class _AdapterFunctionSurrogate(CallableObjectProxy): def __init__(self, wrapped, adapter): super(_AdapterFunctionSurrogate, self).__init__(wrapped) self._self_adapter = adapter @property def __code__(self): return _AdapterFunctionCode(self.__wrapped__.__code__, self._self_adapter.__code__) @property def __defaults__(self): return self._self_adapter.__defaults__ @property def __kwdefaults__(self): return self._self_adapter.__kwdefaults__ @property def __signature__(self): if 'signature' not in globals(): return self._self_adapter.__signature__ else: # Can't allow this to fail on Python 3 else it falls # through to using __wrapped__, but that will be the # wrong function we want to derive the signature # from. Thus generate the signature ourselves. return signature(self._self_adapter) if PY2: func_code = __code__ func_defaults = __defaults__ class _BoundAdapterWrapper(BoundFunctionWrapper): @property def __func__(self): return _AdapterFunctionSurrogate(self.__wrapped__.__func__, self._self_parent._self_adapter) if PY2: im_func = __func__ class AdapterWrapper(FunctionWrapper): __bound_function_wrapper__ = _BoundAdapterWrapper def __init__(self, *args, **kwargs): adapter = kwargs.pop('adapter') super(AdapterWrapper, self).__init__(*args, **kwargs) self._self_surrogate = _AdapterFunctionSurrogate( self.__wrapped__, adapter) self._self_adapter = adapter @property def __code__(self): return self._self_surrogate.__code__ @property def __defaults__(self): return self._self_surrogate.__defaults__ @property def __kwdefaults__(self): return self._self_surrogate.__kwdefaults__ if PY2: func_code = __code__ func_defaults = __defaults__ @property def __signature__(self): return self._self_surrogate.__signature__ class AdapterFactory(object): def __call__(self, wrapped): raise NotImplementedError() class DelegatedAdapterFactory(AdapterFactory): def __init__(self, factory): super(DelegatedAdapterFactory, self).__init__() self.factory = factory def __call__(self, wrapped): return self.factory(wrapped) adapter_factory = DelegatedAdapterFactory # Decorator for creating other decorators. This decorator and the # wrappers which they use are designed to properly preserve any name # attributes, function signatures etc, in addition to the wrappers # themselves acting like a transparent proxy for the original wrapped # function so the wrapper is effectively indistinguishable from the # original wrapped function. def decorator(wrapper=None, enabled=None, adapter=None): # The decorator should be supplied with a single positional argument # which is the wrapper function to be used to implement the # decorator. This may be preceded by a step whereby the keyword # arguments are supplied to customise the behaviour of the # decorator. The 'adapter' argument is used to optionally denote a # separate function which is notionally used by an adapter # decorator. In that case parts of the function '__code__' and # '__defaults__' attributes are used from the adapter function # rather than those of the wrapped function. This allows for the # argument specification from inspect.getargspec() and similar # functions to be overridden with a prototype for a different # function than what was wrapped. The 'enabled' argument provides a # way to enable/disable the use of the decorator. If the type of # 'enabled' is a boolean, then it is evaluated immediately and the # wrapper not even applied if it is False. If not a boolean, it will # be evaluated when the wrapper is called for an unbound wrapper, # and when binding occurs for a bound wrapper. When being evaluated, # if 'enabled' is callable it will be called to obtain the value to # be checked. If False, the wrapper will not be called and instead # the original wrapped function will be called directly instead. if wrapper is not None: # Helper function for creating wrapper of the appropriate # time when we need it down below. def _build(wrapped, wrapper, enabled=None, adapter=None): if adapter: if isinstance(adapter, AdapterFactory): adapter = adapter(wrapped) if not callable(adapter): ns = {} if not isinstance(adapter, string_types): adapter = formatargspec(*adapter) exec_('def adapter{0}: pass'.format(adapter), ns, ns) adapter = ns['adapter'] return AdapterWrapper(wrapped=wrapped, wrapper=wrapper, enabled=enabled, adapter=adapter) return FunctionWrapper(wrapped=wrapped, wrapper=wrapper, enabled=enabled) # The wrapper has been provided so return the final decorator. # The decorator is itself one of our function wrappers so we # can determine when it is applied to functions, instance methods # or class methods. This allows us to bind the instance or class # method so the appropriate self or cls attribute is supplied # when it is finally called. def _wrapper(wrapped, instance, args, kwargs): # We first check for the case where the decorator was applied # to a class type. # # @decorator # class mydecoratorclass(object): # def __init__(self, arg=None): # self.arg = arg # def __call__(self, wrapped, instance, args, kwargs): # return wrapped(*args, **kwargs) # # @mydecoratorclass(arg=1) # def function(): # pass # # In this case an instance of the class is to be used as the # decorator wrapper function. If args was empty at this point, # then it means that there were optional keyword arguments # supplied to be used when creating an instance of the class # to be used as the wrapper function. if instance is None and isclass(wrapped) and not args: # We still need to be passed the target function to be # wrapped as yet, so we need to return a further function # to be able to capture it. def _capture(target_wrapped): # Now have the target function to be wrapped and need # to create an instance of the class which is to act # as the decorator wrapper function. Before we do that, # we need to first check that use of the decorator # hadn't been disabled by a simple boolean. If it was, # the target function to be wrapped is returned instead. _enabled = enabled if type(_enabled) is bool: if not _enabled: return target_wrapped _enabled = None # Now create an instance of the class which is to act # as the decorator wrapper function. Any arguments had # to be supplied as keyword only arguments so that is # all we pass when creating it. target_wrapper = wrapped(**kwargs) # Finally build the wrapper itself and return it. return _build(target_wrapped, target_wrapper, _enabled, adapter) return _capture # We should always have the target function to be wrapped at # this point as the first (and only) value in args. target_wrapped = args[0] # Need to now check that use of the decorator hadn't been # disabled by a simple boolean. If it was, then target # function to be wrapped is returned instead. _enabled = enabled if type(_enabled) is bool: if not _enabled: return target_wrapped _enabled = None # We now need to build the wrapper, but there are a couple of # different cases we need to consider. if instance is None: if isclass(wrapped): # In this case the decorator was applied to a class # type but optional keyword arguments were not supplied # for initialising an instance of the class to be used # as the decorator wrapper function. # # @decorator # class mydecoratorclass(object): # def __init__(self, arg=None): # self.arg = arg # def __call__(self, wrapped, instance, # args, kwargs): # return wrapped(*args, **kwargs) # # @mydecoratorclass # def function(): # pass # # We still need to create an instance of the class to # be used as the decorator wrapper function, but no # arguments are pass. target_wrapper = wrapped() else: # In this case the decorator was applied to a normal # function, or possibly a static method of a class. # # @decorator # def mydecoratorfuntion(wrapped, instance, # args, kwargs): # return wrapped(*args, **kwargs) # # @mydecoratorfunction # def function(): # pass # # That normal function becomes the decorator wrapper # function. target_wrapper = wrapper else: if isclass(instance): # In this case the decorator was applied to a class # method. # # class myclass(object): # @decorator # @classmethod # def decoratorclassmethod(cls, wrapped, # instance, args, kwargs): # return wrapped(*args, **kwargs) # # instance = myclass() # # @instance.decoratorclassmethod # def function(): # pass # # This one is a bit strange because binding was actually # performed on the wrapper created by our decorator # factory. We need to apply that binding to the decorator # wrapper function which which the decorator factory # was applied to. target_wrapper = wrapper.__get__(None, instance) else: # In this case the decorator was applied to an instance # method. # # class myclass(object): # @decorator # def decoratorclassmethod(self, wrapped, # instance, args, kwargs): # return wrapped(*args, **kwargs) # # instance = myclass() # # @instance.decoratorclassmethod # def function(): # pass # # This one is a bit strange because binding was actually # performed on the wrapper created by our decorator # factory. We need to apply that binding to the decorator # wrapper function which which the decorator factory # was applied to. target_wrapper = wrapper.__get__(instance, type(instance)) # Finally build the wrapper itself and return it. return _build(target_wrapped, target_wrapper, _enabled, adapter) # We first return our magic function wrapper here so we can # determine in what context the decorator factory was used. In # other words, it is itself a universal decorator. return _build(wrapper, _wrapper) else: # The wrapper still has not been provided, so we are just # collecting the optional keyword arguments. Return the # decorator again wrapped in a partial using the collected # arguments. return partial(decorator, enabled=enabled, adapter=adapter) # Decorator for implementing thread synchronization. It can be used as a # decorator, in which case the synchronization context is determined by # what type of function is wrapped, or it can also be used as a context # manager, where the user needs to supply the correct synchronization # context. It is also possible to supply an object which appears to be a # synchronization primitive of some sort, by virtue of having release() # and acquire() methods. In that case that will be used directly as the # synchronization primitive without creating a separate lock against the # derived or supplied context. def synchronized(wrapped): # Determine if being passed an object which is a synchronization # primitive. We can't check by type for Lock, RLock, Semaphore etc, # as the means of creating them isn't the type. Therefore use the # existence of acquire() and release() methods. This is more # extensible anyway as it allows custom synchronization mechanisms. if hasattr(wrapped, 'acquire') and hasattr(wrapped, 'release'): # We remember what the original lock is and then return a new # decorator which accesses and locks it. When returning the new # decorator we wrap it with an object proxy so we can override # the context manager methods in case it is being used to wrap # synchronized statements with a 'with' statement. lock = wrapped @decorator def _synchronized(wrapped, instance, args, kwargs): # Execute the wrapped function while the original supplied # lock is held. with lock: return wrapped(*args, **kwargs) class _PartialDecorator(CallableObjectProxy): def __enter__(self): lock.acquire() return lock def __exit__(self, *args): lock.release() return _PartialDecorator(wrapped=_synchronized) # Following only apply when the lock is being created automatically # based on the context of what was supplied. In this case we supply # a final decorator, but need to use FunctionWrapper directly as we # want to derive from it to add context manager methods in case it is # being used to wrap synchronized statements with a 'with' statement. def _synchronized_lock(context): # Attempt to retrieve the lock for the specific context. lock = vars(context).get('_synchronized_lock', None) if lock is None: # There is no existing lock defined for the context we # are dealing with so we need to create one. This needs # to be done in a way to guarantee there is only one # created, even if multiple threads try and create it at # the same time. We can't always use the setdefault() # method on the __dict__ for the context. This is the # case where the context is a class, as __dict__ is # actually a dictproxy. What we therefore do is use a # meta lock on this wrapper itself, to control the # creation and assignment of the lock attribute against # the context. meta_lock = vars(synchronized).setdefault( '_synchronized_meta_lock', Lock()) with meta_lock: # We need to check again for whether the lock we want # exists in case two threads were trying to create it # at the same time and were competing to create the # meta lock. lock = vars(context).get('_synchronized_lock', None) if lock is None: lock = RLock() setattr(context, '_synchronized_lock', lock) return lock def _synchronized_wrapper(wrapped, instance, args, kwargs): # Execute the wrapped function while the lock for the # desired context is held. If instance is None then the # wrapped function is used as the context. with _synchronized_lock(instance or wrapped): return wrapped(*args, **kwargs) class _FinalDecorator(FunctionWrapper): def __enter__(self): self._self_lock = _synchronized_lock(self.__wrapped__) self._self_lock.acquire() return self._self_lock def __exit__(self, *args): self._self_lock.release() return _FinalDecorator(wrapped=wrapped, wrapper=_synchronized_wrapper)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/decorators.py
decorators.py
"""This module implements a post import hook mechanism styled after what is described in PEP-369. Note that it doesn't cope with modules being reloaded. """ import sys import threading PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: import importlib string_types = str, else: string_types = basestring, from .decorators import synchronized # The dictionary registering any post import hooks to be triggered once # the target module has been imported. Once a module has been imported # and the hooks fired, the list of hooks recorded against the target # module will be truncacted but the list left in the dictionary. This # acts as a flag to indicate that the module had already been imported. _post_import_hooks = {} _post_import_hooks_init = False _post_import_hooks_lock = threading.RLock() # Register a new post import hook for the target module name. This # differs from the PEP-369 implementation in that it also allows the # hook function to be specified as a string consisting of the name of # the callback in the form 'module:function'. This will result in a # proxy callback being registered which will defer loading of the # specified module containing the callback function until required. def _create_import_hook_from_string(name): def import_hook(module): module_name, function = name.split(':') attrs = function.split('.') __import__(module_name) callback = sys.modules[module_name] for attr in attrs: callback = getattr(callback, attr) return callback(module) return import_hook @synchronized(_post_import_hooks_lock) def register_post_import_hook(hook, name): # Create a deferred import hook if hook is a string name rather than # a callable function. if isinstance(hook, string_types): hook = _create_import_hook_from_string(hook) # Automatically install the import hook finder if it has not already # been installed. global _post_import_hooks_init if not _post_import_hooks_init: _post_import_hooks_init = True sys.meta_path.insert(0, ImportHookFinder()) # Determine if any prior registration of a post import hook for # the target modules has occurred and act appropriately. hooks = _post_import_hooks.get(name, None) if hooks is None: # No prior registration of post import hooks for the target # module. We need to check whether the module has already been # imported. If it has we fire the hook immediately and add an # empty list to the registry to indicate that the module has # already been imported and hooks have fired. Otherwise add # the post import hook to the registry. module = sys.modules.get(name, None) if module is not None: _post_import_hooks[name] = [] hook(module) else: _post_import_hooks[name] = [hook] elif hooks == []: # A prior registration of port import hooks for the target # module was done and the hooks already fired. Fire the hook # immediately. module = sys.modules[name] hook(module) else: # A prior registration of port import hooks for the target # module was done but the module has not yet been imported. _post_import_hooks[name].append(hook) # Register post import hooks defined as package entry points. def _create_import_hook_from_entrypoint(entrypoint): def import_hook(module): __import__(entrypoint.module_name) callback = sys.modules[entrypoint.module_name] for attr in entrypoint.attrs: callback = getattr(callback, attr) return callback(module) return import_hook def discover_post_import_hooks(group): try: import pkg_resources except ImportError: return for entrypoint in pkg_resources.iter_entry_points(group=group): callback = _create_import_hook_from_entrypoint(entrypoint) register_post_import_hook(callback, entrypoint.name) # Indicate that a module has been loaded. Any post import hooks which # were registered against the target module will be invoked. If an # exception is raised in any of the post import hooks, that will cause # the import of the target module to fail. @synchronized(_post_import_hooks_lock) def notify_module_loaded(module): name = getattr(module, '__name__', None) hooks = _post_import_hooks.get(name, None) if hooks: _post_import_hooks[name] = [] for hook in hooks: hook(module) # A custom module import finder. This intercepts attempts to import # modules and watches out for attempts to import target modules of # interest. When a module of interest is imported, then any post import # hooks which are registered will be invoked. class _ImportHookLoader: def load_module(self, fullname): module = sys.modules[fullname] notify_module_loaded(module) return module class _ImportHookChainedLoader: def __init__(self, loader): self.loader = loader def load_module(self, fullname): module = self.loader.load_module(fullname) notify_module_loaded(module) return module class ImportHookFinder: def __init__(self): self.in_progress = {} @synchronized(_post_import_hooks_lock) def find_module(self, fullname, path=None): # If the module being imported is not one we have registered # post import hooks for, we can return immediately. We will # take no further part in the importing of this module. if not fullname in _post_import_hooks: return None # When we are interested in a specific module, we will call back # into the import system a second time to defer to the import # finder that is supposed to handle the importing of the module. # We set an in progress flag for the target module so that on # the second time through we don't trigger another call back # into the import system and cause a infinite loop. if fullname in self.in_progress: return None self.in_progress[fullname] = True # Now call back into the import system again. try: if PY3: # For Python 3 we need to use find_loader() from # the importlib module. It doesn't actually # import the target module and only finds the # loader. If a loader is found, we need to return # our own loader which will then in turn call the # real loader to import the module and invoke the # post import hooks. loader = importlib.find_loader(fullname, path) if loader: return _ImportHookChainedLoader(loader) else: # For Python 2 we don't have much choice but to # call back in to __import__(). This will # actually cause the module to be imported. If no # module could be found then ImportError will be # raised. Otherwise we return a loader which # returns the already loaded module and invokes # the post import hooks. __import__(fullname) return _ImportHookLoader() finally: del self.in_progress[fullname] # Decorator for marking that a function should be called as a post # import hook when the target module is imported. def when_imported(name): def register(hook): register_post_import_hook(hook, name) return hook return register
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/importer.py
importer.py
# This is a copy of the inspect.getcallargs() function from Python 2.7 # so we can provide it for use under Python 2.6. As the code in this # file derives from the Python distribution, it falls under the version # of the PSF license used for Python 2.7. from inspect import getargspec, ismethod import sys def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" args, varargs, varkw, defaults = getargspec(func) f_name = func.__name__ arg2value = {} # The following closures are basically because of tuple parameter unpacking. assigned_tuple_params = [] def assign(arg, value): if isinstance(arg, str): arg2value[arg] = value else: assigned_tuple_params.append(arg) value = iter(value) for i, subarg in enumerate(arg): try: subvalue = next(value) except StopIteration: raise ValueError('need more than %d %s to unpack' % (i, 'values' if i > 1 else 'value')) assign(subarg, subvalue) try: next(value) except StopIteration: pass else: raise ValueError('too many values to unpack') def is_assigned(arg): if isinstance(arg, str): return arg in arg2value return arg in assigned_tuple_params if ismethod(func) and func.im_self is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.im_self,) + positional num_pos = len(positional) num_total = num_pos + len(named) num_args = len(args) num_defaults = len(defaults) if defaults else 0 for arg, value in zip(args, positional): assign(arg, value) if varargs: if num_pos > num_args: assign(varargs, positional[-(num_pos-num_args):]) else: assign(varargs, ()) elif 0 < num_args < num_pos: raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at most' if defaults else 'exactly', num_args, 'arguments' if num_args > 1 else 'argument', num_total)) elif num_args == 0 and num_total: if varkw: if num_pos: # XXX: We should use num_pos, but Python also uses num_total: raise TypeError('%s() takes exactly 0 arguments ' '(%d given)' % (f_name, num_total)) else: raise TypeError('%s() takes no arguments (%d given)' % (f_name, num_total)) for arg in args: if isinstance(arg, str) and arg in named: if is_assigned(arg): raise TypeError("%s() got multiple values for keyword " "argument '%s'" % (f_name, arg)) else: assign(arg, named.pop(arg)) if defaults: # fill in any missing values with the defaults for arg, value in zip(args[-num_defaults:], defaults): if not is_assigned(arg): assign(arg, value) if varkw: assign(varkw, named) elif named: unexpected = next(iter(named)) if isinstance(unexpected, unicode): unexpected = unexpected.encode(sys.getdefaultencoding(), 'replace') raise TypeError("%s() got an unexpected keyword argument '%s'" % (f_name, unexpected)) unassigned = num_args - len([arg for arg in args if is_assigned(arg)]) if unassigned: num_required = num_args - num_defaults raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at least' if defaults else 'exactly', num_required, 'arguments' if num_required > 1 else 'argument', num_total)) return arg2value
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/arguments.py
arguments.py
import os import sys import functools import operator import weakref import inspect PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, else: string_types = basestring, def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" return meta("NewBase", bases, {}) class _ObjectProxyMethods(object): # We use properties to override the values of __module__ and # __doc__. If we add these in ObjectProxy, the derived class # __dict__ will still be setup to have string variants of these # attributes and the rules of descriptors means that they appear to # take precedence over the properties in the base class. To avoid # that, we copy the properties into the derived class type itself # via a meta class. In that way the properties will always take # precedence. @property def __module__(self): return self.__wrapped__.__module__ @__module__.setter def __module__(self, value): self.__wrapped__.__module__ = value @property def __doc__(self): return self.__wrapped__.__doc__ @__doc__.setter def __doc__(self, value): self.__wrapped__.__doc__ = value # We similar use a property for __dict__. We need __dict__ to be # explicit to ensure that vars() works as expected. @property def __dict__(self): return self.__wrapped__.__dict__ # Need to also propagate the special __weakref__ attribute for case # where decorating classes which will define this. If do not define # it and use a function like inspect.getmembers() on a decorator # class it will fail. This can't be in the derived classes. @property def __weakref__(self): return self.__wrapped__.__weakref__ class _ObjectProxyMetaType(type): def __new__(cls, name, bases, dictionary): # Copy our special properties into the class so that they # always take precedence over attributes of the same name added # during construction of a derived class. This is to save # duplicating the implementation for them in all derived classes. dictionary.update(vars(_ObjectProxyMethods)) return type.__new__(cls, name, bases, dictionary) class ObjectProxy(with_metaclass(_ObjectProxyMetaType)): __slots__ = '__wrapped__' def __init__(self, wrapped): object.__setattr__(self, '__wrapped__', wrapped) # Python 3.2+ has the __qualname__ attribute, but it does not # allow it to be overridden using a property and it must instead # be an actual string object instead. try: object.__setattr__(self, '__qualname__', wrapped.__qualname__) except AttributeError: pass @property def __name__(self): return self.__wrapped__.__name__ @__name__.setter def __name__(self, value): self.__wrapped__.__name__ = value @property def __class__(self): return self.__wrapped__.__class__ @__class__.setter def __class__(self, value): self.__wrapped__.__class__ = value @property def __annotations__(self): return self.__wrapped__.__anotations__ @__annotations__.setter def __annotations__(self, value): self.__wrapped__.__annotations__ = value def __dir__(self): return dir(self.__wrapped__) def __str__(self): return str(self.__wrapped__) if PY3: def __bytes__(self): return bytes(self.__wrapped__) def __repr__(self): return '<%s at 0x%x for %s at 0x%x>' % ( type(self).__name__, id(self), type(self.__wrapped__).__name__, id(self.__wrapped__)) def __reversed__(self): return reversed(self.__wrapped__) if PY3: def __round__(self): return round(self.__wrapped__) def __lt__(self, other): return self.__wrapped__ < other def __le__(self, other): return self.__wrapped__ <= other def __eq__(self, other): return self.__wrapped__ == other def __ne__(self, other): return self.__wrapped__ != other def __gt__(self, other): return self.__wrapped__ > other def __ge__(self, other): return self.__wrapped__ >= other def __hash__(self): return hash(self.__wrapped__) def __nonzero__(self): return bool(self.__wrapped__) def __bool__(self): return bool(self.__wrapped__) def __setattr__(self, name, value): if name.startswith('_self_'): object.__setattr__(self, name, value) elif name == '__wrapped__': object.__setattr__(self, name, value) try: object.__delattr__(self, '__qualname__') except AttributeError: pass try: object.__setattr__(self, '__qualname__', value.__qualname__) except AttributeError: pass elif name == '__qualname__': setattr(self.__wrapped__, name, value) object.__setattr__(self, name, value) elif hasattr(type(self), name): object.__setattr__(self, name, value) else: setattr(self.__wrapped__, name, value) def __getattr__(self, name): # If we are being to lookup '__wrapped__' then the # '__init__()' method cannot have been called. if name == '__wrapped__': raise ValueError('wrapper has not been initialised') return getattr(self.__wrapped__, name) def __delattr__(self, name): if name.startswith('_self_'): object.__delattr__(self, name) elif name == '__wrapped__': raise TypeError('__wrapped__ must be an object') elif name == '__qualname__': object.__delattr__(self, name) delattr(self.__wrapped__, name) elif hasattr(type(self), name): object.__delattr__(self, name) else: delattr(self.__wrapped__, name) def __add__(self, other): return self.__wrapped__ + other def __sub__(self, other): return self.__wrapped__ - other def __mul__(self, other): return self.__wrapped__ * other def __div__(self, other): return operator.div(self.__wrapped__, other) def __truediv__(self, other): return operator.truediv(self.__wrapped__, other) def __floordiv__(self, other): return self.__wrapped__ // other def __mod__(self, other): return self.__wrapped__ % other def __divmod__(self, other): return divmod(self.__wrapped__, other) def __pow__(self, other, *args): return pow(self.__wrapped__, other, *args) def __lshift__(self, other): return self.__wrapped__ << other def __rshift__(self, other): return self.__wrapped__ >> other def __and__(self, other): return self.__wrapped__ & other def __xor__(self, other): return self.__wrapped__ ^ other def __or__(self, other): return self.__wrapped__ | other def __radd__(self, other): return other + self.__wrapped__ def __rsub__(self, other): return other - self.__wrapped__ def __rmul__(self, other): return other * self.__wrapped__ def __rdiv__(self, other): return operator.div(other, self.__wrapped__) def __rtruediv__(self, other): return operator.truediv(other, self.__wrapped__) def __rfloordiv__(self, other): return other // self.__wrapped__ def __rmod__(self, other): return other % self.__wrapped__ def __rdivmod__(self, other): return divmod(other, self.__wrapped__) def __rpow__(self, other, *args): return pow(other, self.__wrapped__, *args) def __rlshift__(self, other): return other << self.__wrapped__ def __rrshift__(self, other): return other >> self.__wrapped__ def __rand__(self, other): return other & self.__wrapped__ def __rxor__(self, other): return other ^ self.__wrapped__ def __ror__(self, other): return other | self.__wrapped__ def __iadd__(self, other): self.__wrapped__ += other return self def __isub__(self, other): self.__wrapped__ -= other return self def __imul__(self, other): self.__wrapped__ *= other return self def __idiv__(self, other): self.__wrapped__ = operator.idiv(self.__wrapped__, other) return self def __itruediv__(self, other): self.__wrapped__ = operator.itruediv(self.__wrapped__, other) return self def __ifloordiv__(self, other): self.__wrapped__ //= other return self def __imod__(self, other): self.__wrapped__ %= other return self def __ipow__(self, other): self.__wrapped__ **= other return self def __ilshift__(self, other): self.__wrapped__ <<= other return self def __irshift__(self, other): self.__wrapped__ >>= other return self def __iand__(self, other): self.__wrapped__ &= other return self def __ixor__(self, other): self.__wrapped__ ^= other return self def __ior__(self, other): self.__wrapped__ |= other return self def __neg__(self): return -self.__wrapped__ def __pos__(self): return +self.__wrapped__ def __abs__(self): return abs(self.__wrapped__) def __invert__(self): return ~self.__wrapped__ def __int__(self): return int(self.__wrapped__) def __long__(self): return long(self.__wrapped__) def __float__(self): return float(self.__wrapped__) def __oct__(self): return oct(self.__wrapped__) def __hex__(self): return hex(self.__wrapped__) def __index__(self): return operator.index(self.__wrapped__) def __len__(self): return len(self.__wrapped__) def __contains__(self, value): return value in self.__wrapped__ def __getitem__(self, key): return self.__wrapped__[key] def __setitem__(self, key, value): self.__wrapped__[key] = value def __delitem__(self, key): del self.__wrapped__[key] def __getslice__(self, i, j): return self.__wrapped__[i:j] def __setslice__(self, i, j, value): self.__wrapped__[i:j] = value def __delslice__(self, i, j): del self.__wrapped__[i:j] def __enter__(self): return self.__wrapped__.__enter__() def __exit__(self, *args, **kwargs): return self.__wrapped__.__exit__(*args, **kwargs) def __iter__(self): return iter(self.__wrapped__) class CallableObjectProxy(ObjectProxy): def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) class _FunctionWrapperBase(ObjectProxy): __slots__ = ('_self_instance', '_self_wrapper', '_self_enabled', '_self_binding', '_self_parent') def __init__(self, wrapped, instance, wrapper, enabled=None, binding='function', parent=None): super(_FunctionWrapperBase, self).__init__(wrapped) object.__setattr__(self, '_self_instance', instance) object.__setattr__(self, '_self_wrapper', wrapper) object.__setattr__(self, '_self_enabled', enabled) object.__setattr__(self, '_self_binding', binding) object.__setattr__(self, '_self_parent', parent) def __get__(self, instance, owner): # This method is actually doing double duty for both unbound and # bound derived wrapper classes. It should possibly be broken up # and the distinct functionality moved into the derived classes. # Can't do that straight away due to some legacy code which is # relying on it being here in this base class. # # The distinguishing attribute which determines whether we are # being called in an unbound or bound wrapper is the parent # attribute. If binding has never occurred, then the parent will # be None. # # First therefore, is if we are called in an unbound wrapper. In # this case we perform the binding. # # We have one special case to worry about here. This is where we # are decorating a nested class. In this case the wrapped class # would not have a __get__() method to call. In that case we # simply return self. # # Note that we otherwise still do binding even if instance is # None and accessing an unbound instance method from a class. # This is because we need to be able to later detect that # specific case as we will need to extract the instance from the # first argument of those passed in. if self._self_parent is None: if not inspect.isclass(self.__wrapped__): descriptor = self.__wrapped__.__get__(instance, owner) return self.__bound_function_wrapper__(descriptor, instance, self._self_wrapper, self._self_enabled, self._self_binding, self) return self # Now we have the case of binding occurring a second time on what # was already a bound function. In this case we would usually # return ourselves again. This mirrors what Python does. # # The special case this time is where we were originally bound # with an instance of None and we were likely an instance # method. In that case we rebind against the original wrapped # function from the parent again. if self._self_instance is None and self._self_binding == 'function': descriptor = self._self_parent.__wrapped__.__get__( instance, owner) return self._self_parent.__bound_function_wrapper__( descriptor, instance, self._self_wrapper, self._self_enabled, self._self_binding, self._self_parent) return self def __call__(self, *args, **kwargs): # If enabled has been specified, then evaluate it at this point # and if the wrapper is not to be executed, then simply return # the bound function rather than a bound wrapper for the bound # function. When evaluating enabled, if it is callable we call # it, otherwise we evaluate it as a boolean. if self._self_enabled is not None: if callable(self._self_enabled): if not self._self_enabled(): return self.__wrapped__(*args, **kwargs) elif not self._self_enabled: return self.__wrapped__(*args, **kwargs) # This can occur where initial function wrapper was applied to # a function that was already bound to an instance. In that case # we want to extract the instance from the function and use it. if self._self_binding == 'function': if self._self_instance is None: instance = getattr(self.__wrapped__, '__self__', None) if instance is not None: return self._self_wrapper(self.__wrapped__, instance, args, kwargs) # This is generally invoked when the wrapped function is being # called as a normal function and is not bound to a class as an # instance method. This is also invoked in the case where the # wrapped function was a method, but this wrapper was in turn # wrapped using the staticmethod decorator. return self._self_wrapper(self.__wrapped__, self._self_instance, args, kwargs) class BoundFunctionWrapper(_FunctionWrapperBase): def __call__(self, *args, **kwargs): # If enabled has been specified, then evaluate it at this point # and if the wrapper is not to be executed, then simply return # the bound function rather than a bound wrapper for the bound # function. When evaluating enabled, if it is callable we call # it, otherwise we evaluate it as a boolean. if self._self_enabled is not None: if callable(self._self_enabled): if not self._self_enabled(): return self.__wrapped__(*args, **kwargs) elif not self._self_enabled: return self.__wrapped__(*args, **kwargs) # We need to do things different depending on whether we are # likely wrapping an instance method vs a static method or class # method. if self._self_binding == 'function': if self._self_instance is None: # This situation can occur where someone is calling the # instancemethod via the class type and passing the instance # as the first argument. We need to shift the args before # making the call to the wrapper and effectively bind the # instance to the wrapped function using a partial so the # wrapper doesn't see anything as being different. if not args: raise TypeError('missing 1 required positional argument') instance, args = args[0], args[1:] wrapped = functools.partial(self.__wrapped__, instance) return self._self_wrapper(wrapped, instance, args, kwargs) return self._self_wrapper(self.__wrapped__, self._self_instance, args, kwargs) else: # As in this case we would be dealing with a classmethod or # staticmethod, then _self_instance will only tell us whether # when calling the classmethod or staticmethod they did it via an # instance of the class it is bound to and not the case where # done by the class type itself. We thus ignore _self_instance # and use the __self__ attribute of the bound function instead. # For a classmethod, this means instance will be the class type # and for a staticmethod it will be None. This is probably the # more useful thing we can pass through even though we loose # knowledge of whether they were called on the instance vs the # class type, as it reflects what they have available in the # decoratored function. instance = getattr(self.__wrapped__, '__self__', None) return self._self_wrapper(self.__wrapped__, instance, args, kwargs) class FunctionWrapper(_FunctionWrapperBase): __bound_function_wrapper__ = BoundFunctionWrapper def __init__(self, wrapped, wrapper, enabled=None): # What it is we are wrapping here could be anything. We need to # try and detect specific cases though. In particular, we need # to detect when we are given something that is a method of a # class. Further, we need to know when it is likely an instance # method, as opposed to a class or static method. This can # become problematic though as there isn't strictly a fool proof # method of knowing. # # The situations we could encounter when wrapping a method are: # # 1. The wrapper is being applied as part of a decorator which # is a part of the class definition. In this case what we are # given is the raw unbound function, classmethod or staticmethod # wrapper objects. # # The problem here is that we will not know we are being applied # in the context of the class being set up. This becomes # important later for the case of an instance method, because in # that case we just see it as a raw function and can't # distinguish it from wrapping a normal function outside of # a class context. # # 2. The wrapper is being applied when performing monkey # patching of the class type afterwards and the method to be # wrapped was retrieved direct from the __dict__ of the class # type. This is effectively the same as (1) above. # # 3. The wrapper is being applied when performing monkey # patching of the class type afterwards and the method to be # wrapped was retrieved from the class type. In this case # binding will have been performed where the instance against # which the method is bound will be None at that point. # # This case is a problem because we can no longer tell if the # method was a static method, plus if using Python3, we cannot # tell if it was an instance method as the concept of an # unnbound method no longer exists. # # 4. The wrapper is being applied when performing monkey # patching of an instance of a class. In this case binding will # have been perfomed where the instance was not None. # # This case is a problem because we can no longer tell if the # method was a static method. # # Overall, the best we can do is look at the original type of the # object which was wrapped prior to any binding being done and # see if it is an instance of classmethod or staticmethod. In # the case where other decorators are between us and them, if # they do not propagate the __class__ attribute so that the # isinstance() checks works, then likely this will do the wrong # thing where classmethod and staticmethod are used. # # Since it is likely to be very rare that anyone even puts # decorators around classmethod and staticmethod, likelihood of # that being an issue is very small, so we accept it and suggest # that those other decorators be fixed. It is also only an issue # if a decorator wants to actually do things with the arguments. # # As to not being able to identify static methods properly, we # just hope that that isn't something people are going to want # to wrap, or if they do suggest they do it the correct way by # ensuring that it is decorated in the class definition itself, # or patch it in the __dict__ of the class type. # # So to get the best outcome we can, whenever we aren't sure what # it is, we label it as a 'function'. If it was already bound and # that is rebound later, we assume that it will be an instance # method and try an cope with the possibility that the 'self' # argument it being passed as an explicit argument and shuffle # the arguments around to extract 'self' for use as the instance. if isinstance(wrapped, classmethod): binding = 'classmethod' elif isinstance(wrapped, staticmethod): binding = 'staticmethod' elif hasattr(wrapped, '__self__'): if inspect.isclass(wrapped.__self__): binding = 'classmethod' else: binding = 'function' else: binding = 'function' super(FunctionWrapper, self).__init__(wrapped, None, wrapper, enabled, binding) try: if not os.environ.get('WRAPT_DISABLE_EXTENSIONS'): from ._wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, _FunctionWrapperBase) except ImportError: pass # Helper functions for applying wrappers to existing functions. def resolve_path(module, name): if isinstance(module, string_types): __import__(module) module = sys.modules[module] parent = module path = name.split('.') attribute = path[0] original = getattr(parent, attribute) for attribute in path[1:]: parent = original # We can't just always use getattr() because in doing # that on a class it will cause binding to occur which # will complicate things later and cause some things not # to work. For the case of a class we therefore access # the __dict__ directly. To cope though with the wrong # class being given to us, or a method being moved into # a base class, we need to walk the class hierarchy to # work out exactly which __dict__ the method was defined # in, as accessing it from __dict__ will fail if it was # not actually on the class given. Fallback to using # getattr() if we can't find it. If it truly doesn't # exist, then that will fail. if inspect.isclass(original): for cls in inspect.getmro(original): if attribute in vars(cls): original = vars(cls)[attribute] break else: original = getattr(original, attribute) else: original = getattr(original, attribute) return (parent, attribute, original) def apply_patch(parent, attribute, replacement): setattr(parent, attribute, replacement) def wrap_object(module, name, factory, args=(), kwargs={}): (parent, attribute, original) = resolve_path(module, name) wrapper = factory(original, *args, **kwargs) apply_patch(parent, attribute, wrapper) return wrapper # Function for applying a proxy object to an attribute of a class # instance. The wrapper works by defining an attribute of the same name # on the class which is a descriptor and which intercepts access to the # instance attribute. Note that this cannot be used on attributes which # are themselves defined by a property object. class AttributeWrapper(object): def __init__(self, attribute, factory, args, kwargs): self.attribute = attribute self.factory = factory self.args = args self.kwargs = kwargs def __get__(self, instance, owner): value = instance.__dict__[self.attribute] return self.factory(value, *self.args, **self.kwargs) def __set__(self, instance, value): instance.__dict__[self.attribute] = value def __delete__(self, instance): del instance.__dict__[self.attribute] def wrap_object_attribute(module, name, factory, args=(), kwargs={}): path, attribute = name.rsplit('.', 1) parent = resolve_path(module, path)[2] wrapper = AttributeWrapper(attribute, factory, args, kwargs) apply_patch(parent, attribute, wrapper) return wrapper # Functions for creating a simple decorator using a FunctionWrapper, # plus short cut functions for applying wrappers to functions. These are # for use when doing monkey patching. For a more featured way of # creating decorators see the decorator decorator instead. def function_wrapper(wrapper): def _wrapper(wrapped, instance, args, kwargs): target_wrapped = args[0] if instance is None: target_wrapper = wrapper elif inspect.isclass(instance): target_wrapper = wrapper.__get__(None, instance) else: target_wrapper = wrapper.__get__(instance, type(instance)) return FunctionWrapper(target_wrapped, target_wrapper) return FunctionWrapper(wrapper, _wrapper) def wrap_function_wrapper(module, name, wrapper): return wrap_object(module, name, FunctionWrapper, (wrapper,)) def patch_function_wrapper(module, name): def _wrapper(wrapper): return wrap_object(module, name, FunctionWrapper, (wrapper,)) return _wrapper def transient_function_wrapper(module, name): def _decorator(wrapper): def _wrapper(wrapped, instance, args, kwargs): target_wrapped = args[0] if instance is None: target_wrapper = wrapper elif inspect.isclass(instance): target_wrapper = wrapper.__get__(None, instance) else: target_wrapper = wrapper.__get__(instance, type(instance)) def _execute(wrapped, instance, args, kwargs): (parent, attribute, original) = resolve_path(module, name) replacement = FunctionWrapper(original, target_wrapper) setattr(parent, attribute, replacement) try: return wrapped(*args, **kwargs) finally: setattr(parent, attribute, original) return FunctionWrapper(target_wrapped, _execute) return FunctionWrapper(wrapper, _wrapper) return _decorator # A weak function proxy. This will work on instance methods, class # methods, static methods and regular functions. Special treatment is # needed for the method types because the bound method is effectively a # transient object and applying a weak reference to one will immediately # result in it being destroyed and the weakref callback called. The weak # reference is therefore applied to the instance the method is bound to # and the original function. The function is then rebound at the point # of a call via the weak function proxy. def _weak_function_proxy_callback(ref, proxy, callback): if proxy._self_expired: return proxy._self_expired = True # This could raise an exception. We let it propagate back and let # the weakref.proxy() deal with it, at which point it generally # prints out a short error message direct to stderr and keeps going. if callback is not None: callback(proxy) class WeakFunctionProxy(ObjectProxy): __slots__ = ('_self_expired', '_self_instance') def __init__(self, wrapped, callback=None): # We need to determine if the wrapped function is actually a # bound method. In the case of a bound method, we need to keep a # reference to the original unbound function and the instance. # This is necessary because if we hold a reference to the bound # function, it will be the only reference and given it is a # temporary object, it will almost immediately expire and # the weakref callback triggered. So what is done is that we # hold a reference to the instance and unbound function and # when called bind the function to the instance once again and # then call it. Note that we avoid using a nested function for # the callback here so as not to cause any odd reference cycles. _callback = callback and functools.partial( _weak_function_proxy_callback, proxy=self, callback=callback) self._self_expired = False if isinstance(wrapped, _FunctionWrapperBase): self._self_instance = weakref.ref(wrapped._self_instance, _callback) if wrapped._self_parent is not None: super(WeakFunctionProxy, self).__init__( weakref.proxy(wrapped._self_parent, _callback)) else: super(WeakFunctionProxy, self).__init__( weakref.proxy(wrapped, _callback)) return try: self._self_instance = weakref.ref(wrapped.__self__, _callback) super(WeakFunctionProxy, self).__init__( weakref.proxy(wrapped.__func__, _callback)) except AttributeError: self._self_instance = None super(WeakFunctionProxy, self).__init__( weakref.proxy(wrapped, _callback)) def __call__(self, *args, **kwargs): # We perform a boolean check here on the instance and wrapped # function as that will trigger the reference error prior to # calling if the reference had expired. instance = self._self_instance and self._self_instance() function = self.__wrapped__ and self.__wrapped__ # If the wrapped function was originally a bound function, for # which we retained a reference to the instance and the unbound # function we need to rebind the function and then call it. If # not just called the wrapped function. if instance is None: return self.__wrapped__(*args, **kwargs) return function.__get__(instance, type(instance))(*args, **kwargs)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/wrappers.py
wrappers.py
__version_info__ = ('1', '10', '11') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch, wrap_object, wrap_object_attribute, function_wrapper, wrap_function_wrapper, patch_function_wrapper, transient_function_wrapper) from .decorators import (adapter_factory, AdapterFactory, decorator, synchronized) from .importer import (register_post_import_hook, when_imported, notify_module_loaded, discover_post_import_hooks) try: from inspect import getcallargs except ImportError: from .arguments import getcallargs
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/utils/wrapt/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import decimal import re EVENTS_API_PATH = "intake/v2/events" AGENT_CONFIG_PATH = "config/v1/agents" TRACE_CONTEXT_VERSION = 0 TRACEPARENT_HEADER_NAME = "traceparent" TRACEPARENT_LEGACY_HEADER_NAME = "zuqa-traceparent" TRACESTATE_HEADER_NAME = "tracestate" TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" KEYWORD_MAX_LENGTH = 1024 HTTP_WITH_BODY = {"POST", "PUT", "PATCH", "DELETE"} MASK = 8 * "*" EXCEPTION_CHAIN_MAX_DEPTH = 50 ERROR = "error" TRANSACTION = "transaction" SPAN = "span" METRICSET = "metricset" TRANSACTION_METRICSET = "transaction_metricset" LABEL_RE = re.compile('[.*"]') HARDCODED_PROCESSORS = ["zuqa.processors.add_context_lines_to_frames"] try: # Python 2 LABEL_TYPES = (bool, int, long, float, decimal.Decimal) except NameError: # Python 3 LABEL_TYPES = (bool, int, float, decimal.Decimal)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/conf/constants.py
constants.py
# BSD 3-Clause License # # Copyright (c) 2012, the Sentry Team, see AUTHORS for more details # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE import logging import os import re import socket import threading from zuqa.utils import compat, starmatch_to_regex from zuqa.utils.logging import get_logger from zuqa.utils.threading import IntervalTimer, ThreadManager __all__ = ("setup_logging", "Config") logger = get_logger("zuqa.conf") class ConfigurationError(ValueError): def __init__(self, msg, field_name): self.field_name = field_name super(ValueError, self).__init__(msg) class _ConfigValue(object): def __init__(self, dict_key, env_key=None, type=compat.text_type, validators=None, default=None, required=False): self.type = type self.dict_key = dict_key self.validators = validators self.default = default self.required = required if env_key is None: env_key = "ZUQA_" + dict_key self.env_key = env_key def __get__(self, instance, owner): if instance: return instance._values.get(self.dict_key, self.default) else: return self.default def __set__(self, instance, value): value = self._validate(instance, value) instance._values[self.dict_key] = value def _validate(self, instance, value): if value is None and self.required: raise ConfigurationError( "Configuration error: value for {} is required.".format(self.dict_key), self.dict_key ) if self.validators and value is not None: for validator in self.validators: value = validator(value, self.dict_key) if self.type and value is not None: try: value = self.type(value) except ValueError as e: raise ConfigurationError("{}: {}".format(self.dict_key, compat.text_type(e)), self.dict_key) instance._errors.pop(self.dict_key, None) return value class _ListConfigValue(_ConfigValue): def __init__(self, dict_key, list_separator=",", **kwargs): self.list_separator = list_separator super(_ListConfigValue, self).__init__(dict_key, **kwargs) def __set__(self, instance, value): if isinstance(value, compat.string_types): value = value.split(self.list_separator) elif value is not None: value = list(value) if value: value = [self.type(item) for item in value] instance._values[self.dict_key] = value class _DictConfigValue(_ConfigValue): def __init__(self, dict_key, item_separator=",", keyval_separator="=", **kwargs): self.item_separator = item_separator self.keyval_separator = keyval_separator super(_DictConfigValue, self).__init__(dict_key, **kwargs) def __set__(self, instance, value): if isinstance(value, compat.string_types): items = (item.split(self.keyval_separator) for item in value.split(self.item_separator)) value = {key.strip(): self.type(val.strip()) for key, val in items} elif not isinstance(value, dict): # TODO: better error handling value = None instance._values[self.dict_key] = value class _BoolConfigValue(_ConfigValue): def __init__(self, dict_key, true_string="true", false_string="false", **kwargs): self.true_string = true_string self.false_string = false_string super(_BoolConfigValue, self).__init__(dict_key, **kwargs) def __set__(self, instance, value): if isinstance(value, compat.string_types): if value.lower() == self.true_string: value = True elif value.lower() == self.false_string: value = False instance._values[self.dict_key] = bool(value) class RegexValidator(object): def __init__(self, regex, verbose_pattern=None): self.regex = regex self.verbose_pattern = verbose_pattern or regex def __call__(self, value, field_name): value = compat.text_type(value) match = re.match(self.regex, value) if match: return value raise ConfigurationError("{} does not match pattern {}".format(value, self.verbose_pattern), field_name) class UnitValidator(object): def __init__(self, regex, verbose_pattern, unit_multipliers): self.regex = regex self.verbose_pattern = verbose_pattern self.unit_multipliers = unit_multipliers def __call__(self, value, field_name): value = compat.text_type(value) match = re.match(self.regex, value, re.IGNORECASE) if not match: raise ConfigurationError("{} does not match pattern {}".format(value, self.verbose_pattern), field_name) val, unit = match.groups() try: val = int(val) * self.unit_multipliers[unit] except KeyError: raise ConfigurationError("{} is not a supported unit".format(unit), field_name) return val duration_validator = UnitValidator(r"^((?:-)?\d+)(ms|s|m)$", r"\d+(ms|s|m)", {"ms": 1, "s": 1000, "m": 60000}) size_validator = UnitValidator( r"^(\d+)(b|kb|mb|gb)$", r"\d+(b|KB|MB|GB)", {"b": 1, "kb": 1024, "mb": 1024 * 1024, "gb": 1024 * 1024 * 1024} ) class ExcludeRangeValidator(object): def __init__(self, range_start, range_end, range_desc): self.range_start = range_start self.range_end = range_end self.range_desc = range_desc def __call__(self, value, field_name): if self.range_start <= value <= self.range_end: raise ConfigurationError( "{} cannot be in range: {}".format( value, self.range_desc.format(**{"range_start": self.range_start, "range_end": self.range_end}) ), field_name, ) return value class FileIsReadableValidator(object): def __call__(self, value, field_name): value = os.path.normpath(value) if not os.path.exists(value): raise ConfigurationError("{} does not exist".format(value), field_name) elif not os.path.isfile(value): raise ConfigurationError("{} is not a file".format(value), field_name) elif not os.access(value, os.R_OK): raise ConfigurationError("{} is not readable".format(value), field_name) return value class _ConfigBase(object): _NO_VALUE = object() # sentinel object def __init__(self, config_dict=None, env_dict=None, inline_dict=None): self._values = {} self._errors = {} self.update(config_dict, env_dict, inline_dict) def update(self, config_dict=None, env_dict=None, inline_dict=None): if config_dict is None: config_dict = {} if env_dict is None: env_dict = os.environ if inline_dict is None: inline_dict = {} for field, config_value in self.__class__.__dict__.items(): if not isinstance(config_value, _ConfigValue): continue new_value = self._NO_VALUE # first check environment if config_value.env_key and config_value.env_key in env_dict: new_value = env_dict[config_value.env_key] # check the inline config elif field in inline_dict: new_value = inline_dict[field] # finally, check config dictionary elif config_value.dict_key in config_dict: new_value = config_dict[config_value.dict_key] # only set if new_value changed. We'll fall back to the field default if not. if new_value is not self._NO_VALUE: try: setattr(self, field, new_value) except ConfigurationError as e: self._errors[e.field_name] = str(e) @property def values(self): return self._values @values.setter def values(self, values): self._values = values @property def errors(self): return self._errors class Config(_ConfigBase): service_name = _ConfigValue("SERVICE_NAME", validators=[RegexValidator("^[a-zA-Z0-9 _-]+$")], required=True) service_node_name = _ConfigValue("SERVICE_NODE_NAME", default=None) environment = _ConfigValue("ENVIRONMENT", default=None) secret_token = _ConfigValue("SECRET_TOKEN") api_key = _ConfigValue("API_KEY") debug = _BoolConfigValue("DEBUG", default=False) server_url = _ConfigValue("SERVER_URL", default="http://localhost:32140", required=True) server_cert = _ConfigValue("SERVER_CERT", default=None, required=False, validators=[FileIsReadableValidator()]) verify_server_cert = _BoolConfigValue("VERIFY_SERVER_CERT", default=True) include_paths = _ListConfigValue("INCLUDE_PATHS") exclude_paths = _ListConfigValue("EXCLUDE_PATHS", default=compat.get_default_library_patters()) filter_exception_types = _ListConfigValue("FILTER_EXCEPTION_TYPES") server_timeout = _ConfigValue( "SERVER_TIMEOUT", type=float, validators=[ UnitValidator(r"^((?:-)?\d+)(ms|s|m)?$", r"\d+(ms|s|m)", {"ms": 0.001, "s": 1, "m": 60, None: 1000}) ], default=5, ) hostname = _ConfigValue("HOSTNAME", default=socket.gethostname()) auto_log_stacks = _BoolConfigValue("AUTO_LOG_STACKS", default=True) transport_class = _ConfigValue("TRANSPORT_CLASS", default="zuqa.transport.http.Transport", required=True) processors = _ListConfigValue( "PROCESSORS", default=[ "zuqa.processors.sanitize_stacktrace_locals", "zuqa.processors.sanitize_http_request_cookies", "zuqa.processors.sanitize_http_response_cookies", "zuqa.processors.sanitize_http_headers", "zuqa.processors.sanitize_http_wsgi_env", "zuqa.processors.sanitize_http_request_querystring", "zuqa.processors.sanitize_http_request_body", ], ) metrics_sets = _ListConfigValue( "METRICS_SETS", default=[ "zuqa.metrics.sets.cpu.CPUMetricSet", "zuqa.metrics.sets.transactions.TransactionsMetricSet", ], ) metrics_interval = _ConfigValue( "METRICS_INTERVAL", type=int, validators=[duration_validator, ExcludeRangeValidator(1, 99, "{range_start} - {range_end} ms")], default=100, ) breakdown_metrics = _BoolConfigValue("BREAKDOWN_METRICS", default=True) disable_metrics = _ListConfigValue("DISABLE_METRICS", type=starmatch_to_regex, default=[]) central_config = _BoolConfigValue("CENTRAL_CONFIG", default=True) api_request_size = _ConfigValue("API_REQUEST_SIZE", type=int, validators=[size_validator], default=768 * 1024) api_request_time = _ConfigValue("API_REQUEST_TIME", type=int, validators=[duration_validator], default=1 * 1000) transaction_sample_rate = _ConfigValue("TRANSACTION_SAMPLE_RATE", type=float, default=1.0) transaction_max_spans = _ConfigValue("TRANSACTION_MAX_SPANS", type=int, default=500) stack_trace_limit = _ConfigValue("STACK_TRACE_LIMIT", type=int, default=500) span_frames_min_duration = _ConfigValue( "SPAN_FRAMES_MIN_DURATION", default=5, validators=[ UnitValidator(r"^((?:-)?\d+)(ms|s|m)?$", r"\d+(ms|s|m)", {"ms": 1, "s": 1000, "m": 60000, None: 1}) ], type=int, ) collect_local_variables = _ConfigValue("COLLECT_LOCAL_VARIABLES", default="errors") source_lines_error_app_frames = _ConfigValue("SOURCE_LINES_ERROR_APP_FRAMES", type=int, default=5) source_lines_error_library_frames = _ConfigValue("SOURCE_LINES_ERROR_LIBRARY_FRAMES", type=int, default=5) source_lines_span_app_frames = _ConfigValue("SOURCE_LINES_SPAN_APP_FRAMES", type=int, default=0) source_lines_span_library_frames = _ConfigValue("SOURCE_LINES_SPAN_LIBRARY_FRAMES", type=int, default=0) local_var_max_length = _ConfigValue("LOCAL_VAR_MAX_LENGTH", type=int, default=200) local_var_list_max_length = _ConfigValue("LOCAL_VAR_LIST_MAX_LENGTH", type=int, default=10) local_var_dict_max_length = _ConfigValue("LOCAL_VAR_DICT_MAX_LENGTH", type=int, default=10) capture_body = _ConfigValue( "CAPTURE_BODY", default="off", validators=[lambda val, _: {"errors": "error", "transactions": "transaction"}.get(val, val)], ) async_mode = _BoolConfigValue("ASYNC_MODE", default=True) instrument_django_middleware = _BoolConfigValue("INSTRUMENT_DJANGO_MIDDLEWARE", default=True) autoinsert_django_middleware = _BoolConfigValue("AUTOINSERT_DJANGO_MIDDLEWARE", default=True) transactions_ignore_patterns = _ListConfigValue("TRANSACTIONS_IGNORE_PATTERNS", default=[]) service_version = _ConfigValue("SERVICE_VERSION") framework_name = _ConfigValue("FRAMEWORK_NAME", default=None) framework_version = _ConfigValue("FRAMEWORK_VERSION", default=None) global_labels = _DictConfigValue("GLOBAL_LABELS", default=None) disable_send = _BoolConfigValue("DISABLE_SEND", default=False) enabled = _BoolConfigValue("ENABLED", default=True) recording = _BoolConfigValue("RECORDING", default=True) instrument = _BoolConfigValue("INSTRUMENT", default=True) enable_distributed_tracing = _BoolConfigValue("ENABLE_DISTRIBUTED_TRACING", default=True) capture_headers = _BoolConfigValue("CAPTURE_HEADERS", default=True) django_transaction_name_from_route = _BoolConfigValue("DJANGO_TRANSACTION_NAME_FROM_ROUTE", default=False) disable_log_record_factory = _BoolConfigValue("DISABLE_LOG_RECORD_FACTORY", default=False) use_elastic_traceparent_header = _BoolConfigValue("USE_ELASTIC_TRACEPARENT_HEADER", default=True) @property def is_recording(self): if not self.enabled: return False else: return self.recording class VersionedConfig(ThreadManager): """ A thin layer around Config that provides versioning """ __slots__ = ( "_config", "_version", "_first_config", "_first_version", "_lock", "transport", "_update_thread", "pid", ) def __init__(self, config_object, version, transport=None): """ Create a new VersionedConfig with an initial Config object :param config_object: the initial Config object :param version: a version identifier for the configuration """ self._config = self._first_config = config_object self._version = self._first_version = version self.transport = transport self._lock = threading.Lock() self._update_thread = None super(VersionedConfig, self).__init__() def update(self, version, **config): """ Update the configuration version :param version: version identifier for the new configuration :param config: a key/value map of new configuration :return: configuration errors, if any """ new_config = Config() new_config.values = self._config.values.copy() # pass an empty env dict to ensure the environment doesn't get precedence new_config.update(inline_dict=config, env_dict={}) if not new_config.errors: with self._lock: self._version = version self._config = new_config else: return new_config.errors def reset(self): """ Reset state to the original configuration """ with self._lock: self._version = self._first_version self._config = self._first_config @property def changed(self): return self._config != self._first_config def __getattr__(self, item): return getattr(self._config, item) def __setattr__(self, name, value): if name not in self.__slots__: setattr(self._config, name, value) else: super(VersionedConfig, self).__setattr__(name, value) @property def config_version(self): return self._version def update_config(self): if not self.transport: logger.warning("No transport set for config updates, skipping") return logger.debug("Checking for new config...") keys = {"service": {"name": self.service_name}} if self.environment: keys["service"]["environment"] = self.environment new_version, new_config, next_run = self.transport.get_config(self.config_version, keys) if new_version and new_config: errors = self.update(new_version, **new_config) if errors: logger.error("Error applying new configuration: %s", repr(errors)) else: logger.info( "Applied new configuration: %s", "; ".join( "%s=%s" % (compat.text_type(k), compat.text_type(v)) for k, v in compat.iteritems(new_config) ), ) elif new_version == self.config_version: logger.debug("Remote config unchanged") elif not new_config and self.changed: logger.debug("Remote config disappeared, resetting to original") self.reset() return next_run def start_thread(self, pid=None): self._update_thread = IntervalTimer( self.update_config, 1, "eapm conf updater", daemon=True, evaluate_function_interval=True ) self._update_thread.start() super(VersionedConfig, self).start_thread(pid=pid) def stop_thread(self): if self._update_thread: self._update_thread.cancel() self._update_thread = None def setup_logging(handler, exclude=("gunicorn", "south", "zuqa.errors")): """ Configures logging to pipe to ZUQA. - ``exclude`` is a list of loggers that shouldn't go to ZUQA. For a typical Python install: >>> from zuqa.handlers.logging import LoggingHandler >>> client = ZUQA(...) >>> setup_logging(LoggingHandler(client)) Within Django: >>> from zuqa.contrib.django.handlers import LoggingHandler >>> setup_logging(LoggingHandler()) Returns a boolean based on if logging was configured or not. """ logger = logging.getLogger() if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler) return True
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/conf/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import threading import time from collections import defaultdict from zuqa.conf import constants from zuqa.utils import compat from zuqa.utils.logging import get_logger from zuqa.utils.module_import import import_string from zuqa.utils.threading import IntervalTimer, ThreadManager logger = get_logger("zuqa.metrics") DISTINCT_LABEL_LIMIT = 1000 class MetricsRegistry(ThreadManager): def __init__(self, client, tags=None): """ Creates a new metric registry :param client: client instance :param tags: """ self.client = client self._metricsets = {} self._tags = tags or {} self._collect_timer = None self.collect_actively = False # for transaction specific metrics self.last_transaction_name = None # for transaction specific metrics self.transaction_metrics_data = [] # for transaction specific metrics super(MetricsRegistry, self).__init__() def register(self, class_path): """ Register a new metric set :param class_path: a string with the import path of the metricset class """ if class_path in self._metricsets: return else: try: class_obj = import_string(class_path) self._metricsets[class_path] = class_obj(self) except ImportError as e: logger.warning("Could not register %s metricset: %s", class_path, compat.text_type(e)) def get_metricset(self, class_path): try: return self._metricsets[class_path] except KeyError: raise MetricSetNotFound(class_path) def collect(self): """ Collect metrics from all registered metric sets and queues them for sending :return: """ if self.collect_actively: if self.client.config.is_recording: logger.debug("Collecting metrics") for _, metricset in compat.iteritems(self._metricsets): for data in metricset.collect(): self.transaction_metrics_data.append(data) elif len(self.transaction_metrics_data) > 0: self.client.queue(constants.TRANSACTION_METRICSET, { "url": self.last_transaction_name, "metricsets": self.transaction_metrics_data }, flush=True) self.transaction_metrics_data = [] def start_thread(self, pid=None): super(MetricsRegistry, self).start_thread(pid=pid) if self.client.config.metrics_interval: self._collect_timer = IntervalTimer( self.collect, self.collect_interval, name="eapm metrics collect timer", daemon=True ) logger.debug("Starting metrics collect timer") self._collect_timer.start() def stop_thread(self): if self._collect_timer and self._collect_timer.is_alive(): logger.debug("Cancelling collect timer") self._collect_timer.cancel() self._collect_timer = None @property def collect_interval(self): return self.client.config.metrics_interval / 1000.0 @property def ignore_patterns(self): return self.client.config.disable_metrics or [] class MetricsSet(object): def __init__(self, registry): self._lock = threading.Lock() self._counters = {} self._gauges = {} self._timers = {} self._registry = registry self._label_limit_logged = False def counter(self, name, reset_on_collect=False, **labels): """ Returns an existing or creates and returns a new counter :param name: name of the counter :param reset_on_collect: indicate if the counter should be reset to 0 when collecting :param labels: a flat key/value map of labels :return: the counter object """ return self._metric(self._counters, Counter, name, reset_on_collect, labels) def gauge(self, name, reset_on_collect=False, **labels): """ Returns an existing or creates and returns a new gauge :param name: name of the gauge :param reset_on_collect: indicate if the gouge should be reset to 0 when collecting :param labels: a flat key/value map of labels :return: the gauge object """ return self._metric(self._gauges, Gauge, name, reset_on_collect, labels) def timer(self, name, reset_on_collect=False, **labels): """ Returns an existing or creates and returns a new timer :param name: name of the timer :param reset_on_collect: indicate if the timer should be reset to 0 when collecting :param labels: a flat key/value map of labels :return: the timer object """ return self._metric(self._timers, Timer, name, reset_on_collect, labels) def _metric(self, container, metric_class, name, reset_on_collect, labels): """ Returns an existing or creates and returns a metric :param container: the container for the metric :param metric_class: the class of the metric :param name: name of the metric :param reset_on_collect: indicate if the metric should be reset to 0 when collecting :param labels: a flat key/value map of labels :return: the metric object """ labels = self._labels_to_key(labels) key = (name, labels) with self._lock: if key not in container: if any(pattern.match(name) for pattern in self._registry.ignore_patterns): metric = noop_metric elif len(self._gauges) + len(self._counters) + len(self._timers) >= DISTINCT_LABEL_LIMIT: if not self._label_limit_logged: self._label_limit_logged = True logger.warning( "The limit of %d metricsets has been reached, no new metricsets will be created." % DISTINCT_LABEL_LIMIT ) metric = noop_metric else: metric = metric_class(name, reset_on_collect=reset_on_collect) container[key] = metric return container[key] def collect(self): """ Collects all metrics attached to this metricset, and returns it as a generator with one or more elements. More than one element is returned if labels are used. The format of the return value should be { "samples": {"metric.name": {"value": some_float}, ...}, "timestamp": unix epoch in microsecond precision } """ self.before_collect() timestamp = int(time.time() * 1000000) samples = defaultdict(dict) if self._counters: # iterate over a copy of the dict to avoid threading issues, see #717 for (name, labels), c in compat.iteritems(self._counters.copy()): if c is not noop_metric: val = c.val if val or not c.reset_on_collect: samples[labels].update({name: {"value": val}}) if c.reset_on_collect: c.reset() if self._gauges: for (name, labels), g in compat.iteritems(self._gauges.copy()): if g is not noop_metric: val = g.val if val or not g.reset_on_collect: samples[labels].update({name: {"value": val}}) if g.reset_on_collect: g.reset() if self._timers: for (name, labels), t in compat.iteritems(self._timers.copy()): if t is not noop_metric: val, count = t.val if val or not t.reset_on_collect: samples[labels].update({name + ".sum.us": {"value": int(val * 1000000)}}) samples[labels].update({name + ".count": {"value": count}}) if t.reset_on_collect: t.reset() if samples: for labels, sample in compat.iteritems(samples): result = {"samples": sample, "timestamp": timestamp} if labels: result["tags"] = {k: v for k, v in labels} yield self.before_yield(result) def before_collect(self): """ A method that is called right before collection. Can be used to gather metrics. :return: """ pass def before_yield(self, data): return data def _labels_to_key(self, labels): return tuple((k, compat.text_type(v)) for k, v in sorted(compat.iteritems(labels))) class SpanBoundMetricSet(MetricsSet): def before_yield(self, data): tags = data.get("tags", None) if tags: span_type, span_subtype = tags.pop("span.type", None), tags.pop("span.subtype", "") if span_type or span_subtype: data["span"] = {"type": span_type, "subtype": span_subtype} transaction_name, transaction_type = tags.pop("transaction.name", None), tags.pop("transaction.type", None) if transaction_name or transaction_type: data["transaction"] = {"name": transaction_name, "type": transaction_type} return data class Counter(object): __slots__ = ("name", "_lock", "_initial_value", "_val", "reset_on_collect") def __init__(self, name, initial_value=0, reset_on_collect=False): """ Creates a new counter :param name: name of the counter :param initial_value: initial value of the counter, defaults to 0 """ self.name = name self._lock = threading.Lock() self._val = self._initial_value = initial_value self.reset_on_collect = reset_on_collect def inc(self, delta=1): """ Increments the counter. If no delta is provided, it is incremented by one :param delta: the amount to increment the counter by :returns the counter itself """ with self._lock: self._val += delta return self def dec(self, delta=1): """ Decrements the counter. If no delta is provided, it is decremented by one :param delta: the amount to decrement the counter by :returns the counter itself """ with self._lock: self._val -= delta return self def reset(self): """ Reset the counter to the initial value :returns the counter itself """ with self._lock: self._val = self._initial_value return self @property def val(self): """Returns the current value of the counter""" return self._val class Gauge(object): __slots__ = ("name", "_val", "reset_on_collect") def __init__(self, name, reset_on_collect=False): """ Creates a new gauge :param name: label of the gauge """ self.name = name self._val = None self.reset_on_collect = reset_on_collect @property def val(self): return self._val @val.setter def val(self, value): self._val = value def reset(self): self._val = 0 class Timer(object): __slots__ = ("name", "_val", "_count", "_lock", "reset_on_collect") def __init__(self, name=None, reset_on_collect=False): self.name = name self._val = 0 self._count = 0 self._lock = threading.Lock() self.reset_on_collect = reset_on_collect def update(self, duration, count=1): with self._lock: self._val += duration self._count += count def reset(self): with self._lock: self._val = 0 self._count = 0 @property def val(self): with self._lock: return self._val, self._count class NoopMetric(object): """ A no-op metric that implements the "interface" of both Counter and Gauge. Note that even when using a no-op metric, the value itself will still be calculated. """ def __init__(self, label, initial_value=0): return @property def val(self): return None @val.setter def val(self, value): return def inc(self, delta=1): return def dec(self, delta=-1): return def update(self, duration, count=1): return def reset(self): return noop_metric = NoopMetric("noop") class MetricSetNotFound(LookupError): def __init__(self, class_path): super(MetricSetNotFound, self).__init__("%s metric set not found" % class_path)
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/base_metrics.py
base_metrics.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/__init__.py
__init__.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import platform if platform.system() == "Linux" and "ZUQA_FORCE_PSUTIL_METRICS" not in os.environ: from zuqa.metrics.sets.cpu_linux import CPUMetricSet # noqa: F401 else: from zuqa.metrics.sets.cpu_psutil import CPUMetricSet # noqa: F401
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/sets/cpu.py
cpu.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import re import resource import threading from zuqa.metrics.base_metrics import MetricsSet SYS_STATS = "/proc/stat" MEM_STATS = "/proc/meminfo" PROC_STATS = "/proc/self/stat" CPU_FIELDS = ("user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal", "guest", "guest_nice") MEM_FIELDS = ("MemTotal", "MemAvailable", "MemFree", "Buffers", "Cached") whitespace_re = re.compile(r"\s+") if not os.path.exists(SYS_STATS): raise ImportError("This metric set is only available on Linux") class CPUMetricSet(MetricsSet): def __init__(self, registry, sys_stats_file=SYS_STATS, process_stats_file=PROC_STATS, memory_stats_file=MEM_STATS): self.page_size = resource.getpagesize() self.previous = {} self._read_data_lock = threading.Lock() self.sys_stats_file = sys_stats_file self.process_stats_file = process_stats_file self.memory_stats_file = memory_stats_file self._sys_clock_ticks = os.sysconf("SC_CLK_TCK") with self._read_data_lock: self.previous.update(self.read_process_stats()) self.previous.update(self.read_system_stats()) super(CPUMetricSet, self).__init__(registry) def before_collect(self): new = self.read_process_stats() new.update(self.read_system_stats()) with self._read_data_lock: prev = self.previous delta = {k: new[k] - prev[k] for k in new.keys()} try: cpu_usage_ratio = delta["cpu_usage"] / delta["cpu_total"] except ZeroDivisionError: cpu_usage_ratio = 0 self.gauge("system.cpu.total.norm.pct").val = cpu_usage_ratio # MemAvailable not present in linux before kernel 3.14 # fallback to MemFree + Buffers + Cache if not present - see #500 if "MemAvailable" in new: mem_free = new["MemAvailable"] else: mem_free = sum(new.get(mem_field, 0) for mem_field in ("MemFree", "Buffers", "Cached")) self.gauge("system.memory.actual.free").val = mem_free self.gauge("system.memory.total").val = new["MemTotal"] try: cpu_process_percent = delta["proc_total_time"] / delta["cpu_total"] except ZeroDivisionError: cpu_process_percent = 0 self.gauge("system.process.cpu.total.norm.pct").val = cpu_process_percent self.gauge("system.process.memory.size").val = new["vsize"] self.gauge("system.process.memory.rss.bytes").val = new["rss"] * self.page_size self.previous = new def read_system_stats(self): stats = {} with open(self.sys_stats_file, "r") as pidfile: for line in pidfile: if line.startswith("cpu "): fields = whitespace_re.split(line)[1:-1] num_fields = len(fields) # Not all fields are available on all platforms (e.g. RHEL 6 does not provide steal, guest, and # guest_nice. If a field is missing, we default to 0 f = {field: int(fields[i]) if i < num_fields else 0 for i, field in enumerate(CPU_FIELDS)} stats["cpu_total"] = float( f["user"] + f["nice"] + f["system"] + f["idle"] + f["iowait"] + f["irq"] + f["softirq"] + f["steal"] ) stats["cpu_usage"] = stats["cpu_total"] - (f["idle"] + f["iowait"]) break with open(self.memory_stats_file, "r") as memfile: for line in memfile: metric_name = line.split(":")[0] if metric_name in MEM_FIELDS: value_in_bytes = int(whitespace_re.split(line)[1]) * 1024 stats[metric_name] = value_in_bytes return stats def read_process_stats(self): stats = {} with open(self.process_stats_file, "r") as pidfile: data = pidfile.readline().split(" ") stats["utime"] = int(data[13]) stats["stime"] = int(data[14]) stats["proc_total_time"] = stats["utime"] + stats["stime"] stats["vsize"] = int(data[22]) stats["rss"] = int(data[23]) return stats
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/sets/cpu_linux.py
cpu_linux.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from zuqa.metrics.base_metrics import MetricsSet try: import psutil except ImportError: raise ImportError("psutil not found. Install it to get system and process metrics") class CPUMetricSet(MetricsSet): def __init__(self, registry): psutil.cpu_percent(interval=None) self._process = psutil.Process() self._process.cpu_percent(interval=None) super(CPUMetricSet, self).__init__(registry) def before_collect(self): self.gauge("system.cpu.total.norm.pct").val = psutil.cpu_percent(interval=None) / 100.0 self.gauge("system.memory.actual.free").val = psutil.virtual_memory().available self.gauge("system.memory.total").val = psutil.virtual_memory().total p = self._process if hasattr(p, "oneshot"): # new in psutil 5.0 with p.oneshot(): memory_info = p.memory_info() cpu_percent = p.cpu_percent(interval=None) else: memory_info = p.memory_info() cpu_percent = p.cpu_percent(interval=None) self.gauge("system.process.cpu.total.norm.pct").val = cpu_percent / 100.0 / psutil.cpu_count() self.gauge("system.process.memory.size").val = memory_info.vms self.gauge("system.process.memory.rss.bytes").val = memory_info.rss
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/sets/cpu_psutil.py
cpu_psutil.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import from zuqa.metrics.base_metrics import SpanBoundMetricSet class TransactionsMetricSet(SpanBoundMetricSet): pass
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/sets/transactions.py
transactions.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import from zuqa.metrics.base_metrics import SpanBoundMetricSet class BreakdownMetricSet(SpanBoundMetricSet): pass
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/sets/breakdown.py
breakdown.py
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zuqa-agent-python
/zuqa-agent-python-1.0.0a1.tar.gz/zuqa-agent-python-1.0.0a1/zuqa/metrics/sets/__init__.py
__init__.py
import re from discord.ext.commands import Cog __all__ = ('setup',) class ZuraaaVoteChecker(Cog): """ Cog que vai escutar as mensagens. Attributes ---------- vote_streak: :class:`int` A quantidade de votos desde que a cog carregou. """ def __init__(self, bot): self.__bot = bot self.__bot.zuraaa_vote_streak = 0 fmt = fr'\((\d+)\) (?=votou no bot `{bot.user}`)' self.__compiled_re = re.compile(fmt) @Cog.listener() async def on_message(self, message): await self.__bot.wait_until_ready() if not message.channel.id == 537433191393525760: return match = self.__compiled_re.search(message.content) if match: user_id = int(match.group(1)) user = self.__bot.get_user(user_id) if not user: user = await self.__bot.fetch_user(user_id) self.__bot.dispatch('zuraaa_vote', user) @Cog.listener() async def on_zuraaa_vote(self, _): self.__bot.zuraaa_vote_streak += 1 def setup(bot): bot.add_cog(ZuraaaVoteChecker(bot))
zuraaa-vote-checker
/zuraaa_vote_checker-0.1.3-py3-none-any.whl/zuraaaVoteChecker/cog.py
cog.py
__title__ = "zuraaa-vote-checker" __author__ = "uKaigo" __license__ = "MIT" __version__ = "0.1.3" from collections import namedtuple from .cog import * ver_tuple = namedtuple('VersionInfo', 'major minor micro releaselevel serial') version_info = ver_tuple(0, 1, 3, 'final', 0) del(namedtuple) del(ver_tuple)
zuraaa-vote-checker
/zuraaa_vote_checker-0.1.3-py3-none-any.whl/zuraaaVoteChecker/__init__.py
__init__.py
This repository is automatically updated from https://github.com/zurb/bower-foundation ============= `Foundation`_ ============= .. _Foundation: http://foundation.zurb.com Foundation is the most advanced responsive front-end framework in the world. You can quickly prototype and build sites or apps that work on any kind of device with Foundation, which includes layout constructs (like a fully responsive grid), elements and best practices. To get started, check out http://foundation.zurb.com/docs Installation ============ To get going with Foundation python module you can install it from `PyPi package`_: .. _PyPi package: https://pypi.python.org/pypi/zurb-foundation .. sourcecode:: sh pip install zurb-foundation Documentation ============= Foundation documentation pages are available at http://foundation.zurb.com/docs Python package ============== After installation you can use *pkg_resource* module to access assets: .. sourcecode:: python import pkg_resources as_string = pkg_resources.resource_string("zurb_foundation", "js/vendor/custom.modernizr.js") full_path_to_file = pkg_resources.resource_filename("zurb_foundation", "js/vendor/custom.modernizr.js") file_like = pkg_resources.resource_stream("zurb_foundation", "js/vendor/custom.modernizr.js") Package consists of: *js*, compiled *css* and *scss* files.
zurb-foundation
/zurb-foundation-5.5.3.tar.gz/zurb-foundation-5.5.3/README.rst
README.rst
__version__ = "5.5.3"
zurb-foundation
/zurb-foundation-5.5.3.tar.gz/zurb-foundation-5.5.3/__init__.py
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup import imp import glob here = os.path.dirname(os.path.abspath(__file__)) zurb_pkg = "zurb_foundation" version = imp.load_source(zurb_pkg, os.path.join(here, '__init__.py')).__version__ here = os.path.dirname(__file__) f = open(os.path.join(here, "README.rst"), "rt") readme = f.read() f.close() setup( name='zurb-foundation', version=version, description='The most advanced responsive front-end framework in the world. Quickly create prototypes and production code for sites and apps that work on any kind of device', long_description=readme, author='ZURB Inc.', author_email = "[email protected]", maintainer = "Arkadiusz Dzięgiel", maintainer_email = "[email protected]", url='http://foundation.zurb.com', packages=[zurb_pkg], package_dir={zurb_pkg:"."}, package_data={zurb_pkg: list(glob.glob("scss/*.*"))+list(glob.glob("scss/*/*.*"))+list(glob.glob("scss/*/*/*.*"))+list(glob.glob("css/*.*"))+list(glob.glob("js/*.*"))+list(glob.glob("js/*/*.*"))}, include_package_data = True, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries', ] )
zurb-foundation
/zurb-foundation-5.5.3.tar.gz/zurb-foundation-5.5.3/setup.py
setup.py