forked from grpc/grpc-java
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ServerXdsClient.java
260 lines (239 loc) · 9.28 KB
/
ServerXdsClient.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
/*
* 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.checkArgument;
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.base.Stopwatch;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import io.envoyproxy.envoy.config.core.v3.Address;
import io.envoyproxy.envoy.config.core.v3.TrafficDirection;
import io.envoyproxy.envoy.config.listener.v3.FilterChain;
import io.envoyproxy.envoy.config.listener.v3.FilterChainMatch;
import io.envoyproxy.envoy.config.listener.v3.Listener;
import io.grpc.Status;
import io.grpc.SynchronizationContext.ScheduledHandle;
import io.grpc.internal.BackoffPolicy;
import io.grpc.xds.EnvoyProtoData.Node;
import io.grpc.xds.XdsLogger.XdsLogLevel;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* XdsClient implementation for server side usages.
*/
final class ServerXdsClient extends AbstractXdsClient {
// Longest time to wait, since the subscription to some resource, for concluding its absence.
@VisibleForTesting
static final int INITIAL_RESOURCE_FETCH_TIMEOUT_SEC = 15;
@Nullable
private ListenerWatcher listenerWatcher;
private int listenerPort = -1;
private final boolean useNewApiForListenerQuery;
@Nullable private final String instanceIp;
private String grpcServerResourceId;
@Nullable
private ScheduledHandle ldsRespTimer;
ServerXdsClient(
XdsChannel channel,
Node node,
ScheduledExecutorService timeService,
BackoffPolicy.Provider backoffPolicyProvider,
Supplier<Stopwatch> stopwatchSupplier,
boolean useNewApiForListenerQuery,
String instanceIp,
String grpcServerResourceId) {
super(channel, node, timeService, backoffPolicyProvider, stopwatchSupplier);
this.useNewApiForListenerQuery = channel.isUseProtocolV3() && useNewApiForListenerQuery;
this.instanceIp = (instanceIp != null ? instanceIp : "0.0.0.0");
this.grpcServerResourceId = grpcServerResourceId != null ? grpcServerResourceId : "grpc/server";
}
@Override
void watchListenerData(final int port, final ListenerWatcher watcher) {
checkState(listenerWatcher == null, "ListenerWatcher already registered");
listenerWatcher = checkNotNull(watcher, "watcher");
checkArgument(port > 0, "port needs to be > 0");
listenerPort = port;
if (useNewApiForListenerQuery) {
String listeningAddress = instanceIp + ":" + listenerPort;
grpcServerResourceId =
grpcServerResourceId + "?udpa.resource.listening_address=" + listeningAddress;
} else {
grpcServerResourceId = ":" + listenerPort;
}
getSyncContext().execute(new Runnable() {
@Override
public void run() {
getLogger().log(XdsLogLevel.INFO, "Started watching listener for port {0}", port);
if (!useNewApiForListenerQuery) {
updateNodeMetadataForListenerRequest(port);
}
adjustResourceSubscription(ResourceType.LDS);
if (!isInBackoff()) {
ldsRespTimer =
getSyncContext()
.schedule(
new ListenerResourceFetchTimeoutTask(grpcServerResourceId),
INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, getTimeService());
}
}
});
}
@Nullable
@Override
Collection<String> getSubscribedResources(ResourceType type) {
if (type != ResourceType.LDS) {
return null;
}
if (useNewApiForListenerQuery) {
return ImmutableList.<String>of(grpcServerResourceId);
} else {
return Collections.emptyList();
}
}
/** In case of Listener watcher metadata to be updated to include port. */
private void updateNodeMetadataForListenerRequest(int port) {
Map<String, Object> newMetadata = new HashMap<>();
if (node.getMetadata() != null) {
newMetadata.putAll(node.getMetadata());
}
newMetadata.put("TRAFFICDIRECTOR_INBOUND_INTERCEPTION_PORT", "15001");
newMetadata.put("TRAFFICDIRECTOR_INBOUND_BACKEND_PORTS", "" + port);
newMetadata.put("INSTANCE_IP", instanceIp);
node = node.toBuilder().setMetadata(newMetadata).build();
}
@Override
protected void handleLdsResponse(String versionInfo, List<Any> resources, String nonce) {
// Unpack Listener messages.
Listener requestedListener = null;
getLogger().log(XdsLogLevel.DEBUG, "Listener count: {0}", resources.size());
try {
for (com.google.protobuf.Any res : resources) {
if (res.getTypeUrl().equals(ResourceType.LDS.typeUrlV2())) {
res = res.toBuilder().setTypeUrl(ResourceType.LDS.typeUrl()).build();
}
Listener listener = res.unpack(Listener.class);
getLogger().log(XdsLogLevel.DEBUG, "Found listener {0}", listener.toString());
if (isRequestedListener(listener)) {
requestedListener = listener;
getLogger().log(XdsLogLevel.DEBUG, "Requested listener found: {0}", listener.getName());
}
}
} catch (InvalidProtocolBufferException e) {
getLogger().log(XdsLogLevel.WARNING, "Failed to unpack Listeners in LDS response {0}", e);
nackResponse(ResourceType.LDS, nonce, "Malformed LDS response: " + e);
return;
}
ListenerUpdate listenerUpdate = null;
if (requestedListener != null) {
if (ldsRespTimer != null) {
ldsRespTimer.cancel();
ldsRespTimer = null;
}
try {
listenerUpdate = ListenerUpdate.newBuilder()
.setListener(EnvoyServerProtoData.Listener.fromEnvoyProtoListener(requestedListener))
.build();
} catch (InvalidProtocolBufferException e) {
getLogger().log(XdsLogLevel.WARNING, "Failed to unpack Listener in LDS response {0}", e);
nackResponse(ResourceType.LDS, nonce, "Malformed LDS response: " + e);
return;
}
} else {
if (ldsRespTimer == null) {
listenerWatcher.onResourceDoesNotExist(grpcServerResourceId);
}
}
ackResponse(ResourceType.LDS, versionInfo, nonce);
if (listenerUpdate != null) {
listenerWatcher.onListenerChanged(listenerUpdate);
}
}
private boolean isRequestedListener(Listener listener) {
if (useNewApiForListenerQuery) {
return grpcServerResourceId.equals(listener.getName())
&& listener.getTrafficDirection().equals(TrafficDirection.INBOUND)
&& isAddressMatching(listener.getAddress(), listenerPort);
}
return isAddressMatching(listener.getAddress(), 15001)
&& hasMatchingFilter(listener.getFilterChainsList());
}
private boolean isAddressMatching(Address address, int portToMatch) {
return address.hasSocketAddress() && address.getSocketAddress().getPortValue() == portToMatch;
}
private boolean hasMatchingFilter(List<FilterChain> filterChainsList) {
// TODO(sanjaypujare): if myIp to be checked against filterChainMatch.getPrefixRangesList()
for (FilterChain filterChain : filterChainsList) {
FilterChainMatch filterChainMatch = filterChain.getFilterChainMatch();
if (listenerPort == filterChainMatch.getDestinationPort().getValue()) {
return true;
}
}
return false;
}
@Override
protected void handleStreamClosed(Status error) {
cleanUpResourceTimer();
if (listenerWatcher != null) {
listenerWatcher.onError(error);
}
}
@Override
protected void handleStreamRestarted() {
if (listenerWatcher != null) {
ldsRespTimer =
getSyncContext()
.schedule(
new ListenerResourceFetchTimeoutTask(grpcServerResourceId),
INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, getTimeService());
}
}
@Override
protected void handleShutdown() {
cleanUpResourceTimer();
}
private void cleanUpResourceTimer() {
if (ldsRespTimer != null) {
ldsRespTimer.cancel();
ldsRespTimer = null;
}
}
@VisibleForTesting
final class ListenerResourceFetchTimeoutTask implements Runnable {
private String resourceName;
ListenerResourceFetchTimeoutTask(String resourceName) {
this.resourceName = resourceName;
}
@Override
public void run() {
getLogger().log(
XdsLogLevel.WARNING,
"Did not receive resource info {0} after {1} seconds, conclude it absent",
resourceName, INITIAL_RESOURCE_FETCH_TIMEOUT_SEC);
ldsRespTimer = null;
listenerWatcher.onResourceDoesNotExist(resourceName);
}
}
}