summary refs log tree commit diff
path: root/synapse/http/request_metrics.py
blob: 0984870e7e5d9781c92ce112968ca6dd01dd841b (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
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
#
# 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.

import logging

from prometheus_client.core import Counter, Histogram
from synapse.metrics import LaterGauge

from synapse.util.logcontext import LoggingContext

logger = logging.getLogger(__name__)


# total number of responses served, split by method/servlet/tag
response_count = Counter("synapse_http_server_response_count", "", ["method", "servlet", "tag"])

requests_counter = Counter("synapse_http_server_requests_received", "", ["method", "servlet"])

outgoing_responses_counter = Counter("synapse_http_server_responses", "", ["method", "code"])

response_timer = Histogram("synapse_http_server_response_time_seconds", "", ["method", "servlet", "tag"])

response_ru_utime = Counter("synapse_http_server_response_ru_utime_seconds", "", ["method", "servlet", "tag"])

response_ru_stime = Counter("synapse_http_server_response_ru_stime_seconds", "", ["method", "servlet", "tag"])

response_db_txn_count = Counter("synapse_http_server_response_db_txn_count", "", ["method", "servlet", "tag"])

# seconds spent waiting for db txns, excluding scheduling time, when processing
# this request
response_db_txn_duration = Counter("synapse_http_server_response_db_txn_duration_seconds", "", ["method", "servlet", "tag"])

# seconds spent waiting for a db connection, when processing this request
response_db_sched_duration = Counter("synapse_http_request_response_db_sched_duration_seconds", "", ["method", "servlet", "tag"]
)

# size in bytes of the response written
response_size = Counter("synapse_http_request_response_size", "", ["method", "servlet", "tag"]
)

# In flight metrics are incremented while the requests are in flight, rather
# than when the response was written.

in_flight_requests_ru_utime = Counter("synapse_http_request_in_flight_requests_ru_utime_seconds", "", ["method", "servlet"])

in_flight_requests_ru_stime = Counter("synapse_http_request_in_flight_requests_ru_stime_seconds", "", ["method", "servlet"])

in_flight_requests_db_txn_count = Counter("synapse_http_request_in_flight_requests_db_txn_count", "", ["method", "servlet"])

# seconds spent waiting for db txns, excluding scheduling time, when processing
# this request
in_flight_requests_db_txn_duration = Counter("synapse_http_request_in_flight_requests_db_txn_duration_seconds", "", ["method", "servlet"])

# seconds spent waiting for a db connection, when processing this request
in_flight_requests_db_sched_duration = Counter("synapse_http_request_in_flight_requests_db_sched_duration_seconds", "", ["method", "servlet"])

# The set of all in flight requests, set[RequestMetrics]
_in_flight_requests = set()


def _collect_in_flight():
    """Called just before metrics are collected, so we use it to update all
    the in flight request metrics
    """

    for rm in _in_flight_requests:
        rm.update_metrics()


metrics.register_collector(_collect_in_flight)


def _get_in_flight_counts():
    """Returns a count of all in flight requests by (method, server_name)

    Returns:
        dict[tuple[str, str], int]
    """

    # Map from (method, name) -> int, the number of in flight requests of that
    # type
    counts = {}
    for rm in _in_flight_requests:
        key = (rm.method, rm.name,)
        counts[key] = counts.get(key, 0) + 1

    return counts

LaterGauge(
    "synapse_http_request_metrics_in_flight_requests_count", "",
    ["method", "servlet"],
    _get_in_flight_counts
)


class RequestMetrics(object):
    def start(self, time_msec, name, method):
        self.start = time_msec
        self.start_context = LoggingContext.current_context()
        self.name = name
        self.method = method

        self._request_stats = _RequestStats.from_context(self.start_context)

        _in_flight_requests.add(self)

    def stop(self, time_msec, request):
        _in_flight_requests.discard(self)

        context = LoggingContext.current_context()

        tag = ""
        if context:
            tag = context.tag

            if context != self.start_context:
                logger.warn(
                    "Context have unexpectedly changed %r, %r",
                    context, self.start_context
                )
                return

        outgoing_responses_counter.labels(request.method, str(request.code)).inc()

        response_count.labels(request.method, self.name, tag).inc()

        response_timer.labels(request.method, self.name, tag).observe(time_msec - self.start)

        ru_utime, ru_stime = context.get_resource_usage()

        response_ru_utime.labels(request.method, self.name, tag).inc(ru_utime)
        response_ru_stime.labels(request.method, self.name, tag).inc(ru_stime)
        response_db_txn_count.labels(request.method, self.name, tag).inc(context.db_txn_count)
        response_db_txn_duration.labels(request.method, self.name, tag).inc(context.db_txn_duration_ms / 1000.)
        response_db_sched_duration.labels(request.method, self.name, tag).inc(
            context.db_sched_duration_ms / 1000.)

        response_size.labels(request.method, self.name, tag).inc(request.sentLength)

        # We always call this at the end to ensure that we update the metrics
        # regardless of whether a call to /metrics while the request was in
        # flight.
        self.update_metrics()

    def update_metrics(self):
        """Updates the in flight metrics with values from this request.
        """
        diff = self._request_stats.update(self.start_context)

        in_flight_requests_ru_utime.labels(self.method, self.name).inc(diff.ru_utime)
        in_flight_requests_ru_stime.labels(self.method, self.name).inc(diff.ru_stime)

        in_flight_requests_db_txn_count.labels(self.method, self.name).inc(diff.db_txn_count)

        in_flight_requests_db_txn_duration.labels(self.method, self.name).inc(diff.db_txn_duration_ms / 1000.)

        in_flight_requests_db_sched_duration.labels(self.method, self.name).inc(diff.db_sched_duration_ms / 1000.)


class _RequestStats(object):
    """Keeps tracks of various metrics for an in flight request.
    """

    __slots__ = [
        "ru_utime", "ru_stime",
        "db_txn_count", "db_txn_duration_ms", "db_sched_duration_ms",
    ]

    def __init__(self, ru_utime, ru_stime, db_txn_count,
                 db_txn_duration_ms, db_sched_duration_ms):
        self.ru_utime = ru_utime
        self.ru_stime = ru_stime
        self.db_txn_count = db_txn_count
        self.db_txn_duration_ms = db_txn_duration_ms
        self.db_sched_duration_ms = db_sched_duration_ms

    @staticmethod
    def from_context(context):
        ru_utime, ru_stime = context.get_resource_usage()

        return _RequestStats(
            ru_utime, ru_stime,
            context.db_txn_count,
            context.db_txn_duration_ms,
            context.db_sched_duration_ms,
        )

    def update(self, context):
        """Updates the current values and returns the difference between the
        old and new values.

        Returns:
            _RequestStats: The difference between the old and new values
        """
        new = _RequestStats.from_context(context)

        diff = _RequestStats(
            new.ru_utime - self.ru_utime,
            new.ru_stime - self.ru_stime,
            new.db_txn_count - self.db_txn_count,
            new.db_txn_duration_ms - self.db_txn_duration_ms,
            new.db_sched_duration_ms - self.db_sched_duration_ms,
        )

        self.ru_utime = new.ru_utime
        self.ru_stime = new.ru_stime
        self.db_txn_count = new.db_txn_count
        self.db_txn_duration_ms = new.db_txn_duration_ms
        self.db_sched_duration_ms = new.db_sched_duration_ms

        return diff