summary refs log tree commit diff
path: root/synapse/logging/opentracing.py
blob: bd53f2365eaa40661ec0adb68f4de3bc3d92a4f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# -*- coding: utf-8 -*-
# Copyright 2019 The Matrix.org Foundation C.I.C.d
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# NOTE
# This is a small wrapper around opentracing because opentracing is not currently
# packaged downstream (specifically debian). Since opentracing instrumentation is
# fairly invasive it was awkward to make it optional. As a result we opted to encapsulate
# all opentracing state in these methods which effectively noop if opentracing is
# not present. We should strongly consider encouraging the downstream distributers
# to package opentracing and making opentracing a full dependency. In order to facilitate
# this move the methods have work very similarly to opentracing's and it should only
# be a matter of few regexes to move over to opentracing's access patterns proper.

try:
    import opentracing
except ImportError:
    opentracing = None
try:
    from jaeger_client import Config as JaegerConfig
    from synapse.logging.scopecontextmanager import LogContextScopeManager
except ImportError:
    JaegerConfig = None
    LogContextScopeManager = None

import contextlib
import logging
import re
from functools import wraps
from twisted.internet import defer

from canonicaljson import json

from twisted.internet import defer

logger = logging.getLogger(__name__)
import inspect


class _DumTagNames(object):
    """wrapper of opentracings tags. We need to have them if we
    want to reference them without opentracing around. Clearly they
    should never actually show up in a trace. `set_tags` overwrites
    these with the correct ones."""

    INVALID_TAG = "invalid-tag"
    COMPONENT = INVALID_TAG
    DATABASE_INSTANCE = INVALID_TAG
    DATABASE_STATEMENT = INVALID_TAG
    DATABASE_TYPE = INVALID_TAG
    DATABASE_USER = INVALID_TAG
    ERROR = INVALID_TAG
    HTTP_METHOD = INVALID_TAG
    HTTP_STATUS_CODE = INVALID_TAG
    HTTP_URL = INVALID_TAG
    MESSAGE_BUS_DESTINATION = INVALID_TAG
    PEER_ADDRESS = INVALID_TAG
    PEER_HOSTNAME = INVALID_TAG
    PEER_HOST_IPV4 = INVALID_TAG
    PEER_HOST_IPV6 = INVALID_TAG
    PEER_PORT = INVALID_TAG
    PEER_SERVICE = INVALID_TAG
    SAMPLING_PRIORITY = INVALID_TAG
    SERVICE = INVALID_TAG
    SPAN_KIND = INVALID_TAG
    SPAN_KIND_CONSUMER = INVALID_TAG
    SPAN_KIND_PRODUCER = INVALID_TAG
    SPAN_KIND_RPC_CLIENT = INVALID_TAG
    SPAN_KIND_RPC_SERVER = INVALID_TAG


def only_if_tracing(func):
    """Executes the function only if we're tracing. Otherwise return.
    Assumes the function wrapped may return None"""

    @wraps(func)
    def _only_if_tracing_inner(*args, **kwargs):
        if opentracing:
            return func(*args, **kwargs)
        else:
            return

    return _only_if_tracing_inner


# Block everything by default
_homeserver_whitelist = None

tags = _DumTagNames


def init_tracer(config):
    """Set the whitelists and initialise the JaegerClient tracer

    Args:
        config (Config)
        The config used by the homeserver. Here it's used to set the service
        name to the homeserver's.
    """
    global opentracing
    if not config.tracer_config.get("tracer_enabled", False):
        # We don't have a tracer
        opentracing = None
        return

    if not opentracing:
        logger.error(
            "The server has been configure to use opentracing but opentracing is not installed."
        )
        raise ModuleNotFoundError("opentracing")

    if not JaegerConfig:
        logger.error(
            "The server has been configure to use opentracing but opentracing is not installed."
        )

    # Include the worker name
    name = config.worker_name if config.worker_name else "master"

    set_homeserver_whitelist(config.tracer_config["homeserver_whitelist"])
    jaeger_config = JaegerConfig(
        config={"sampler": {"type": "const", "param": 1}, "logging": True},
        service_name="{} {}".format(config.server_name, name),
        scope_manager=LogContextScopeManager(config),
    )
    jaeger_config.initialize_tracer()

    # Set up tags to be opentracing's tags
    global tags
    tags = opentracing.tags


@contextlib.contextmanager
def _noop_context_manager(*args, **kwargs):
    """Does absolutely nothing really well. Can be entered and exited arbitrarily.
    Good substitute for an opentracing scope."""
    yield


# Could use kwargs but I want these to be explicit
def start_active_span(
    operation_name,
    child_of=None,
    references=None,
    tags=None,
    start_time=None,
    ignore_active_span=False,
    finish_on_close=True,
):
    """Starts an active opentracing span. Note, the scope doesn't become active
    until it has been entered, however, the span starts from the time this
    message is called.
    Args:
        See opentracing.tracer
    Returns:
        scope (Scope) or noop_context_manager
    """
    if opentracing is None:
        return _noop_context_manager()
    else:
        # We need to enter the scope here for the logcontext to become active
        return opentracing.tracer.start_active_span(
            operation_name,
            child_of=child_of,
            references=references,
            tags=tags,
            start_time=start_time,
            ignore_active_span=ignore_active_span,
            finish_on_close=finish_on_close,
        )


def start_active_span_follows_from(operation_name, contexts):
    if opentracing is None:
        return _noop_context_manager()
    else:
        references = [opentracing.follows_from(context) for context in contexts]
        scope = start_active_span(operation_name, references=references)
        return scope


@only_if_tracing
def set_tag(key, value):
    """Set's a tag on the active span"""
    opentracing.tracer.active_span.set_tag(key, value)


@only_if_tracing
def log_kv(key_values, timestamp=None):
    """Log to the active span"""
    opentracing.tracer.active_span.log_kv(key_values, timestamp)


# Note: we don't have a get baggage items because we're trying to hide all
# scope and span state from synapse. I think this method may also be useless
# as a result

# I also thinks it's dangerous with respect to pii. If the whitelisting
# is missconfigured or buggy span information will leak. This is no issue
# if it's jaeger span id's but baggage can contain any arbitrary data. I would
# suggest removing this.
@only_if_tracing
def set_baggage_item(key, value):
    """Attach baggage to the active span"""
    opentracing.tracer.active_span.set_baggage_item(key, value)


@only_if_tracing
def set_operation_name(operation_name):
    """Sets the operation name of the active span"""
    opentracing.tracer.active_span.set_operation_name(operation_name)


@only_if_tracing
def set_homeserver_whitelist(homeserver_whitelist):
    """Sets the whitelist

    Args:
        homeserver_whitelist (iterable of strings): regex of whitelisted homeservers
    """
    global _homeserver_whitelist
    if homeserver_whitelist:
        # Makes a single regex which accepts all passed in regexes in the list
        _homeserver_whitelist = re.compile(
            "({})".format(")|(".join(homeserver_whitelist))
        )


@only_if_tracing
def whitelisted_homeserver(destination):
    """Checks if a destination matches the whitelist
    Args:
        destination (String)"""
    global _homeserver_whitelist
    if _homeserver_whitelist:
        return _homeserver_whitelist.match(destination)
    return False


def start_active_span_from_context(
    headers,
    operation_name,
    references=None,
    tags=None,
    start_time=None,
    ignore_active_span=False,
    finish_on_close=True,
):
    """
    Extracts a span context from Twisted Headers.
    args:
        headers (twisted.web.http_headers.Headers)
    returns:
        span_context (opentracing.span.SpanContext)
    """
    # Twisted encodes the values as lists whereas opentracing doesn't.
    # So, we take the first item in the list.
    # Also, twisted uses byte arrays while opentracing expects strings.
    if opentracing is None:
        return _noop_context_manager()

    header_dict = {k.decode(): v[0].decode() for k, v in headers.getAllRawHeaders()}
    context = opentracing.tracer.extract(opentracing.Format.HTTP_HEADERS, header_dict)

    return opentracing.tracer.start_active_span(
        operation_name,
        child_of=context,
        references=references,
        tags=tags,
        start_time=start_time,
        ignore_active_span=ignore_active_span,
        finish_on_close=finish_on_close,
    )


@only_if_tracing
def start_active_span_from_edu(
    edu_content,
    operation_name,
    references=[],
    tags=None,
    start_time=None,
    ignore_active_span=False,
    finish_on_close=True,
):
    """
    Extracts a span context from an edu and uses it to start a new active span

    Args:
      edu_content (Dict): and edu_content with a `context` field whose value is
      canonical json for a dict which contains opentracing information.
    """
    carrier = json.loads(edu_content.get("context", "{}")).get("opentracing", {})
    context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
    _references = [
        opentracing.child_of(span_context_from_string(x))
        for x in carrier.get("references", [])
    ]

    # For some reason jaeger decided not to support the visualisation of multiple parent
    # spans or explicitely show references. I include the span context as a tag here as
    # an aid to people debugging but it's really not an ideal solution.

    references += _references

    scope = opentracing.tracer.start_active_span(
        operation_name,
        child_of=context,
        references=references,
        tags=tags,
        start_time=start_time,
        ignore_active_span=ignore_active_span,
        finish_on_close=finish_on_close,
    )

    scope.span.set_tag("references", carrier.get("references", []))
    return scope


@only_if_tracing
def inject_active_span_twisted_headers(headers, destination):
    """
    Injects a span context into twisted headers inplace

    Args:
        headers (twisted.web.http_headers.Headers)
        span (opentracing.Span)

    Returns:
        Inplace modification of headers

    Note:
        The headers set by the tracer are custom to the tracer implementation which
        should be unique enough that they don't interfere with any headers set by
        synapse or twisted. If we're still using jaeger these headers would be those
        here:
        https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
    """

    if not whitelisted_homeserver(destination):
        return

    span = opentracing.tracer.active_span
    carrier = {}
    opentracing.tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier)

    for key, value in carrier.items():
        headers.addRawHeaders(key, value)


@only_if_tracing
def inject_active_span_byte_dict(headers, destination):
    """
    Injects a span context into a dict where the headers are encoded as byte
    strings

    Args:
        headers (dict)
        span (opentracing.Span)

    Returns:
        Inplace modification of headers

    Note:
        The headers set by the tracer are custom to the tracer implementation which
        should be unique enough that they don't interfere with any headers set by
        synapse or twisted. If we're still using jaeger these headers would be those
        here:
        https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
    """
    if not whitelisted_homeserver(destination):
        return

    span = opentracing.tracer.active_span

    carrier = {}
    opentracing.tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier)

    for key, value in carrier.items():
        headers[key.encode()] = [value.encode()]


@only_if_tracing
def inject_active_span_text_map(carrier, destination=None):
    if destination and not whitelisted_homeserver(destination):
        return

    opentracing.tracer.inject(
        opentracing.tracer.active_span, opentracing.Format.TEXT_MAP, carrier
    )


def active_span_context_as_string():
    if not opentracing:
        return None

    carrier = {}
    opentracing.tracer.inject(
        opentracing.tracer.active_span, opentracing.Format.TEXT_MAP, carrier
    )
    return json.dumps(carrier)


@only_if_tracing
def span_context_from_string(carrier):
    carrier = json.loads(carrier)
    return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)


@only_if_tracing
def extract_text_map(carrier):
    return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)


def trace_deferred(func):
    """Decorator to trace a defered function. Sets the operation name to that of the
    function's."""


def trace_servlet(servlet_name, func):
    """Decorator which traces a serlet. It starts a span with some servlet specific
    tags such as the servlet_name and request information"""

    @wraps(func)
    @defer.inlineCallbacks
    def _trace_servlet_inner(request, *args, **kwargs):
        with start_active_span_from_context(
            request.requestHeaders,
            "incoming-client-request",
            tags={
                "request_id": request.get_request_id(),
                tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
                tags.HTTP_METHOD: request.get_method(),
                tags.HTTP_URL: request.get_redacted_uri(),
                tags.PEER_HOST_IPV6: request.getClientIP(),
                "servlet_name": servlet_name,
            },
        ):
            result = yield defer.maybeDeferred(func, request, *args, **kwargs)
        defer.returnValue(result)

    return _trace_servlet_inner


def trace_defered_function(func):
    @wraps(func)
    @defer.inlineCallbacks
    def _trace_deferred_inner(self, *args, **kwargs):
        with start_active_span(func.__name__):
            r = yield func(self, *args, **kwargs)
            defer.returnValue(r)

    return _trace_deferred_inner


def trace_deferred_using_operation_name(name):
    """Decorator to trace a defered function. Explicitely sets the operation_name to name"""

    def trace_deferred(func):
        @wraps(func)
        @defer.inlineCallbacks
        def _trace_deferred_inner(self, *args, **kwargs):
            # Start scope
            with start_active_span(name):
                r = yield func(self, *args, **kwargs)
                defer.returnValue(r)

        return _trace_deferred_inner

    return trace_deferred


def trace(func):
    """Decorator to trace a normal function. Sets the operation name to that of the
    function's."""

    @wraps(func)
    def _trace_inner(self, *args, **kwargs):
        with start_active_span(func.__name__):
            return func(self, *args, **kwargs)

    return _trace_inner


def trace_using_operation_name(operation_name):
    """Decorator to trace a function. Explicitely sets the operation_name to name"""

    def trace(func):
        @wraps(func)
        def _trace_inner(self, *args, **kwargs):
            with start_active_span(operation_name):
                return func(self, *args, **kwargs)

        return _trace_inner

    return trace


def tag_args(func):
    @wraps(func)
    def _tag_args_inner(self, *args, **kwargs):
        set_tag("args", args)
        set_tag("kwargs", kwargs)
        return func(self, *args, **kwargs)

    return _tag_args_inner


def wrap_in_span(func):
    """Its purpose is to wrap a function that is being passed into a context
    which is a complete break from the current logcontext. This function creates
    a non active span from the current context and closes it after the function
    executes."""

    # I haven't use this function yet

    if not TracerUtil._opentracing:
        return func

    parent_span = opentracing.tracer.active_span

    @wraps(func)
    def _wrap_in_span_inner(self, *args, **kwargs):
        span = opentracing.tracer.start_span(func.__name__, child_of=parent_span)
        try:
            return func(self, *args, **kwargs)
        except Exception as e:
            span.set_tag("error", True)
            span.log_kv({"exception", e})
            raise
        finally:
            span.finish()

    return _wrap_in_span_inner