forked from grpc/grpc-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
XdsClientImpl.java
1788 lines (1659 loc) · 70.6 KB
/
XdsClientImpl.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2019 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.InvalidProtocolBufferException;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import com.google.rpc.Code;
import io.envoyproxy.envoy.api.v2.Cluster;
import io.envoyproxy.envoy.api.v2.Cluster.DiscoveryType;
import io.envoyproxy.envoy.api.v2.Cluster.EdsClusterConfig;
import io.envoyproxy.envoy.api.v2.Cluster.LbPolicy;
import io.envoyproxy.envoy.api.v2.ClusterLoadAssignment;
import io.envoyproxy.envoy.api.v2.DiscoveryRequest;
import io.envoyproxy.envoy.api.v2.DiscoveryResponse;
import io.envoyproxy.envoy.api.v2.Listener;
import io.envoyproxy.envoy.api.v2.RouteConfiguration;
import io.envoyproxy.envoy.api.v2.core.Address;
import io.envoyproxy.envoy.api.v2.core.Node;
import io.envoyproxy.envoy.api.v2.listener.FilterChain;
import io.envoyproxy.envoy.api.v2.listener.FilterChainMatch;
import io.envoyproxy.envoy.api.v2.route.Route;
import io.envoyproxy.envoy.api.v2.route.VirtualHost;
import io.envoyproxy.envoy.config.filter.network.http_connection_manager.v2.HttpConnectionManager;
import io.envoyproxy.envoy.config.filter.network.http_connection_manager.v2.Rds;
import io.envoyproxy.envoy.service.discovery.v2.AggregatedDiscoveryServiceGrpc;
import io.grpc.InternalLogId;
import io.grpc.ManagedChannel;
import io.grpc.Status;
import io.grpc.SynchronizationContext;
import io.grpc.SynchronizationContext.ScheduledHandle;
import io.grpc.internal.BackoffPolicy;
import io.grpc.stub.StreamObserver;
import io.grpc.xds.Bootstrapper.ServerInfo;
import io.grpc.xds.EnvoyProtoData.DropOverload;
import io.grpc.xds.EnvoyProtoData.Locality;
import io.grpc.xds.EnvoyProtoData.LocalityLbEndpoints;
import io.grpc.xds.EnvoyProtoData.RouteAction;
import io.grpc.xds.EnvoyProtoData.RouteMatch;
import io.grpc.xds.LoadReportClient.LoadReportCallback;
import io.grpc.xds.XdsLogger.XdsLogLevel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
final class XdsClientImpl extends XdsClient {
// Longest time to wait, since the subscription to some resource, for concluding its absence.
@VisibleForTesting
static final int INITIAL_RESOURCE_FETCH_TIMEOUT_SEC = 15;
@VisibleForTesting
static final String ADS_TYPE_URL_LDS = "type.googleapis.com/envoy.api.v2.Listener";
@VisibleForTesting
static final String ADS_TYPE_URL_RDS =
"type.googleapis.com/envoy.api.v2.RouteConfiguration";
@VisibleForTesting
static final String ADS_TYPE_URL_CDS = "type.googleapis.com/envoy.api.v2.Cluster";
@VisibleForTesting
static final String ADS_TYPE_URL_EDS =
"type.googleapis.com/envoy.api.v2.ClusterLoadAssignment";
// For now we do not support path matching unless enabled manually.
private static final boolean ENABLE_PATH_MATCHING = Boolean.parseBoolean(
System.getenv("ENABLE_EXPERIMENTAL_PATH_MATCHING"));
private final MessagePrinter respPrinter = new MessagePrinter();
private final InternalLogId logId;
private final XdsLogger logger;
// Name of the target server this gRPC client is trying to talk to.
private final String targetName;
private final ManagedChannel channel;
private final SynchronizationContext syncContext;
private final ScheduledExecutorService timeService;
private final BackoffPolicy.Provider backoffPolicyProvider;
private final Supplier<Stopwatch> stopwatchSupplier;
private final Stopwatch adsStreamRetryStopwatch;
// The node identifier to be included in xDS requests. Management server only requires the
// first request to carry the node identifier on a stream. It should be identical if present
// more than once.
private Node node;
// Cached data for CDS responses, keyed by cluster names.
// Optimization: cache ClusterUpdate, which contains only information needed by gRPC, instead
// of whole Cluster messages to reduce memory usage.
private final Map<String, ClusterUpdate> clusterNamesToClusterUpdates = new HashMap<>();
// Cached CDS resources that are known to be absent.
private final Set<String> absentCdsResources = new HashSet<>();
// Cached data for EDS responses, keyed by cluster names.
// CDS responses indicate absence of clusters and EDS responses indicate presence of clusters.
// Optimization: cache EndpointUpdate, which contains only information needed by gRPC, instead
// of whole ClusterLoadAssignment messages to reduce memory usage.
private final Map<String, EndpointUpdate> clusterNamesToEndpointUpdates = new HashMap<>();
// Cached EDS resources that are known to be absent.
private final Set<String> absentEdsResources = new HashSet<>();
// Cluster watchers waiting for cluster information updates. Multiple cluster watchers
// can watch on information for the same cluster.
private final Map<String, Set<ClusterWatcher>> clusterWatchers = new HashMap<>();
// Endpoint watchers waiting for endpoint updates for each cluster. Multiple endpoint
// watchers can watch endpoints in the same cluster.
private final Map<String, Set<EndpointWatcher>> endpointWatchers = new HashMap<>();
// Resource fetch timers are used to conclude absence of resources. Each timer is activated when
// subscription for the resource starts and disarmed on first update for the resource.
// Timers for concluding CDS resources not found.
private final Map<String, ScheduledHandle> cdsRespTimers = new HashMap<>();
// Timers for concluding EDS resources not found.
private final Map<String, ScheduledHandle> edsRespTimers = new HashMap<>();
// Timer for concluding the currently requesting LDS resource not found.
@Nullable
private ScheduledHandle ldsRespTimer;
// Timer for concluding the currently requesting RDS resource not found.
@Nullable
private ScheduledHandle rdsRespTimer;
@Nullable
private AdsStream adsStream;
@Nullable
private BackoffPolicy retryBackoffPolicy;
@Nullable
private ScheduledHandle rpcRetryTimer;
@Nullable
private LoadReportClient lrsClient;
// Following fields are set only after the ConfigWatcher registered. Once set, they should
// never change. Only a ConfigWatcher or ListenerWatcher can be registered.
@Nullable
private ConfigWatcher configWatcher;
// The "xds:" URI (including port suffix if present) that the gRPC client targets for.
@Nullable
private String ldsResourceName;
// only a ConfigWatcher or ListenerWatcher can be registered.
@Nullable
private ListenerWatcher listenerWatcher;
private int listenerPort = -1;
XdsClientImpl(
String targetName,
List<ServerInfo> servers, // list of management servers
XdsChannelFactory channelFactory,
Node node,
SynchronizationContext syncContext,
ScheduledExecutorService timeService,
BackoffPolicy.Provider backoffPolicyProvider,
Supplier<Stopwatch> stopwatchSupplier) {
this.targetName = checkNotNull(targetName, "targetName");
this.channel =
checkNotNull(channelFactory, "channelFactory")
.createChannel(checkNotNull(servers, "servers"));
this.node = checkNotNull(node, "node");
this.syncContext = checkNotNull(syncContext, "syncContext");
this.timeService = checkNotNull(timeService, "timeService");
this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider");
this.stopwatchSupplier = checkNotNull(stopwatchSupplier, "stopwatch");
adsStreamRetryStopwatch = stopwatchSupplier.get();
logId = InternalLogId.allocate("xds-client", targetName);
logger = XdsLogger.withLogId(logId);
logger.log(XdsLogLevel.INFO, "Created");
}
@Override
void shutdown() {
logger.log(XdsLogLevel.INFO, "Shutting down");
channel.shutdown();
if (adsStream != null) {
adsStream.close(Status.CANCELLED.withDescription("shutdown").asException());
}
cleanUpResources();
if (lrsClient != null) {
lrsClient.stopLoadReporting();
lrsClient = null;
}
if (rpcRetryTimer != null) {
rpcRetryTimer.cancel();
}
}
/**
* Purge cache for resources and cancel resource fetch timers.
*/
private void cleanUpResources() {
clusterNamesToClusterUpdates.clear();
absentCdsResources.clear();
clusterNamesToEndpointUpdates.clear();
absentEdsResources.clear();
if (ldsRespTimer != null) {
ldsRespTimer.cancel();
ldsRespTimer = null;
}
if (rdsRespTimer != null) {
rdsRespTimer.cancel();
rdsRespTimer = null;
}
for (ScheduledHandle handle : cdsRespTimers.values()) {
handle.cancel();
}
cdsRespTimers.clear();
for (ScheduledHandle handle : edsRespTimers.values()) {
handle.cancel();
}
edsRespTimers.clear();
}
@Override
void watchConfigData(String targetAuthority, ConfigWatcher watcher) {
checkState(configWatcher == null, "watcher for %s already registered", targetAuthority);
checkState(listenerWatcher == null, "ListenerWatcher already registered");
ldsResourceName = checkNotNull(targetAuthority, "targetAuthority");
configWatcher = checkNotNull(watcher, "watcher");
logger.log(XdsLogLevel.INFO, "Started watching config {0}", ldsResourceName);
if (rpcRetryTimer != null && rpcRetryTimer.isPending()) {
// Currently in retry backoff.
return;
}
if (adsStream == null) {
startRpcStream();
}
adsStream.sendXdsRequest(ADS_TYPE_URL_LDS, ImmutableList.of(ldsResourceName));
ldsRespTimer =
syncContext
.schedule(
new LdsResourceFetchTimeoutTask(ldsResourceName),
INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, timeService);
}
@Override
void watchClusterData(String clusterName, ClusterWatcher watcher) {
checkNotNull(clusterName, "clusterName");
checkNotNull(watcher, "watcher");
boolean needRequest = false;
if (!clusterWatchers.containsKey(clusterName)) {
logger.log(XdsLogLevel.INFO, "Start watching cluster {0}", clusterName);
needRequest = true;
clusterWatchers.put(clusterName, new HashSet<ClusterWatcher>());
}
Set<ClusterWatcher> watchers = clusterWatchers.get(clusterName);
checkState(!watchers.contains(watcher), "watcher for %s already registered", clusterName);
watchers.add(watcher);
// If local cache contains cluster information to be watched, notify the watcher immediately.
if (absentCdsResources.contains(clusterName)) {
logger.log(XdsLogLevel.DEBUG, "Cluster resource {0} is known to be absent", clusterName);
watcher.onError(
Status.NOT_FOUND
.withDescription(
"Cluster resource [" + clusterName + "] not found."));
return;
}
if (clusterNamesToClusterUpdates.containsKey(clusterName)) {
logger.log(XdsLogLevel.DEBUG, "Retrieve cluster info {0} from local cache", clusterName);
watcher.onClusterChanged(clusterNamesToClusterUpdates.get(clusterName));
return;
}
if (needRequest) {
if (rpcRetryTimer != null && rpcRetryTimer.isPending()) {
// Currently in retry backoff.
return;
}
if (adsStream == null) {
startRpcStream();
}
adsStream.sendXdsRequest(ADS_TYPE_URL_CDS, clusterWatchers.keySet());
ScheduledHandle timeoutHandle =
syncContext
.schedule(
new CdsResourceFetchTimeoutTask(clusterName),
INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, timeService);
cdsRespTimers.put(clusterName, timeoutHandle);
}
}
@Override
void cancelClusterDataWatch(String clusterName, ClusterWatcher watcher) {
checkNotNull(watcher, "watcher");
Set<ClusterWatcher> watchers = clusterWatchers.get(clusterName);
checkState(
watchers != null && watchers.contains(watcher),
"watcher for %s was not registered", clusterName);
watchers.remove(watcher);
if (watchers.isEmpty()) {
logger.log(XdsLogLevel.INFO, "Stop watching cluster {0}", clusterName);
clusterWatchers.remove(clusterName);
// Remove the corresponding CDS entry.
absentCdsResources.remove(clusterName);
clusterNamesToClusterUpdates.remove(clusterName);
// Cancel and delete response timer waiting for the corresponding resource.
if (cdsRespTimers.containsKey(clusterName)) {
cdsRespTimers.get(clusterName).cancel();
cdsRespTimers.remove(clusterName);
}
// No longer interested in this cluster, send an updated CDS request to unsubscribe
// this resource.
if (rpcRetryTimer != null && rpcRetryTimer.isPending()) {
// Currently in retry backoff.
return;
}
checkState(adsStream != null,
"Severe bug: ADS stream was not created while an endpoint watcher was registered");
adsStream.sendXdsRequest(ADS_TYPE_URL_CDS, clusterWatchers.keySet());
}
}
@Override
void watchEndpointData(String clusterName, EndpointWatcher watcher) {
checkNotNull(watcher, "watcher");
boolean needRequest = false;
if (!endpointWatchers.containsKey(clusterName)) {
logger.log(XdsLogLevel.INFO, "Start watching endpoints in cluster {0}", clusterName);
needRequest = true;
endpointWatchers.put(clusterName, new HashSet<EndpointWatcher>());
}
Set<EndpointWatcher> watchers = endpointWatchers.get(clusterName);
checkState(!watchers.contains(watcher), "watcher for %s already registered", clusterName);
watchers.add(watcher);
// If local cache contains endpoint information for the cluster to be watched, notify
// the watcher immediately.
if (absentEdsResources.contains(clusterName)) {
logger.log(
XdsLogLevel.DEBUG,
"Endpoint resource for cluster {0} is known to be absent.", clusterName);
watcher.onError(
Status.NOT_FOUND
.withDescription(
"Endpoint resource for cluster " + clusterName + " not found."));
return;
}
if (clusterNamesToEndpointUpdates.containsKey(clusterName)) {
logger.log(
XdsLogLevel.DEBUG,
"Retrieve endpoints info for cluster {0} from local cache.", clusterName);
watcher.onEndpointChanged(clusterNamesToEndpointUpdates.get(clusterName));
return;
}
if (needRequest) {
if (rpcRetryTimer != null && rpcRetryTimer.isPending()) {
// Currently in retry backoff.
return;
}
if (adsStream == null) {
startRpcStream();
}
adsStream.sendXdsRequest(ADS_TYPE_URL_EDS, endpointWatchers.keySet());
ScheduledHandle timeoutHandle =
syncContext
.schedule(
new EdsResourceFetchTimeoutTask(clusterName),
INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, timeService);
edsRespTimers.put(clusterName, timeoutHandle);
}
}
@Override
void cancelEndpointDataWatch(String clusterName, EndpointWatcher watcher) {
checkNotNull(watcher, "watcher");
Set<EndpointWatcher> watchers = endpointWatchers.get(clusterName);
checkState(
watchers != null && watchers.contains(watcher),
"watcher for %s was not registered", clusterName);
watchers.remove(watcher);
if (watchers.isEmpty()) {
logger.log(XdsLogLevel.INFO, "Stop watching endpoints in cluster {0}", clusterName);
endpointWatchers.remove(clusterName);
// Remove the corresponding EDS cache entry.
absentEdsResources.remove(clusterName);
clusterNamesToEndpointUpdates.remove(clusterName);
// Cancel and delete response timer waiting for the corresponding resource.
if (edsRespTimers.containsKey(clusterName)) {
edsRespTimers.get(clusterName).cancel();
edsRespTimers.remove(clusterName);
}
// No longer interested in this cluster, send an updated EDS request to unsubscribe
// this resource.
if (rpcRetryTimer != null && rpcRetryTimer.isPending()) {
// Currently in retry backoff.
return;
}
adsStream.sendXdsRequest(ADS_TYPE_URL_EDS, endpointWatchers.keySet());
}
}
@Override
void watchListenerData(int port, ListenerWatcher watcher) {
checkState(configWatcher == null,
"ListenerWatcher cannot be set when ConfigWatcher set");
checkState(listenerWatcher == null, "ListenerWatcher already registered");
listenerWatcher = checkNotNull(watcher, "watcher");
checkArgument(port > 0, "port needs to be > 0");
this.listenerPort = port;
logger.log(XdsLogLevel.INFO, "Started watching listener for port {0}", port);
if (rpcRetryTimer != null && rpcRetryTimer.isPending()) {
// Currently in retry backoff.
return;
}
if (adsStream == null) {
startRpcStream();
}
updateNodeMetadataForListenerRequest(port);
adsStream.sendXdsRequest(ADS_TYPE_URL_LDS, ImmutableList.<String>of());
ldsRespTimer =
syncContext
.schedule(
new ListenerResourceFetchTimeoutTask(":" + port),
INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, timeService);
}
/** In case of Listener watcher metadata to be updated to include port. */
private void updateNodeMetadataForListenerRequest(int port) {
// TODO(sanjaypujare): fields of metadata to update to be finalized
Struct newMetadata = node.getMetadata().toBuilder()
.putFields("listener_inbound_port",
Value.newBuilder().setStringValue("" + port).build())
.build();
node = node.toBuilder().setMetadata(newMetadata).build();
}
@Override
void reportClientStats(
String clusterName, @Nullable String clusterServiceName, LoadStatsStore loadStatsStore) {
if (lrsClient == null) {
lrsClient =
new LoadReportClient(
logId,
targetName,
channel,
node,
syncContext,
timeService,
backoffPolicyProvider,
stopwatchSupplier);
lrsClient.startLoadReporting(new LoadReportCallback() {
@Override
public void onReportResponse(long reportIntervalNano) {}
});
}
logger.log(
XdsLogLevel.INFO,
"Report loads for cluster: {0}, cluster_service: {1}", clusterName, clusterServiceName);
lrsClient.addLoadStatsStore(clusterName, clusterServiceName, loadStatsStore);
}
@Override
void cancelClientStatsReport(String clusterName, @Nullable String clusterServiceName) {
checkState(lrsClient != null, "load reporting was never started");
logger.log(
XdsLogLevel.INFO,
"Stop reporting loads for cluster: {0}, cluster_service: {1}",
clusterName,
clusterServiceName);
lrsClient.removeLoadStatsStore(clusterName, clusterServiceName);
// TODO(chengyuanzhang): can be optimized to stop load reporting if no more loads need
// to be reported.
}
@Override
public String toString() {
return logId.toString();
}
/**
* Establishes the RPC connection by creating a new RPC stream on the given channel for
* xDS protocol communication.
*/
private void startRpcStream() {
checkState(adsStream == null, "Previous adsStream has not been cleared yet");
AggregatedDiscoveryServiceGrpc.AggregatedDiscoveryServiceStub stub =
AggregatedDiscoveryServiceGrpc.newStub(channel);
adsStream = new AdsStream(stub);
adsStream.start();
logger.log(XdsLogLevel.INFO, "ADS stream started");
adsStreamRetryStopwatch.reset().start();
}
/**
* Calls handleLdsResponseForListener or handleLdsResponseForConfigUpdate based on which watcher
* was set.
*/
private void handleLdsResponse(DiscoveryResponse ldsResponse) {
checkState((configWatcher != null) != (listenerWatcher != null),
"No LDS request was ever sent. Management server is doing something wrong");
if (logger.isLoggable(XdsLogLevel.DEBUG)) {
logger.log(
XdsLogLevel.DEBUG, "Received LDS response:\n{0}", respPrinter.print(ldsResponse));
}
if (listenerWatcher != null) {
handleLdsResponseForListener(ldsResponse);
} else {
handleLdsResponseForConfigUpdate(ldsResponse);
}
}
/**
* Handles LDS response to find the HttpConnectionManager message for the requested resource name.
* Proceed with the resolved RouteConfiguration in HttpConnectionManager message of the requested
* listener, if exists, to find the VirtualHost configuration for the "xds:" URI
* (with the port, if any, stripped off). Or sends an RDS request if configured for dynamic
* resolution. The response is NACKed if contains invalid data for gRPC's usage. Otherwise, an
* ACK request is sent to management server.
*/
private void handleLdsResponseForConfigUpdate(DiscoveryResponse ldsResponse) {
checkState(ldsResourceName != null && configWatcher != null,
"LDS request for ConfigWatcher was never sent!");
// Unpack Listener messages.
List<Listener> listeners = new ArrayList<>(ldsResponse.getResourcesCount());
List<String> listenerNames = new ArrayList<>(ldsResponse.getResourcesCount());
try {
for (com.google.protobuf.Any res : ldsResponse.getResourcesList()) {
Listener listener = res.unpack(Listener.class);
listeners.add(listener);
listenerNames.add(listener.getName());
}
} catch (InvalidProtocolBufferException e) {
logger.log(XdsLogLevel.WARNING, "Failed to unpack Listeners in LDS response {0}", e);
adsStream.sendNackRequest(
ADS_TYPE_URL_LDS, ImmutableList.of(ldsResourceName),
ldsResponse.getVersionInfo(), "Malformed LDS response: " + e);
return;
}
logger.log(XdsLogLevel.INFO, "Received LDS response for resources: {0}", listenerNames);
// Unpack HttpConnectionManager messages.
HttpConnectionManager requestedHttpConnManager = null;
try {
for (Listener listener : listeners) {
HttpConnectionManager hm =
listener.getApiListener().getApiListener().unpack(HttpConnectionManager.class);
if (listener.getName().equals(ldsResourceName)) {
requestedHttpConnManager = hm;
}
}
} catch (InvalidProtocolBufferException e) {
logger.log(
XdsLogLevel.WARNING,
"Failed to unpack HttpConnectionManagers in Listeners of LDS response {0}", e);
adsStream.sendNackRequest(
ADS_TYPE_URL_LDS, ImmutableList.of(ldsResourceName),
ldsResponse.getVersionInfo(), "Malformed LDS response: " + e);
return;
}
String errorMessage = null;
// Routes found in the in-lined RouteConfiguration, if exists.
List<EnvoyProtoData.Route> routes = null;
// RouteConfiguration name to be used as the resource name for RDS request, if exists.
String rdsRouteConfigName = null;
// Process the requested Listener if exists, either extract cluster information from in-lined
// RouteConfiguration message or send an RDS request for dynamic resolution.
if (requestedHttpConnManager != null) {
logger.log(XdsLogLevel.DEBUG, "Found http connection manager");
// The HttpConnectionManager message must either provide the RouteConfiguration directly
// in-line or tell the client to use RDS to obtain it.
// TODO(chengyuanzhang): if both route_config and rds are set, it should be either invalid
// data or one supersedes the other. TBD.
if (requestedHttpConnManager.hasRouteConfig()) {
RouteConfiguration rc = requestedHttpConnManager.getRouteConfig();
routes = findRoutesInRouteConfig(rc, ldsResourceName);
String errorDetail = validateRoutes(routes);
if (errorDetail != null) {
errorMessage =
"Listener " + ldsResourceName + " : cannot find a valid cluster name in any "
+ "virtual hosts inside RouteConfiguration with domains matching: "
+ ldsResourceName
+ " with the reason : " + errorDetail;
}
} else if (requestedHttpConnManager.hasRds()) {
Rds rds = requestedHttpConnManager.getRds();
if (!rds.getConfigSource().hasAds()) {
errorMessage =
"Listener " + ldsResourceName + " : for using RDS, config_source must be "
+ "set to use ADS.";
} else {
rdsRouteConfigName = rds.getRouteConfigName();
}
} else {
errorMessage = "Listener " + ldsResourceName + " : HttpConnectionManager message must "
+ "either provide the RouteConfiguration directly in-line or tell the client to "
+ "use RDS to obtain it.";
}
}
if (errorMessage != null) {
adsStream.sendNackRequest(
ADS_TYPE_URL_LDS, ImmutableList.of(ldsResourceName),
ldsResponse.getVersionInfo(), errorMessage);
return;
}
adsStream.sendAckRequest(ADS_TYPE_URL_LDS, ImmutableList.of(ldsResourceName),
ldsResponse.getVersionInfo());
if (routes != null || rdsRouteConfigName != null) {
if (ldsRespTimer != null) {
ldsRespTimer.cancel();
ldsRespTimer = null;
}
}
if (routes != null) {
// Found clusterName in the in-lined RouteConfiguration.
String clusterName = routes.get(routes.size() - 1).getRouteAction().get().getCluster();
if (!ENABLE_PATH_MATCHING) {
logger.log(
XdsLogLevel.INFO,
"Found cluster name (inlined in route config): {0}", clusterName);
} else {
logger.log(
XdsLogLevel.INFO,
"Found routes (inlined in route config): {0}", routes);
}
ConfigUpdate configUpdate = ConfigUpdate.newBuilder()
.setClusterName(clusterName).addRoutes(routes).build();
configWatcher.onConfigChanged(configUpdate);
} else if (rdsRouteConfigName != null) {
// Send an RDS request if the resource to request has changed.
if (!rdsRouteConfigName.equals(adsStream.rdsResourceName)) {
logger.log(
XdsLogLevel.INFO,
"Use RDS to dynamically resolve route config, resource name: {0}", rdsRouteConfigName);
adsStream.sendXdsRequest(ADS_TYPE_URL_RDS, ImmutableList.of(rdsRouteConfigName));
// Cancel the timer for fetching the previous RDS resource.
if (rdsRespTimer != null) {
rdsRespTimer.cancel();
}
rdsRespTimer =
syncContext
.schedule(
new RdsResourceFetchTimeoutTask(rdsRouteConfigName),
INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS, timeService);
}
} else {
// The requested Listener is removed by management server.
if (ldsRespTimer == null) {
configWatcher.onError(
Status.NOT_FOUND.withDescription(
"Listener resource for listener " + ldsResourceName + " does not exist"));
}
}
}
private void handleLdsResponseForListener(DiscoveryResponse ldsResponse) {
checkState(ldsResourceName == null && listenerPort > 0 && listenerWatcher != null,
"LDS request for ListenerWatcher was never sent!");
// Unpack Listener messages.
Listener requestedListener = null;
logger.log(XdsLogLevel.DEBUG, "Listener count: {0}", ldsResponse.getResourcesCount());
try {
for (com.google.protobuf.Any res : ldsResponse.getResourcesList()) {
Listener listener = res.unpack(Listener.class);
logger.log(XdsLogLevel.DEBUG, "Found listener {0}", listener.toString());
if (isRequestedListener(listener)) {
requestedListener = listener;
logger.log(XdsLogLevel.DEBUG, "Requested listener found: {0}", listener.getName());
}
}
} catch (InvalidProtocolBufferException e) {
logger.log(XdsLogLevel.WARNING, "Failed to unpack Listeners in LDS response {0}", e);
adsStream.sendNackRequest(
ADS_TYPE_URL_LDS, ImmutableList.<String>of(),
ldsResponse.getVersionInfo(), "Malformed LDS response: " + e);
return;
}
adsStream.sendAckRequest(ADS_TYPE_URL_LDS, ImmutableList.<String>of(),
ldsResponse.getVersionInfo());
if (requestedListener != null) {
if (ldsRespTimer != null) {
ldsRespTimer.cancel();
ldsRespTimer = null;
}
ListenerUpdate listenerUpdate = ListenerUpdate.newBuilder()
.setListener(EnvoyServerProtoData.Listener.fromEnvoyProtoListener(requestedListener))
.build();
listenerWatcher.onListenerChanged(listenerUpdate);
} else {
if (ldsRespTimer == null) {
listenerWatcher.onError(Status.NOT_FOUND.withDescription("did not find listener for "
+ listenerPort));
}
}
}
private boolean isRequestedListener(Listener listener) {
// TODO(sanjaypujare): check listener.getName() once we know what xDS server returns
return isAddressMatching(listener.getAddress())
&& hasMatchingFilter(listener.getFilterChainsList());
}
private boolean isAddressMatching(Address address) {
// TODO(sanjaypujare): check IP address once we know xDS server will include it
return address.hasSocketAddress()
&& (address.getSocketAddress().getPortValue() == listenerPort);
}
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;
}
/**
* Handles RDS response to find the RouteConfiguration message for the requested resource name.
* Proceed with the resolved RouteConfiguration if exists to find the VirtualHost configuration
* for the "xds:" URI (with the port, if any, stripped off). The response is NACKed if contains
* invalid data for gRPC's usage. Otherwise, an ACK request is sent to management server.
*/
private void handleRdsResponse(DiscoveryResponse rdsResponse) {
if (logger.isLoggable(XdsLogLevel.DEBUG)) {
logger.log(XdsLogLevel.DEBUG, "Received RDS response:\n{0}", respPrinter.print(rdsResponse));
}
checkState(adsStream.rdsResourceName != null,
"Never requested for RDS resources, management server is doing something wrong");
// Unpack RouteConfiguration messages.
List<String> routeConfigNames = new ArrayList<>(rdsResponse.getResourcesCount());
RouteConfiguration requestedRouteConfig = null;
try {
for (com.google.protobuf.Any res : rdsResponse.getResourcesList()) {
RouteConfiguration rc = res.unpack(RouteConfiguration.class);
routeConfigNames.add(rc.getName());
if (rc.getName().equals(adsStream.rdsResourceName)) {
requestedRouteConfig = rc;
}
}
} catch (InvalidProtocolBufferException e) {
logger.log(
XdsLogLevel.WARNING, "Failed to unpack RouteConfiguration in RDS response {0}", e);
adsStream.sendNackRequest(
ADS_TYPE_URL_RDS, ImmutableList.of(adsStream.rdsResourceName),
rdsResponse.getVersionInfo(), "Malformed RDS response: " + e);
return;
}
logger.log(
XdsLogLevel.INFO, "Received RDS response for resources: {0}", routeConfigNames);
// Resolved cluster name for the requested resource, if exists.
List<EnvoyProtoData.Route> routes = null;
if (requestedRouteConfig != null) {
routes = findRoutesInRouteConfig(requestedRouteConfig, ldsResourceName);
String errorDetail = validateRoutes(routes);
if (errorDetail != null) {
adsStream.sendNackRequest(
ADS_TYPE_URL_RDS, ImmutableList.of(adsStream.rdsResourceName),
rdsResponse.getVersionInfo(),
"RouteConfiguration " + requestedRouteConfig.getName() + ": cannot find a "
+ "valid cluster name in any virtual hosts with domains matching: "
+ ldsResourceName
+ " with the reason: " + errorDetail);
return;
}
}
adsStream.sendAckRequest(ADS_TYPE_URL_RDS, ImmutableList.of(adsStream.rdsResourceName),
rdsResponse.getVersionInfo());
// Notify the ConfigWatcher if this RDS response contains the most recently requested
// RDS resource.
if (routes != null) {
if (rdsRespTimer != null) {
rdsRespTimer.cancel();
rdsRespTimer = null;
}
// Found clusterName in the in-lined RouteConfiguration.
String clusterName = routes.get(routes.size() - 1).getRouteAction().get().getCluster();
if (!ENABLE_PATH_MATCHING) {
logger.log(XdsLogLevel.INFO, "Found cluster name: {0}", clusterName);
} else {
logger.log(XdsLogLevel.INFO, "Found {0} routes", routes.size());
logger.log(XdsLogLevel.DEBUG, "Found routes: {0}", routes);
}
ConfigUpdate configUpdate = ConfigUpdate.newBuilder()
.setClusterName(clusterName).addRoutes(routes).build();
configWatcher.onConfigChanged(configUpdate);
}
}
/**
* Processes a RouteConfiguration message to find the routes that requests for the given host will
* be routed to.
*/
@VisibleForTesting
static List<EnvoyProtoData.Route> findRoutesInRouteConfig(
RouteConfiguration config, String hostName) {
List<VirtualHost> virtualHosts = config.getVirtualHostsList();
// Domain search order:
// 1. Exact domain names: ``www.foo.com``.
// 2. Suffix domain wildcards: ``*.foo.com`` or ``*-bar.foo.com``.
// 3. Prefix domain wildcards: ``foo.*`` or ``foo-*``.
// 4. Special wildcard ``*`` matching any domain.
//
// The longest wildcards match first.
// Assuming only a single virtual host in the entire route configuration can match
// on ``*`` and a domain must be unique across all virtual hosts.
int matchingLen = -1; // longest length of wildcard pattern that matches host name
boolean exactMatchFound = false; // true if a virtual host with exactly matched domain found
VirtualHost targetVirtualHost = null; // target VirtualHost with longest matched domain
for (VirtualHost vHost : virtualHosts) {
for (String domain : vHost.getDomainsList()) {
boolean selected = false;
if (matchHostName(hostName, domain)) { // matching
if (!domain.contains("*")) { // exact matching
exactMatchFound = true;
targetVirtualHost = vHost;
break;
} else if (domain.length() > matchingLen) { // longer matching pattern
selected = true;
} else if (domain.length() == matchingLen && domain.startsWith("*")) { // suffix matching
selected = true;
}
}
if (selected) {
matchingLen = domain.length();
targetVirtualHost = vHost;
}
}
if (exactMatchFound) {
break;
}
}
List<EnvoyProtoData.Route> routes = new ArrayList<>();
// Proceed with the virtual host that has longest wildcard matched domain name with the
// hostname in original "xds:" URI.
// Note we would consider upstream cluster not found if the virtual host is not configured
// correctly for gRPC, even if there exist other virtual hosts with (lower priority)
// matching domains.
if (targetVirtualHost != null) {
List<Route> routesProto = targetVirtualHost.getRoutesList();
for (Route route : routesProto) {
routes.add(EnvoyProtoData.Route.fromEnvoyProtoRoute(route));
}
}
return routes;
}
/**
* Validates the given list of routes and returns error details if there's any error.
*/
@Nullable
private static String validateRoutes(List<EnvoyProtoData.Route> routes) {
if (routes.isEmpty()) {
return "No routes found";
}
// We only validate the default route unless path matching is enabled.
if (!ENABLE_PATH_MATCHING) {
EnvoyProtoData.Route route = routes.get(routes.size() - 1);
RouteMatch routeMatch = route.getRouteMatch();
if (!routeMatch.getPath().isEmpty() || !routeMatch.getPrefix().isEmpty()
|| routeMatch.hasRegex()) {
return "The last route must be the default route";
}
if (!route.getRouteAction().isPresent()) {
return "Route action is not specified for the default route";
}
if (route.getRouteAction().get().getCluster().isEmpty()) {
return "Cluster is not specified for the default route";
}
return null;
}
// We do more validation if path matching is enabled, but whether every single route is required
// to be valid for grpc is TBD.
// For now we consider the whole list invalid if anything invalid for grpc is found.
// TODO(zdapeng): Fix it if the decision is different from current implementation.
// TODO(zdapeng): Add test for validation.
Set<String> prefixMatches = new HashSet<>();
Set<String> pathMatches = new HashSet<>();
for (int i = 0; i < routes.size(); i++) {
EnvoyProtoData.Route route = routes.get(i);
if (!route.getRouteAction().isPresent()) {
return "Route action is not specified for one of the routes";
}
RouteMatch routeMatch = route.getRouteMatch();
String prefix = routeMatch.getPrefix();
String path = routeMatch.getPath();
if (!prefix.isEmpty()) {
if (!prefix.startsWith("/") || !prefix.endsWith("/") || prefix.length() < 3) {
return "Prefix route match must be in the format of '/service/'";
}
if (prefixMatches.contains(prefix)) {
return "Duplicate prefix match found";
}
prefixMatches.add(prefix);
} else if (!path.isEmpty()) {
int lastSlash = path.lastIndexOf('/');
if (!path.startsWith("/") || lastSlash == 0 || lastSlash == path.length() - 1) {
return "Path route match must be in the format of '/service/method'";
}
if (pathMatches.contains(path)) {
return "Duplicate path match found";
}
pathMatches.add(path);
} else if (routeMatch.hasRegex()) {
return "Regex route match not supported";
} else { // Default route match
if (i != routes.size() - 1) {
return "Default route found but is not the last route in the route list";
}
}
if (i == routes.size() - 1) {
if (!prefix.isEmpty() || !path.isEmpty()) {
return "The last route must be the default route";
}
}
RouteAction routeAction = route.getRouteAction().get();
if (routeAction.getCluster().isEmpty() && routeAction.getWeightedCluster().isEmpty()) {
return "Either cluster or weighted cluster route action must be provided";
}
}
return null;
}
/**
* Handles CDS response, which contains a list of Cluster messages with information for a logical
* cluster. The response is NACKed if messages for requested resources contain invalid
* information for gRPC's usage. Otherwise, an ACK request is sent to management server.
* Response data for requested clusters is cached locally, in case of new cluster watchers
* interested in the same clusters are added later.
*/
private void handleCdsResponse(DiscoveryResponse cdsResponse) {
if (logger.isLoggable(XdsLogLevel.DEBUG)) {
logger.log(XdsLogLevel.DEBUG, "Received CDS response:\n{0}", respPrinter.print(cdsResponse));
}
adsStream.cdsRespNonce = cdsResponse.getNonce();
// Unpack Cluster messages.
List<Cluster> clusters = new ArrayList<>(cdsResponse.getResourcesCount());
List<String> clusterNames = new ArrayList<>(cdsResponse.getResourcesCount());
try {
for (com.google.protobuf.Any res : cdsResponse.getResourcesList()) {
Cluster cluster = res.unpack(Cluster.class);
clusters.add(cluster);
clusterNames.add(cluster.getName());
}
} catch (InvalidProtocolBufferException e) {
logger.log(XdsLogLevel.WARNING, "Failed to unpack Clusters in CDS response {0}", e);
adsStream.sendNackRequest(
ADS_TYPE_URL_CDS, clusterWatchers.keySet(),
cdsResponse.getVersionInfo(), "Malformed CDS response: " + e);
return;
}
logger.log(XdsLogLevel.INFO, "Received CDS response for resources: {0}", clusterNames);
String errorMessage = null;
// Cluster information update for requested clusters received in this CDS response.