forked from grpc/grpc-node
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxds-dependency-manager.ts
827 lines (786 loc) · 29.8 KB
/
xds-dependency-manager.ts
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
/*
* Copyright 2024 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.
*/
import { experimental, logVerbosity, Metadata, status, StatusObject } from "@grpc/grpc-js";
import { Listener__Output } from "./generated/envoy/config/listener/v3/Listener";
import { RouteConfiguration__Output } from "./generated/envoy/config/route/v3/RouteConfiguration";
import { VirtualHost__Output } from "./generated/envoy/config/route/v3/VirtualHost";
import { CdsUpdate, ClusterResourceType } from "./xds-resource-type/cluster-resource-type";
import { Watcher, XdsClient } from "./xds-client";
import { Locality__Output } from "./generated/envoy/config/core/v3/Locality";
import { DropCategory } from "./load-balancer-xds-cluster-impl";
import Endpoint = experimental.Endpoint;
import Resolver = experimental.Resolver;
import createResolver = experimental.createResolver;
import { decodeSingleResource, HTTP_CONNECTION_MANGER_TYPE_URL } from "./resources";
import { RouteConfigurationResourceType } from "./xds-resource-type/route-config-resource-type";
import { ListenerResourceType } from "./xds-resource-type/listener-resource-type";
import { ClusterLoadAssignment__Output } from "./generated/envoy/config/endpoint/v3/ClusterLoadAssignment";
import { EndpointResourceType } from "./xds-resource-type/endpoint-resource-type";
import { SocketAddress__Output } from "./generated/envoy/config/core/v3/SocketAddress";
import { EXPERIMENTAL_DUALSTACK_ENDPOINTS } from "./environment";
const TRACER_NAME = 'xds_resolver';
function trace(text: string): void {
experimental.trace(logVerbosity.DEBUG, TRACER_NAME, text);
}
interface WeightedEndpoint {
endpoint: Endpoint;
weight: number;
}
interface LocalityEntry {
locality: Locality__Output;
weight: number;
endpoints: WeightedEndpoint[];
}
interface PriorityEntry {
localities: LocalityEntry[];
}
interface EndpointResource {
priorities: PriorityEntry[];
dropCategories: DropCategory[];
}
export interface EndpointConfig {
type: 'endpoint';
endpoints?: EndpointResource;
resolutionNote?: string;
}
export interface AggregateConfig {
type: 'aggregate';
leafClusters: string[];
}
export interface ClusterConfig {
cluster: CdsUpdate;
children: EndpointConfig | AggregateConfig;
}
export type StatusOr<T> = {
success: true;
value: T
} | {
success: false;
error: StatusObject;
}
export interface ClusterResult {
clusterConfig?: ClusterConfig;
status?: StatusObject;
}
export interface XdsConfig {
listener: Listener__Output;
routeConfig: RouteConfiguration__Output;
virtualHost: VirtualHost__Output;
clusters: Map<string, StatusOr<ClusterConfig>>;
}
export interface XdsConfigWatcher {
onUpdate(xdsConfig: XdsConfig): void;
onError(context: string, status: StatusObject): void;
onResourceDoesNotExist(context: string): void;
}
interface AggregateClusterInfo {
type: 'AGGREGATE';
cdsUpdate: CdsUpdate;
}
interface EdsClusterInfo {
type: 'EDS';
cdsUpdate: CdsUpdate;
edsServiceName: string;
watcher: Watcher<ClusterLoadAssignment__Output>;
latestUpdate?: EndpointResource;
resolutionNote?: string;
}
interface LogicalDnsClusterInfo {
type: 'LOGICAL_DNS';
cdsUpdate: CdsUpdate;
dnsHostname: string;
resolver: Resolver;
latestUpdate?: EndpointResource;
resolutionNote?: string;
}
type ClusterInfo = AggregateClusterInfo | EdsClusterInfo | LogicalDnsClusterInfo;
interface ClusterEntry {
watcher: Watcher<CdsUpdate>;
latestUpdate?: StatusOr<ClusterInfo>;
children: string[];
}
interface ClusterGraph {
[name: string]: ClusterEntry;
}
type ClusterTreeUpdatedResult = {result: true} | {result: false, reason: string};
function isClusterTreeFullyUpdated(tree: ClusterGraph, roots: string[]): ClusterTreeUpdatedResult {
const toCheck: string[] = [...roots];
const visited = new Set<string>();
while (toCheck.length > 0) {
const next = toCheck.shift()!;
if (visited.has(next)) {
continue;
}
visited.add(next);
if (!tree[next]) {
return {
result: false,
reason: 'Missing expected cluster entry ' + next
};
}
if (!tree[next].latestUpdate) {
return {
result: false,
reason: 'Cluster entry ' + next + ' not updated'
};
}
if (tree[next].latestUpdate.success) {
if (tree[next].latestUpdate.value.type !== 'AGGREGATE') {
if (!(tree[next].latestUpdate.value.latestUpdate)) {
return {
result: false,
reason: 'Cluster entry ' + next + ' endpoint not updated'
};
}
}
}
toCheck.push(...tree[next].children);
}
return {result: true};
}
// Better match type has smaller value.
enum MatchType {
EXACT_MATCH,
SUFFIX_MATCH,
PREFIX_MATCH,
UNIVERSE_MATCH,
INVALID_MATCH,
};
function domainPatternMatchType(domainPattern: string): MatchType {
if (domainPattern.length === 0) {
return MatchType.INVALID_MATCH;
}
if (domainPattern.indexOf('*') < 0) {
return MatchType.EXACT_MATCH;
}
if (domainPattern === '*') {
return MatchType.UNIVERSE_MATCH;
}
if (domainPattern.startsWith('*')) {
return MatchType.SUFFIX_MATCH;
}
if (domainPattern.endsWith('*')) {
return MatchType.PREFIX_MATCH;
}
return MatchType.INVALID_MATCH;
}
function domainMatch(matchType: MatchType, domainPattern: string, expectedHostName: string) {
switch (matchType) {
case MatchType.EXACT_MATCH:
return expectedHostName === domainPattern;
case MatchType.SUFFIX_MATCH:
return expectedHostName.endsWith(domainPattern.substring(1));
case MatchType.PREFIX_MATCH:
return expectedHostName.startsWith(domainPattern.substring(0, domainPattern.length - 1));
case MatchType.UNIVERSE_MATCH:
return true;
case MatchType.INVALID_MATCH:
return false;
}
}
interface HasDomains {
domains: string[];
}
export function findVirtualHostForDomain<T extends HasDomains>(virutalHostList: T[], domain: string): T | null {
let targetVhost: T | null = null;
let bestMatchType: MatchType = MatchType.INVALID_MATCH;
let longestMatch = 0;
for (const virtualHost of virutalHostList) {
for (const domainPattern of virtualHost.domains) {
const matchType = domainPatternMatchType(domainPattern);
// If we already have a match of a better type, skip this one
if (matchType > bestMatchType) {
continue;
}
// If we already have a longer match of the same type, skip this one
if (matchType === bestMatchType && domainPattern.length <= longestMatch) {
continue;
}
if (domainMatch(matchType, domainPattern, domain)) {
targetVhost = virtualHost;
bestMatchType = matchType;
longestMatch = domainPattern.length;
}
if (bestMatchType === MatchType.EXACT_MATCH) {
break;
}
}
if (bestMatchType === MatchType.EXACT_MATCH) {
break;
}
}
return targetVhost;
}
function getEdsResource(edsUpdate: ClusterLoadAssignment__Output): EndpointResource {
const result: PriorityEntry[] = [];
const dropCategories: DropCategory[] = [];
if (edsUpdate.policy) {
for (const dropOverload of edsUpdate.policy.drop_overloads) {
if (!dropOverload.drop_percentage) {
continue;
}
let requestsPerMillion: number;
switch (dropOverload.drop_percentage.denominator) {
case 'HUNDRED':
requestsPerMillion = dropOverload.drop_percentage.numerator * 10_000;
break;
case 'TEN_THOUSAND':
requestsPerMillion = dropOverload.drop_percentage.numerator * 100;
break;
case 'MILLION':
requestsPerMillion = dropOverload.drop_percentage.numerator;
break;
}
dropCategories.push({
category: dropOverload.category,
requests_per_million: requestsPerMillion
});
}
}
for (const endpoint of edsUpdate.endpoints) {
if (!endpoint.load_balancing_weight) {
continue;
}
const endpoints: WeightedEndpoint[] = endpoint.lb_endpoints.filter(lbEndpoint => lbEndpoint.health_status === 'UNKNOWN' || lbEndpoint.health_status === 'HEALTHY').map(
(lbEndpoint) => {
/* The validator in the XdsClient class ensures that each endpoint has
* a socket_address with an IP address and a port_value. */
let socketAddresses: SocketAddress__Output[];
if (EXPERIMENTAL_DUALSTACK_ENDPOINTS) {
socketAddresses = [
lbEndpoint.endpoint!.address!.socket_address!,
...lbEndpoint.endpoint!.additional_addresses.map(additionalAddress => additionalAddress.address!.socket_address!)
];
} else {
socketAddresses = [lbEndpoint.endpoint!.address!.socket_address!];
}
return {
endpoint: {
addresses: socketAddresses.map(socketAddress => ({
host: socketAddress.address!,
port: socketAddress.port_value!
}))
},
weight: lbEndpoint.load_balancing_weight?.value ?? 1
};
}
);
if (endpoints.length === 0) {
continue;
}
let priorityEntry: PriorityEntry;
if (result[endpoint.priority]) {
priorityEntry = result[endpoint.priority];
} else {
priorityEntry = {
localities: []
};
result[endpoint.priority] = priorityEntry;
}
priorityEntry.localities.push({
locality: endpoint.locality!,
endpoints: endpoints,
weight: endpoint.load_balancing_weight.value
});
}
// Collapse spaces in sparse array
return {
priorities: result.filter(priority => priority),
dropCategories: dropCategories
};
}
function getDnsResource(endpoints: Endpoint[]): EndpointResource {
return {
priorities: [{
localities: [{
locality: {
region: '',
zone: '',
sub_zone: ''
},
weight: 1,
endpoints: endpoints.map(endpoint => ({endpoint: endpoint, weight: 1}))
}]
}],
dropCategories: []
}
}
export class XdsDependencyManager {
private ldsWatcher: Watcher<Listener__Output>;
private rdsWatcher: Watcher<RouteConfiguration__Output>;
private latestListener: Listener__Output | null = null;
private latestRouteConfigName: string | null = null;
private latestRouteConfiguration: RouteConfiguration__Output | null = null;
private clusterRoots: string[] = [];
private subscribedClusters: {[cluster: string]: number} = {};
private clusterForest: ClusterGraph = {};
constructor(private xdsClient: XdsClient, private listenerResourceName: string, private dataPlaneAuthority: string, private watcher: XdsConfigWatcher) {
this.ldsWatcher = new Watcher<Listener__Output>({
onResourceChanged: (update: Listener__Output) => {
if (!update.api_listener) {
this.trace('Received Listener resource not usable on client');
this.handleListenerDoesNotExist();
return;
}
this.latestListener = update;
const httpConnectionManager = decodeSingleResource(HTTP_CONNECTION_MANGER_TYPE_URL, update.api_listener!.api_listener!.value);
switch (httpConnectionManager.route_specifier) {
case 'rds': {
const routeConfigName = httpConnectionManager.rds!.route_config_name;
if (this.latestRouteConfigName !== routeConfigName) {
if (this.latestRouteConfigName !== null) {
this.trace('RDS.cancelWatch(' + this.latestRouteConfigName + '): Route config name changed');
RouteConfigurationResourceType.cancelWatch(this.xdsClient, this.latestRouteConfigName, this.rdsWatcher);
this.latestRouteConfiguration = null;
this.clusterRoots = [];
this.pruneOrphanClusters();
}
this.trace('RDS.startWatch(' + routeConfigName + '): New route config name');
RouteConfigurationResourceType.startWatch(this.xdsClient, routeConfigName, this.rdsWatcher);
this.latestRouteConfigName = routeConfigName;
}
break;
}
case 'route_config':
if (this.latestRouteConfigName) {
this.trace('RDS.cancelWatch(' + this.latestRouteConfigName + '): Listener switched to embedded route config');
RouteConfigurationResourceType.cancelWatch(this.xdsClient, this.latestRouteConfigName, this.rdsWatcher);
this.latestRouteConfigName = null;
}
this.handleRouteConfig(httpConnectionManager.route_config!);
break;
default:
// This is prevented by the validation rules
}
},
onError: (error: StatusObject) => {
/* A transient error only needs to bubble up as a failure if we have
* not already provided a ServiceConfig for the upper layer to use */
if (!this.latestListener) {
this.trace('Resolution error due to xDS client transient error ' + error.details);
this.watcher.onError(`Listener ${listenerResourceName}`, error);
}
},
onResourceDoesNotExist: () => {
this.trace('Resolution error: LDS resource does not exist');
this.handleListenerDoesNotExist();
}
});
this.rdsWatcher = new Watcher<RouteConfiguration__Output>({
onResourceChanged: (update: RouteConfiguration__Output) => {
this.handleRouteConfig(update);
},
onError: (error: StatusObject) => {
if (!this.latestRouteConfiguration) {
this.watcher.onError(`RouteConfiguration ${this.latestRouteConfigName}`, error);
}
},
onResourceDoesNotExist: () => {
this.watcher.onResourceDoesNotExist(`RouteConfiguration ${this.latestRouteConfigName}`);
this.clusterRoots = [];
this.pruneOrphanClusters();
}
});
this.trace('LDS.startWatch(' + listenerResourceName + '): Startup');
ListenerResourceType.startWatch(this.xdsClient, listenerResourceName, this.ldsWatcher);
}
private trace(text: string) {
trace('[' + this.listenerResourceName + '] ' + text);
}
private handleListenerDoesNotExist() {
if (this.latestRouteConfigName) {
this.trace('RDS.cancelWatch(' + this.latestRouteConfigName + '): LDS resource does not exist');
RouteConfigurationResourceType.cancelWatch(this.xdsClient, this.latestRouteConfigName, this.rdsWatcher);
this.latestRouteConfigName = null;
this.latestRouteConfiguration = null;
this.clusterRoots = [];
this.pruneOrphanClusters();
}
this.watcher.onResourceDoesNotExist(`Listener ${this.listenerResourceName}`);
}
private maybeSendUpdate() {
if (!this.latestListener) {
this.trace('Not sending update: no Listener update received');
return;
}
if (!this.latestRouteConfiguration) {
this.trace('Not sending update: no RouteConfiguration update received');
return;
}
const clusterTreeUpdated = isClusterTreeFullyUpdated(this.clusterForest, this.clusterRoots);
if (!clusterTreeUpdated.result) {
this.trace('Not sending update: ' + clusterTreeUpdated.reason);
return;
}
const update: XdsConfig = {
listener: this.latestListener,
routeConfig: this.latestRouteConfiguration,
virtualHost: findVirtualHostForDomain(this.latestRouteConfiguration.virtual_hosts, this.dataPlaneAuthority)!,
clusters: new Map()
};
for (const [clusterName, entry] of Object.entries(this.clusterForest)) {
if (!entry.latestUpdate) {
this.trace('Not sending update: Cluster entry ' + clusterName + ' not updated (not caught by isClusterTreeFullyUpdated)');
return;
}
if (entry.latestUpdate.success) {
let clusterChildren: EndpointConfig | AggregateConfig;
if (entry.latestUpdate.value.type === 'AGGREGATE') {
clusterChildren = {
type: 'aggregate',
leafClusters: entry.children
};
} else {
clusterChildren = {
type: 'endpoint',
endpoints: entry.latestUpdate.value.latestUpdate ? entry.latestUpdate.value.latestUpdate : undefined,
resolutionNote: entry.latestUpdate.value.resolutionNote
};
}
update.clusters.set(clusterName, {
success: true,
value: {
cluster: entry.latestUpdate.value.cdsUpdate,
children: clusterChildren
}
});
} else {
update.clusters.set(clusterName, {
success: false,
error: entry.latestUpdate.error
});
}
}
this.watcher.onUpdate(update);
}
private addCluster(clusterName: string) {
if (clusterName in this.clusterForest) {
return;
}
const entry: ClusterEntry = {
watcher: new Watcher<CdsUpdate>({
onResourceChanged: (update: CdsUpdate) => {
switch (update.type) {
case 'AGGREGATE':
if (entry.latestUpdate?.success) {
switch (entry.latestUpdate.value.type) {
case 'AGGREGATE':
break;
case 'EDS':
this.trace('EDS.cancelWatch(' + entry.latestUpdate.value.edsServiceName + '): Cluster switched to aggregate');
EndpointResourceType.cancelWatch(this.xdsClient, entry.latestUpdate.value.edsServiceName, entry.latestUpdate.value.watcher);
break;
case 'LOGICAL_DNS':
entry.latestUpdate.value.resolver.destroy();
break;
}
}
entry.children = update.aggregateChildren;
entry.latestUpdate = {
success: true,
value: {
type: 'AGGREGATE',
cdsUpdate: update
}
}
for (const child of update.aggregateChildren) {
this.addCluster(child);
}
this.pruneOrphanClusters();
this.maybeSendUpdate();
break;
case 'EDS':
const edsServiceName = update.edsServiceName ?? clusterName;
if (entry.latestUpdate?.success) {
switch (entry.latestUpdate.value.type) {
case 'AGGREGATE':
entry.children = [];
this.pruneOrphanClusters();
break;
case 'EDS':
// If the names are the same, keep the watch
if (entry.latestUpdate.value.edsServiceName !== edsServiceName) {
this.trace('EDS.cancelWatch(' + entry.latestUpdate.value.edsServiceName + '): EDS service name changed');
EndpointResourceType.cancelWatch(this.xdsClient, entry.latestUpdate.value.edsServiceName, entry.latestUpdate.value.watcher);
this.trace('EDS.startWatch(' + edsServiceName + '): EDS service name changed');
EndpointResourceType.startWatch(this.xdsClient, edsServiceName, entry.latestUpdate.value.watcher);
entry.latestUpdate.value.edsServiceName = edsServiceName;
entry.latestUpdate.value.latestUpdate = undefined;
entry.latestUpdate.value.resolutionNote = undefined;
}
entry.latestUpdate.value.cdsUpdate = update;
this.maybeSendUpdate();
return;
case 'LOGICAL_DNS':
entry.latestUpdate.value.resolver.destroy();
break;
}
}
const edsWatcher = new Watcher<ClusterLoadAssignment__Output>({
onResourceChanged: (endpoint: ClusterLoadAssignment__Output) => {
if (entry.latestUpdate?.success && entry.latestUpdate.value.type === 'EDS') {
entry.latestUpdate.value.latestUpdate = getEdsResource(endpoint);
entry.latestUpdate.value.resolutionNote = undefined;
this.maybeSendUpdate();
}
},
onError: error => {
if (entry.latestUpdate?.success && entry.latestUpdate.value.type === 'EDS') {
if (!entry.latestUpdate.value.latestUpdate) {
entry.latestUpdate.value.resolutionNote = `Control plane error: ${error.details}`;
this.maybeSendUpdate();
}
}
},
onResourceDoesNotExist: () => {
if (entry.latestUpdate?.success && entry.latestUpdate.value.type === 'EDS') {
entry.latestUpdate.value.resolutionNote = 'Resource does not exist';
entry.latestUpdate.value.latestUpdate = undefined;
this.maybeSendUpdate();
}
}
});
entry.latestUpdate = {
success: true,
value: {
type: 'EDS',
cdsUpdate: update,
edsServiceName: edsServiceName,
watcher: edsWatcher
}
};
this.trace('EDS.startWatch(' + edsServiceName + '): New EDS service name');
EndpointResourceType.startWatch(this.xdsClient, edsServiceName, edsWatcher);
this.maybeSendUpdate();
break;
case 'LOGICAL_DNS': {
if (entry.latestUpdate?.success) {
switch (entry.latestUpdate.value.type) {
case 'AGGREGATE':
entry.children = [];
this.pruneOrphanClusters();
break;
case 'EDS':
this.trace('EDS.cancelWatch(' + entry.latestUpdate.value.edsServiceName + '): Cluster switched to DNS');
EndpointResourceType.cancelWatch(this.xdsClient, entry.latestUpdate.value.edsServiceName, entry.latestUpdate.value.watcher);
break;
case 'LOGICAL_DNS':
if (entry.latestUpdate.value.dnsHostname === update.dnsHostname) {
entry.latestUpdate.value.cdsUpdate = update;
this.maybeSendUpdate();
return;
}
}
}
this.trace('Creating DNS resolver for hostname ' + update.dnsHostname!);
const resolver = createResolver({scheme: 'dns', path: update.dnsHostname!}, {
onSuccessfulResolution: endpointList => {
if (entry.latestUpdate?.success && entry.latestUpdate.value.type === 'LOGICAL_DNS') {
entry.latestUpdate.value.latestUpdate = getDnsResource(endpointList);
this.maybeSendUpdate();
}
},
onError: error => {
if (entry.latestUpdate?.success && entry.latestUpdate.value.type === 'LOGICAL_DNS') {
if (!entry.latestUpdate.value.latestUpdate) {
entry.latestUpdate.value.resolutionNote = `DNS resolution error: ${error.details}`;
this.maybeSendUpdate();
}
}
}
}, {'grpc.service_config_disable_resolution': 1});
entry.latestUpdate = {
success: true,
value: {
type: 'LOGICAL_DNS',
cdsUpdate: update,
dnsHostname: update.dnsHostname!,
resolver: resolver
}
}
resolver.updateResolution();
this.maybeSendUpdate();
break;
}
}
},
onError: error => {
if (!entry.latestUpdate?.success) {
entry.latestUpdate = {
success: false,
error: error
};
this.maybeSendUpdate();
}
},
onResourceDoesNotExist: () => {
if (entry.latestUpdate?.success) {
switch (entry.latestUpdate.value.type) {
case 'EDS':
this.trace('EDS.cancelWatch(' + entry.latestUpdate.value.edsServiceName + '): CDS resource does not exist');
EndpointResourceType.cancelWatch(this.xdsClient, entry.latestUpdate.value.edsServiceName, entry.latestUpdate.value.watcher);
break;
case 'LOGICAL_DNS':
entry.latestUpdate.value.resolver.destroy();
break;
default:
break;
}
}
entry.latestUpdate = {
success: false,
error: {
code: status.UNAVAILABLE,
details: `Cluster resource ${clusterName} does not exist`,
metadata: new Metadata()
}
};
this.maybeSendUpdate();
}
}),
children: []
}
this.clusterForest[clusterName] = entry;
this.trace('CDS.startWatch(' + clusterName + '): Cluster added');
ClusterResourceType.startWatch(this.xdsClient, clusterName, entry.watcher);
}
addClusterSubscription(clusterName: string) {
this.subscribedClusters[clusterName] = (this.subscribedClusters[clusterName] ?? 0) + 1;
this.addCluster(clusterName);
let removeFunctionCalled = false;
return () => {
if (!removeFunctionCalled) {
removeFunctionCalled = true;
if (clusterName in this.subscribedClusters) {
this.subscribedClusters[clusterName] -= 1;
if (this.subscribedClusters[clusterName] <= 0) {
delete this.subscribedClusters[clusterName];
if (this.pruneOrphanClusters()) {
this.maybeSendUpdate();
}
}
}
}
};
}
private removeCluster(clusterName: string) {
if (!(clusterName in this.clusterForest)) {
return;
}
const entry = this.clusterForest[clusterName];
if (entry.latestUpdate?.success) {
switch (entry.latestUpdate.value.type) {
case 'EDS':
this.trace('EDS.cancelWatch(' + entry.latestUpdate.value.edsServiceName + '): Cluster ' + clusterName + ' removed');
EndpointResourceType.cancelWatch(this.xdsClient, entry.latestUpdate.value.edsServiceName, entry.latestUpdate.value.watcher);
break;
case 'LOGICAL_DNS':
entry.latestUpdate.value.resolver.destroy();
break;
default:
break;
}
}
this.trace('CDS.cancelWatch(' + clusterName + '): Cluster removed');
ClusterResourceType.cancelWatch(this.xdsClient, clusterName, entry.watcher);
delete this.clusterForest[clusterName];
}
/**
* Prune any clusters that are not descendents of any root clusters,
* including subscribed clusters.
* @returns True if any clusters were pruned, false otherwise
*/
private pruneOrphanClusters(): boolean {
const toCheck = [...this.clusterRoots, ...Object.keys(this.subscribedClusters)];
const visited = new Set<string>();
while(toCheck.length > 0) {
const next = toCheck.shift()!;
if (visited.has(next)) {
continue;
}
if (next in this.clusterForest) {
toCheck.push(...this.clusterForest[next].children);
}
visited.add(next);
}
let removedAnyClusters = false;
for (const clusterName of Object.keys(this.clusterForest)) {
if (!visited.has(clusterName)) {
removedAnyClusters = true;
this.removeCluster(clusterName);
}
}
return removedAnyClusters;
}
private handleRouteConfig(routeConfig: RouteConfiguration__Output) {
this.latestRouteConfiguration = routeConfig;
const virtualHost = findVirtualHostForDomain(routeConfig.virtual_hosts, this.dataPlaneAuthority);
if (!virtualHost) {
this.clusterRoots = [];
this.pruneOrphanClusters();
this.watcher.onError(`RouteConfiguration ${routeConfig.name}`, {
code: status.UNAVAILABLE,
details: `No matching route found for ${this.dataPlaneAuthority}`,
metadata: new Metadata()
});
// Report error
return;
}
const allConfigClusters = new Set<string>();
for (const route of virtualHost.routes) {
switch(route.route!.cluster_specifier) {
case 'cluster_header':
break;
case 'cluster':
allConfigClusters.add(route.route!.cluster!);
break;
case 'weighted_clusters':
for (const clusterWeight of route.route!.weighted_clusters!.clusters) {
allConfigClusters.add(clusterWeight.name);
}
break;
default:
/* The validation logic should prevent us from reaching this point.
* This is just for the type checker. */
break;
}
}
this.clusterRoots = [...allConfigClusters];
this.pruneOrphanClusters();
for (const clusterName of this.clusterRoots) {
this.addCluster(clusterName);
}
this.maybeSendUpdate();
}
updateResolution() {
for (const clusterEntry of Object.values(this.clusterForest)) {
if (clusterEntry.latestUpdate?.success && clusterEntry.latestUpdate.value.type === 'LOGICAL_DNS') {
clusterEntry.latestUpdate.value.resolver.updateResolution();
}
}
}
destroy() {
this.trace('LDS.cancelWatch(' + this.listenerResourceName + '): destroy');
ListenerResourceType.cancelWatch(this.xdsClient, this.listenerResourceName, this.ldsWatcher);
if (this.latestRouteConfigName) {
this.trace('RDS.cancelWatch(' + this.latestRouteConfigName + '): destroy');
RouteConfigurationResourceType.cancelWatch(this.xdsClient, this.latestRouteConfigName, this.rdsWatcher);
}
this.clusterRoots = [];
this.subscribedClusters = {};
this.pruneOrphanClusters();
}
}