forked from grpc/grpc-java
/
XdsClientWrapperForServerSds.java
407 lines (363 loc) · 13.8 KB
/
XdsClientWrapperForServerSds.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
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
/*
* Copyright 2020 The gRPC Authors
*
* 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.
*/
package io.grpc.xds;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import io.grpc.Internal;
import io.grpc.InternalLogId;
import io.grpc.Status;
import io.grpc.SynchronizationContext;
import io.grpc.internal.ExponentialBackoffPolicy;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.SharedResourceHolder;
import io.grpc.xds.EnvoyProtoData.Node;
import io.grpc.xds.EnvoyServerProtoData.CidrRange;
import io.grpc.xds.EnvoyServerProtoData.DownstreamTlsContext;
import io.grpc.xds.EnvoyServerProtoData.FilterChain;
import io.grpc.xds.EnvoyServerProtoData.FilterChainMatch;
import io.grpc.xds.XdsClient.XdsChannel;
import io.netty.channel.Channel;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Serves as a wrapper for {@link XdsClientImpl} used on the server side by {@link
* io.grpc.xds.internal.sds.XdsServerBuilder}.
*/
@Internal
public final class XdsClientWrapperForServerSds {
private static final Logger logger =
Logger.getLogger(XdsClientWrapperForServerSds.class.getName());
private static final TimeServiceResource timeServiceResource =
new TimeServiceResource("GrpcServerXdsClient");
private EnvoyServerProtoData.Listener curListener;
@SuppressWarnings("unused")
@Nullable private XdsClient xdsClient;
private final int port;
private ScheduledExecutorService timeService;
private XdsClient.ListenerWatcher listenerWatcher;
@VisibleForTesting final Set<ServerWatcher> serverWatchers = new HashSet<>();
/**
* Creates a {@link XdsClientWrapperForServerSds}.
*
* @param port server's port for which listener config is needed.
*/
public XdsClientWrapperForServerSds(int port) {
this.port = port;
}
private SynchronizationContext createSynchronizationContext() {
final InternalLogId logId =
InternalLogId.allocate("XdsClientWrapperForServerSds", Integer.toString(port));
return new SynchronizationContext(
new Thread.UncaughtExceptionHandler() {
// needed by syncContext
private boolean panicMode;
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.log(
Level.SEVERE,
"[" + logId + "] Uncaught exception in the SynchronizationContext. Panic!",
e);
panic(e);
}
void panic(final Throwable t) {
if (panicMode) {
// Preserve the first panic information
return;
}
panicMode = true;
shutdown();
}
});
}
public boolean hasXdsClient() {
return xdsClient != null;
}
/** Creates an XdsClient and starts a watch. */
public void createXdsClientAndStart() throws IOException {
checkState(xdsClient == null, "start() called more than once");
Bootstrapper.BootstrapInfo bootstrapInfo;
XdsChannel channel;
try {
bootstrapInfo = Bootstrapper.getInstance().readBootstrap();
List<Bootstrapper.ServerInfo> serverList = bootstrapInfo.getServers();
if (serverList.isEmpty()) {
throw new XdsInitializationException("No management server provided by bootstrap");
}
channel = XdsChannelFactory.getInstance().createChannel(serverList);
} catch (XdsInitializationException e) {
reportError(Status.fromThrowable(e));
throw new IOException(e);
}
Node node = bootstrapInfo.getNode();
timeService = SharedResourceHolder.get(timeServiceResource);
XdsClientImpl xdsClientImpl =
new XdsClientImpl(
"",
channel,
node,
createSynchronizationContext(),
timeService,
new ExponentialBackoffPolicy.Provider(),
GrpcUtil.STOPWATCH_SUPPLIER);
start(xdsClientImpl);
}
/** Accepts an XdsClient and starts a watch. */
@VisibleForTesting
public void start(XdsClient xdsClient) {
checkState(this.xdsClient == null, "start() called more than once");
checkNotNull(xdsClient, "xdsClient");
this.xdsClient = xdsClient;
this.listenerWatcher =
new XdsClient.ListenerWatcher() {
@Override
public void onListenerChanged(XdsClient.ListenerUpdate update) {
curListener = update.getListener();
reportSuccess();
}
@Override
public void onResourceDoesNotExist(String resourceName) {
logger.log(Level.WARNING, "Resource {0} is unavailable", resourceName);
curListener = null;
reportError(Status.NOT_FOUND.withDescription(resourceName));
}
@Override
public void onError(Status error) {
logger.log(
Level.WARNING, "ListenerWatcher in XdsClientWrapperForServerSds: {0}", error);
reportError(error);
}
};
xdsClient.watchListenerData(port, listenerWatcher);
}
/**
* Locates the best matching FilterChain to the channel from the current listener and if found
* returns the DownstreamTlsContext from that FilterChain, else null.
*/
@Nullable
public DownstreamTlsContext getDownstreamTlsContext(Channel channel) {
if (curListener != null && channel != null) {
SocketAddress localAddress = channel.localAddress();
checkState(
localAddress instanceof InetSocketAddress,
"Channel localAddress is expected to be InetSocketAddress");
InetSocketAddress localInetAddr = (InetSocketAddress) localAddress;
checkState(
port == localInetAddr.getPort(),
"Channel localAddress port does not match requested listener port");
return getDownstreamTlsContext(localInetAddr);
}
return null;
}
private DownstreamTlsContext getDownstreamTlsContext(InetSocketAddress localInetAddr) {
checkNotNull(localInetAddr, "localInetAddr");
if (curListener != null) {
List<FilterChain> filterChains = curListener.getFilterChains();
FilterChainComparator comparator = new FilterChainComparator(localInetAddr);
FilterChain bestMatch =
filterChains.isEmpty() ? null : Collections.max(filterChains, comparator);
if (bestMatch != null && comparator.isMatching(bestMatch.getFilterChainMatch())) {
return bestMatch.getDownstreamTlsContext();
}
}
return null;
}
/** Adds a {@link ServerWatcher} to the list. */
public void addServerWatcher(ServerWatcher serverWatcher) {
checkNotNull(serverWatcher, "serverWatcher");
synchronized (serverWatchers) {
serverWatchers.add(serverWatcher);
}
if (curListener != null) {
serverWatcher.onSuccess(getDownstreamTlsContext(new InetSocketAddress(port)));
}
}
/** Removes a {@link ServerWatcher} from the list. */
public void removeServerWatcher(ServerWatcher serverWatcher) {
checkNotNull(serverWatcher, "serverWatcher");
synchronized (serverWatchers) {
serverWatchers.remove(serverWatcher);
}
}
private Set<ServerWatcher> getServerWatchers() {
synchronized (serverWatchers) {
return ImmutableSet.copyOf(serverWatchers);
}
}
private void reportError(Status status) {
for (ServerWatcher watcher : getServerWatchers()) {
watcher.onError(status);
}
}
private void reportSuccess() {
DownstreamTlsContext downstreamTlsContext =
getDownstreamTlsContext(new InetSocketAddress(port));
for (ServerWatcher watcher : getServerWatchers()) {
watcher.onSuccess(downstreamTlsContext);
}
}
@VisibleForTesting
XdsClient.ListenerWatcher getListenerWatcher() {
return listenerWatcher;
}
/** Watcher interface for the clients of this class. */
public interface ServerWatcher {
/** Called to report errors from the control plane including "not found". */
void onError(Status error);
/** Called to report successful receipt of server config. */
void onSuccess(DownstreamTlsContext downstreamTlsContext);
}
private static final class FilterChainComparator implements Comparator<FilterChain> {
private final InetSocketAddress localAddress;
private enum Match {
NO_MATCH,
EMPTY_PREFIX_RANGE_MATCH,
IPANY_MATCH,
EXACT_ADDRESS_MATCH
}
private FilterChainComparator(InetSocketAddress localAddress) {
checkNotNull(localAddress, "localAddress cannot be null");
this.localAddress = localAddress;
}
@Override
public int compare(FilterChain first, FilterChain second) {
checkNotNull(first, "first arg cannot be null");
checkNotNull(second, "second arg cannot be null");
FilterChainMatch firstMatch = first.getFilterChainMatch();
FilterChainMatch secondMatch = second.getFilterChainMatch();
if (firstMatch == null) {
return (secondMatch == null) ? 0 : (isMatching(secondMatch) ? -1 : 1);
} else {
return (secondMatch == null)
? (isMatching(firstMatch) ? 1 : -1)
: compare(firstMatch, secondMatch);
}
}
private int compare(FilterChainMatch first, FilterChainMatch second) {
int channelPort = localAddress.getPort();
if (first.getDestinationPort() == channelPort) {
return (second.getDestinationPort() == channelPort)
? compare(first.getPrefixRanges(), second.getPrefixRanges())
: (isInetAddressMatching(first.getPrefixRanges()) ? 1 : 0);
} else {
return (second.getDestinationPort() == channelPort)
? (isInetAddressMatching(second.getPrefixRanges()) ? -1 : 0)
: 0;
}
}
private int compare(List<CidrRange> first, List<CidrRange> second) {
return getInetAddressMatch(first).ordinal() - getInetAddressMatch(second).ordinal();
}
private boolean isInetAddressMatching(List<CidrRange> prefixRanges) {
return getInetAddressMatch(prefixRanges).ordinal() > Match.NO_MATCH.ordinal();
}
private Match getInetAddressMatch(List<CidrRange> prefixRanges) {
if (prefixRanges == null || prefixRanges.isEmpty()) {
return Match.EMPTY_PREFIX_RANGE_MATCH;
}
InetAddress localInetAddress = localAddress.getAddress();
for (CidrRange cidrRange : prefixRanges) {
if (cidrRange.getPrefixLen() == 32) {
try {
InetAddress cidrAddr = InetAddress.getByName(cidrRange.getAddressPrefix());
if (cidrAddr.isAnyLocalAddress()) {
return Match.IPANY_MATCH;
}
if (cidrAddr.equals(localInetAddress)) {
return Match.EXACT_ADDRESS_MATCH;
}
} catch (UnknownHostException e) {
logger.log(Level.WARNING, "cidrRange address parsing", e);
// continue
}
}
// TODO(sanjaypujare): implement prefix match logic as needed
}
return Match.NO_MATCH;
}
private boolean isMatching(FilterChainMatch filterChainMatch) {
if (filterChainMatch == null) {
return true;
}
int destPort = filterChainMatch.getDestinationPort();
if (destPort != localAddress.getPort()) {
return false;
}
return isInetAddressMatching(filterChainMatch.getPrefixRanges());
}
}
/** Shutdown this instance and release resources. */
public void shutdown() {
logger.log(Level.FINER, "Shutdown");
if (xdsClient != null) {
xdsClient.shutdown();
xdsClient = null;
}
if (timeService != null) {
timeService = SharedResourceHolder.release(timeServiceResource, timeService);
}
}
private static final class TimeServiceResource
implements SharedResourceHolder.Resource<ScheduledExecutorService> {
private final String name;
TimeServiceResource(String name) {
this.name = name;
}
@Override
public ScheduledExecutorService create() {
// Use Netty's DefaultThreadFactory in order to get the benefit of FastThreadLocal.
ThreadFactory threadFactory = new DefaultThreadFactory(name, /* daemon= */ true);
if (Epoll.isAvailable()) {
return new EpollEventLoopGroup(1, threadFactory);
} else {
return Executors.newSingleThreadScheduledExecutor(threadFactory);
}
}
@SuppressWarnings("FutureReturnValueIgnored")
@Override
public void close(ScheduledExecutorService instance) {
try {
if (instance instanceof EpollEventLoopGroup) {
((EpollEventLoopGroup)instance).shutdownGracefully(0, 0, TimeUnit.SECONDS).sync();
} else {
instance.shutdown();
}
} catch (InterruptedException e) {
logger.log(Level.SEVERE, "Interrupted during shutdown", e);
Thread.currentThread().interrupt();
}
}
}
}