forked from grpc/grpc-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxds_dependency_manager_test.go
More file actions
1476 lines (1322 loc) · 52.9 KB
/
xds_dependency_manager_test.go
File metadata and controls
1476 lines (1322 loc) · 52.9 KB
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 2025 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 xdsdepmgr_test
import (
"context"
"fmt"
"regexp"
"strings"
"testing"
"time"
xxhash "github.com/cespare/xxhash/v2"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/google/uuid"
"google.golang.org/grpc/internal/grpctest"
"google.golang.org/grpc/internal/testutils"
"google.golang.org/grpc/internal/testutils/xds/e2e"
"google.golang.org/grpc/internal/xds/bootstrap"
"google.golang.org/grpc/internal/xds/clients"
"google.golang.org/grpc/internal/xds/xdsclient"
"google.golang.org/grpc/internal/xds/xdsclient/xdsresource"
"google.golang.org/grpc/internal/xds/xdsdepmgr"
"google.golang.org/grpc/resolver"
"google.golang.org/protobuf/types/known/wrapperspb"
v3clusterpb "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
v3corepb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
v3endpointpb "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
v3listenerpb "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
v3routepb "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
v3routerpb "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/router/v3"
v3httppb "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
_ "google.golang.org/grpc/internal/xds/httpfilter/router" // Register the router filter
)
type s struct {
grpctest.Tester
}
func Test(t *testing.T) {
xdsdepmgr.EnableClusterAndEndpointsWatch = true
grpctest.RunSubTests(t, s{})
}
const (
defaultTestTimeout = 10 * time.Second
defaultTestShortTimeout = 100 * time.Microsecond
defaultTestServiceName = "service-name"
defaultTestRouteConfigName = "route-config-name"
defaultTestClusterName = "cluster-name"
defaultTestEDSServiceName = "eds-service-name"
)
func newStringP(s string) *string {
return &s
}
// testWatcher is an implementation of the ConfigWatcher interface that sends
// the updates and errors received from the dependency manager to respective
// channels, for the tests to verify.
type testWatcher struct {
updateCh chan *xdsresource.XDSConfig
errorCh chan error
done chan struct{}
}
// Update sends the received XDSConfig update to the update channel. Does not
// send updates if the done channel is closed. The done channel is closed in the
// cases of errors because management server keeps sending error updates that
// cases multiple updates to be sent from dependency manager causing the update
// channel to be blocked.
func (w *testWatcher) Update(cfg *xdsresource.XDSConfig) {
select {
case <-w.done:
return
case w.updateCh <- cfg:
}
}
// Error sends the received error to the error channel.
func (w *testWatcher) Error(err error) {
w.errorCh <- err
}
func verifyError(ctx context.Context, errCh chan error, wantErr, wantNodeID string) error {
select {
case gotErr := <-errCh:
if gotErr == nil {
return fmt.Errorf("got nil error from resolver, want error %q", wantErr)
}
if !strings.Contains(gotErr.Error(), wantErr) {
return fmt.Errorf("got error from resolver %q, want %q", gotErr, wantErr)
}
if !strings.Contains(gotErr.Error(), wantNodeID) {
return fmt.Errorf("got error from resolver %q, want nodeID %q", gotErr, wantNodeID)
}
case <-ctx.Done():
return fmt.Errorf("timeout waiting for error from dependency manager")
}
return nil
}
// This function determines the stable, canonical order for any two
// resolver.Endpoint structs.
func lessEndpoint(a, b resolver.Endpoint) bool {
return getHash(a) < getHash(b)
}
func getHash(e resolver.Endpoint) uint64 {
h := xxhash.New()
// We iterate through all addresses to ensure the hash represents
// the full endpoint identity.
for _, addr := range e.Addresses {
h.Write([]byte(addr.Addr))
h.Write([]byte(addr.ServerName))
}
return h.Sum64()
}
func verifyXDSConfig(ctx context.Context, xdsCh chan *xdsresource.XDSConfig, errCh chan error, want *xdsresource.XDSConfig) error {
select {
case <-ctx.Done():
return fmt.Errorf("timeout waiting for update from dependency manager")
case update := <-xdsCh:
cmpOpts := []cmp.Option{
cmpopts.EquateEmpty(),
cmpopts.IgnoreFields(xdsresource.HTTPFilter{}, "Filter", "Config"),
cmpopts.IgnoreFields(xdsresource.ListenerUpdate{}, "Raw"),
cmpopts.IgnoreFields(xdsresource.RouteConfigUpdate{}, "Raw"),
cmpopts.IgnoreFields(xdsresource.ClusterUpdate{}, "Raw", "LBPolicy", "TelemetryLabels"),
cmpopts.IgnoreFields(xdsresource.EndpointsUpdate{}, "Raw"),
// Used for EndpointConfig.ResolutionNote and ClusterResult.Err fields.
cmp.Transformer("ErrorsToString", func(in error) string {
if in == nil {
return "" // Treat nil as an empty string
}
s := in.Error()
// Replace all sequences of whitespace (including newlines and
// tabs) with a single standard space.
s = regexp.MustCompile(`\s+`).ReplaceAllString(s, " ")
// Trim any leading/trailing space that might be left over and
// return error as string.
return strings.TrimSpace(s)
}),
cmpopts.SortSlices(lessEndpoint),
}
if diff := cmp.Diff(update, want, cmpOpts...); diff != "" {
return fmt.Errorf("received unexpected update from dependency manager. Diff (-got +want):\n%v", diff)
}
case err := <-errCh:
return fmt.Errorf("received unexpected error from dependency manager: %v", err)
}
return nil
}
func makeXDSConfig(routeConfigName, clusterName, edsServiceName, addr string) *xdsresource.XDSConfig {
return &xdsresource.XDSConfig{
Listener: &xdsresource.ListenerUpdate{
RouteConfigName: routeConfigName,
HTTPFilters: []xdsresource.HTTPFilter{{Name: "router"}},
},
RouteConfig: &xdsresource.RouteConfigUpdate{
VirtualHosts: []*xdsresource.VirtualHost{
{
Domains: []string{defaultTestServiceName},
Routes: []*xdsresource.Route{{
Prefix: newStringP("/"),
WeightedClusters: []xdsresource.WeightedCluster{{Name: clusterName, Weight: 100}},
ActionType: xdsresource.RouteActionRoute,
}},
},
},
},
VirtualHost: &xdsresource.VirtualHost{
Domains: []string{defaultTestServiceName},
Routes: []*xdsresource.Route{{
Prefix: newStringP("/"),
WeightedClusters: []xdsresource.WeightedCluster{{Name: clusterName, Weight: 100}},
ActionType: xdsresource.RouteActionRoute},
},
},
Clusters: map[string]*xdsresource.ClusterResult{
clusterName: {
Config: xdsresource.ClusterConfig{Cluster: &xdsresource.ClusterUpdate{
ClusterType: xdsresource.ClusterTypeEDS,
ClusterName: clusterName,
EDSServiceName: edsServiceName,
},
EndpointConfig: &xdsresource.EndpointConfig{
EDSUpdate: &xdsresource.EndpointsUpdate{
Localities: []xdsresource.Locality{
{ID: clients.Locality{
Region: "region-1",
Zone: "zone-1",
SubZone: "subzone-1",
},
Endpoints: []xdsresource.Endpoint{
{
ResolverEndpoint: resolver.Endpoint{Addresses: []resolver.Address{{Addr: addr}}},
HealthStatus: xdsresource.EndpointHealthStatusUnknown,
Weight: 1,
},
},
Weight: 1,
},
},
},
},
},
},
},
}
}
// setupManagementServerAndClient creates a management server, an xds client and
// returns the node ID, management server and xds client.
func setupManagementServerAndClient(t *testing.T, allowResourceSubset bool) (string, *e2e.ManagementServer, xdsclient.XDSClient) {
t.Helper()
nodeID := uuid.New().String()
mgmtServer, bootstrapContents := setupManagementServerForTest(t, nodeID, allowResourceSubset)
xdsClient := createXDSClient(t, bootstrapContents)
return nodeID, mgmtServer, xdsClient
}
func createXDSClient(t *testing.T, bootstrapContents []byte) xdsclient.XDSClient {
t.Helper()
config, err := bootstrap.NewConfigFromContents(bootstrapContents)
if err != nil {
t.Fatalf("Failed to parse bootstrap contents: %s, %v", string(bootstrapContents), err)
}
pool := xdsclient.NewPool(config)
if err != nil {
t.Fatalf("Failed to create an xDS client pool: %v", err)
}
c, cancel, err := pool.NewClientForTesting(xdsclient.OptionsForTesting{Name: t.Name()})
if err != nil {
t.Fatalf("Failed to create an xDS client: %v", err)
}
t.Cleanup(cancel)
return c
}
// Spins up an xDS management server and sets up the xDS bootstrap
// configuration.
//
// Returns the following:
// - A reference to the xDS management server
// - Contents of the bootstrap configuration pointing to xDS management
// server
func setupManagementServerForTest(t *testing.T, nodeID string, allowResourceSubset bool) (*e2e.ManagementServer, []byte) {
t.Helper()
mgmtServer := e2e.StartManagementServer(t, e2e.ManagementServerOptions{
AllowResourceSubset: allowResourceSubset,
})
t.Cleanup(mgmtServer.Stop)
bootstrapContents := e2e.DefaultBootstrapContents(t, nodeID, mgmtServer.Address)
return mgmtServer, bootstrapContents
}
// makeAggregateClusterResource returns an aggregate cluster resource with the
// given name and list of child names.
func makeAggregateClusterResource(name string, childNames []string) *v3clusterpb.Cluster {
return e2e.ClusterResourceWithOptions(e2e.ClusterOptions{
ClusterName: name,
Type: e2e.ClusterTypeAggregate,
ChildNames: childNames,
})
}
// makeLogicalDNSClusterResource returns a LOGICAL_DNS cluster resource with the
// given name and given DNS host and port.
func makeLogicalDNSClusterResource(name, dnsHost string, dnsPort uint32) *v3clusterpb.Cluster {
return e2e.ClusterResourceWithOptions(e2e.ClusterOptions{
ClusterName: name,
Type: e2e.ClusterTypeLogicalDNS,
DNSHostName: dnsHost,
DNSPort: dnsPort,
})
}
// Tests the happy case where the dependency manager receives all the required
// resources and verifies that Update is called with the correct XDSConfig.
func (s) TestHappyCase(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Clusters[0].EdsClusterConfig.ServiceName, "localhost:8080")
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
}
// Tests the case where the listener contains an inline route configuration and
// verifies that Update is called with the correct XDSConfig.
func (s) TestInlineRouteConfig(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
hcm := testutils.MarshalAny(t, &v3httppb.HttpConnectionManager{
RouteSpecifier: &v3httppb.HttpConnectionManager_RouteConfig{
RouteConfig: e2e.DefaultRouteConfig(defaultTestRouteConfigName, defaultTestServiceName, defaultTestClusterName),
},
HttpFilters: []*v3httppb.HttpFilter{e2e.HTTPFilter("router", &v3routerpb.Router{})}, // router fields are unused by grpc
})
listener := &v3listenerpb.Listener{
Name: defaultTestServiceName,
ApiListener: &v3listenerpb.ApiListener{ApiListener: hcm},
FilterChains: []*v3listenerpb.FilterChain{{
Name: "filter-chain-name",
Filters: []*v3listenerpb.Filter{{
Name: wellknown.HTTPConnectionManager,
ConfigType: &v3listenerpb.Filter_TypedConfig{TypedConfig: hcm},
}},
}},
}
cluster := e2e.DefaultCluster(defaultTestClusterName, defaultTestEDSServiceName, e2e.SecurityLevelNone)
endpoint := e2e.DefaultEndpoint(defaultTestEDSServiceName, "localhost", []uint32{8080})
resources := e2e.UpdateOptions{
NodeID: nodeID,
Listeners: []*v3listenerpb.Listener{listener},
Clusters: []*v3clusterpb.Cluster{cluster},
Endpoints: []*v3endpointpb.ClusterLoadAssignment{endpoint},
SkipValidation: true,
}
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
wantXdsConfig := makeXDSConfig(defaultTestRouteConfigName, defaultTestClusterName, defaultTestEDSServiceName, "localhost:8080")
wantXdsConfig.Listener.InlineRouteConfig = wantXdsConfig.RouteConfig
wantXdsConfig.Listener.RouteConfigName = ""
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
}
// Tests the case where dependency manager only receives listener resource but
// does not receive route config resource. Verifies that Update is not called
// since we do not have all resources.
func (s) TestNoRouteConfigResource(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
listener := e2e.DefaultClientListener(defaultTestServiceName, defaultTestRouteConfigName)
if err := mgmtServer.Update(ctx, e2e.UpdateOptions{
NodeID: nodeID,
Listeners: []*v3listenerpb.Listener{listener},
SkipValidation: true,
}); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
sCtx, sCancel := context.WithTimeout(ctx, defaultTestShortTimeout)
defer sCancel()
select {
case <-sCtx.Done():
case update := <-watcher.updateCh:
t.Fatalf("Received unexpected update from dependency manager: %+v", update)
case err := <-watcher.errorCh:
t.Fatalf("Received unexpected error from dependency manager: %v", err)
}
}
// Tests the case where dependency manager receives a listener resource error by
// sending the correct update first and then removing the listener resource. It
// verifies that Error is called with the correct error.
func (s) TestListenerResourceNotFoundError(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Send a correct update first
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Clusters[0].EdsClusterConfig.ServiceName, "localhost:8080")
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
// Remove listener resource so that we get listener resource error.
resources.Listeners = nil
resources.SkipValidation = true
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
if err := verifyError(ctx, watcher.errorCh, fmt.Sprintf("xds: resource %q of type %q has been removed", defaultTestServiceName, "ListenerResource"), nodeID); err != nil {
t.Fatal(err)
}
}
// Tests the scenario where the Dependency Manager receives an invalid
// RouteConfiguration from the management server. The test provides a
// malformed resource to trigger a NACK, and verifies that the Dependency
// Manager propagates the resulting error via Error method.
func (s) TestRouteConfigResourceError(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
listener := e2e.DefaultClientListener(defaultTestServiceName, defaultTestRouteConfigName)
route := e2e.DefaultRouteConfig(defaultTestRouteConfigName, defaultTestServiceName, defaultTestClusterName)
// Remove the Match to make sure the route resource is NACKed by XDSClient
// sending a route resource error to dependency manager.
route.VirtualHosts[0].Routes[0].Match = nil
resources := e2e.UpdateOptions{
NodeID: nodeID,
Listeners: []*v3listenerpb.Listener{listener},
Routes: []*v3routepb.RouteConfiguration{route},
SkipValidation: true,
}
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
if err := verifyError(ctx, watcher.errorCh, "route resource error", nodeID); err != nil {
t.Fatal(err)
}
}
// Tests the case where a received route configuration update has no virtual
// hosts. Verifies that Error is called with the expected error.
func (s) TestNoVirtualHost(t *testing.T) {
nodeID := uuid.New().String()
mgmtServer, bc := setupManagementServerForTest(t, nodeID, false)
xdsClient := createXDSClient(t, bc)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
// Make the virtual host match nil so that the route config is NACKed.
resources.Routes[0].VirtualHosts = nil
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
if err := verifyError(ctx, watcher.errorCh, "could not find VirtualHost", nodeID); err != nil {
t.Fatal(err)
}
}
// Tests the case where we already have a cached resource and then we get a
// route resource with no virtual host, which also results in error being sent
// across.
func (s) TestNoVirtualHost_ExistingResource(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
// Verify valid update.
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Endpoints[0].ClusterName, "localhost:8080")
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
// 3. Send route update with no virtual host.
resources.Routes[0].VirtualHosts = nil
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
// 4. Verify error.
if err := verifyError(ctx, watcher.errorCh, "could not find VirtualHost", nodeID); err != nil {
t.Fatal(err)
}
}
// Tests the case where we get an ambient error and verify that we correctly log
// a warning for it. To make sure we get an ambient error, we send a correct
// update first, then send an invalid one and then send the valid resource
// again. We send the valid resource again so that we can be sure the ambient
// error reaches the dependency manager since there is no other way to wait for
// it.
func (s) TestAmbientError(t *testing.T) {
// Expect a warning log for the ambient error.
grpctest.ExpectWarning("Listener resource ambient error")
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Configure a valid resources.
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
// Wait for the initial valid update.
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Clusters[0].EdsClusterConfig.ServiceName, "localhost:8080")
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
// Configure a listener resource that is expected to be NACKed because it
// does not contain the `RouteSpecifier` field in the HTTPConnectionManager.
// Since a valid one is already cached, this should result in an ambient
// error.
hcm := testutils.MarshalAny(t, &v3httppb.HttpConnectionManager{
HttpFilters: []*v3httppb.HttpFilter{e2e.HTTPFilter("router", &v3routerpb.Router{})},
})
lis := &v3listenerpb.Listener{
Name: defaultTestServiceName,
ApiListener: &v3listenerpb.ApiListener{ApiListener: hcm},
FilterChains: []*v3listenerpb.FilterChain{{
Name: "filter-chain-name",
Filters: []*v3listenerpb.Filter{{
Name: wellknown.HTTPConnectionManager,
ConfigType: &v3listenerpb.Filter_TypedConfig{TypedConfig: hcm},
}},
}},
}
resources.Listeners = []*v3listenerpb.Listener{lis}
resources.SkipValidation = true
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
// We expect no call to Error or Update on our watcher. We just wait for a
// short duration to ensure that.
sCtx, sCancel := context.WithTimeout(ctx, defaultTestShortTimeout)
defer sCancel()
select {
case err := <-watcher.errorCh:
t.Fatalf("Unexpected call to Error %v", err)
case update := <-watcher.updateCh:
t.Fatalf("Unexpected call to Update %+v", update)
case <-sCtx.Done():
}
// Send valid resources again.
resources = e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
}
// Tests the case where the cluster name changes in the route resource update
// and verify that each time Update is called with correct cluster name.
func (s) TestRouteResourceUpdate(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Configure initial resources
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
// Wait for the first update.
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Clusters[0].EdsClusterConfig.ServiceName, "localhost:8080")
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
// Update route to point to a new cluster.
newClusterName := "new-cluster-name"
route2 := e2e.DefaultRouteConfig(resources.Routes[0].Name, defaultTestServiceName, newClusterName)
cluster2 := e2e.DefaultCluster(newClusterName, newClusterName, e2e.SecurityLevelNone)
endpoints2 := e2e.DefaultEndpoint(newClusterName, "localhost", []uint32{8081})
resources.Routes = []*v3routepb.RouteConfiguration{route2}
resources.Clusters = []*v3clusterpb.Cluster{cluster2}
resources.Endpoints = []*v3endpointpb.ClusterLoadAssignment{endpoints2}
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
// Wait for the second update and verify it has the new cluster.
wantXdsConfig.RouteConfig.VirtualHosts[0].Routes[0].WeightedClusters[0].Name = newClusterName
wantXdsConfig.VirtualHost.Routes[0].WeightedClusters[0].Name = newClusterName
wantXdsConfig.Clusters = map[string]*xdsresource.ClusterResult{
newClusterName: {
Config: xdsresource.ClusterConfig{
Cluster: &xdsresource.ClusterUpdate{
ClusterName: newClusterName,
ClusterType: xdsresource.ClusterTypeEDS,
EDSServiceName: newClusterName,
},
EndpointConfig: &xdsresource.EndpointConfig{
EDSUpdate: &xdsresource.EndpointsUpdate{
Localities: []xdsresource.Locality{
{ID: clients.Locality{
Region: "region-1",
Zone: "zone-1",
SubZone: "subzone-1",
},
Endpoints: []xdsresource.Endpoint{
{
ResolverEndpoint: resolver.Endpoint{Addresses: []resolver.Address{{Addr: "localhost:8081"}}},
HealthStatus: xdsresource.EndpointHealthStatusUnknown,
Weight: 1,
},
},
Weight: 1,
},
},
},
},
},
},
}
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
}
// Tests the case where the route resource is first sent from the management
// server and the changed to be inline with the listener and then again changed
// to be received from the management server. It verifies that each time Update
// is called with the correct XDSConfig.
func (s) TestRouteResourceChangeToInline(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Initial resources with defaultTestClusterName
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
// Wait for the first update.
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Clusters[0].EdsClusterConfig.ServiceName, "localhost:8080")
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
// Update route to point to a new cluster and make it inline with the
// listener.
newClusterName := "new-cluster-name"
hcm := testutils.MarshalAny(t, &v3httppb.HttpConnectionManager{
RouteSpecifier: &v3httppb.HttpConnectionManager_RouteConfig{
RouteConfig: e2e.DefaultRouteConfig(defaultTestRouteConfigName, defaultTestServiceName, newClusterName),
},
HttpFilters: []*v3httppb.HttpFilter{e2e.HTTPFilter("router", &v3routerpb.Router{})}, // router fields are unused by grpc
})
resources.Listeners[0].ApiListener.ApiListener = hcm
resources.Clusters = []*v3clusterpb.Cluster{e2e.DefaultCluster(newClusterName, defaultTestEDSServiceName, e2e.SecurityLevelNone)}
resources.Endpoints = []*v3endpointpb.ClusterLoadAssignment{e2e.DefaultEndpoint(defaultTestEDSServiceName, "localhost", []uint32{8081})}
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
// Wait for the second update and verify it has the new cluster.
wantInlineXdsConfig := &xdsresource.XDSConfig{
Listener: &xdsresource.ListenerUpdate{
HTTPFilters: []xdsresource.HTTPFilter{{Name: "router"}},
InlineRouteConfig: &xdsresource.RouteConfigUpdate{
VirtualHosts: []*xdsresource.VirtualHost{
{
Domains: []string{defaultTestServiceName},
Routes: []*xdsresource.Route{{
Prefix: newStringP("/"),
WeightedClusters: []xdsresource.WeightedCluster{{Name: newClusterName, Weight: 100}},
ActionType: xdsresource.RouteActionRoute,
}},
},
},
},
},
RouteConfig: &xdsresource.RouteConfigUpdate{
VirtualHosts: []*xdsresource.VirtualHost{
{
Domains: []string{defaultTestServiceName},
Routes: []*xdsresource.Route{{
Prefix: newStringP("/"),
WeightedClusters: []xdsresource.WeightedCluster{{Name: newClusterName, Weight: 100}},
ActionType: xdsresource.RouteActionRoute,
}},
},
},
},
VirtualHost: &xdsresource.VirtualHost{
Domains: []string{defaultTestServiceName},
Routes: []*xdsresource.Route{{
Prefix: newStringP("/"),
WeightedClusters: []xdsresource.WeightedCluster{{Name: newClusterName, Weight: 100}},
ActionType: xdsresource.RouteActionRoute},
},
},
Clusters: map[string]*xdsresource.ClusterResult{
newClusterName: {
Config: xdsresource.ClusterConfig{Cluster: &xdsresource.ClusterUpdate{
ClusterType: xdsresource.ClusterTypeEDS,
ClusterName: newClusterName,
EDSServiceName: defaultTestEDSServiceName,
},
EndpointConfig: &xdsresource.EndpointConfig{
EDSUpdate: &xdsresource.EndpointsUpdate{
Localities: []xdsresource.Locality{
{ID: clients.Locality{
Region: "region-1",
Zone: "zone-1",
SubZone: "subzone-1",
},
Endpoints: []xdsresource.Endpoint{
{
ResolverEndpoint: resolver.Endpoint{Addresses: []resolver.Address{{Addr: "localhost:8081"}}},
HealthStatus: xdsresource.EndpointHealthStatusUnknown,
Weight: 1,
},
},
Weight: 1,
},
},
},
},
},
},
},
}
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantInlineXdsConfig); err != nil {
t.Fatal(err)
}
// Change the route resource back to non-inline.
resources = e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
}
// Tests the case where the dependency manager receives a cluster resource error
// and verifies that Update is called with XDSConfig containing cluster error.
func (s) TestClusterResourceError(t *testing.T) {
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
done: make(chan struct{}),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
resources.Clusters[0].LrsServer = &v3corepb.ConfigSource{ConfigSourceSpecifier: &v3corepb.ConfigSource_Ads{}}
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Clusters[0].EdsClusterConfig.ServiceName, "localhost:8080")
wantXdsConfig.Clusters[resources.Clusters[0].Name] = &xdsresource.ClusterResult{Err: fmt.Errorf("[xDS node id: %v]: %v", nodeID, fmt.Errorf("unsupported config_source_specifier *corev3.ConfigSource_Ads in lrs_server field"))}
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
// Close the watcher done channel to stop sending updates because management
// server keeps sending the error updates repeatedly causing the update from
// dependency manager to be blocked.
close(watcher.done)
}
// Tests the case where the dependency manager receives a cluster resource
// ambient error. A valid cluster resource is sent first, then an invalid
// one and then the valid resource again. The valid resource is sent again
// to make sure that the ambient error reaches the dependency manager since
// there is no other way to wait for it.
func (s) TestClusterAmbientError(t *testing.T) {
// Expect a warning log for the ambient error.
grpctest.ExpectWarning("Cluster resource ambient error")
nodeID, mgmtServer, xdsClient := setupManagementServerAndClient(t, false)
watcher := &testWatcher{
updateCh: make(chan *xdsresource.XDSConfig),
errorCh: make(chan error),
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
resources := e2e.DefaultClientResources(e2e.ResourceParams{
NodeID: nodeID,
DialTarget: defaultTestServiceName,
Host: "localhost",
Port: 8080,
SecLevel: e2e.SecurityLevelNone,
})
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
dm := xdsdepmgr.New(defaultTestServiceName, defaultTestServiceName, xdsClient, watcher)
defer dm.Close()
wantXdsConfig := makeXDSConfig(resources.Routes[0].Name, resources.Clusters[0].Name, resources.Clusters[0].EdsClusterConfig.ServiceName, "localhost:8080")
if err := verifyXDSConfig(ctx, watcher.updateCh, watcher.errorCh, wantXdsConfig); err != nil {
t.Fatal(err)
}
// Configure a cluster resource that is expected to be NACKed because it
// does not contain the `LrsServer` field. Since a valid one is already
// cached, this should result in an ambient error.
resources.Clusters[0].LrsServer = &v3corepb.ConfigSource{ConfigSourceSpecifier: &v3corepb.ConfigSource_Ads{}}
if err := mgmtServer.Update(ctx, resources); err != nil {
t.Fatal(err)
}
select {
case <-time.After(defaultTestShortTimeout):
case update := <-watcher.updateCh: