forked from grpc/grpc-java
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ClientXdsClientTestBase.java
2894 lines (2611 loc) · 144 KB
/
ClientXdsClientTestBase.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.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static io.grpc.xds.AbstractXdsClient.ResourceType.CDS;
import static io.grpc.xds.AbstractXdsClient.ResourceType.EDS;
import static io.grpc.xds.AbstractXdsClient.ResourceType.LDS;
import static io.grpc.xds.AbstractXdsClient.ResourceType.RDS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import io.envoyproxy.envoy.config.route.v3.FilterConfig;
import io.envoyproxy.envoy.extensions.filters.http.router.v3.Router;
import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CertificateProviderPluginInstance;
import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CommonTlsContext;
import io.grpc.BindableService;
import io.grpc.ChannelCredentials;
import io.grpc.Context;
import io.grpc.Context.CancellableContext;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.Status;
import io.grpc.Status.Code;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.internal.BackoffPolicy;
import io.grpc.internal.FakeClock;
import io.grpc.internal.FakeClock.ScheduledTask;
import io.grpc.internal.FakeClock.TaskFilter;
import io.grpc.internal.TimeProvider;
import io.grpc.testing.GrpcCleanupRule;
import io.grpc.xds.AbstractXdsClient.ResourceType;
import io.grpc.xds.Bootstrapper.AuthorityInfo;
import io.grpc.xds.Bootstrapper.CertificateProviderInfo;
import io.grpc.xds.Bootstrapper.ServerInfo;
import io.grpc.xds.ClientXdsClient.XdsChannelFactory;
import io.grpc.xds.Endpoints.DropOverload;
import io.grpc.xds.Endpoints.LbEndpoint;
import io.grpc.xds.Endpoints.LocalityLbEndpoints;
import io.grpc.xds.EnvoyProtoData.Node;
import io.grpc.xds.EnvoyServerProtoData.FilterChain;
import io.grpc.xds.FaultConfig.FractionalPercent.DenominatorType;
import io.grpc.xds.LoadStatsManager2.ClusterDropStats;
import io.grpc.xds.XdsClient.CdsResourceWatcher;
import io.grpc.xds.XdsClient.CdsUpdate;
import io.grpc.xds.XdsClient.CdsUpdate.ClusterType;
import io.grpc.xds.XdsClient.CdsUpdate.LbPolicy;
import io.grpc.xds.XdsClient.EdsResourceWatcher;
import io.grpc.xds.XdsClient.EdsUpdate;
import io.grpc.xds.XdsClient.LdsResourceWatcher;
import io.grpc.xds.XdsClient.LdsUpdate;
import io.grpc.xds.XdsClient.RdsResourceWatcher;
import io.grpc.xds.XdsClient.RdsUpdate;
import io.grpc.xds.XdsClient.ResourceMetadata;
import io.grpc.xds.XdsClient.ResourceMetadata.ResourceMetadataStatus;
import io.grpc.xds.XdsClient.ResourceMetadata.UpdateFailureState;
import io.grpc.xds.XdsClient.ResourceWatcher;
import io.grpc.xds.internal.sds.CommonTlsContextTestsUtil;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
/**
* Tests for {@link ClientXdsClient}.
*/
@RunWith(JUnit4.class)
public abstract class ClientXdsClientTestBase {
private static final String SERVER_URI = "trafficdirector.googleapis.com";
private static final String SERVER_URI_CUSTOME_AUTHORITY = "trafficdirector2.googleapis.com";
private static final String SERVER_URI_EMPTY_AUTHORITY = "trafficdirector3.googleapis.com";
private static final String LDS_RESOURCE = "listener.googleapis.com";
private static final String RDS_RESOURCE = "route-configuration.googleapis.com";
private static final String CDS_RESOURCE = "cluster.googleapis.com";
private static final String EDS_RESOURCE = "cluster-load-assignment.googleapis.com";
private static final String LISTENER_RESOURCE =
"grpc/server?xds.resource.listening_address=0.0.0.0:7000";
private static final String VERSION_1 = "42";
private static final String VERSION_2 = "43";
private static final String VERSION_3 = "44";
private static final Node NODE = Node.newBuilder().build();
private static final Any FAILING_ANY = MessageFactory.FAILING_ANY;
private static final ChannelCredentials CHANNEL_CREDENTIALS = InsecureChannelCredentials.create();
private final ServerInfo lrsServerInfo =
ServerInfo.create(SERVER_URI, CHANNEL_CREDENTIALS, useProtocolV3());
private static final FakeClock.TaskFilter RPC_RETRY_TASK_FILTER =
new FakeClock.TaskFilter() {
@Override
public boolean shouldAccept(Runnable command) {
return command.toString().contains(AbstractXdsClient.RpcRetryTask.class.getSimpleName());
}
};
private static final FakeClock.TaskFilter LDS_RESOURCE_FETCH_TIMEOUT_TASK_FILTER =
new TaskFilter() {
@Override
public boolean shouldAccept(Runnable command) {
return command.toString().contains(LDS.toString());
}
};
private static final FakeClock.TaskFilter RDS_RESOURCE_FETCH_TIMEOUT_TASK_FILTER =
new TaskFilter() {
@Override
public boolean shouldAccept(Runnable command) {
return command.toString().contains(RDS.toString());
}
};
private static final FakeClock.TaskFilter CDS_RESOURCE_FETCH_TIMEOUT_TASK_FILTER =
new TaskFilter() {
@Override
public boolean shouldAccept(Runnable command) {
return command.toString().contains(CDS.toString());
}
};
private static final FakeClock.TaskFilter EDS_RESOURCE_FETCH_TIMEOUT_TASK_FILTER =
new FakeClock.TaskFilter() {
@Override
public boolean shouldAccept(Runnable command) {
return command.toString().contains(EDS.toString());
}
};
@Rule
public final GrpcCleanupRule cleanupRule = new GrpcCleanupRule();
private final FakeClock fakeClock = new FakeClock();
protected final Queue<DiscoveryRpcCall> resourceDiscoveryCalls = new ArrayDeque<>();
protected final Queue<LrsRpcCall> loadReportCalls = new ArrayDeque<>();
protected final AtomicBoolean adsEnded = new AtomicBoolean(true);
protected final AtomicBoolean lrsEnded = new AtomicBoolean(true);
private final MessageFactory mf = createMessageFactory();
private static final long TIME_INCREMENT = TimeUnit.SECONDS.toNanos(1);
/** Fake time provider increments time TIME_INCREMENT each call. */
private final TimeProvider timeProvider = new TimeProvider() {
private long count;
@Override
public long currentTimeNanos() {
return ++count * TIME_INCREMENT;
}
};
private static final int VHOST_SIZE = 2;
// LDS test resources.
private final Any testListenerVhosts = Any.pack(mf.buildListenerWithApiListener(LDS_RESOURCE,
mf.buildRouteConfiguration("do not care", mf.buildOpaqueVirtualHosts(VHOST_SIZE))));
private final Any testListenerRds =
Any.pack(mf.buildListenerWithApiListenerForRds(LDS_RESOURCE, RDS_RESOURCE));
// RDS test resources.
private final Any testRouteConfig =
Any.pack(mf.buildRouteConfiguration(RDS_RESOURCE, mf.buildOpaqueVirtualHosts(VHOST_SIZE)));
// CDS test resources.
private final Any testClusterRoundRobin =
Any.pack(mf.buildEdsCluster(CDS_RESOURCE, null, "round_robin", null,
null, false, null, "envoy.transport_sockets.tls", null
));
// EDS test resources.
private final Message lbEndpointHealthy =
mf.buildLocalityLbEndpoints("region1", "zone1", "subzone1",
mf.buildLbEndpoint("192.168.0.1", 8080, "healthy", 2), 1, 0);
// Locality with 0 endpoints
private final Message lbEndpointEmpty =
mf.buildLocalityLbEndpoints("region3", "zone3", "subzone3",
ImmutableList.<Message>of(), 2, 1);
// Locality with 0-weight endpoint
private final Message lbEndpointZeroWeight =
mf.buildLocalityLbEndpoints("region4", "zone4", "subzone4",
mf.buildLbEndpoint("192.168.142.5", 80, "unknown", 5), 0, 2);
private final Any testClusterLoadAssignment = Any.pack(mf.buildClusterLoadAssignment(EDS_RESOURCE,
ImmutableList.of(lbEndpointHealthy, lbEndpointEmpty, lbEndpointZeroWeight),
ImmutableList.of(mf.buildDropOverload("lb", 200), mf.buildDropOverload("throttle", 1000))));
@Captor
private ArgumentCaptor<LdsUpdate> ldsUpdateCaptor;
@Captor
private ArgumentCaptor<RdsUpdate> rdsUpdateCaptor;
@Captor
private ArgumentCaptor<CdsUpdate> cdsUpdateCaptor;
@Captor
private ArgumentCaptor<EdsUpdate> edsUpdateCaptor;
@Captor
private ArgumentCaptor<Status> errorCaptor;
@Mock
private BackoffPolicy.Provider backoffPolicyProvider;
@Mock
private BackoffPolicy backoffPolicy1;
@Mock
private BackoffPolicy backoffPolicy2;
@Mock
private LdsResourceWatcher ldsResourceWatcher;
@Mock
private RdsResourceWatcher rdsResourceWatcher;
@Mock
private CdsResourceWatcher cdsResourceWatcher;
@Mock
private EdsResourceWatcher edsResourceWatcher;
@Mock
private TlsContextManager tlsContextManager;
private ManagedChannel channel;
private ManagedChannel channelForCustomAuthority;
private ManagedChannel channelForEmptyAuthority;
private ClientXdsClient xdsClient;
private boolean originalEnableFaultInjection;
private boolean originalEnableRbac;
private boolean originalEnableLeastRequest;
private boolean originalEnableFederation;
@Before
public void setUp() throws IOException {
// Init mocks.
MockitoAnnotations.initMocks(this);
when(backoffPolicyProvider.get()).thenReturn(backoffPolicy1, backoffPolicy2);
when(backoffPolicy1.nextBackoffNanos()).thenReturn(10L, 100L);
when(backoffPolicy2.nextBackoffNanos()).thenReturn(20L, 200L);
// Start the server and the client.
originalEnableFaultInjection = ClientXdsClient.enableFaultInjection;
ClientXdsClient.enableFaultInjection = true;
originalEnableRbac = ClientXdsClient.enableRbac;
assertThat(originalEnableRbac).isTrue();
originalEnableLeastRequest = ClientXdsClient.enableLeastRequest;
ClientXdsClient.enableLeastRequest = true;
originalEnableFederation = BootstrapperImpl.enableFederation;
final String serverName = InProcessServerBuilder.generateName();
cleanupRule.register(
InProcessServerBuilder
.forName(serverName)
.addService(createAdsService())
.addService(createLrsService())
.directExecutor()
.build()
.start());
channel =
cleanupRule.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
XdsChannelFactory xdsChannelFactory = new XdsChannelFactory() {
@Override
ManagedChannel create(ServerInfo serverInfo) {
if (serverInfo.target().equals(SERVER_URI)) {
return channel;
}
if (serverInfo.target().equals(SERVER_URI_CUSTOME_AUTHORITY)) {
if (channelForCustomAuthority == null) {
channelForCustomAuthority = cleanupRule.register(
InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
return channelForCustomAuthority;
}
if (serverInfo.target().equals(SERVER_URI_EMPTY_AUTHORITY)) {
if (channelForEmptyAuthority == null) {
channelForEmptyAuthority = cleanupRule.register(
InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
return channelForEmptyAuthority;
}
throw new IllegalArgumentException("Can not create channel for " + serverInfo);
}
};
Bootstrapper.BootstrapInfo bootstrapInfo =
Bootstrapper.BootstrapInfo.builder()
.servers(Arrays.asList(
Bootstrapper.ServerInfo.create(SERVER_URI, CHANNEL_CREDENTIALS, useProtocolV3())))
.node(EnvoyProtoData.Node.newBuilder().build())
.authorities(ImmutableMap.of(
"authority.xds.com",
AuthorityInfo.create(
"xdstp://authority.xds.com/envoy.config.listener.v3.Listener/%s",
ImmutableList.of(Bootstrapper.ServerInfo.create(
SERVER_URI_CUSTOME_AUTHORITY, CHANNEL_CREDENTIALS, useProtocolV3()))),
"",
AuthorityInfo.create(
"xdstp:///envoy.config.listener.v3.Listener/%s",
ImmutableList.of(Bootstrapper.ServerInfo.create(
SERVER_URI_EMPTY_AUTHORITY, CHANNEL_CREDENTIALS, useProtocolV3())))))
.certProviders(ImmutableMap.of("cert-instance-name",
CertificateProviderInfo.create("file-watcher", ImmutableMap.<String, Object>of())))
.build();
xdsClient =
new ClientXdsClient(
xdsChannelFactory,
bootstrapInfo,
Context.ROOT,
fakeClock.getScheduledExecutorService(),
backoffPolicyProvider,
fakeClock.getStopwatchSupplier(),
timeProvider,
tlsContextManager);
assertThat(resourceDiscoveryCalls).isEmpty();
assertThat(loadReportCalls).isEmpty();
}
@After
public void tearDown() {
ClientXdsClient.enableFaultInjection = originalEnableFaultInjection;
ClientXdsClient.enableRbac = originalEnableRbac;
ClientXdsClient.enableLeastRequest = originalEnableLeastRequest;
BootstrapperImpl.enableFederation = originalEnableFederation;
xdsClient.shutdown();
channel.shutdown(); // channel not owned by XdsClient
assertThat(adsEnded.get()).isTrue();
assertThat(lrsEnded.get()).isTrue();
assertThat(fakeClock.getPendingTasks()).isEmpty();
}
protected abstract boolean useProtocolV3();
protected abstract BindableService createAdsService();
protected abstract BindableService createLrsService();
protected abstract MessageFactory createMessageFactory();
protected static boolean matchErrorDetail(
com.google.rpc.Status errorDetail, int expectedCode, List<String> expectedMessages) {
if (expectedCode != errorDetail.getCode()) {
return false;
}
List<String> errors = Splitter.on('\n').splitToList(errorDetail.getMessage());
if (errors.size() != expectedMessages.size()) {
return false;
}
for (int i = 0; i < errors.size(); i++) {
if (!errors.get(i).startsWith(expectedMessages.get(i))) {
return false;
}
}
return true;
}
private void verifySubscribedResourcesMetadataSizes(
int ldsSize, int cdsSize, int rdsSize, int edsSize) {
Map<ResourceType, Map<String, ResourceMetadata>> subscribedResourcesMetadata =
awaitSubscribedResourcesMetadata();
assertThat(subscribedResourcesMetadata.get(LDS)).hasSize(ldsSize);
assertThat(subscribedResourcesMetadata.get(CDS)).hasSize(cdsSize);
assertThat(subscribedResourcesMetadata.get(RDS)).hasSize(rdsSize);
assertThat(subscribedResourcesMetadata.get(EDS)).hasSize(edsSize);
}
private Map<ResourceType, Map<String, ResourceMetadata>> awaitSubscribedResourcesMetadata() {
try {
return xdsClient.getSubscribedResourcesMetadataSnapshot().get(20, TimeUnit.SECONDS);
} catch (Exception e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new AssertionError(e);
}
}
/** Verify the resource requested, but not updated. */
private void verifyResourceMetadataRequested(ResourceType type, String resourceName) {
verifyResourceMetadata(
type, resourceName, null, ResourceMetadataStatus.REQUESTED, "", 0, false);
}
/** Verify that the requested resource does not exist. */
private void verifyResourceMetadataDoesNotExist(ResourceType type, String resourceName) {
verifyResourceMetadata(
type, resourceName, null, ResourceMetadataStatus.DOES_NOT_EXIST, "", 0, false);
}
/** Verify the resource to be acked. */
private void verifyResourceMetadataAcked(
ResourceType type, String resourceName, Any rawResource, String versionInfo,
long updateTimeNanos) {
verifyResourceMetadata(type, resourceName, rawResource, ResourceMetadataStatus.ACKED,
versionInfo, updateTimeNanos, false);
}
/**
* Verify the resource to be nacked, and every i-th line of error details to begin with
* corresponding i-th element of {@code List<String> failedDetails}.
*/
private void verifyResourceMetadataNacked(
ResourceType type, String resourceName, Any rawResource, String versionInfo,
long updateTime, String failedVersion, long failedUpdateTimeNanos,
List<String> failedDetails) {
ResourceMetadata resourceMetadata =
verifyResourceMetadata(type, resourceName, rawResource, ResourceMetadataStatus.NACKED,
versionInfo, updateTime, true);
UpdateFailureState errorState = resourceMetadata.getErrorState();
assertThat(errorState).isNotNull();
String name = type.toString() + " resource '" + resourceName + "' metadata error ";
assertWithMessage(name + "failedVersion").that(errorState.getFailedVersion())
.isEqualTo(failedVersion);
assertWithMessage(name + "failedUpdateTimeNanos").that(errorState.getFailedUpdateTimeNanos())
.isEqualTo(failedUpdateTimeNanos);
List<String> errors = Splitter.on('\n').splitToList(errorState.getFailedDetails());
for (int i = 0; i < errors.size(); i++) {
assertWithMessage(name + "failedDetails line " + i).that(errors.get(i))
.startsWith(failedDetails.get(i));
}
}
private ResourceMetadata verifyResourceMetadata(
ResourceType type, String resourceName, Any rawResource, ResourceMetadataStatus status,
String versionInfo, long updateTimeNanos, boolean hasErrorState) {
ResourceMetadata metadata = awaitSubscribedResourcesMetadata().get(type).get(resourceName);
assertThat(metadata).isNotNull();
String name = type.toString() + " resource '" + resourceName + "' metadata field ";
assertWithMessage(name + "status").that(metadata.getStatus()).isEqualTo(status);
assertWithMessage(name + "version").that(metadata.getVersion()).isEqualTo(versionInfo);
assertWithMessage(name + "rawResource").that(metadata.getRawResource()).isEqualTo(rawResource);
assertWithMessage(name + "updateTimeNanos").that(metadata.getUpdateTimeNanos())
.isEqualTo(updateTimeNanos);
if (hasErrorState) {
assertWithMessage(name + "errorState").that(metadata.getErrorState()).isNotNull();
} else {
assertWithMessage(name + "errorState").that(metadata.getErrorState()).isNull();
}
return metadata;
}
/**
* Helper method to validate {@link XdsClient.EdsUpdate} created for the test CDS resource
* {@link ClientXdsClientTestBase#testClusterLoadAssignment}.
*/
private void validateTestClusterLoadAssigment(EdsUpdate edsUpdate) {
assertThat(edsUpdate.clusterName).isEqualTo(EDS_RESOURCE);
assertThat(edsUpdate.dropPolicies)
.containsExactly(
DropOverload.create("lb", 200),
DropOverload.create("throttle", 1000));
assertThat(edsUpdate.localityLbEndpointsMap)
.containsExactly(
Locality.create("region1", "zone1", "subzone1"),
LocalityLbEndpoints.create(
ImmutableList.of(LbEndpoint.create("192.168.0.1", 8080, 2, true)), 1, 0),
Locality.create("region3", "zone3", "subzone3"),
LocalityLbEndpoints.create(ImmutableList.<LbEndpoint>of(), 2, 1));
}
@Test
public void ldsResourceNotFound() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
Any listener = Any.pack(mf.buildListenerWithApiListener("bar.googleapis.com",
mf.buildRouteConfiguration("route-bar.googleapis.com", mf.buildOpaqueVirtualHosts(1))));
call.sendResponse(LDS, listener, VERSION_1, "0000");
// Client sends an ACK LDS request.
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_1, "0000", NODE);
verifyNoInteractions(ldsResourceWatcher);
verifyResourceMetadataRequested(LDS, LDS_RESOURCE);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
// Server failed to return subscribed resource within expected time window.
fakeClock.forwardTime(ClientXdsClient.INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS);
verify(ldsResourceWatcher).onResourceDoesNotExist(LDS_RESOURCE);
assertThat(fakeClock.getPendingTasks(LDS_RESOURCE_FETCH_TIMEOUT_TASK_FILTER)).isEmpty();
verifyResourceMetadataDoesNotExist(LDS, LDS_RESOURCE);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
}
@Test
public void ldsResponseErrorHandling_allResourcesFailedUnpack() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
verifyResourceMetadataRequested(LDS, LDS_RESOURCE);
call.sendResponse(LDS, ImmutableList.of(FAILING_ANY, FAILING_ANY), VERSION_1, "0000");
// Resulting metadata unchanged because the response has no identifiable subscribed resources.
verifyResourceMetadataRequested(LDS, LDS_RESOURCE);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
// The response NACKed with errors indicating indices of the failed resources.
call.verifyRequestNack(LDS, LDS_RESOURCE, "", "0000", NODE, ImmutableList.of(
"LDS response Resource index 0 - can't decode Listener: ",
"LDS response Resource index 1 - can't decode Listener: "));
verifyNoInteractions(ldsResourceWatcher);
}
@Test
public void ldsResponseErrorHandling_someResourcesFailedUnpack() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
verifyResourceMetadataRequested(LDS, LDS_RESOURCE);
// Correct resource is in the middle to ensure processing continues on errors.
List<Any> resources = ImmutableList.of(FAILING_ANY, testListenerRds, FAILING_ANY);
call.sendResponse(LDS, resources, VERSION_1, "0000");
// All errors recorded in the metadata of successfully unpacked subscribed resources.
List<String> errors = ImmutableList.of(
"LDS response Resource index 0 - can't decode Listener: ",
"LDS response Resource index 2 - can't decode Listener: ");
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, testListenerRds, VERSION_1, TIME_INCREMENT);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
// The response is NACKed with the same error message.
call.verifyRequestNack(LDS, LDS_RESOURCE, "", "0000", NODE, errors);
verify(ldsResourceWatcher).onChanged(any(LdsUpdate.class));
}
/**
* Tests a subscribed LDS resource transitioned to and from the invalid state.
*
* @see <a href="https://github.com/grpc/proposal/blob/master/A40-csds-support.md#ads-parsing-logic-update-continue-after-first-error">
* A40-csds-support.md</a>.
*/
@Test
public void ldsResponseErrorHandling_subscribedResourceInvalid() {
List<String> subscribedResourceNames = ImmutableList.of("A", "B", "C");
xdsClient.watchLdsResource("A", ldsResourceWatcher);
xdsClient.watchLdsResource("B", ldsResourceWatcher);
xdsClient.watchLdsResource("C", ldsResourceWatcher);
DiscoveryRpcCall call = resourceDiscoveryCalls.poll();
assertThat(call).isNotNull();
verifyResourceMetadataRequested(LDS, "A");
verifyResourceMetadataRequested(LDS, "B");
verifyResourceMetadataRequested(LDS, "C");
verifySubscribedResourcesMetadataSizes(3, 0, 0, 0);
// LDS -> {A, B, C}, version 1
ImmutableMap<String, Any> resourcesV1 = ImmutableMap.of(
"A", Any.pack(mf.buildListenerWithApiListenerForRds("A", "A.1")),
"B", Any.pack(mf.buildListenerWithApiListenerForRds("B", "B.1")),
"C", Any.pack(mf.buildListenerWithApiListenerForRds("C", "C.1")));
call.sendResponse(LDS, resourcesV1.values().asList(), VERSION_1, "0000");
// {A, B, C} -> ACK, version 1
verifyResourceMetadataAcked(LDS, "A", resourcesV1.get("A"), VERSION_1, TIME_INCREMENT);
verifyResourceMetadataAcked(LDS, "B", resourcesV1.get("B"), VERSION_1, TIME_INCREMENT);
verifyResourceMetadataAcked(LDS, "C", resourcesV1.get("C"), VERSION_1, TIME_INCREMENT);
call.verifyRequest(LDS, subscribedResourceNames, VERSION_1, "0000", NODE);
// LDS -> {A, B}, version 2
// Failed to parse endpoint B
ImmutableMap<String, Any> resourcesV2 = ImmutableMap.of(
"A", Any.pack(mf.buildListenerWithApiListenerForRds("A", "A.2")),
"B", Any.pack(mf.buildListenerWithApiListenerInvalid("B")));
call.sendResponse(LDS, resourcesV2.values().asList(), VERSION_2, "0001");
// {A} -> ACK, version 2
// {B} -> NACK, version 1, rejected version 2, rejected reason: Failed to parse B
// {C} -> does not exist
List<String> errorsV2 = ImmutableList.of("LDS response Listener 'B' validation error: ");
verifyResourceMetadataAcked(LDS, "A", resourcesV2.get("A"), VERSION_2, TIME_INCREMENT * 2);
verifyResourceMetadataNacked(LDS, "B", resourcesV1.get("B"), VERSION_1, TIME_INCREMENT,
VERSION_2, TIME_INCREMENT * 2, errorsV2);
verifyResourceMetadataDoesNotExist(LDS, "C");
call.verifyRequestNack(LDS, subscribedResourceNames, VERSION_1, "0001", NODE, errorsV2);
// LDS -> {B, C} version 3
ImmutableMap<String, Any> resourcesV3 = ImmutableMap.of(
"B", Any.pack(mf.buildListenerWithApiListenerForRds("B", "B.3")),
"C", Any.pack(mf.buildListenerWithApiListenerForRds("C", "C.3")));
call.sendResponse(LDS, resourcesV3.values().asList(), VERSION_3, "0002");
// {A} -> does not exist
// {B, C} -> ACK, version 3
verifyResourceMetadataDoesNotExist(LDS, "A");
verifyResourceMetadataAcked(LDS, "B", resourcesV3.get("B"), VERSION_3, TIME_INCREMENT * 3);
verifyResourceMetadataAcked(LDS, "C", resourcesV3.get("C"), VERSION_3, TIME_INCREMENT * 3);
call.verifyRequest(LDS, subscribedResourceNames, VERSION_3, "0002", NODE);
verifySubscribedResourcesMetadataSizes(3, 0, 0, 0);
}
@Test
public void ldsResponseErrorHandling_subscribedResourceInvalid_withRdsSubscriptioin() {
List<String> subscribedResourceNames = ImmutableList.of("A", "B", "C");
xdsClient.watchLdsResource("A", ldsResourceWatcher);
xdsClient.watchRdsResource("A.1", rdsResourceWatcher);
xdsClient.watchLdsResource("B", ldsResourceWatcher);
xdsClient.watchRdsResource("B.1", rdsResourceWatcher);
xdsClient.watchLdsResource("C", ldsResourceWatcher);
xdsClient.watchRdsResource("C.1", rdsResourceWatcher);
DiscoveryRpcCall call = resourceDiscoveryCalls.poll();
assertThat(call).isNotNull();
verifyResourceMetadataRequested(LDS, "A");
verifyResourceMetadataRequested(LDS, "B");
verifyResourceMetadataRequested(LDS, "C");
verifyResourceMetadataRequested(RDS, "A.1");
verifyResourceMetadataRequested(RDS, "B.1");
verifyResourceMetadataRequested(RDS, "C.1");
verifySubscribedResourcesMetadataSizes(3, 0, 3, 0);
// LDS -> {A, B, C}, version 1
ImmutableMap<String, Any> resourcesV1 = ImmutableMap.of(
"A", Any.pack(mf.buildListenerWithApiListenerForRds("A", "A.1")),
"B", Any.pack(mf.buildListenerWithApiListenerForRds("B", "B.1")),
"C", Any.pack(mf.buildListenerWithApiListenerForRds("C", "C.1")));
call.sendResponse(LDS, resourcesV1.values().asList(), VERSION_1, "0000");
// {A, B, C} -> ACK, version 1
verifyResourceMetadataAcked(LDS, "A", resourcesV1.get("A"), VERSION_1, TIME_INCREMENT);
verifyResourceMetadataAcked(LDS, "B", resourcesV1.get("B"), VERSION_1, TIME_INCREMENT);
verifyResourceMetadataAcked(LDS, "C", resourcesV1.get("C"), VERSION_1, TIME_INCREMENT);
call.verifyRequest(LDS, subscribedResourceNames, VERSION_1, "0000", NODE);
// RDS -> {A.1, B.1, C.1}, version 1
List<Message> vhostsV1 = mf.buildOpaqueVirtualHosts(1);
ImmutableMap<String, Any> resourcesV11 = ImmutableMap.of(
"A.1", Any.pack(mf.buildRouteConfiguration("A.1", vhostsV1)),
"B.1", Any.pack(mf.buildRouteConfiguration("B.1", vhostsV1)),
"C.1", Any.pack(mf.buildRouteConfiguration("C.1", vhostsV1)));
call.sendResponse(RDS, resourcesV11.values().asList(), VERSION_1, "0000");
// {A.1, B.1, C.1} -> ACK, version 1
verifyResourceMetadataAcked(RDS, "A.1", resourcesV11.get("A.1"), VERSION_1, TIME_INCREMENT * 2);
verifyResourceMetadataAcked(RDS, "B.1", resourcesV11.get("B.1"), VERSION_1, TIME_INCREMENT * 2);
verifyResourceMetadataAcked(RDS, "C.1", resourcesV11.get("C.1"), VERSION_1, TIME_INCREMENT * 2);
// LDS -> {A, B}, version 2
// Failed to parse endpoint B
ImmutableMap<String, Any> resourcesV2 = ImmutableMap.of(
"A", Any.pack(mf.buildListenerWithApiListenerForRds("A", "A.2")),
"B", Any.pack(mf.buildListenerWithApiListenerInvalid("B")));
call.sendResponse(LDS, resourcesV2.values().asList(), VERSION_2, "0001");
// {A} -> ACK, version 2
// {B} -> NACK, version 1, rejected version 2, rejected reason: Failed to parse B
// {C} -> does not exist
List<String> errorsV2 = ImmutableList.of("LDS response Listener 'B' validation error: ");
verifyResourceMetadataAcked(LDS, "A", resourcesV2.get("A"), VERSION_2, TIME_INCREMENT * 3);
verifyResourceMetadataNacked(
LDS, "B", resourcesV1.get("B"), VERSION_1, TIME_INCREMENT, VERSION_2, TIME_INCREMENT * 3,
errorsV2);
verifyResourceMetadataDoesNotExist(LDS, "C");
call.verifyRequestNack(LDS, subscribedResourceNames, VERSION_1, "0001", NODE, errorsV2);
// {A.1} -> does not exist
// {B.1} -> version 1
// {C.1} -> does not exist
verifyResourceMetadataDoesNotExist(RDS, "A.1");
verifyResourceMetadataAcked(RDS, "B.1", resourcesV11.get("B.1"), VERSION_1, TIME_INCREMENT * 2);
verifyResourceMetadataDoesNotExist(RDS, "C.1");
}
@Test
public void ldsResourceFound_containsVirtualHosts() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
// Client sends an ACK LDS request.
call.sendResponse(LDS, testListenerVhosts, VERSION_1, "0000");
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_1, "0000", NODE);
verify(ldsResourceWatcher).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().virtualHosts())
.hasSize(VHOST_SIZE);
assertThat(fakeClock.getPendingTasks(LDS_RESOURCE_FETCH_TIMEOUT_TASK_FILTER)).isEmpty();
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, testListenerVhosts, VERSION_1, TIME_INCREMENT);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
}
@Test
public void ldsResourceFound_containsRdsName() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
call.sendResponse(LDS, testListenerRds, VERSION_1, "0000");
// Client sends an ACK LDS request.
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_1, "0000", NODE);
verify(ldsResourceWatcher).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().rdsName())
.isEqualTo(RDS_RESOURCE);
assertThat(fakeClock.getPendingTasks(LDS_RESOURCE_FETCH_TIMEOUT_TASK_FILTER)).isEmpty();
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, testListenerRds, VERSION_1, TIME_INCREMENT);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
}
@Test
public void cachedLdsResource_data() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
// Client sends an ACK LDS request.
call.sendResponse(LDS, testListenerRds, VERSION_1, "0000");
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_1, "0000", NODE);
LdsResourceWatcher watcher = mock(LdsResourceWatcher.class);
xdsClient.watchLdsResource(LDS_RESOURCE, watcher);
verify(watcher).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().rdsName())
.isEqualTo(RDS_RESOURCE);
call.verifyNoMoreRequest();
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, testListenerRds, VERSION_1, TIME_INCREMENT);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
}
@Test
public void cachedLdsResource_absent() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
fakeClock.forwardTime(ClientXdsClient.INITIAL_RESOURCE_FETCH_TIMEOUT_SEC, TimeUnit.SECONDS);
verify(ldsResourceWatcher).onResourceDoesNotExist(LDS_RESOURCE);
// Add another watcher.
LdsResourceWatcher watcher = mock(LdsResourceWatcher.class);
xdsClient.watchLdsResource(LDS_RESOURCE, watcher);
verify(watcher).onResourceDoesNotExist(LDS_RESOURCE);
call.verifyNoMoreRequest();
verifyResourceMetadataDoesNotExist(LDS, LDS_RESOURCE);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
}
@Test
public void ldsResourceUpdated() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
verifyResourceMetadataRequested(LDS, LDS_RESOURCE);
// Initial LDS response.
call.sendResponse(LDS, testListenerVhosts, VERSION_1, "0000");
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_1, "0000", NODE);
verify(ldsResourceWatcher).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().virtualHosts())
.hasSize(VHOST_SIZE);
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, testListenerVhosts, VERSION_1, TIME_INCREMENT);
// Updated LDS response.
call.sendResponse(LDS, testListenerRds, VERSION_2, "0001");
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_2, "0001", NODE);
verify(ldsResourceWatcher, times(2)).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().rdsName())
.isEqualTo(RDS_RESOURCE);
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, testListenerRds, VERSION_2, TIME_INCREMENT * 2);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
assertThat(channelForCustomAuthority).isNull();
assertThat(channelForEmptyAuthority).isNull();
}
@Test
public void ldsResourceUpdated_withXdstpResourceName() {
BootstrapperImpl.enableFederation = true;
String ldsResourceName = useProtocolV3()
? "xdstp://authority.xds.com/envoy.config.listener.v3.Listener/listener1"
: "xdstp://authority.xds.com/envoy.api.v2.Listener/listener1";
DiscoveryRpcCall call = startResourceWatcher(LDS, ldsResourceName, ldsResourceWatcher);
assertThat(channelForCustomAuthority).isNotNull();
verifyResourceMetadataRequested(LDS, ldsResourceName);
Any testListenerVhosts = Any.pack(mf.buildListenerWithApiListener(ldsResourceName,
mf.buildRouteConfiguration("do not care", mf.buildOpaqueVirtualHosts(VHOST_SIZE))));
call.sendResponse(LDS, testListenerVhosts, VERSION_1, "0000");
call.verifyRequest(LDS, ldsResourceName, VERSION_1, "0000", NODE);
verify(ldsResourceWatcher).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().virtualHosts())
.hasSize(VHOST_SIZE);
verifyResourceMetadataAcked(
LDS, ldsResourceName, testListenerVhosts, VERSION_1, TIME_INCREMENT);
}
@Test
public void ldsResourceUpdated_withXdstpResourceName_withEmptyAuthority() {
BootstrapperImpl.enableFederation = true;
String ldsResourceName = useProtocolV3()
? "xdstp:///envoy.config.listener.v3.Listener/listener1"
: "xdstp:///envoy.api.v2.Listener/listener1";
DiscoveryRpcCall call = startResourceWatcher(LDS, ldsResourceName, ldsResourceWatcher);
assertThat(channelForEmptyAuthority).isNotNull();
verifyResourceMetadataRequested(LDS, ldsResourceName);
Any testListenerVhosts = Any.pack(mf.buildListenerWithApiListener(ldsResourceName,
mf.buildRouteConfiguration("do not care", mf.buildOpaqueVirtualHosts(VHOST_SIZE))));
call.sendResponse(LDS, testListenerVhosts, VERSION_1, "0000");
call.verifyRequest(LDS, ldsResourceName, VERSION_1, "0000", NODE);
verify(ldsResourceWatcher).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().virtualHosts())
.hasSize(VHOST_SIZE);
verifyResourceMetadataAcked(
LDS, ldsResourceName, testListenerVhosts, VERSION_1, TIME_INCREMENT);
}
@Test
public void ldsResourceUpdated_withXdstpResourceName_witUnorderedContextParams() {
BootstrapperImpl.enableFederation = true;
String ldsResourceName = useProtocolV3()
? "xdstp://authority.xds.com/envoy.config.listener.v3.Listener/listener1/a?bar=2&foo=1"
: "xdstp://authority.xds.com/envoy.api.v2.Listener/listener1/a?bar=2&foo=1";
DiscoveryRpcCall call = startResourceWatcher(LDS, ldsResourceName, ldsResourceWatcher);
assertThat(channelForCustomAuthority).isNotNull();
String ldsResourceNameWithUnorderedContextParams = useProtocolV3()
? "xdstp://authority.xds.com/envoy.config.listener.v3.Listener/listener1/a?foo=1&bar=2"
: "xdstp://authority.xds.com/envoy.api.v2.Listener/listener1/a?foo=1&bar=2";
Any testListenerVhosts = Any.pack(mf.buildListenerWithApiListener(
ldsResourceNameWithUnorderedContextParams,
mf.buildRouteConfiguration("do not care", mf.buildOpaqueVirtualHosts(VHOST_SIZE))));
call.sendResponse(LDS, testListenerVhosts, VERSION_1, "0000");
call.verifyRequest(
LDS, ldsResourceName, VERSION_1, "0000", NODE);
}
@Test
public void ldsResourceUpdated_withXdstpResourceName_withWrongType() {
BootstrapperImpl.enableFederation = true;
String ldsResourceName = useProtocolV3()
? "xdstp://authority.xds.com/envoy.config.listener.v3.Listener/listener1"
: "xdstp://authority.xds.com/envoy.api.v2.Listener/listener1";
DiscoveryRpcCall call = startResourceWatcher(LDS, ldsResourceName, ldsResourceWatcher);
assertThat(channelForCustomAuthority).isNotNull();
String ldsResourceNameWithWrongType =
"xdstp://authority.xds.com/envoy.config.route.v3.RouteConfiguration/listener1";
Any testListenerVhosts = Any.pack(mf.buildListenerWithApiListener(
ldsResourceNameWithWrongType,
mf.buildRouteConfiguration("do not care", mf.buildOpaqueVirtualHosts(VHOST_SIZE))));
call.sendResponse(LDS, testListenerVhosts, VERSION_1, "0000");
call.verifyRequestNack(
LDS, ldsResourceName, "", "0000", NODE,
ImmutableList.of(
"Unsupported resource name: " + ldsResourceNameWithWrongType + " for type: LDS"));
}
@Test
public void rdsResourceUpdated_withXdstpResourceName_withWrongType() {
BootstrapperImpl.enableFederation = true;
String rdsResourceName = useProtocolV3()
? "xdstp://authority.xds.com/envoy.config.route.v3.RouteConfiguration/route1"
: "xdstp://authority.xds.com/envoy.api.v2.RouteConfiguration/route1";
DiscoveryRpcCall call = startResourceWatcher(RDS, rdsResourceName, rdsResourceWatcher);
assertThat(channelForCustomAuthority).isNotNull();
String rdsResourceNameWithWrongType =
"xdstp://authority.xds.com/envoy.config.listener.v3.Listener/route1";
Any testRouteConfig = Any.pack(mf.buildRouteConfiguration(
rdsResourceNameWithWrongType, mf.buildOpaqueVirtualHosts(VHOST_SIZE)));
call.sendResponse(RDS, testRouteConfig, VERSION_1, "0000");
call.verifyRequestNack(
RDS, rdsResourceName, "", "0000", NODE,
ImmutableList.of(
"Unsupported resource name: " + rdsResourceNameWithWrongType + " for type: RDS"));
}
@Test
public void cdsResourceUpdated_withXdstpResourceName_withWrongType() {
BootstrapperImpl.enableFederation = true;
String cdsResourceName = useProtocolV3()
? "xdstp://authority.xds.com/envoy.config.cluster.v3.Cluster/cluster1"
: "xdstp://authority.xds.com/envoy.api.v2.Cluster/cluster1";
DiscoveryRpcCall call = startResourceWatcher(CDS, cdsResourceName, cdsResourceWatcher);
assertThat(channelForCustomAuthority).isNotNull();
String cdsResourceNameWithWrongType =
"xdstp://authority.xds.com/envoy.config.listener.v3.Listener/cluster1";
Any testClusterConfig = Any.pack(mf.buildEdsCluster(
cdsResourceNameWithWrongType, null, "round_robin", null, null, false, null,
"envoy.transport_sockets.tls", null));
call.sendResponse(CDS, testClusterConfig, VERSION_1, "0000");
call.verifyRequestNack(
CDS, cdsResourceName, "", "0000", NODE,
ImmutableList.of(
"Unsupported resource name: " + cdsResourceNameWithWrongType + " for type: CDS"));
}
@Test
public void edsResourceUpdated_withXdstpResourceName_withWrongType() {
BootstrapperImpl.enableFederation = true;
String edsResourceName = useProtocolV3()
? "xdstp://authority.xds.com/envoy.config.endpoint.v3.ClusterLoadAssignment/cluster1"
: "xdstp://authority.xds.com/envoy.api.v2.ClusterLoadAssignment/cluster1";
DiscoveryRpcCall call = startResourceWatcher(EDS, edsResourceName, edsResourceWatcher);
assertThat(channelForCustomAuthority).isNotNull();
String edsResourceNameWithWrongType =
"xdstp://authority.xds.com/envoy.config.listener.v3.Listener/cluster1";
Any testEdsConfig = Any.pack(mf.buildClusterLoadAssignment(
edsResourceNameWithWrongType,
ImmutableList.of(mf.buildLocalityLbEndpoints(
"region2", "zone2", "subzone2",
mf.buildLbEndpoint("172.44.2.2", 8000, "unknown", 3), 2, 0)),
ImmutableList.of()));
call.sendResponse(EDS, testEdsConfig, VERSION_1, "0000");
call.verifyRequestNack(
EDS, edsResourceName, "", "0000", NODE,
ImmutableList.of(
"Unsupported resource name: " + edsResourceNameWithWrongType + " for type: EDS"));
}
@Test
public void ldsResourceUpdate_withFaultInjection() {
Assume.assumeTrue(useProtocolV3());
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
Any listener = Any.pack(
mf.buildListenerWithApiListener(
LDS_RESOURCE,
mf.buildRouteConfiguration(
"do not care",
ImmutableList.of(
mf.buildVirtualHost(
mf.buildOpaqueRoutes(1),
ImmutableMap.of(
"irrelevant",
Any.pack(FilterConfig.newBuilder().setIsOptional(true).build()),
"envoy.fault",
mf.buildHttpFaultTypedConfig(
300L, 1000, "cluster1", ImmutableList.<String>of(), 100, null, null,
null))),
mf.buildVirtualHost(
mf.buildOpaqueRoutes(2),
ImmutableMap.of(
"envoy.fault",
mf.buildHttpFaultTypedConfig(
null, null, "cluster2", ImmutableList.<String>of(), 101, null, 503,
2000))))),
ImmutableList.of(
mf.buildHttpFilter("irrelevant", null, true),
mf.buildHttpFilter(
"envoy.fault",
mf.buildHttpFaultTypedConfig(
1L, 2, "cluster1", ImmutableList.<String>of(), 3, null, null,
null),
false),
mf.buildHttpFilter("terminal", Any.pack(Router.newBuilder().build()), true))));
call.sendResponse(LDS, listener, VERSION_1, "0000");
// Client sends an ACK LDS request.
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_1, "0000", NODE);
verify(ldsResourceWatcher).onChanged(ldsUpdateCaptor.capture());
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, listener, VERSION_1, TIME_INCREMENT);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
LdsUpdate ldsUpdate = ldsUpdateCaptor.getValue();
assertThat(ldsUpdate.httpConnectionManager().virtualHosts()).hasSize(2);
assertThat(ldsUpdate.httpConnectionManager().httpFilterConfigs().get(0).name)
.isEqualTo("envoy.fault");
FaultConfig faultConfig = (FaultConfig) ldsUpdate.httpConnectionManager().virtualHosts().get(0)
.filterConfigOverrides().get("envoy.fault");
assertThat(faultConfig.faultDelay().delayNanos()).isEqualTo(300);
assertThat(faultConfig.faultDelay().percent().numerator()).isEqualTo(1000);
assertThat(faultConfig.faultDelay().percent().denominatorType())
.isEqualTo(DenominatorType.MILLION);
assertThat(faultConfig.faultAbort()).isNull();
assertThat(faultConfig.maxActiveFaults()).isEqualTo(100);
faultConfig = (FaultConfig) ldsUpdate.httpConnectionManager().virtualHosts().get(1)
.filterConfigOverrides().get("envoy.fault");
assertThat(faultConfig.faultDelay()).isNull();
assertThat(faultConfig.faultAbort().status().getCode()).isEqualTo(Status.Code.UNAVAILABLE);
assertThat(faultConfig.faultAbort().percent().numerator()).isEqualTo(2000);
assertThat(faultConfig.faultAbort().percent().denominatorType())
.isEqualTo(DenominatorType.MILLION);
assertThat(faultConfig.maxActiveFaults()).isEqualTo(101);
}
@Test
public void ldsResourceDeleted() {
DiscoveryRpcCall call = startResourceWatcher(LDS, LDS_RESOURCE, ldsResourceWatcher);
verifyResourceMetadataRequested(LDS, LDS_RESOURCE);
// Initial LDS response.
call.sendResponse(LDS, testListenerVhosts, VERSION_1, "0000");
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_1, "0000", NODE);
verify(ldsResourceWatcher).onChanged(ldsUpdateCaptor.capture());
assertThat(ldsUpdateCaptor.getValue().httpConnectionManager().virtualHosts())
.hasSize(VHOST_SIZE);
verifyResourceMetadataAcked(LDS, LDS_RESOURCE, testListenerVhosts, VERSION_1, TIME_INCREMENT);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
// Empty LDS response deletes the listener.
call.sendResponse(LDS, Collections.<Any>emptyList(), VERSION_2, "0001");
call.verifyRequest(LDS, LDS_RESOURCE, VERSION_2, "0001", NODE);
verify(ldsResourceWatcher).onResourceDoesNotExist(LDS_RESOURCE);
verifyResourceMetadataDoesNotExist(LDS, LDS_RESOURCE);
verifySubscribedResourcesMetadataSizes(1, 0, 0, 0);
}
@Test
public void multipleLdsWatchers() {