aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/ConnectionMetricAggregator.java
blob: 79ed382fab8050ba4162f007be13d5993a3900a0 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.server.jetty;

import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.http.ServerConfig;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.component.AbstractLifeCycle;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicLong;

import static com.yahoo.jdisc.http.server.jetty.RequestUtils.getConnector;
import static com.yahoo.jdisc.http.server.jetty.RequestUtils.isHttpServerConnection;

/**
 * @author bjorncs
 */
class ConnectionMetricAggregator extends AbstractLifeCycle implements Connection.Listener, HttpChannel.Listener{

    private final SimpleConcurrentIdentityHashMap<Connection, ConnectionMetrics> connectionsMetrics = new SimpleConcurrentIdentityHashMap<>();

    private final Metric metricAggregator;
    private final Collection<String> monitoringHandlerPaths;

    ConnectionMetricAggregator(ServerConfig serverConfig, Metric metricAggregator) {
        this.monitoringHandlerPaths = serverConfig.metric().monitoringHandlerPaths();
        this.metricAggregator = metricAggregator;
    }

    @Override public void onOpened(Connection connection) {}

    @Override
    public void onClosed(Connection connection) {
        if (isHttpServerConnection(connection)) {
            connectionsMetrics.remove(connection).ifPresent(metrics ->
                    metricAggregator.set(MetricDefinitions.REQUESTS_PER_CONNECTION, metrics.requests.get(), metrics.metricContext));
        }
    }

    @Override
    public void onRequestBegin(Request request) {
        if (monitoringHandlerPaths.stream()
                .anyMatch(pathPrefix -> request.getRequestURI().startsWith(pathPrefix))){
            return;
        }
        Connection connection = request.getHttpChannel().getConnection();
        if (isHttpServerConnection(connection)) {
            ConnectionMetrics metrics = this.connectionsMetrics.computeIfAbsent(
                    connection,
                    () -> new ConnectionMetrics(getConnector(request).getConnectorMetricContext()));
            metrics.requests.incrementAndGet();
        }
    }

    private static class ConnectionMetrics {
        final AtomicLong requests = new AtomicLong();
        final Metric.Context metricContext;

        ConnectionMetrics(Metric.Context metricContext) {
            this.metricContext = metricContext;
        }
    }
}