-
Notifications
You must be signed in to change notification settings - Fork 896
/
DefaultClientFactory.java
304 lines (253 loc) · 9.92 KB
/
DefaultClientFactory.java
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
/*
* Copyright 2017 LINE Corporation
*
* LINE Corporation licenses this file to you 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:
*
* https://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.
*/
package com.linecorp.armeria.client;
import static java.util.Objects.requireNonNull;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Streams;
import com.linecorp.armeria.client.endpoint.EndpointGroup;
import com.linecorp.armeria.common.Scheme;
import com.linecorp.armeria.common.SessionProtocol;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.util.AsyncCloseableSupport;
import com.linecorp.armeria.common.util.ReleasableHolder;
import com.linecorp.armeria.common.util.ShutdownHooks;
import io.micrometer.core.instrument.MeterRegistry;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.resolver.AddressResolverGroup;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetectorFactory;
import io.netty.util.ResourceLeakTracker;
/**
* A {@link ClientFactory} which combines all discovered {@link ClientFactory} implementations.
*
* <h2>How are the {@link ClientFactory}s discovered?</h2>
*
* <p>{@link DefaultClientFactory} looks up the {@link ClientFactoryProvider}s available in the current JVM
* using Java SPI (Service Provider Interface). The {@link ClientFactoryProvider} implementations will create
* the {@link ClientFactory} implementations.
*/
final class DefaultClientFactory implements ClientFactory {
private static final Logger logger = LoggerFactory.getLogger(DefaultClientFactory.class);
private static final ResourceLeakDetector<ClientFactory> leakDetector =
ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ClientFactory.class);
private static volatile boolean shutdownHookDisabled;
static final DefaultClientFactory DEFAULT =
(DefaultClientFactory) ClientFactory.builder().build();
static final DefaultClientFactory INSECURE =
(DefaultClientFactory) ClientFactory.builder().tlsNoVerify().build();
static {
if (DefaultClientFactory.class.getClassLoader() == ClassLoader.getSystemClassLoader()) {
try {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (!shutdownHookDisabled) {
ClientFactory.closeDefault();
}
}));
} catch (IllegalStateException e) {
logger.debug("Skipped adding a shutdown hook to the DefaultClientFactory.", e);
}
}
}
static void disableShutdownHook0() {
shutdownHookDisabled = true;
}
private final HttpClientFactory httpClientFactory;
private final Multimap<Scheme, ClientFactory> clientFactories;
private final List<ClientFactory> clientFactoriesToClose;
private final AsyncCloseableSupport closeable = AsyncCloseableSupport.of(this::closeAsync);
@Nullable
private final ResourceLeakTracker<ClientFactory> leakTracker = leakDetector.track(this);
DefaultClientFactory(HttpClientFactory httpClientFactory) {
this.httpClientFactory = httpClientFactory;
final List<ClientFactory> availableClientFactories = new ArrayList<>();
// Give priority to custom client factories.
Streams.stream(ServiceLoader.load(ClientFactoryProvider.class,
DefaultClientFactory.class.getClassLoader()))
.map(provider -> provider.newFactory(httpClientFactory))
.forEach(availableClientFactories::add);
availableClientFactories.add(httpClientFactory);
final ImmutableListMultimap.Builder<Scheme, ClientFactory> builder = ImmutableListMultimap.builder();
for (ClientFactory f : availableClientFactories) {
f.supportedSchemes().forEach(s -> builder.put(s, f));
}
clientFactories = builder.build();
clientFactoriesToClose = ImmutableList.copyOf(availableClientFactories).reverse();
}
@Override
public Set<Scheme> supportedSchemes() {
return clientFactories.keySet();
}
@Override
public EventLoopGroup eventLoopGroup() {
return httpClientFactory.eventLoopGroup();
}
@Override
public Supplier<EventLoop> eventLoopSupplier() {
return httpClientFactory.eventLoopSupplier();
}
@Override
public ReleasableHolder<EventLoop> acquireEventLoop(SessionProtocol sessionProtocol,
EndpointGroup endpointGroup,
@Nullable Endpoint endpoint) {
return httpClientFactory.acquireEventLoop(sessionProtocol, endpointGroup, endpoint);
}
@Override
public MeterRegistry meterRegistry() {
return httpClientFactory.meterRegistry();
}
@Override
@Deprecated
public void setMeterRegistry(MeterRegistry meterRegistry) {
httpClientFactory.setMeterRegistry(meterRegistry);
}
@Override
public int numConnections() {
return httpClientFactory.numConnections();
}
@Override
public ClientFactoryOptions options() {
return httpClientFactory.options();
}
@Override
public Object newClient(ClientBuilderParams params) {
if (isClosing()) {
throw new IllegalStateException("Cannot create a client because the factory is closing.");
}
validateParams(params);
final Scheme scheme = params.scheme();
final Class<?> clientType = params.clientType();
for (ClientFactory factory : clientFactories.get(scheme)) {
if (factory.isClientTypeSupported(clientType)) {
return factory.newClient(params);
}
}
// Since we passed validation, there should have been at least 1 factory for this scheme,
// but for some reason none of these passed the filter.
throw new IllegalStateException(
"No ClientFactory for scheme: " + scheme + " matched clientType: " + clientType);
}
@Override
public <T> T unwrap(Object client, Class<T> type) {
final T params = ClientFactory.super.unwrap(client, type);
if (params != null) {
return params;
}
for (ClientFactory factory : clientFactories.values()) {
final T p = factory.unwrap(client, type);
if (p != null) {
return p;
}
}
return null;
}
@Override
public ClientFactory unwrap() {
return httpClientFactory;
}
@Nullable
@Override
public <T> T as(Class<T> type) {
requireNonNull(type, "type");
T result = ClientFactory.super.as(type);
if (result != null) {
return result;
}
for (ClientFactory f : clientFactories.values()) {
result = f.as(type);
if (result != null) {
return result;
}
}
return null;
}
@Override
public boolean isClosing() {
return closeable.isClosing();
}
@Override
public boolean isClosed() {
return closeable.isClosed();
}
@Override
public CompletableFuture<?> whenClosed() {
return closeable.whenClosed();
}
@Override
public CompletableFuture<?> closeAsync() {
return closeAsync(true);
}
CompletableFuture<?> closeAsync(boolean checkDefault) {
if (checkDefault && checkDefault()) {
return whenClosed();
}
return closeable.closeAsync();
}
private void closeAsync(CompletableFuture<?> future) {
if (leakTracker != null) {
leakTracker.close(this);
}
final CompletableFuture<?>[] delegateCloseFutures =
clientFactoriesToClose.stream()
.map(ClientFactory::closeAsync)
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(delegateCloseFutures).handle((unused, cause) -> {
if (cause != null) {
future.completeExceptionally(cause);
} else {
future.complete(null);
}
return null;
});
}
@Override
public void close() {
if (checkDefault()) {
return;
}
closeable.close();
}
@Override
public CompletableFuture<Void> closeOnJvmShutdown(Runnable whenClosing) {
requireNonNull(whenClosing, "whenClosing");
return ShutdownHooks.addClosingTask(this, whenClosing);
}
private boolean checkDefault() {
// The global default should never be closed.
if (this == DEFAULT || this == INSECURE) {
logger.debug("Refusing to close the default {}; must be closed via closeDefault()",
ClientFactory.class.getSimpleName());
return true;
}
return false;
}
@VisibleForTesting
AddressResolverGroup<InetSocketAddress> addressResolverGroup() {
return httpClientFactory.addressResolverGroup();
}
}