|
| 1 | +#!/usr/bin/python |
| 2 | +# |
| 3 | +# Copyright The OpenTelemetry Authors |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +from logging import getLogger |
| 17 | +from typing import Any, Type, TypeVar |
| 18 | +from urllib.parse import quote as urllib_quote |
| 19 | + |
| 20 | +# pylint: disable=no-name-in-module |
| 21 | +from django import conf, get_version |
| 22 | +from django.db import connection |
| 23 | +from django.db.backends.utils import CursorDebugWrapper |
| 24 | + |
| 25 | +from opentelemetry.trace.propagation.tracecontext import ( |
| 26 | + TraceContextTextMapPropagator, |
| 27 | +) |
| 28 | + |
| 29 | +_propagator = TraceContextTextMapPropagator() |
| 30 | + |
| 31 | +_django_version = get_version() |
| 32 | +_logger = getLogger(__name__) |
| 33 | + |
| 34 | +T = TypeVar("T") # pylint: disable-msg=invalid-name |
| 35 | + |
| 36 | + |
| 37 | +class SqlCommenter: |
| 38 | + """ |
| 39 | + Middleware to append a comment to each database query with details about |
| 40 | + the framework and the execution context. |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, get_response) -> None: |
| 44 | + self.get_response = get_response |
| 45 | + |
| 46 | + def __call__(self, request) -> Any: |
| 47 | + with connection.execute_wrapper(_QueryWrapper(request)): |
| 48 | + return self.get_response(request) |
| 49 | + |
| 50 | + |
| 51 | +class _QueryWrapper: |
| 52 | + def __init__(self, request) -> None: |
| 53 | + self.request = request |
| 54 | + |
| 55 | + def __call__(self, execute: Type[T], sql, params, many, context) -> T: |
| 56 | + # pylint: disable-msg=too-many-locals |
| 57 | + with_framework = getattr( |
| 58 | + conf.settings, "SQLCOMMENTER_WITH_FRAMEWORK", True |
| 59 | + ) |
| 60 | + with_controller = getattr( |
| 61 | + conf.settings, "SQLCOMMENTER_WITH_CONTROLLER", True |
| 62 | + ) |
| 63 | + with_route = getattr(conf.settings, "SQLCOMMENTER_WITH_ROUTE", True) |
| 64 | + with_app_name = getattr( |
| 65 | + conf.settings, "SQLCOMMENTER_WITH_APP_NAME", True |
| 66 | + ) |
| 67 | + with_opentelemetry = getattr( |
| 68 | + conf.settings, "SQLCOMMENTER_WITH_OPENTELEMETRY", True |
| 69 | + ) |
| 70 | + with_db_driver = getattr( |
| 71 | + conf.settings, "SQLCOMMENTER_WITH_DB_DRIVER", True |
| 72 | + ) |
| 73 | + |
| 74 | + db_driver = context["connection"].settings_dict.get("ENGINE", "") |
| 75 | + resolver_match = self.request.resolver_match |
| 76 | + |
| 77 | + sql_comment = _generate_sql_comment( |
| 78 | + # Information about the controller. |
| 79 | + controller=resolver_match.view_name |
| 80 | + if resolver_match and with_controller |
| 81 | + else None, |
| 82 | + # route is the pattern that matched a request with a controller i.e. the regex |
| 83 | + # See https://docs.djangoproject.com/en/stable/ref/urlresolvers/#django.urls.ResolverMatch.route |
| 84 | + # getattr() because the attribute doesn't exist in Django < 2.2. |
| 85 | + route=getattr(resolver_match, "route", None) |
| 86 | + if resolver_match and with_route |
| 87 | + else None, |
| 88 | + # app_name is the application namespace for the URL pattern that matches the URL. |
| 89 | + # See https://docs.djangoproject.com/en/stable/ref/urlresolvers/#django.urls.ResolverMatch.app_name |
| 90 | + app_name=(resolver_match.app_name or None) |
| 91 | + if resolver_match and with_app_name |
| 92 | + else None, |
| 93 | + # Framework centric information. |
| 94 | + framework=f"django:{_django_version}" if with_framework else None, |
| 95 | + # Information about the database and driver. |
| 96 | + db_driver=db_driver if with_db_driver else None, |
| 97 | + **_get_opentelemetry_values() if with_opentelemetry else {}, |
| 98 | + ) |
| 99 | + |
| 100 | + # TODO: MySQL truncates logs > 1024B so prepend comments |
| 101 | + # instead of statements, if the engine is MySQL. |
| 102 | + # See: |
| 103 | + # * https://github.com/basecamp/marginalia/issues/61 |
| 104 | + # * https://github.com/basecamp/marginalia/pull/80 |
| 105 | + sql += sql_comment |
| 106 | + |
| 107 | + # Add the query to the query log if debugging. |
| 108 | + if context["cursor"].__class__ is CursorDebugWrapper: |
| 109 | + context["connection"].queries_log.append(sql) |
| 110 | + |
| 111 | + return execute(sql, params, many, context) |
| 112 | + |
| 113 | + |
| 114 | +def _generate_sql_comment(**meta) -> str: |
| 115 | + """ |
| 116 | + Return a SQL comment with comma delimited key=value pairs created from |
| 117 | + **meta kwargs. |
| 118 | + """ |
| 119 | + key_value_delimiter = "," |
| 120 | + |
| 121 | + if not meta: # No entries added. |
| 122 | + return "" |
| 123 | + |
| 124 | + # Sort the keywords to ensure that caching works and that testing is |
| 125 | + # deterministic. It eases visual inspection as well. |
| 126 | + return ( |
| 127 | + " /*" |
| 128 | + + key_value_delimiter.join( |
| 129 | + f"{_url_quote(key)}={_url_quote(value)!r}" |
| 130 | + for key, value in sorted(meta.items()) |
| 131 | + if value is not None |
| 132 | + ) |
| 133 | + + "*/" |
| 134 | + ) |
| 135 | + |
| 136 | + |
| 137 | +def _url_quote(value) -> str: |
| 138 | + if not isinstance(value, (str, bytes)): |
| 139 | + return value |
| 140 | + _quoted = urllib_quote(value) |
| 141 | + # Since SQL uses '%' as a keyword, '%' is a by-product of url quoting |
| 142 | + # e.g. foo,bar --> foo%2Cbar |
| 143 | + # thus in our quoting, we need to escape it too to finally give |
| 144 | + # foo,bar --> foo%%2Cbar |
| 145 | + return _quoted.replace("%", "%%") |
| 146 | + |
| 147 | + |
| 148 | +def _get_opentelemetry_values() -> dict or None: |
| 149 | + """ |
| 150 | + Return the OpenTelemetry Trace and Span IDs if Span ID is set in the |
| 151 | + OpenTelemetry execution context. |
| 152 | + """ |
| 153 | + return _propagator.inject({}) |
0 commit comments