1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import {
|
18 | Resolver,
|
19 | ResolverListener,
|
20 | registerResolver,
|
21 | registerDefaultScheme,
|
22 | } from './resolver';
|
23 | import * as dns from 'dns';
|
24 | import * as util from 'util';
|
25 | import { extractAndSelectServiceConfig, ServiceConfig } from './service-config';
|
26 | import { Status } from './constants';
|
27 | import { StatusObject } from './call-interface';
|
28 | import { Metadata } from './metadata';
|
29 | import * as logging from './logging';
|
30 | import { LogVerbosity } from './constants';
|
31 | import { SubchannelAddress, TcpSubchannelAddress } from './subchannel-address';
|
32 | import { GrpcUri, uriToString, splitHostPort } from './uri-parser';
|
33 | import { isIPv6, isIPv4 } from 'net';
|
34 | import { ChannelOptions } from './channel-options';
|
35 | import { BackoffOptions, BackoffTimeout } from './backoff-timeout';
|
36 |
|
37 | const TRACER_NAME = 'dns_resolver';
|
38 |
|
39 | function trace(text: string): void {
|
40 | logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text);
|
41 | }
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | const DEFAULT_PORT = 443;
|
47 |
|
48 | const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30_000;
|
49 |
|
50 | const resolveTxtPromise = util.promisify(dns.resolveTxt);
|
51 | const dnsLookupPromise = util.promisify(dns.lookup);
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | function mergeArrays<T>(...arrays: T[][]): T[] {
|
58 | const result: T[] = [];
|
59 | for (
|
60 | let i = 0;
|
61 | i <
|
62 | Math.max.apply(
|
63 | null,
|
64 | arrays.map(array => array.length)
|
65 | );
|
66 | i++
|
67 | ) {
|
68 | for (const array of arrays) {
|
69 | if (i < array.length) {
|
70 | result.push(array[i]);
|
71 | }
|
72 | }
|
73 | }
|
74 | return result;
|
75 | }
|
76 |
|
77 |
|
78 |
|
79 |
|
80 | class DnsResolver implements Resolver {
|
81 | private readonly ipResult: SubchannelAddress[] | null;
|
82 | private readonly dnsHostname: string | null;
|
83 | private readonly port: number | null;
|
84 | |
85 |
|
86 |
|
87 |
|
88 |
|
89 | private readonly minTimeBetweenResolutionsMs: number;
|
90 | private pendingLookupPromise: Promise<dns.LookupAddress[]> | null = null;
|
91 | private pendingTxtPromise: Promise<string[][]> | null = null;
|
92 | private latestLookupResult: TcpSubchannelAddress[] | null = null;
|
93 | private latestServiceConfig: ServiceConfig | null = null;
|
94 | private latestServiceConfigError: StatusObject | null = null;
|
95 | private percentage: number;
|
96 | private defaultResolutionError: StatusObject;
|
97 | private backoff: BackoffTimeout;
|
98 | private continueResolving = false;
|
99 | private nextResolutionTimer: NodeJS.Timeout;
|
100 | private isNextResolutionTimerRunning = false;
|
101 | private isServiceConfigEnabled = true;
|
102 | constructor(
|
103 | private target: GrpcUri,
|
104 | private listener: ResolverListener,
|
105 | channelOptions: ChannelOptions
|
106 | ) {
|
107 | trace('Resolver constructed for target ' + uriToString(target));
|
108 | const hostPort = splitHostPort(target.path);
|
109 | if (hostPort === null) {
|
110 | this.ipResult = null;
|
111 | this.dnsHostname = null;
|
112 | this.port = null;
|
113 | } else {
|
114 | if (isIPv4(hostPort.host) || isIPv6(hostPort.host)) {
|
115 | this.ipResult = [
|
116 | {
|
117 | host: hostPort.host,
|
118 | port: hostPort.port ?? DEFAULT_PORT,
|
119 | },
|
120 | ];
|
121 | this.dnsHostname = null;
|
122 | this.port = null;
|
123 | } else {
|
124 | this.ipResult = null;
|
125 | this.dnsHostname = hostPort.host;
|
126 | this.port = hostPort.port ?? DEFAULT_PORT;
|
127 | }
|
128 | }
|
129 | this.percentage = Math.random() * 100;
|
130 |
|
131 | if (channelOptions['grpc.service_config_disable_resolution'] === 1) {
|
132 | this.isServiceConfigEnabled = false;
|
133 | }
|
134 |
|
135 | this.defaultResolutionError = {
|
136 | code: Status.UNAVAILABLE,
|
137 | details: `Name resolution failed for target ${uriToString(this.target)}`,
|
138 | metadata: new Metadata(),
|
139 | };
|
140 |
|
141 | const backoffOptions: BackoffOptions = {
|
142 | initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'],
|
143 | maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'],
|
144 | };
|
145 |
|
146 | this.backoff = new BackoffTimeout(() => {
|
147 | if (this.continueResolving) {
|
148 | this.startResolutionWithBackoff();
|
149 | }
|
150 | }, backoffOptions);
|
151 | this.backoff.unref();
|
152 |
|
153 | this.minTimeBetweenResolutionsMs =
|
154 | channelOptions['grpc.dns_min_time_between_resolutions_ms'] ??
|
155 | DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS;
|
156 | this.nextResolutionTimer = setTimeout(() => {}, 0);
|
157 | clearTimeout(this.nextResolutionTimer);
|
158 | }
|
159 |
|
160 | |
161 |
|
162 |
|
163 |
|
164 | private startResolution() {
|
165 | if (this.ipResult !== null) {
|
166 | trace('Returning IP address for target ' + uriToString(this.target));
|
167 | setImmediate(() => {
|
168 | this.listener.onSuccessfulResolution(
|
169 | this.ipResult!,
|
170 | null,
|
171 | null,
|
172 | null,
|
173 | {}
|
174 | );
|
175 | });
|
176 | this.backoff.stop();
|
177 | this.backoff.reset();
|
178 | this.stopNextResolutionTimer();
|
179 | return;
|
180 | }
|
181 | if (this.dnsHostname === null) {
|
182 | trace('Failed to parse DNS address ' + uriToString(this.target));
|
183 | setImmediate(() => {
|
184 | this.listener.onError({
|
185 | code: Status.UNAVAILABLE,
|
186 | details: `Failed to parse DNS address ${uriToString(this.target)}`,
|
187 | metadata: new Metadata(),
|
188 | });
|
189 | });
|
190 | this.stopNextResolutionTimer();
|
191 | } else {
|
192 | if (this.pendingLookupPromise !== null) {
|
193 | return;
|
194 | }
|
195 | trace('Looking up DNS hostname ' + this.dnsHostname);
|
196 | |
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 | this.latestLookupResult = null;
|
203 | const hostname: string = this.dnsHostname;
|
204 | |
205 |
|
206 |
|
207 |
|
208 | this.pendingLookupPromise = dnsLookupPromise(hostname, { all: true });
|
209 | this.pendingLookupPromise.then(
|
210 | addressList => {
|
211 | if (this.pendingLookupPromise === null) {
|
212 | return;
|
213 | }
|
214 | this.pendingLookupPromise = null;
|
215 | this.backoff.reset();
|
216 | this.backoff.stop();
|
217 | const ip4Addresses: dns.LookupAddress[] = addressList.filter(
|
218 | addr => addr.family === 4
|
219 | );
|
220 | const ip6Addresses: dns.LookupAddress[] = addressList.filter(
|
221 | addr => addr.family === 6
|
222 | );
|
223 | this.latestLookupResult = mergeArrays(ip6Addresses, ip4Addresses).map(
|
224 | addr => ({ host: addr.address, port: +this.port! })
|
225 | );
|
226 | const allAddressesString: string =
|
227 | '[' +
|
228 | this.latestLookupResult
|
229 | .map(addr => addr.host + ':' + addr.port)
|
230 | .join(',') +
|
231 | ']';
|
232 | trace(
|
233 | 'Resolved addresses for target ' +
|
234 | uriToString(this.target) +
|
235 | ': ' +
|
236 | allAddressesString
|
237 | );
|
238 | if (this.latestLookupResult.length === 0) {
|
239 | this.listener.onError(this.defaultResolutionError);
|
240 | return;
|
241 | }
|
242 | |
243 |
|
244 |
|
245 |
|
246 | this.listener.onSuccessfulResolution(
|
247 | this.latestLookupResult,
|
248 | this.latestServiceConfig,
|
249 | this.latestServiceConfigError,
|
250 | null,
|
251 | {}
|
252 | );
|
253 | },
|
254 | err => {
|
255 | if (this.pendingLookupPromise === null) {
|
256 | return;
|
257 | }
|
258 | trace(
|
259 | 'Resolution error for target ' +
|
260 | uriToString(this.target) +
|
261 | ': ' +
|
262 | (err as Error).message
|
263 | );
|
264 | this.pendingLookupPromise = null;
|
265 | this.stopNextResolutionTimer();
|
266 | this.listener.onError(this.defaultResolutionError);
|
267 | }
|
268 | );
|
269 | |
270 |
|
271 | if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) {
|
272 | |
273 |
|
274 |
|
275 | this.pendingTxtPromise = resolveTxtPromise(hostname);
|
276 | this.pendingTxtPromise.then(
|
277 | txtRecord => {
|
278 | if (this.pendingTxtPromise === null) {
|
279 | return;
|
280 | }
|
281 | this.pendingTxtPromise = null;
|
282 | try {
|
283 | this.latestServiceConfig = extractAndSelectServiceConfig(
|
284 | txtRecord,
|
285 | this.percentage
|
286 | );
|
287 | } catch (err) {
|
288 | this.latestServiceConfigError = {
|
289 | code: Status.UNAVAILABLE,
|
290 | details: `Parsing service config failed with error ${
|
291 | (err as Error).message
|
292 | }`,
|
293 | metadata: new Metadata(),
|
294 | };
|
295 | }
|
296 | if (this.latestLookupResult !== null) {
|
297 | |
298 |
|
299 |
|
300 |
|
301 | this.listener.onSuccessfulResolution(
|
302 | this.latestLookupResult,
|
303 | this.latestServiceConfig,
|
304 | this.latestServiceConfigError,
|
305 | null,
|
306 | {}
|
307 | );
|
308 | }
|
309 | },
|
310 | err => {
|
311 | |
312 |
|
313 |
|
314 |
|
315 |
|
316 |
|
317 |
|
318 | }
|
319 | );
|
320 | }
|
321 | }
|
322 | }
|
323 |
|
324 | private startNextResolutionTimer() {
|
325 | clearTimeout(this.nextResolutionTimer);
|
326 | this.nextResolutionTimer = setTimeout(() => {
|
327 | this.stopNextResolutionTimer();
|
328 | if (this.continueResolving) {
|
329 | this.startResolutionWithBackoff();
|
330 | }
|
331 | }, this.minTimeBetweenResolutionsMs).unref?.();
|
332 | this.isNextResolutionTimerRunning = true;
|
333 | }
|
334 |
|
335 | private stopNextResolutionTimer() {
|
336 | clearTimeout(this.nextResolutionTimer);
|
337 | this.isNextResolutionTimerRunning = false;
|
338 | }
|
339 |
|
340 | private startResolutionWithBackoff() {
|
341 | if (this.pendingLookupPromise === null) {
|
342 | this.continueResolving = false;
|
343 | this.backoff.runOnce();
|
344 | this.startNextResolutionTimer();
|
345 | this.startResolution();
|
346 | }
|
347 | }
|
348 |
|
349 | updateResolution() {
|
350 | |
351 |
|
352 |
|
353 |
|
354 | if (this.pendingLookupPromise === null) {
|
355 | if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) {
|
356 | if (this.isNextResolutionTimerRunning) {
|
357 | trace('resolution update delayed by "min time between resolutions" rate limit');
|
358 | } else {
|
359 | trace('resolution update delayed by backoff timer until ' + this.backoff.getEndTime().toISOString());
|
360 | }
|
361 | this.continueResolving = true;
|
362 | } else {
|
363 | this.startResolutionWithBackoff();
|
364 | }
|
365 | }
|
366 | }
|
367 |
|
368 | |
369 |
|
370 |
|
371 |
|
372 |
|
373 | destroy() {
|
374 | this.continueResolving = false;
|
375 | this.backoff.reset();
|
376 | this.backoff.stop();
|
377 | this.stopNextResolutionTimer();
|
378 | this.pendingLookupPromise = null;
|
379 | this.pendingTxtPromise = null;
|
380 | this.latestLookupResult = null;
|
381 | this.latestServiceConfig = null;
|
382 | this.latestServiceConfigError = null;
|
383 | }
|
384 |
|
385 | |
386 |
|
387 |
|
388 |
|
389 |
|
390 | static getDefaultAuthority(target: GrpcUri): string {
|
391 | return target.path;
|
392 | }
|
393 | }
|
394 |
|
395 |
|
396 |
|
397 |
|
398 |
|
399 | export function setup(): void {
|
400 | registerResolver('dns', DnsResolver);
|
401 | registerDefaultScheme('dns');
|
402 | }
|
403 |
|
404 | export interface DnsUrl {
|
405 | host: string;
|
406 | port?: string;
|
407 | }
|