aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottler.java
blob: 06a9986e996053528080545640aefab0d20aa911 (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
// Copyright Yahoo. 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.http.ConnectorConfig;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.SelectorManager;
import org.eclipse.jetty.server.AbstractConnector;
import org.eclipse.jetty.server.ConnectionLimit;
import org.eclipse.jetty.server.LowResourceMonitor;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.statistic.RateStatistic;
import org.eclipse.jetty.util.thread.Scheduler;

import java.nio.channels.SelectableChannel;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * Monitor various resource constraints and throttles new connections once a threshold is exceeded.
 * Implementation inspired by Jetty's {@link LowResourceMonitor}, {@link AcceptRateLimit} and {@link ConnectionLimit}.
 *
 * @author bjorncs
 */
@ManagedObject("Monitor various resource constraints and throttles new connections once a threshold is exceeded")
class ConnectionThrottler extends ContainerLifeCycle implements SelectorManager.AcceptListener {

    private static final Logger log = Logger.getLogger(ConnectionThrottler.class.getName());

    private final Object monitor = new Object();
    private final Collection<ResourceLimit> resourceLimits = new ArrayList<>();
    private final AbstractConnector connector;
    private final Duration idleTimeout;
    private final Scheduler scheduler;

    private boolean isRegistered = false;
    private boolean isThrottling = false;

    ConnectionThrottler(AbstractConnector connector, ConnectorConfig.Throttling config) {
        this(Jvm.fromRuntime(), new RateStatistic(1, TimeUnit.SECONDS), connector.getScheduler(), connector, config);
    }

    // Intended for unit testing
    ConnectionThrottler(Jvm runtime,
                        RateStatistic rateStatistic,
                        Scheduler scheduler,
                        AbstractConnector connector,
                        ConnectorConfig.Throttling config) {
        this.connector = connector;
        if (config.maxHeapUtilization() != -1) {
            this.resourceLimits.add(new HeapResourceLimit(runtime, config.maxHeapUtilization()));
        }
        if (config.maxConnections() != -1) {
            this.resourceLimits.add(new ConnectionLimitThreshold(config.maxConnections()));
        }
        if (config.maxAcceptRate() != -1) {
            this.resourceLimits.add(new AcceptRateLimit(rateStatistic, config.maxAcceptRate()));
        }
        this.idleTimeout = config.idleTimeout() != -1 ? Duration.ofMillis((long) (config.idleTimeout()*1000)) : null;
        this.scheduler = scheduler;
    }

    void registerWithConnector() {
        synchronized (monitor) {
            if (isRegistered) return;
            isRegistered = true;
            resourceLimits.forEach(connector::addBean);
            connector.addBean(this);
        }
    }

    @Override
    public void onAccepting(SelectableChannel channel) {
        throttleIfAnyThresholdIsExceeded();
    }

    private void throttleIfAnyThresholdIsExceeded() {
        synchronized (monitor) {
            if (isThrottling) return;
            List<String> reasons = getThrottlingReasons();
            if (reasons.isEmpty()) return;
            log.warning(String.format("Throttling new connection. Reasons: %s", reasons));
            isThrottling = true;
            if (connector.isAccepting()) {
                connector.setAccepting(false);
            }
            if (idleTimeout != null) {
                log.warning(String.format("Applying idle timeout to existing connections: timeout=%sms", idleTimeout));
                connector.getConnectedEndPoints()
                        .forEach(endPoint -> endPoint.setIdleTimeout(idleTimeout.toMillis()));
            }
            scheduler.schedule(this::unthrottleIfBelowThresholds, 1, TimeUnit.SECONDS);
        }
    }

    private void unthrottleIfBelowThresholds() {
        synchronized (monitor) {
            if (!isThrottling) return;
            List<String> reasons = getThrottlingReasons();
            if (!reasons.isEmpty()) {
                log.warning(String.format("Throttling continued. Reasons: %s", reasons));
                scheduler.schedule(this::unthrottleIfBelowThresholds, 1, TimeUnit.SECONDS);
                return;
            }
            if (idleTimeout != null) {
                long originalTimeout = connector.getIdleTimeout();
                log.info(String.format("Reverting idle timeout for existing connections: timeout=%sms", originalTimeout));
                connector.getConnectedEndPoints()
                        .forEach(endPoint -> endPoint.setIdleTimeout(originalTimeout));
            }
            log.info("Throttling disabled - resource thresholds no longer exceeded");
            if (!connector.isAccepting()) {
                connector.setAccepting(true);
            }
            isThrottling = false;
        }
    }

    private List<String> getThrottlingReasons() {
        synchronized (monitor) {
            return resourceLimits.stream()
                    .map(ResourceLimit::isThresholdExceeded)
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .toList();
        }
    }

    private interface ResourceLimit extends LifeCycle, SelectorManager.AcceptListener, Connection.Listener {
        /**
         * @return A string containing the reason if threshold exceeded, empty otherwise.
         */
        Optional<String> isThresholdExceeded();

        @Override default void onOpened(Connection connection) {}

        @Override default void onClosed(Connection connection) {}
    }

    /**
     * Note: implementation inspired by Jetty's {@link LowResourceMonitor}
     */
    private static class HeapResourceLimit extends AbstractLifeCycle implements ResourceLimit {
        private final Jvm runtime;
        private final double maxHeapUtilization;

        HeapResourceLimit(Jvm runtime, double maxHeapUtilization) {
            this.runtime = runtime;
            this.maxHeapUtilization = maxHeapUtilization;
        }

        @Override
        public Optional<String> isThresholdExceeded() {
            double heapUtilization = (runtime.maxMemory() - runtime.freeMemory()) / (double) runtime.maxMemory();
            if (heapUtilization > maxHeapUtilization) {
                return Optional.of(String.format("Max heap utilization exceeded: %f%%>%f%%", heapUtilization*100, maxHeapUtilization*100));
            }
            return Optional.empty();
        }
    }

    /**
     * Note: implementation inspired by Jetty's {@link org.eclipse.jetty.server.AcceptRateLimit}
     */
    private static class AcceptRateLimit extends AbstractLifeCycle implements ResourceLimit {
        private final Object monitor = new Object();
        private final RateStatistic rateStatistic;
        private final int maxAcceptRate;

        AcceptRateLimit(RateStatistic rateStatistic, int maxAcceptRate) {
            this.rateStatistic = rateStatistic;
            this.maxAcceptRate = maxAcceptRate;
        }

        @Override
        public Optional<String> isThresholdExceeded() {
            synchronized (monitor) {
                int acceptRate = rateStatistic.getRate();
                if (acceptRate > maxAcceptRate) {
                    return Optional.of(String.format("Max accept rate exceeded: %d>%d", acceptRate, maxAcceptRate));
                }
                return Optional.empty();
            }
        }

        @Override
        public void onAccepting(SelectableChannel channel) {
            synchronized (monitor) {
                rateStatistic.record();
            }
        }

        @Override
        protected void doStop() {
            synchronized (monitor) {
                rateStatistic.reset();
            }
        }
    }

    /**
     * Note: implementation inspired by Jetty's {@link ConnectionLimit}.
     */
    private static class ConnectionLimitThreshold extends AbstractLifeCycle implements ResourceLimit {
        private final Object monitor = new Object();
        private final int maxConnections;
        private final Set<SelectableChannel> connectionsAccepting = new HashSet<>();
        private int connectionOpened;

        ConnectionLimitThreshold(int maxConnections) {
            this.maxConnections = maxConnections;
        }

        @Override
        public Optional<String> isThresholdExceeded() {
            synchronized (monitor) {
                int totalConnections = connectionOpened + connectionsAccepting.size();
                if (totalConnections > maxConnections) {
                    return Optional.of(String.format("Max connection exceeded: %d>%d", totalConnections, maxConnections));
                }
                return Optional.empty();
            }
        }

        @Override
        public void onOpened(Connection connection) {
            synchronized (monitor) {
                connectionsAccepting.remove(connection.getEndPoint().getTransport());
                ++connectionOpened;
            }
        }

        @Override
        public void onClosed(Connection connection) {
            synchronized (monitor) {
                --connectionOpened;
            }
        }

        @Override
        public void onAccepting(SelectableChannel channel) {
            synchronized (monitor) {
                connectionsAccepting.add(channel);
            }

        }

        @Override
        public void onAcceptFailed(SelectableChannel channel, Throwable cause) {
            synchronized (monitor) {
                connectionsAccepting.remove(channel);
            }
        }

        @Override
        protected void doStop() {
            synchronized (monitor) {
                connectionsAccepting.clear();
                connectionOpened = 0;
            }
        }
    }

    interface Jvm {
        long maxMemory();
        long freeMemory();

        static Jvm fromRuntime() {
            return new Jvm() {
                final Runtime rt = Runtime.getRuntime();

                @Override public long maxMemory() { return rt.maxMemory(); }
                @Override public long freeMemory() { return rt.freeMemory(); }
            };
        }
    }
}