From 168d7d0063bdf82e83cd8be6a3b66aca4f74d8bc Mon Sep 17 00:00:00 2001 From: songzhendong12315 Date: Wed, 16 Sep 2026 21:14:40 +0800 Subject: [PATCH 1/6] feat(grpc): optional multi-backend DNS expand and periodic re-resolve When SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY is set, expand comma-separated hostname backends to A/AAAA, re-resolve on an interval, and rebuild the channel when the merged dial set changes. Failed names keep last-known endpoints; interval values must be whole positive integers (overflow and invalid strings fall back to 30s); incomplete/empty DNS logs are throttled. --- .github/workflows/test.yaml | 32 + docs/en/advanced/troubleshooting.md | 27 +- docs/en/contribution/build-and-test.md | 4 +- docs/en/setup/configuration.md | 4 +- .../core/remote/BackendAddressResolver.ts | 204 ++++- src/agent/core/remote/GRPCChannelManager.ts | 299 ++++++- src/config/AgentConfig.ts | 12 + .../dns-periodic/docker-compose.yml | 114 +++ tests/remote-e2e/dns-periodic/server.ts | 87 +++ tests/remote-e2e/dns-periodic/test.ts | 185 +++++ tests/remote/BackendAddressResolver.test.ts | 135 ++++ tests/remote/GRPCChannelManager.test.ts | 733 +++++++++++++++++- 12 files changed, 1805 insertions(+), 31 deletions(-) create mode 100644 tests/remote-e2e/dns-periodic/docker-compose.yml create mode 100644 tests/remote-e2e/dns-periodic/server.ts create mode 100644 tests/remote-e2e/dns-periodic/test.ts diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 5dadc6ad..7183b5c7 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -150,6 +150,38 @@ jobs: npm i npm run test tests/remote-e2e/static-failover/ + TestRemoteE2EDnsPeriodic: + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + node-version: [ 20, 22, 24 ] + env: + SW_NODE_VERSION: ${{ matrix.node-version }} + SW_OAP_IMAGE: ghcr.io/apache/skywalking/oap@sha256:f3fd1982c0344db2150780ea71bd51afc1f8fd7f482f73f01429a72151c857f6 + steps: + - uses: actions/checkout@v4 + with: + submodules: true + + - uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- + + - name: Set Up NodeJS ${{ matrix.node-version }} + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Remote E2E On Node@${{ matrix.node-version }} (dns-periodic real OAP) + run: | + npm i + npm run test tests/remote-e2e/dns-periodic/ + TestRemoteE2EMTLS: runs-on: ubuntu-latest timeout-minutes: 30 diff --git a/docs/en/advanced/troubleshooting.md b/docs/en/advanced/troubleshooting.md index a662a4fd..536b8f15 100644 --- a/docs/en/advanced/troubleshooting.md +++ b/docs/en/advanced/troubleshooting.md @@ -29,9 +29,24 @@ export SW_AGENT_COLLECTOR_BACKEND_SERVICES=oap.example.com:11800 Check DNS, network access, firewall rules, and the OAP gRPC port. One `host:port` uses the grpc-js `dns:` resolver (all A/AAAA records become endpoints and are -re-resolved periodically). A comma-separated list uses a static resolver with `pick_first`: each -name is a literal endpoint only — no DNS expansion or re-resolution per name, so discovery is weaker -than a single DNS name (for example a headless Kubernetes service). +re-resolved on demand by grpc-js when the channel needs fresh addresses — not on a fixed agent timer). A comma-separated list uses a static resolver with `pick_first`: by +default each name is a literal endpoint only — no DNS expansion or re-resolution per name, so +discovery is weaker than a single DNS name (for example a headless Kubernetes service). + +To expand and periodically refresh multiple DNS names, set +`SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY=true` (or `isResolveDnsPeriodically: true` in `agent.start()`). +`SW_AGENT_COLLECTOR_IS_RESOLVE_DNS_PERIODICALLY` is accepted as a Java-aligned alias. +The agent resolves each hostname to all A/AAAA records (each lookup times out after 5s), +dials the resulting IP list via +`sw-static` (including when expansion yields a single IP), and re-resolves every 30 seconds +(override with `SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS`, or the Java-aligned +`SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL`). Failed names keep their last-known endpoints +so a partial DNS outage does not shrink the dial set; the gRPC channel is rebuilt when the +merged address set changes, and open is retried on later ticks if no channel was installed yet. +Timer ticks that arrive while a resolve is still running are skipped (no overlapping resolve). +Under TLS, when endpoints are IP literals, the agent uses the first configured +hostname in the list as SNI / authority unless `SW_AGENT_SSL_TARGET_NAME_OVERRIDE` is set. All backends must +still present certificates that share the needed SANs. An option passed to `agent.start()` replaces the environment value. This includes an empty string: @@ -53,8 +68,10 @@ With Apache OAP, point the agent at the mTLS-enabled `receiver-sharing-server` g (commonly port `11801`, or the port selected by `SW_RECEIVER_GRPC_PORT`). Do not assume that the regular OAP agent listener on port `11800` requests client certificates. -Under TLS with multiple hostnames, certificate verification follows the channel authority (the first -list entry in the configured target). Endpoint pick order may be shuffled by grpc-js, but the target +Under TLS with multiple backends, certificate verification follows the channel authority. +With periodic multi-name DNS expand, that is the first **hostname** in the configured list +(not an IP literal earlier in the list). Without DNS expand, authority follows the first list +entry in the configured target. Endpoint pick order may be shuffled by grpc-js, but the target string — and therefore authority / SNI — stays in config order. Every backend must present a certificate that shares the needed SANs, or failover handshakes fail. Prefer one DNS name with multiple A/AAAA records for TLS high availability. diff --git a/docs/en/contribution/build-and-test.md b/docs/en/contribution/build-and-test.md index 80096ad6..a3f47388 100644 --- a/docs/en/contribution/build-and-test.md +++ b/docs/en/contribution/build-and-test.md @@ -41,10 +41,10 @@ Run the TypeScript lint check: npm run lint ``` -Run unit tests without Docker plugin suites: +Run unit tests without Docker plugin suites or remote e2e: ```bash -npx jest --testPathIgnorePatterns '/node_modules/' '/tests/plugins/' --runInBand +npx jest --testPathIgnorePatterns '/node_modules/' '/tests/plugins/' '/tests/remote-e2e/' --runInBand ``` Run all tests, including Docker plugin suites: diff --git a/docs/en/setup/configuration.md b/docs/en/setup/configuration.md index 15f8d353..2832e2c5 100644 --- a/docs/en/setup/configuration.md +++ b/docs/en/setup/configuration.md @@ -24,7 +24,9 @@ Node.js process. `SW_DISABLE` is checked when `start()` is called. | --- | --- | --- | --- | | `SW_AGENT_NAME` | `serviceName` | `your-nodejs-service` | Service name shown in SkyWalking. | | `SW_AGENT_INSTANCE` | `serviceInstance` | Host name | Service instance name shown in SkyWalking. | -| `SW_AGENT_COLLECTOR_BACKEND_SERVICES` | `collectorAddress` | `127.0.0.1:11800` | OAP gRPC address(es). One `host:port` uses grpc-js `dns:` (all A/AAAA become endpoints; periodically re-resolved). A comma-separated list uses a static resolver with `pick_first` (literal endpoints only; no per-name DNS expansion or re-resolution). Endpoint pick order is shuffled by grpc-js (`shuffleAddressList`); the target string keeps config order so TLS authority / SNI stay on the first list entry. Under TLS, all backends must present certificates that share the needed SANs. Prefer one DNS name with multiple A/AAAA records for TLS high availability. | +| `SW_AGENT_COLLECTOR_BACKEND_SERVICES` | `collectorAddress` | `127.0.0.1:11800` | OAP gRPC address(es). One `host:port` uses grpc-js `dns:` (all A/AAAA become endpoints; re-resolved on demand by grpc-js, not on a fixed agent timer). A comma-separated list uses a static resolver with `pick_first`. By default each list entry is a literal endpoint (no per-name DNS expansion or re-resolution). Set `SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY=true` to expand every hostname to its A/AAAA records and re-resolve every 30s (override with `SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS`), rebuilding the channel when the address set changes or retrying open when no channel is installed yet. Failed names keep last-known endpoints in the dial set so partial DNS outages do not shrink a working channel or block recovery when another name's IPs change. Endpoint pick order is shuffled by grpc-js (`shuffleAddressList`); the target string keeps config order so TLS authority / SNI stay on the first list entry (after DNS expand, the first configured hostname in the list is used as authority when dialing IPs). Under TLS, all backends must present certificates that share the needed SANs. Prefer one DNS name with multiple A/AAAA records for TLS high availability when periodic multi-name DNS is not enabled. | +| `SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY` | `isResolveDnsPeriodically` | `false` | When `true` and `collectorAddress` lists multiple backends that include hostnames, expand each name to all A/AAAA addresses (per-name lookup timeout 5s) and periodically re-resolve (30s). Rebuilds when the resolved set changes; also retries open on later ticks if the channel was never opened. Single-address targets ignore this flag (grpc-js `dns:` already re-resolves). All-IP multi-address lists do not start a timer. `SW_AGENT_COLLECTOR_IS_RESOLVE_DNS_PERIODICALLY` is accepted as a Java-aligned alias. | +| `SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS` | — | `30` | Interval for multi-backend DNS re-resolve when `SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY=true`. Positive decimal integer seconds for the whole value (rejects 1.5, 1e3, 10junk); invalid values and values that overflow the Node timer limit fall back to 30. `SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL` is accepted as a Java-aligned alias (same default 30s). Overlapping ticks while a resolve is still running are skipped. | | `SW_AGENT_SECURE` | `secure` | `false` | Use TLS for the OAP gRPC connection. | | `SW_AGENT_SSL_TRUSTED_CA_PATH` | `sslTrustedCaPath` | Not set | Optional trusted CA certificate file for TLS server verification. Relative paths are resolved from the process working directory. | | `SW_AGENT_SSL_KEY_PATH` | `sslKeyPath` | Not set | Client private key file for mTLS. Must be configured together with `sslCertChainPath` and `secure=true`. | diff --git a/src/agent/core/remote/BackendAddressResolver.ts b/src/agent/core/remote/BackendAddressResolver.ts index e01eefd6..d905837f 100644 --- a/src/agent/core/remote/BackendAddressResolver.ts +++ b/src/agent/core/remote/BackendAddressResolver.ts @@ -17,6 +17,8 @@ * */ +import * as dns from 'dns'; +import * as net from 'net'; import * as grpc from '@grpc/grpc-js'; import { createLogger } from '../../../logging'; @@ -26,6 +28,39 @@ const SW_STATIC_SCHEME = 'sw-static'; let swStaticResolverRegistered = false; +/** Lookup returning all A/AAAA records (injectable for tests). */ +export type DnsLookupAll = (hostname: string) => Promise>; + +const defaultDnsLookupAll: DnsLookupAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true }); + +/** Per-hostname DNS lookup deadline (ms). Hung lookups fail open to the next name / tick. */ +export const DNS_LOOKUP_TIMEOUT_MS = 5_000; + +async function lookupWithTimeout( + hostname: string, + lookup: DnsLookupAll, + timeoutMs: number = DNS_LOOKUP_TIMEOUT_MS, +): Promise> { + let timer: NodeJS.Timeout | undefined; + // Keep a rejection handler so a late failure after timeout does not surface as + // an unhandledRejection (dns.lookup/getaddrinfo cannot be cancelled). + const lookupPromise = lookup(hostname); + void lookupPromise.catch(() => undefined); + try { + return await Promise.race([ + lookupPromise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`DNS lookup timed out after ${timeoutMs}ms`)), timeoutMs); + timer.unref?.(); + }), + ]); + } finally { + if (timer) { + clearTimeout(timer); + } + } +} + /** * Parse one host:port via grpc.experimental.splitHostPort. * Returns normalized host:port or null when invalid (logged at error). @@ -60,15 +95,174 @@ export function parseStaticBackendAddresses(raw: string): string[] { return result; } +/** True when host is an IPv4/IPv6 literal (optional brackets for v6). */ +export function isIpLiteral(host: string): boolean { + const trimmed = host.trim(); + if (!trimmed) { + return false; + } + if (trimmed.startsWith('[') && trimmed.endsWith(']')) { + return net.isIP(trimmed.slice(1, -1)) !== 0; + } + return net.isIP(trimmed) !== 0; +} + +function formatHostPort(host: string, port: number): string { + const normalized = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host; + return `${normalized}:${port}`; +} + +/** + * Whether multi-backend DNS expand + periodic re-resolve should run. + * Single-address targets use grpc-js dns:; all-IP lists need no lookup. + */ +export function shouldExpandBackendDns(addresses: string[]): boolean { + if (addresses.length <= 1) { + return false; + } + for (const entry of addresses) { + const parsed = grpc.experimental.splitHostPort(entry); + if (parsed?.host && !isIpLiteral(parsed.host)) { + return true; + } + } + return false; +} + +/** + * Expand hostnames to all A/AAAA addresses (IPs kept as-is). Failed names are + * logged and skipped; returns [] addresses when nothing resolved. + * `hadLookupFailure` is true when at least one hostname threw/timed out or + * returned no A/AAAA. + * + * Pass `previousByConfigured` so a failed name keeps its last successful + * endpoints — callers can dial a stable merged set instead of shrinking on + * partial DNS outages (and still pick up IP changes from names that resolved). + */ +export type ExpandBackendResult = { + addresses: string[]; + hadLookupFailure: boolean; + /** Per configured host:port → endpoints after this expand (includes kept previous). */ + byConfigured: Map; +}; + +export type ExpandBackendOptions = { + lookup?: DnsLookupAll; + previousByConfigured?: ReadonlyMap; +}; + +export async function expandBackendAddresses( + addresses: string[], + lookupOrOptions: DnsLookupAll | ExpandBackendOptions = defaultDnsLookupAll, +): Promise { + let lookup: DnsLookupAll = defaultDnsLookupAll; + let previousByConfigured: ReadonlyMap = new Map(); + if (typeof lookupOrOptions === 'function') { + lookup = lookupOrOptions; + } else { + lookup = lookupOrOptions.lookup ?? defaultDnsLookupAll; + previousByConfigured = lookupOrOptions.previousByConfigured ?? new Map(); + } + + const byConfigured = new Map(); + const expanded: string[] = []; + const seen = new Set(); + let hadLookupFailure = false; + + const appendUnique = (endpoints: readonly string[]) => { + for (const endpoint of endpoints) { + if (!seen.has(endpoint)) { + seen.add(endpoint); + expanded.push(endpoint); + } + } + }; + + for (const entry of addresses) { + const parsed = grpc.experimental.splitHostPort(entry); + if (!parsed?.host || parsed.port == null) { + continue; + } + const { host, port } = parsed; + + if (isIpLiteral(host)) { + const normalized = formatHostPort(host.startsWith('[') ? host.slice(1, -1) : host, port); + byConfigured.set(entry, [normalized]); + appendUnique([normalized]); + continue; + } + + try { + const records = await lookupWithTimeout(host, lookup); + if (!records.length) { + // Same as throw/timeout: incomplete expand must not drop prior endpoints. + hadLookupFailure = true; + logger.error(`DNS lookup for backend [${host}] returned no addresses`); + const previous = previousByConfigured.get(entry); + if (previous?.length) { + byConfigured.set(entry, [...previous]); + appendUnique(previous); + } + continue; + } + const endpoints: string[] = []; + for (const record of records) { + endpoints.push(formatHostPort(record.address, port)); + } + byConfigured.set(entry, endpoints); + appendUnique(endpoints); + } catch (error) { + hadLookupFailure = true; + logger.error(`Failed to resolve backend [${host}]: ${error}`); + const previous = previousByConfigured.get(entry); + if (previous?.length) { + byConfigured.set(entry, [...previous]); + appendUnique(previous); + } + } + } + + return { addresses: expanded, hadLookupFailure, byConfigured }; +} + +/** True when both lists contain the same host:port values (order-independent). */ +export function sameAddressSet(a: string[], b: string[]): boolean { + if (a.length !== b.length) { + return false; + } + const sortedA = [...a].sort(); + const sortedB = [...b].sort(); + for (let i = 0; i < sortedA.length; i++) { + if (sortedA[i] !== sortedB[i]) { + return false; + } + } + return true; +} + +/** + * First non-IP hostname in the configured list — used as TLS authority after + * expanding backends to IP literals (e.g. `10.0.0.1:11800,oap-b.svc:11800`). + */ +export function firstHostnameAuthority(addresses: string[]): string | undefined { + for (const entry of addresses) { + const parsed = grpc.experimental.splitHostPort(entry); + if (parsed?.host && !isIpLiteral(parsed.host)) { + return parsed.host; + } + } + return undefined; +} + /** * Build a grpc-js channel target. - * - One address: plain host:port (default dns: resolver — multi-IP + periodic re-resolve + natural TLS authority). - * - Multiple: sw-static:/// list for pick_first across explicit backends (literal endpoints only; - * no DNS expansion / re-resolution of each name — weaker discovery than a single dns: target). + * - One address: plain host:port (default dns: resolver — multi-IP + periodic re-resolve + natural TLS authority), + * unless forceStatic is set (DNS-expanded IP lists always use sw-static, even for a single IP). + * - Multiple: sw-static:/// list for pick_first across explicit backends. */ -export function buildNativeGrpcTarget(addresses: string[]): string { +export function buildNativeGrpcTarget(addresses: string[], options: { forceStatic?: boolean } = {}): string { // Caller (openChannel) already requires a non-empty list. - if (addresses.length === 1) { + if (addresses.length === 1 && !options.forceStatic) { return addresses[0]!; } ensureSwStaticResolverRegistered(); diff --git a/src/agent/core/remote/GRPCChannelManager.ts b/src/agent/core/remote/GRPCChannelManager.ts index 8fbf0163..85c45248 100644 --- a/src/agent/core/remote/GRPCChannelManager.ts +++ b/src/agent/core/remote/GRPCChannelManager.ts @@ -23,7 +23,14 @@ import config from '../../../config/AgentConfig'; import { createLogger, throttled } from '../../../logging'; import AgentIDDecorator from './AgentIDDecorator'; import AuthenticationDecorator from './AuthenticationDecorator'; -import { buildNativeGrpcTarget, parseStaticBackendAddresses } from './BackendAddressResolver'; +import { + buildNativeGrpcTarget, + expandBackendAddresses, + firstHostnameAuthority, + parseStaticBackendAddresses, + sameAddressSet, + shouldExpandBackendDns, +} from './BackendAddressResolver'; import GRPCChannel from './GRPCChannel'; import { GRPCChannelListener } from './GRPCChannelListener'; import { GRPCChannelStatus } from './GRPCChannelStatus'; @@ -35,6 +42,41 @@ const logger = createLogger(__filename); const logAuthRejected = throttled(logger, 'error', 30000); const logChannelDisconnected = throttled(logger, 'error', 30000); const logChannelRecovered = throttled(logger, 'warn', 30000); +const logDnsExpandEmpty = throttled(logger, 'error', 30000); +const logDnsExpandIncomplete = throttled(logger, 'warn', 30000); + +/** Aligns with Java collector.grpc_channel_check_interval default (seconds → ms). */ +const DEFAULT_DNS_RE_RESOLVE_INTERVAL_MS = 30_000; + +/** Node timers use a signed 32-bit ms delay; larger values overflow to 1ms. */ +const MAX_DNS_RE_RESOLVE_INTERVAL_MS = 2 ** 31 - 1; + +/** + * Override via SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS, or the Java-aligned + * SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL (seconds). Positive integers only; + * values that overflow the Node timer limit fall back to the default. + */ +export function dnsReResolveIntervalMs(): number { + const raw = + process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS ?? process.env.SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL; + if (raw == null || raw === '') { + return DEFAULT_DNS_RE_RESOLVE_INTERVAL_MS; + } + const trimmed = raw.trim(); + // Require the whole value to be a positive decimal integer (rejects 1.5, 1e3, 10junk). + if (!/^\d+$/.test(trimmed)) { + return DEFAULT_DNS_RE_RESOLVE_INTERVAL_MS; + } + const seconds = Number.parseInt(trimmed, 10); + if (!Number.isSafeInteger(seconds) || seconds <= 0) { + return DEFAULT_DNS_RE_RESOLVE_INTERVAL_MS; + } + const ms = seconds * 1000; + if (!Number.isSafeInteger(ms) || ms > MAX_DNS_RE_RESOLVE_INTERVAL_MS) { + return DEFAULT_DNS_RE_RESOLVE_INTERVAL_MS; + } + return ms; +} /** Placeholder authority — ignored when channelOverride is set (grpc-js client.js). */ const STUB_AUTHORITY = 'skywalking-backend'; @@ -57,7 +99,7 @@ function isGrpcNetworkError(error: unknown): boolean { ); } -function nativeChannelOptions(): ChannelOptions { +function nativeChannelOptions(authorityHostname?: string): ChannelOptions { // No gRPC keepalive: stock OAP (grpc-java) rejects frequent idle pings with GOAWAY // ENHANCE_YOUR_CALM. Agent traffic (trace/heartbeat/metrics) provides liveness. // @@ -66,7 +108,7 @@ function nativeChannelOptions(): ChannelOptions { // proxy) so host-app http_proxy/https_proxy cannot affect the agent channel — // multi-address targets are also broken under HTTP CONNECT (proxy sees the // unresolved comma list). - return { + const options: ChannelOptions = { 'grpc.enable_http_proxy': 0, 'grpc.initial_reconnect_backoff_ms': 1_000, 'grpc.max_reconnect_backoff_ms': 30_000, @@ -92,6 +134,17 @@ function nativeChannelOptions(): ChannelOptions { ], }), }; + + // After DNS expand, endpoints are IP literals — under TLS keep SNI/authority on the + // configured hostname unless the operator already set sslTargetNameOverride + // (TLSChannelBuilder wins then). Plaintext does not need an authority override. + const override = config.sslTargetNameOverride?.trim(); + if (config.secure && !override && authorityHostname) { + options['grpc.default_authority'] = authorityHostname; + options['grpc.ssl_target_name_override'] = authorityHostname; + } + + return options; } /** @@ -104,7 +157,31 @@ export default class GRPCChannelManager implements BootService { private lastStatus: GRPCChannelStatus | null = null; private lastConnectivityState: grpc.connectivityState | null = null; private closed = false; + /** Configured host:port list (pre-DNS expand), used for logs and re-resolve. */ + private configuredServers: string[] = []; + /** Addresses currently used to dial (may be expanded IPs). */ private grpcServers: string[] = []; + /** + * Last successful (or kept) endpoints per configured host:port — used so a + * partial DNS failure does not drop other names' prior IPs from the dial set. + */ + private lastResolvedByConfigured = new Map(); + private dnsRefreshTimer: NodeJS.Timeout | null = null; + /** Guard overlapping ticks — matches Java single-thread scheduleAtFixedRate (no concurrent run). */ + private dnsRefreshInFlight = false; + /** + * After a failed open/rebuild while a prior channel may still be usable, retry open on the + * next tick even if the resolved address set is unchanged. + */ + private dnsOpenNeedsRetry = false; + /** Hostname authority when dialing expanded IPs under TLS. */ + private dnsAuthorityHostname: string | undefined; + /** True while dialing addresses produced by expandBackendAddresses (always sw-static). */ + private dialingExpandedAddresses = false; + /** Skip status transition logs for intentional DISCONNECT→CONNECTED during DNS rebuild. */ + private suppressDnsRebuildStatusLog = false; + /** How many DNS expand/refresh cycles have completed (including empty results). */ + private dnsRefreshCount = 0; getClientOptions(): ClientOptions { if (!this.managedChannel) { @@ -134,6 +211,16 @@ export default class GRPCChannelManager implements BootService { return Number.MAX_SAFE_INTEGER; } + /** Resolved dial targets after DNS expand (IPs), or configured literals when not expanding. */ + getResolvedBackends(): string[] { + return [...this.grpcServers]; + } + + /** Completed DNS expand/refresh cycles (initial + periodic). For e2e / diagnostics. */ + getDnsRefreshCount(): number { + return this.dnsRefreshCount; + } + /** * Auth failures: throttled error only (same token across cluster backends). * Network errors on READY: leave to grpc-js retry / pick_first. @@ -176,50 +263,179 @@ export default class GRPCChannelManager implements BootService { boot(): void { this.closed = false; this.lastConnectivityState = null; + this.stopDnsRefreshTimer(); + this.dnsAuthorityHostname = undefined; + this.dnsRefreshInFlight = false; + this.dnsOpenNeedsRetry = false; + this.dialingExpandedAddresses = false; + this.suppressDnsRebuildStatusLog = false; + this.dnsRefreshCount = 0; + this.lastResolvedByConfigured = new Map(); + const parsed = parseStaticBackendAddresses(config.collectorAddress ?? ''); if (parsed.length === 0) { logger.error('Collector server addresses are not set.'); logger.error('Agent will not uplink any data.'); + this.configuredServers = []; + this.grpcServers = []; this.notify(GRPCChannelStatus.DISCONNECT); return; } - // Keep config order in the target so channel authority / SNI stay stable. + + // Keep config order so channel authority / SNI stay stable when not expanding. // Endpoint pick order is shuffled by pick_first.shuffleAddressList in service_config. + this.configuredServers = [...parsed]; this.grpcServers = [...parsed]; - this.openChannel(this.grpcServers); + + if (config.isResolveDnsPeriodically && shouldExpandBackendDns(parsed)) { + this.dnsAuthorityHostname = firstHostnameAuthority(parsed); + // Start the timer immediately so a hung initial lookup cannot block later retries. + this.startDnsRefreshTimer(); + void this.refreshResolvedBackends(true).catch((error) => { + logger.error(`Initial DNS expand failed: ${error}`); + }); + return; + } + + this.openChannel(parsed); } onComplete(): void {} shutdown(): void { this.closed = true; + this.stopDnsRefreshTimer(); const managed = this.managedChannel; this.managedChannel = null; managed?.shutdownNow(); this.notify(GRPCChannelStatus.DISCONNECT); this.listeners.length = 0; + this.configuredServers = []; this.grpcServers = []; + this.lastResolvedByConfigured = new Map(); + this.dnsAuthorityHostname = undefined; + this.dialingExpandedAddresses = false; + this.dnsOpenNeedsRetry = false; + this.suppressDnsRebuildStatusLog = false; + this.dnsRefreshCount = 0; this.lastConnectivityState = null; } - private openChannel(addresses: string[]): void { - if (this.closed || addresses.length === 0) { + private startDnsRefreshTimer(): void { + this.stopDnsRefreshTimer(); + this.dnsRefreshTimer = setInterval(() => { + void this.refreshResolvedBackends(false).catch((error) => { + logger.error(`Periodic DNS re-resolve failed: ${error}`); + }); + }, dnsReResolveIntervalMs()); + this.dnsRefreshTimer.unref(); + } + + private stopDnsRefreshTimer(): void { + if (this.dnsRefreshTimer) { + clearInterval(this.dnsRefreshTimer); + this.dnsRefreshTimer = null; + } + } + + /** + * Expand configured hostnames to IP endpoints. Opens or rebuilds the channel when + * forceOpen is set or the resolved set changed. Empty resolve keeps the previous channel. + * + * Failed names keep their last successful endpoints (merged dial set) so a partial DNS + * outage neither shrinks a healthy channel nor blocks recovery when another name's IPs + * change while the channel is down. Overlapping timer ticks are skipped (same as Java + * GRPCChannelManager's single-thread scheduleAtFixedRate). Unlike Java, re-resolve runs + * while the channel is connected so multi-name backends can pick up DNS changes without + * waiting for a disconnect. + */ + private async refreshResolvedBackends(forceOpen: boolean): Promise { + if (this.closed) { + return; + } + if (this.dnsRefreshInFlight) { return; } + this.dnsRefreshInFlight = true; + try { + const { + addresses: expanded, + hadLookupFailure, + byConfigured, + } = await expandBackendAddresses(this.configuredServers, { previousByConfigured: this.lastResolvedByConfigured }); + this.lastResolvedByConfigured = byConfigured; + this.dnsRefreshCount += 1; + if (this.closed) { + return; + } + if (expanded.length === 0) { + if (this.managedChannel) { + logDnsExpandEmpty( + `DNS expand produced no backends for [${this.configuredServers.join(',')}]; keeping previous channel`, + ); + } else { + logDnsExpandEmpty( + `DNS expand produced no backends for [${this.configuredServers.join(',')}]; channel not opened`, + ); + if (forceOpen) { + this.notify(GRPCChannelStatus.DISCONNECT); + } + } + return; + } + if (hadLookupFailure) { + logDnsExpandIncomplete( + `DNS expand incomplete for [${this.configuredServers.join( + ',', + )}]; using last-known endpoints for unresolved names`, + ); + } + // Retry open when the previous build failed even if the address set is unchanged. + if (!forceOpen && this.managedChannel && sameAddressSet(expanded, this.grpcServers) && !this.dnsOpenNeedsRetry) { + logger.debug('Periodic DNS re-resolve: backend address set unchanged'); + return; + } + if (!forceOpen && this.managedChannel && !this.dnsOpenNeedsRetry) { + logger.info( + `Periodic DNS re-resolve: backend set changed [${this.grpcServers.join(',')}] -> [${expanded.join( + ',', + )}]; rebuilding channel`, + ); + } + this.dialingExpandedAddresses = true; + if (this.openChannel(expanded)) { + this.grpcServers = expanded; + this.dnsOpenNeedsRetry = false; + } else { + this.dnsOpenNeedsRetry = true; + } + } finally { + this.dnsRefreshInFlight = false; + } + } + + /** @returns true when a channel was installed. */ + private openChannel(addresses: string[]): boolean { + if (this.closed || addresses.length === 0) { + return false; + } let target: string; try { - target = buildNativeGrpcTarget(addresses); + target = buildNativeGrpcTarget(addresses, { forceStatic: this.dialingExpandedAddresses }); } catch (error) { logger.error(`Failed to build gRPC target: ${error}`); - this.notify(GRPCChannelStatus.DISCONNECT); - return; + // Keep a working prior channel; only disconnect when nothing is installed. + if (!this.managedChannel) { + this.notify(GRPCChannelStatus.DISCONNECT); + } + return false; } let built: GRPCChannel; try { built = GRPCChannel.newBuilder(target) - .withChannelOptions(nativeChannelOptions()) + .withChannelOptions(nativeChannelOptions(this.dnsAuthorityHostname)) .addManagedChannelBuilder(new StandardChannelBuilder()) .addManagedChannelBuilder(new TLSChannelBuilder()) .addChannelDecorator(new AgentIDDecorator()) @@ -227,18 +443,55 @@ export default class GRPCChannelManager implements BootService { .build(); } catch (error) { logger.error(`Failed to build gRPC channel for target [${target}]: ${error}`); - this.notify(GRPCChannelStatus.DISCONNECT); - return; + if (!this.managedChannel) { + this.notify(GRPCChannelStatus.DISCONNECT); + } + return false; + } + + // Shutdown may have completed while builders ran (TLS file I/O). + if (this.closed) { + built.shutdownNow(); + return false; } const previous = this.managedChannel; this.managedChannel = built; - // Defensive: boot() opens once today (ServiceManager.booted), but close any prior - // channel if openChannel is ever invoked again. + // Close any prior channel when openChannel is invoked again (DNS rebuild). previous?.shutdownNow(); + if (previous) { + // statusChanged is deduped on CONNECTED→CONNECTED. After replacing the underlying + // grpc.Channel, force DISCONNECT so Trace/Meter/Management recreate stubs on the next + // CONNECTED (otherwise they keep channelOverride on the shut-down channel). + this.lastConnectivityState = null; + if (this.lastStatus === GRPCChannelStatus.CONNECTED) { + // Quiet until CONNECTED is published (may be async via watch — do not clear here). + this.suppressDnsRebuildStatusLog = true; + try { + this.notify(GRPCChannelStatus.DISCONNECT); + } catch (error) { + this.suppressDnsRebuildStatusLog = false; + throw error; + } + } else { + this.suppressDnsRebuildStatusLog = false; + } + } else { + this.suppressDnsRebuildStatusLog = false; + } this.watchConnectivityState(); // watchConnectivityState already requested a connection; do not request again. this.notifyCurrentConnectivityState(false); + // Shutdown may have raced after install — do not report success / commit grpcServers. + if (this.closed || this.managedChannel !== built) { + this.suppressDnsRebuildStatusLog = false; + if (this.managedChannel === built) { + this.managedChannel = null; + built.shutdownNow(); + } + return false; + } + return true; } private watchConnectivityState(): void { @@ -274,10 +527,15 @@ export default class GRPCChannelManager implements BootService { this.notify(GRPCChannelStatus.CONNECTED); return; } - // Handshake in progress — do not treat as disconnect. + // Handshake in progress — do not treat as disconnect; keep rebuild quiet window. if (state === grpc.connectivityState.CONNECTING) { return; } + // Rebuild quiet window ends if the new channel leaves CONNECTING without READY + // (IDLE / TRANSIENT_FAILURE / SHUTDOWN) so later recover logs are not muted forever. + if (this.suppressDnsRebuildStatusLog) { + this.suppressDnsRebuildStatusLog = false; + } // READY→IDLE is grpc-js's normal path after the active connection drops. if (state === grpc.connectivityState.IDLE) { if (previousConnectivity === grpc.connectivityState.READY) { @@ -295,6 +553,10 @@ export default class GRPCChannelManager implements BootService { const previous = this.lastStatus; this.lastStatus = status; this.logStatusTransition(status, previous); + // End the DNS-rebuild quiet window once CONNECTED is delivered (sync or via watch). + if (this.suppressDnsRebuildStatusLog && status === GRPCChannelStatus.CONNECTED) { + this.suppressDnsRebuildStatusLog = false; + } for (const listener of this.listeners) { try { @@ -310,7 +572,10 @@ export default class GRPCChannelManager implements BootService { if (this.closed) { return; } - const backends = this.grpcServers.join(',') || config.collectorAddress || ''; + if (this.suppressDnsRebuildStatusLog) { + return; + } + const backends = this.configuredServers.join(',') || this.grpcServers.join(',') || config.collectorAddress || ''; if (status === GRPCChannelStatus.DISCONNECT) { if (previous === GRPCChannelStatus.CONNECTED) { logChannelDisconnected( diff --git a/src/config/AgentConfig.ts b/src/config/AgentConfig.ts index b46c8603..2f8a1896 100644 --- a/src/config/AgentConfig.ts +++ b/src/config/AgentConfig.ts @@ -23,6 +23,13 @@ export type AgentConfig = { serviceName?: string; serviceInstance?: string; collectorAddress?: string; + /** + * When true and multiple backends include hostnames, expand A/AAAA and + * periodically re-resolve; rebuild when the address set changes, or retry + * open when no channel is installed yet (e.g. after a failed initial expand). + * Single-address targets keep grpc-js dns: re-resolution and ignore this flag. + */ + isResolveDnsPeriodically?: boolean; secure?: boolean; sslTrustedCaPath?: string; sslKeyPath?: string; @@ -185,6 +192,11 @@ const _config = { return os.hostname(); })(), collectorAddress: process.env.SW_AGENT_COLLECTOR_BACKEND_SERVICES || '127.0.0.1:11800', + isResolveDnsPeriodically: ((): boolean => { + const configured = + process.env.SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY ?? process.env.SW_AGENT_COLLECTOR_IS_RESOLVE_DNS_PERIODICALLY; + return configured?.toLowerCase() === 'true'; + })(), secure: process.env.SW_AGENT_SECURE?.toLowerCase() === 'true', sslTrustedCaPath: process.env.SW_AGENT_SSL_TRUSTED_CA_PATH || undefined, sslKeyPath: process.env.SW_AGENT_SSL_KEY_PATH || undefined, diff --git a/tests/remote-e2e/dns-periodic/docker-compose.yml b/tests/remote-e2e/dns-periodic/docker-compose.yml new file mode 100644 index 00000000..85503887 --- /dev/null +++ b/tests/remote-e2e/dns-periodic/docker-compose.yml @@ -0,0 +1,114 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# + +services: + oap: + image: ${SW_OAP_IMAGE:-ghcr.io/apache/skywalking/oap@sha256:f3fd1982c0344db2150780ea71bd51afc1f8fd7f482f73f01429a72151c857f6} + environment: + SW_STORAGE: banyandb + SW_STORAGE_BANYANDB_TARGETS: banyandb:17912 + ports: + - '12802:12800' + expose: + - '11800' + depends_on: + banyandb: + condition: service_healthy + healthcheck: + test: ['CMD', 'bash', '-c', 'cat < /dev/null > /dev/tcp/127.0.0.1/11800'] + interval: 5s + timeout: 60s + retries: 120 + start_period: 90s + networks: + dnsperiodic: + aliases: + - oap-a + + # Separate container IP for oap-b that TCP-proxies to the real OAP — DNS expand + # therefore yields two distinct dial IPs while both reach the same backend. + oap-b-proxy: + image: alpine/socat:1.8.0.0 + command: ['TCP-LISTEN:11800,fork,reuseaddr', 'TCP:oap:11800'] + depends_on: + oap: + condition: service_healthy + healthcheck: + # Probe listen port: /dev/null EOF ends the transfer right after connect. + # (Do not use -u TCP→OPEN:/dev/null — that waits for server data and times out.) + # alpine/socat ENTRYPOINT is socat; CMD-SHELL bypasses it. + test: ['CMD-SHELL', 'socat -T1 /dev/null TCP:127.0.0.1:11800,connect-timeout=1'] + interval: 2s + timeout: 3s + retries: 30 + start_period: 3s + networks: + dnsperiodic: + aliases: + - oap-b + + banyandb: + image: ${SW_BANYANDB_IMAGE:-ghcr.io/apache/skywalking-banyandb:3b83e18fb0481d02e44eaa5df137fcf7b000754b} + command: + - standalone + - --measure-metadata-cache-wait-duration + - 1m + - --stream-metadata-cache-wait-duration + - 1m + expose: + - '17912' + healthcheck: + test: ['CMD', 'sh', '-c', 'nc -nz 127.0.0.1 17912'] + interval: 5s + timeout: 60s + retries: 120 + networks: + - dnsperiodic + + server: + build: + context: ../../.. + dockerfile: tests/plugins/common/Dockerfile.agent + args: + - SW_NODE_VERSION=${SW_NODE_VERSION:-22} + ports: + - '5012:5000' + environment: + SW_AGENT_NAME: nodejs-dns-periodic-e2e + SW_AGENT_INSTANCE: nodejs-dns-periodic-e2e-instance + SW_AGENT_COLLECTOR_BACKEND_SERVICES: oap-a:11800,oap-b:11800 + SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY: 'true' + SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS: '3' + SW_AGENT_RUNTIME_METRICS_REPORTER_ACTIVE: 'false' + volumes: + - .:/app/tests/remote-e2e/dns-periodic + entrypoint: ['bash', '-c', 'npx ts-node /app/tests/remote-e2e/dns-periodic/server.ts'] + depends_on: + oap: + condition: service_healthy + oap-b-proxy: + condition: service_healthy + healthcheck: + test: ['CMD', 'bash', '-c', 'cat < /dev/null > /dev/tcp/127.0.0.1/5000'] + interval: 5s + timeout: 60s + retries: 120 + networks: + - dnsperiodic + +networks: + dnsperiodic: diff --git a/tests/remote-e2e/dns-periodic/server.ts b/tests/remote-e2e/dns-periodic/server.ts new file mode 100644 index 00000000..3064f1bf --- /dev/null +++ b/tests/remote-e2e/dns-periodic/server.ts @@ -0,0 +1,87 @@ +/*! + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 agent from '../../../src'; +import ServiceManager from '../../../src/agent/core/boot/ServiceManager'; +import GRPCChannelManager from '../../../src/agent/core/remote/GRPCChannelManager'; +import * as http from 'http'; + +agent.start({ + serviceName: 'nodejs-dns-periodic-e2e', + maxBufferSize: 1000, +}); + +const server = http.createServer((req, res) => { + const url = req.url || '/'; + if (url === '/ping') { + res.statusCode = 200; + res.end('ok'); + return; + } + + if (url === '/debug/resolved-backends') { + const manager = ServiceManager.INSTANCE.findService(GRPCChannelManager); + const backends = manager?.getResolvedBackends() ?? []; + const dnsRefreshCount = manager?.getDnsRefreshCount() ?? 0; + res.statusCode = 200; + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ backends, dnsRefreshCount })); + return; + } + + if (url === '/flush') { + const deadlineMs = 8000; + let completed = false; + const timer = setTimeout(() => { + if (completed) { + return; + } + completed = true; + res.statusCode = 504; + res.end('flush deadline'); + }, deadlineMs); + + void Promise.resolve(agent.flush()) + .then(() => { + if (completed) { + return; + } + completed = true; + clearTimeout(timer); + res.statusCode = 200; + res.end('flushed'); + }) + .catch((error: unknown) => { + if (completed) { + return; + } + completed = true; + clearTimeout(timer); + const message = error instanceof Error ? error.message : String(error); + res.statusCode = 500; + res.end(`flush failed: ${message}`); + }); + return; + } + + res.statusCode = 404; + res.end('not found'); +}); + +server.listen(5000, () => console.info('Listening on port 5000...')); diff --git a/tests/remote-e2e/dns-periodic/test.ts b/tests/remote-e2e/dns-periodic/test.ts new file mode 100644 index 00000000..5e918f92 --- /dev/null +++ b/tests/remote-e2e/dns-periodic/test.ts @@ -0,0 +1,185 @@ +/*! + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + * + */ + +/* eslint-env jest */ + +import axios from 'axios'; +import waitForExpect from 'wait-for-expect'; +import * as path from 'path'; +import { DockerComposeEnvironment, StartedDockerComposeEnvironment, Wait } from 'testcontainers'; + +const rootDir = path.resolve(__dirname); +const serverUrl = 'http://localhost:5012'; +const oapGraphqlUrl = 'http://localhost:12802/graphql'; +const serviceName = 'nodejs-dns-periodic-e2e'; + +/** OAP Duration with MINUTE step: `yyyy-MM-dd HHmm` in UTC. */ +function formatUtcMinute(date: Date): string { + const pad = (n: number) => String(n).padStart(2, '0'); + return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad( + date.getUTCHours(), + )}${pad(date.getUTCMinutes())}`; +} + +function isIpHostPort(entry: string): boolean { + // IPv4 host:port or bracketed IPv6 host:port — not a DNS name like oap-a. + if (/^\d{1,3}(\.\d{1,3}){3}:\d+$/.test(entry)) { + return true; + } + return /^\[[0-9a-fA-F:]+\]:\d+$/.test(entry); +} + +async function queryGraphql(query: string, variables?: Record): Promise { + const response = await axios.post( + oapGraphqlUrl, + { query, variables }, + { + validateStatus: () => true, + }, + ); + expect(response.status).toBe(200); + expect(response.data.errors).toBeUndefined(); + return response.data.data as T; +} + +describe('remote-e2e dns-periodic with real OAP', () => { + let compose: StartedDockerComposeEnvironment | undefined; + + beforeAll(async () => { + compose = await new DockerComposeEnvironment(rootDir, 'docker-compose.yml') + .withWaitStrategy('server-1', Wait.forHealthCheck()) + .up(); + }); + + afterAll(async () => { + await compose?.down(); + }); + + it('expands multi-hostname backends to IP dial targets and reports traces to OAP', async () => { + if (!compose) { + throw new Error('Docker Compose environment failed to start'); + } + + await waitForExpect(async () => { + expect((await axios.get(`${serverUrl}/ping`)).status).toBe(200); + }); + + // Unique proof of DNS expand: dial list must be IP literals (not oap-a/oap-b), + // and oap-a vs oap-b-proxy must yield at least two distinct addresses. + await waitForExpect( + async () => { + const response = await axios.get(`${serverUrl}/debug/resolved-backends`); + expect(response.status).toBe(200); + const backends = response.data.backends as string[]; + expect(backends.length).toBeGreaterThanOrEqual(2); + for (const backend of backends) { + expect(isIpHostPort(backend)).toBe(true); + expect(backend).not.toMatch(/^oap-[ab]/); + } + const hosts = new Set(backends.map((entry) => entry.replace(/:\d+$/, '').replace(/^\[|\]$/g, ''))); + expect(hosts.size).toBeGreaterThanOrEqual(2); + }, + 60000, + 2000, + ); + + // Prove the configured 3s interval (not the 30s default): next refresh must arrive soon. + const beforeRefresh = (await axios.get(`${serverUrl}/debug/resolved-backends`)).data.dnsRefreshCount as number; + await waitForExpect( + async () => { + const response = await axios.get(`${serverUrl}/debug/resolved-backends`); + expect(response.status).toBe(200); + expect(response.data.dnsRefreshCount).toBeGreaterThan(beforeRefresh); + const backends = response.data.backends as string[]; + expect(backends.length).toBeGreaterThanOrEqual(2); + for (const backend of backends) { + expect(isIpHostPort(backend)).toBe(true); + } + }, + 12000, + 500, + ); + + await axios.get(`${serverUrl}/ping`); + const flush = await axios.get(`${serverUrl}/flush`); + expect(flush.status).toBe(200); + expect(flush.data).toBe('flushed'); + + let serviceId = ''; + await waitForExpect( + async () => { + const data = await queryGraphql<{ listServices: Array<{ id: string; name: string }> }>( + '{ listServices { id name } }', + ); + const service = data.listServices.find((item) => item.name === serviceName); + expect(service).toBeDefined(); + serviceId = service!.id; + }, + 120000, + 3000, + ); + + const now = Date.now(); + const start = formatUtcMinute(new Date(now - 60 * 60 * 1000)); + const end = formatUtcMinute(new Date(now + 5 * 60 * 1000)); + + await waitForExpect( + async () => { + // Same queryTraces shape as mtls e2e (BanyanDB / Trace Query V2). + const data = await queryGraphql<{ + queryTraces: { traces: Array<{ spans: Array<{ serviceCode: string; endpointName: string }> }> }; + }>( + `query($serviceId: ID!, $start: String!, $end: String!) { + queryTraces(condition: { + serviceId: $serviceId + queryDuration: { start: $start, end: $end, step: MINUTE } + traceState: ALL + queryOrder: BY_START_TIME + paging: { pageNum: 1, pageSize: 20 } + }) { + traces { + spans { + serviceCode + endpointName + } + } + } + }`, + { serviceId, start, end }, + ); + + const spans: Array<{ serviceCode: string; endpointName: string }> = []; + for (const trace of data.queryTraces.traces) { + spans.push(...trace.spans); + } + expect(spans.length).toBeGreaterThan(0); + expect(spans).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + serviceCode: serviceName, + endpointName: expect.stringMatching(/\/ping/), + }), + ]), + ); + }, + 120000, + 3000, + ); + }, 300000); +}); diff --git a/tests/remote/BackendAddressResolver.test.ts b/tests/remote/BackendAddressResolver.test.ts index 2cdca8d1..7c0047b1 100644 --- a/tests/remote/BackendAddressResolver.test.ts +++ b/tests/remote/BackendAddressResolver.test.ts @@ -21,7 +21,12 @@ import { buildNativeGrpcTarget, + expandBackendAddresses, + firstHostnameAuthority, + isIpLiteral, parseStaticBackendAddresses, + sameAddressSet, + shouldExpandBackendDns, tryParseHostPort, } from '../../src/agent/core/remote/BackendAddressResolver'; @@ -60,4 +65,134 @@ describe('BackendAddressResolver (comma-separated static backends)', () => { 'sw-static:///collector-a:19876,collector-b:19876', ); }); + + it('buildNativeGrpcTarget can force sw-static for a single expanded IP', () => { + expect(buildNativeGrpcTarget(['10.0.0.1:11800'], { forceStatic: true })).toBe('sw-static:///10.0.0.1:11800'); + }); + + it('detects IP literals', () => { + expect(isIpLiteral('10.0.0.1')).toBe(true); + expect(isIpLiteral('::1')).toBe(true); + expect(isIpLiteral('[2001:db8::1]')).toBe(true); + expect(isIpLiteral('oap.example.com')).toBe(false); + }); + + it('shouldExpandBackendDns only for multi-address lists with hostnames', () => { + expect(shouldExpandBackendDns(['oap.example.com:11800'])).toBe(false); + expect(shouldExpandBackendDns(['10.0.0.1:11800', '10.0.0.2:11800'])).toBe(false); + expect(shouldExpandBackendDns(['oap-a:11800', 'oap-b:11800'])).toBe(true); + expect(shouldExpandBackendDns(['oap-a:11800', '10.0.0.2:11800'])).toBe(true); + }); + + it('sameAddressSet compares order-independently', () => { + expect(sameAddressSet(['a:1', 'b:1'], ['b:1', 'a:1'])).toBe(true); + expect(sameAddressSet(['a:1'], ['a:1', 'b:1'])).toBe(false); + }); + + it('firstHostnameAuthority returns the first non-IP host in the list', () => { + expect(firstHostnameAuthority(['oap-a.svc:11800', 'oap-b.svc:11800'])).toBe('oap-a.svc'); + expect(firstHostnameAuthority(['10.0.0.1:11800', 'oap-b.svc:11800'])).toBe('oap-b.svc'); + expect(firstHostnameAuthority(['10.0.0.1:11800', '10.0.0.2:11800'])).toBeUndefined(); + }); + + it('expandBackendAddresses keeps IPs and expands hostnames via lookup', async () => { + const lookup = jest.fn(async (hostname: string) => { + if (hostname === 'oap-a') { + return [ + { address: '10.0.0.1', family: 4 }, + { address: '10.0.0.2', family: 4 }, + ]; + } + if (hostname === 'oap-b') { + return [{ address: '2001:db8::1', family: 6 }]; + } + return []; + }); + + const result = await expandBackendAddresses(['oap-a:11800', '10.0.0.9:11800', 'oap-b:11800'], lookup); + expect(result.addresses).toEqual(['10.0.0.1:11800', '10.0.0.2:11800', '10.0.0.9:11800', '[2001:db8::1]:11800']); + expect(result.hadLookupFailure).toBe(false); + expect(result.byConfigured.get('oap-a:11800')).toEqual(['10.0.0.1:11800', '10.0.0.2:11800']); + expect(result.byConfigured.get('10.0.0.9:11800')).toEqual(['10.0.0.9:11800']); + expect(result.byConfigured.get('oap-b:11800')).toEqual(['[2001:db8::1]:11800']); + expect(lookup).toHaveBeenCalledWith('oap-a'); + expect(lookup).toHaveBeenCalledWith('oap-b'); + }); + + it('expandBackendAddresses treats empty A/AAAA results as lookup failure', async () => { + const lookup = jest.fn(async (hostname: string) => { + if (hostname === 'oap-a') { + return [{ address: '10.0.0.1', family: 4 }]; + } + return []; + }); + + const result = await expandBackendAddresses(['oap-a:11800', 'oap-b:11800'], lookup); + expect(result.addresses).toEqual(['10.0.0.1:11800']); + expect(result.hadLookupFailure).toBe(true); + expect(result.byConfigured.get('oap-a:11800')).toEqual(['10.0.0.1:11800']); + expect(result.byConfigured.has('oap-b:11800')).toBe(false); + }); + + it('expandBackendAddresses keeps previous endpoints for names that fail this tick', async () => { + const lookup = jest.fn(async (hostname: string) => { + if (hostname === 'oap-a') { + return [{ address: '10.0.0.9', family: 4 }]; + } + throw new Error('ENOTFOUND'); + }); + const previous = new Map([ + ['oap-a:11800', ['10.0.0.1:11800']], + ['oap-b:11800', ['10.0.0.2:11800']], + ]); + + const result = await expandBackendAddresses(['oap-a:11800', 'oap-b:11800'], { + lookup, + previousByConfigured: previous, + }); + expect(result.hadLookupFailure).toBe(true); + expect(result.addresses).toEqual(['10.0.0.9:11800', '10.0.0.2:11800']); + expect(result.byConfigured.get('oap-a:11800')).toEqual(['10.0.0.9:11800']); + expect(result.byConfigured.get('oap-b:11800')).toEqual(['10.0.0.2:11800']); + }); + + it('expandBackendAddresses times out a hung lookup and continues', async () => { + const lookup = jest.fn( + () => + new Promise>(() => { + /* never resolves */ + }), + ); + const started = Date.now(); + const result = await expandBackendAddresses(['hung:11800', '10.0.0.9:11800'], lookup); + expect(Date.now() - started).toBeLessThan(15_000); + expect(result.addresses).toEqual(['10.0.0.9:11800']); + expect(result.hadLookupFailure).toBe(true); + expect(lookup).toHaveBeenCalledWith('hung'); + }, 20000); + + it('does not surface unhandledRejection when lookup fails after timeout', async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => { + unhandled.push(reason); + }; + process.on('unhandledRejection', onUnhandled); + + let rejectLookup: (error: Error) => void = () => undefined; + const lookup = jest.fn( + () => + new Promise>((_, reject) => { + rejectLookup = reject; + }), + ); + + const result = await expandBackendAddresses(['late-fail:11800'], lookup); + expect(result.addresses).toEqual([]); + expect(result.hadLookupFailure).toBe(true); + + rejectLookup(new Error('late ENOTFOUND')); + await new Promise((resolve) => setImmediate(resolve)); + process.off('unhandledRejection', onUnhandled); + expect(unhandled).toEqual([]); + }, 20000); }); diff --git a/tests/remote/GRPCChannelManager.test.ts b/tests/remote/GRPCChannelManager.test.ts index 44731996..8a64cfcc 100644 --- a/tests/remote/GRPCChannelManager.test.ts +++ b/tests/remote/GRPCChannelManager.test.ts @@ -20,7 +20,8 @@ /* eslint-env jest */ import * as grpc from '@grpc/grpc-js'; -import GRPCChannelManager from '../../src/agent/core/remote/GRPCChannelManager'; +import * as BackendAddressResolver from '../../src/agent/core/remote/BackendAddressResolver'; +import GRPCChannelManager, { dnsReResolveIntervalMs } from '../../src/agent/core/remote/GRPCChannelManager'; import { GRPCChannelStatus } from '../../src/agent/core/remote/GRPCChannelStatus'; import config from '../../src/config/AgentConfig'; @@ -56,6 +57,17 @@ function installChannelMock(): void { })); } +async function flushAsyncWork(): Promise { + await Promise.resolve(); + await Promise.resolve(); + await new Promise((resolve) => setImmediate(resolve)); +} + +/** ExpandBackendResult helper for DNS mocks. */ +function dnsExpand(addresses: string[], hadLookupFailure = false) { + return { addresses, hadLookupFailure, byConfigured: new Map() }; +} + describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { const originalCollector = config.collectorAddress; const originalSecure = config.secure; @@ -63,6 +75,7 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { const originalKeyPath = config.sslKeyPath; const originalCertChainPath = config.sslCertChainPath; const originalTargetNameOverride = config.sslTargetNameOverride; + const originalResolveDns = config.isResolveDnsPeriodically; beforeEach(() => { jest.clearAllMocks(); @@ -72,6 +85,9 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { mockIsConnected.mockReturnValue(true); config.collectorAddress = '127.0.0.1:11800'; config.secure = false; + config.isResolveDnsPeriodically = false; + delete process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; + delete process.env.SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL; jest.spyOn(Math, 'random').mockReturnValue(0); }); @@ -82,9 +98,27 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { config.sslKeyPath = originalKeyPath; config.sslCertChainPath = originalCertChainPath; config.sslTargetNameOverride = originalTargetNameOverride; + config.isResolveDnsPeriodically = originalResolveDns; + delete process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; + delete process.env.SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL; + jest.useRealTimers(); jest.restoreAllMocks(); }); + it('dnsReResolveIntervalMs falls back when seconds overflow the Node timer limit', () => { + process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS = '2592000'; + expect(dnsReResolveIntervalMs()).toBe(30_000); + process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS = '60'; + expect(dnsReResolveIntervalMs()).toBe(60_000); + }); + + it('dnsReResolveIntervalMs rejects non-integer interval strings', () => { + for (const raw of ['1.5', '1e3', '10junk', '-1', '0', '']) { + process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS = raw; + expect(dnsReResolveIntervalMs()).toBe(30_000); + } + }); + it('notifies CONNECTED when channel is READY after boot', () => { const listener = { statusChanged: jest.fn() }; const manager = new GRPCChannelManager(); @@ -199,4 +233,701 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { expect(listener.statusChanged).toHaveBeenCalledWith(GRPCChannelStatus.DISCONNECT); manager.shutdown(); }); + + it('does not call DNS expand when isResolveDnsPeriodically is false', async () => { + const expandSpy = jest.spyOn(BackendAddressResolver, 'expandBackendAddresses'); + config.collectorAddress = 'oap-a:11800,oap-b:11800'; + config.isResolveDnsPeriodically = false; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(expandSpy).not.toHaveBeenCalled(); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///oap-a:11800,oap-b:11800'); + manager.shutdown(); + }); + + it('expands multi-hostname backends when isResolveDnsPeriodically is true', async () => { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + config.secure = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(mockNewBuilder).toHaveBeenCalled(); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.1:11800,10.0.0.2:11800'); + const options = mockWithChannelOptions.mock.calls[0][0]; + expect(options['grpc.default_authority']).toBe('oap-a.svc'); + expect(options['grpc.ssl_target_name_override']).toBe('oap-a.svc'); + manager.shutdown(); + }); + + it('does not set TLS authority overrides when secure is false', async () => { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + config.secure = false; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + const options = mockWithChannelOptions.mock.calls[0][0]; + expect(options['grpc.default_authority']).toBeUndefined(); + expect(options['grpc.ssl_target_name_override']).toBeUndefined(); + manager.shutdown(); + }); + + it('uses sw-static even when DNS expand yields a single IP', async () => { + jest.spyOn(BackendAddressResolver, 'expandBackendAddresses').mockResolvedValue(dnsExpand(['10.0.0.1:11800'])); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.1:11800'); + manager.shutdown(); + }); + + it('starts the DNS timer before the initial expand finishes', async () => { + jest.useFakeTimers(); + let resolveExpand: (value: ReturnType) => void = () => undefined; + jest.spyOn(BackendAddressResolver, 'expandBackendAddresses').mockImplementation( + () => + new Promise((resolve) => { + resolveExpand = resolve; + }), + ); + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + expect(setIntervalSpy).toHaveBeenCalled(); + expect(setIntervalSpy.mock.results[0]?.value?.unref).toEqual(expect.any(Function)); + const handle = setIntervalSpy.mock.results[0]?.value as NodeJS.Timeout; + expect(typeof handle.unref).toBe('function'); + + resolveExpand(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + await flushAsyncWork(); + expect(mockNewBuilder).toHaveBeenCalled(); + manager.shutdown(); + }); + + it('skips overlapping DNS ticks while a refresh is in flight', async () => { + jest.useFakeTimers(); + let resolveFirst: (value: ReturnType) => void = () => undefined; + const expandSpy = jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirst = resolve; + }), + ) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + // Ticks during in-flight expand must not queue a busy-loop of immediate re-resolves. + jest.advanceTimersByTime(30_000); + jest.advanceTimersByTime(30_000); + expect(expandSpy).toHaveBeenCalledTimes(1); + + resolveFirst(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + await flushAsyncWork(); + expect(expandSpy).toHaveBeenCalledTimes(1); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.1:11800,10.0.0.2:11800'); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + expect(expandSpy).toHaveBeenCalledTimes(2); + expect(mockNewBuilder.mock.calls[mockNewBuilder.mock.calls.length - 1][0]).toBe( + 'sw-static:///10.0.0.1:11800,10.0.0.3:11800', + ); + manager.shutdown(); + }); + + it('runs the next DNS refresh on the following interval after in-flight completes', async () => { + jest.useFakeTimers(); + let resolveFirst: (value: ReturnType) => void = () => undefined; + const expandSpy = jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirst = resolve; + }), + ) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.4:11800'])); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + + resolveFirst(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + await flushAsyncWork(); + expect(expandSpy).toHaveBeenCalledTimes(1); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + expect(expandSpy).toHaveBeenCalledTimes(2); + + manager.shutdown(); + }); + + it('rebuilds the channel when periodic DNS re-resolve changes the address set', async () => { + jest.useFakeTimers(); + const expandSpy = jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + mockNewBuilder.mockClear(); + mockShutdownNow.mockClear(); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(expandSpy).toHaveBeenCalledTimes(2); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.1:11800,10.0.0.3:11800'); + expect(mockShutdownNow).toHaveBeenCalled(); + manager.shutdown(); + }); + + it('does not rebuild when periodic DNS re-resolve returns the same set', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + mockNewBuilder.mockClear(); + mockShutdownNow.mockClear(); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(mockNewBuilder).not.toHaveBeenCalled(); + expect(mockShutdownNow).not.toHaveBeenCalled(); + manager.shutdown(); + }); + + it('does not expand DNS for a single hostname even when the flag is true', async () => { + const expandSpy = jest.spyOn(BackendAddressResolver, 'expandBackendAddresses'); + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + config.collectorAddress = 'oap.example.com:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(expandSpy).not.toHaveBeenCalled(); + expect(mockNewBuilder.mock.calls[0][0]).toBe('oap.example.com:11800'); + expect(setIntervalSpy).not.toHaveBeenCalled(); + manager.shutdown(); + }); + + it('does not expand DNS for all-IP multi-address lists when the flag is true', async () => { + const expandSpy = jest.spyOn(BackendAddressResolver, 'expandBackendAddresses'); + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + config.collectorAddress = '10.0.0.1:11800,10.0.0.2:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(expandSpy).not.toHaveBeenCalled(); + expect(setIntervalSpy).not.toHaveBeenCalled(); + manager.shutdown(); + }); + + it('keeps the existing channel when a later DNS expand returns no addresses', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand([])); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + mockNewBuilder.mockClear(); + mockShutdownNow.mockClear(); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(mockNewBuilder).not.toHaveBeenCalled(); + expect(mockShutdownNow).not.toHaveBeenCalled(); + manager.shutdown(); + }); + + it('prefers sslTargetNameOverride over auto DNS authority', async () => { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + config.secure = true; + config.sslTargetNameOverride = 'custom.oap.example'; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + const options = mockWithChannelOptions.mock.calls[0][0]; + expect(options['grpc.default_authority']).toBeUndefined(); + expect(options['grpc.ssl_target_name_override']).toBeUndefined(); + manager.shutdown(); + }); + + it('uses the first hostname in a mixed IP+hostname list as TLS authority', async () => { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + config.collectorAddress = '10.0.0.9:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + config.secure = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + const options = mockWithChannelOptions.mock.calls[0][0]; + expect(options['grpc.default_authority']).toBe('oap-b.svc'); + expect(options['grpc.ssl_target_name_override']).toBe('oap-b.svc'); + manager.shutdown(); + }); + + it('clears the DNS refresh timer on shutdown', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + const clearIntervalSpy = jest.spyOn(global, 'clearInterval'); + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(setIntervalSpy).toHaveBeenCalled(); + const timerHandle = setIntervalSpy.mock.results[0]?.value as NodeJS.Timeout; + expect(typeof timerHandle.unref).toBe('function'); + + manager.shutdown(); + expect(clearIntervalSpy).toHaveBeenCalledWith(timerHandle); + }); + + it('retries open on the next tick after a failed channel build', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + + let buildAttempts = 0; + mockNewBuilder.mockImplementation(() => ({ + withChannelOptions: mockWithChannelOptions, + addManagedChannelBuilder: jest.fn().mockReturnThis(), + addChannelDecorator: jest.fn().mockReturnThis(), + build: jest.fn(() => { + buildAttempts += 1; + if (buildAttempts === 1) { + throw new Error('tls boom'); + } + return { + getChannel: () => ({ + getConnectivityState: mockGetConnectivityState, + watchConnectivityState: mockWatchConnectivityState, + }), + getClientOptions: () => ({ channelOverride: {} }), + isConnected: mockIsConnected, + getConnectivityState: mockGetConnectivityState, + shutdownNow: mockShutdownNow, + }; + }), + })); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(buildAttempts).toBe(1); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + + mockNewBuilder.mockClear(); + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(buildAttempts).toBe(2); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.1:11800,10.0.0.2:11800'); + manager.shutdown(); + }); + + it('keeps the existing channel when a DNS rebuild build fails', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])); + + let buildAttempts = 0; + mockNewBuilder.mockImplementation(() => ({ + withChannelOptions: mockWithChannelOptions, + addManagedChannelBuilder: jest.fn().mockReturnThis(), + addChannelDecorator: jest.fn().mockReturnThis(), + build: jest.fn(() => { + buildAttempts += 1; + if (buildAttempts === 2) { + throw new Error('rebuild boom'); + } + return { + getChannel: () => ({ + getConnectivityState: mockGetConnectivityState, + watchConnectivityState: mockWatchConnectivityState, + }), + getClientOptions: () => ({ channelOverride: {} }), + isConnected: mockIsConnected, + getConnectivityState: mockGetConnectivityState, + shutdownNow: mockShutdownNow, + }; + }), + })); + + const listener = { statusChanged: jest.fn() }; + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.addChannelListener(listener); + manager.boot(); + await flushAsyncWork(); + expect(buildAttempts).toBe(1); + expect(listener.statusChanged).toHaveBeenCalledWith(GRPCChannelStatus.CONNECTED); + listener.statusChanged.mockClear(); + mockShutdownNow.mockClear(); + mockNewBuilder.mockClear(); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + // Failed rebuild must not tear down the working channel or flap listeners. + expect(buildAttempts).toBe(2); + expect(mockShutdownNow).not.toHaveBeenCalled(); + expect(listener.statusChanged).not.toHaveBeenCalled(); + expect(() => manager.getClientOptions()).not.toThrow(); + + mockNewBuilder.mockClear(); + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(buildAttempts).toBe(3); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.1:11800,10.0.0.3:11800'); + expect(listener.statusChanged.mock.calls.map((c) => c[0])).toEqual([ + GRPCChannelStatus.DISCONNECT, + GRPCChannelStatus.CONNECTED, + ]); + manager.shutdown(); + }); + + it('keeps the existing channel when a later DNS expand has partial lookup failure', async () => { + jest.useFakeTimers(); + // Merged dial set unchanged (failed name kept last-known IPs) → no rebuild. + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'], true)); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + mockNewBuilder.mockClear(); + mockShutdownNow.mockClear(); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(mockNewBuilder).not.toHaveBeenCalled(); + expect(mockShutdownNow).not.toHaveBeenCalled(); + expect(manager.getResolvedBackends()).toEqual(['10.0.0.1:11800', '10.0.0.2:11800']); + manager.shutdown(); + }); + + it('rebuilds when a successful name changes IP even if another name fails DNS', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + // oap-a moved to .9; oap-b failed but last-known .2 kept in the merged set. + .mockResolvedValueOnce(dnsExpand(['10.0.0.9:11800', '10.0.0.2:11800'], true)); + + mockIsConnected.mockReturnValue(false); + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.TRANSIENT_FAILURE); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + mockNewBuilder.mockClear(); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(mockNewBuilder).toHaveBeenCalledTimes(1); + expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.9:11800,10.0.0.2:11800'); + manager.shutdown(); + }); + + it('forces DISCONNECT then CONNECTED so listeners drop stubs on DNS rebuild', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])); + + const listener = { statusChanged: jest.fn() }; + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.addChannelListener(listener); + manager.boot(); + await flushAsyncWork(); + expect(listener.statusChanged).toHaveBeenCalledWith(GRPCChannelStatus.CONNECTED); + listener.statusChanged.mockClear(); + + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(listener.statusChanged.mock.calls.map((c) => c[0])).toEqual([ + GRPCChannelStatus.DISCONNECT, + GRPCChannelStatus.CONNECTED, + ]); + manager.shutdown(); + }); + + it('keeps rebuild status-log suppress until async READY after DNS rebuild', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])); + + const watchCallbacks: Array<(error?: Error) => void> = []; + mockWatchConnectivityState.mockImplementation((_state, _deadline, cb: (error?: Error) => void) => { + watchCallbacks.push(cb); + }); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.READY); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(false); + expect(manager.getDnsRefreshCount()).toBe(1); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.CONNECTING); + watchCallbacks.length = 0; + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + + expect(manager.getDnsRefreshCount()).toBe(2); + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(true); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.READY); + const latestWatch = watchCallbacks[watchCallbacks.length - 1]; + expect(latestWatch).toBeDefined(); + latestWatch!(); + await flushAsyncWork(); + + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(false); + manager.shutdown(); + }); + + it('clears rebuild status-log suppress when new channel fails without READY', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])); + + const watchCallbacks: Array<(error?: Error) => void> = []; + mockWatchConnectivityState.mockImplementation((_state, _deadline, cb: (error?: Error) => void) => { + watchCallbacks.push(cb); + }); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.READY); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.CONNECTING); + watchCallbacks.length = 0; + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(true); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.TRANSIENT_FAILURE); + watchCallbacks[watchCallbacks.length - 1]!(); + await flushAsyncWork(); + + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(false); + manager.shutdown(); + }); + + it('honors SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS for the refresh timer', async () => { + jest.useFakeTimers(); + const previousInterval = process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; + process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS = '5'; + try { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 5_000); + manager.shutdown(); + } finally { + if (previousInterval === undefined) { + delete process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; + } else { + process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS = previousInterval; + } + } + }); + + it('honors SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL as a Java-aligned alias', async () => { + jest.useFakeTimers(); + const previousDns = process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; + const previousJava = process.env.SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL; + delete process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; + process.env.SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL = '7'; + try { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + const setIntervalSpy = jest.spyOn(global, 'setInterval'); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 7_000); + manager.shutdown(); + } finally { + if (previousDns === undefined) { + delete process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; + } else { + process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS = previousDns; + } + if (previousJava === undefined) { + delete process.env.SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL; + } else { + process.env.SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL = previousJava; + } + } + }); + + it('exposes resolved IP backends after DNS expand', async () => { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + expect(manager.getResolvedBackends()).toEqual(['10.0.0.1:11800', '10.0.0.2:11800']); + manager.shutdown(); + }); + + it('discards a channel built after shutdown', async () => { + const manager = new GRPCChannelManager(); + let resolveExpand: (value: ReturnType) => void = () => undefined; + jest.spyOn(BackendAddressResolver, 'expandBackendAddresses').mockImplementation( + () => + new Promise((resolve) => { + resolveExpand = resolve; + }), + ); + + mockNewBuilder.mockImplementation(() => ({ + withChannelOptions: mockWithChannelOptions, + addManagedChannelBuilder: jest.fn().mockReturnThis(), + addChannelDecorator: jest.fn().mockReturnThis(), + build: jest.fn(() => { + manager.shutdown(); + return { + getChannel: () => ({ + getConnectivityState: mockGetConnectivityState, + watchConnectivityState: mockWatchConnectivityState, + }), + getClientOptions: () => ({ channelOverride: {} }), + isConnected: mockIsConnected, + getConnectivityState: mockGetConnectivityState, + shutdownNow: mockShutdownNow, + }; + }), + })); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + manager.boot(); + resolveExpand(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + await flushAsyncWork(); + + expect(mockShutdownNow).toHaveBeenCalled(); + expect(() => manager.getClientOptions()).toThrow(/not available/); + }); + + it('does not commit resolved backends when shutdown races after channel install', async () => { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.addChannelListener({ + statusChanged: () => { + // Race during openChannel notify after the channel is installed. + manager.shutdown(); + }, + }); + manager.boot(); + await flushAsyncWork(); + + expect(manager.getResolvedBackends()).toEqual([]); + expect(() => manager.getClientOptions()).toThrow(/not available/); + }); }); From 22d1c0085d84b616034824b78eafb6c8111417b9 Mon Sep 17 00:00:00 2001 From: songzhendong12315 Date: Thu, 17 Sep 2026 15:24:32 +0800 Subject: [PATCH 2/6] fix(grpc): address PR review on DNS expand authority, rebuild logs, DNS throttle Preserve HTTP/2 default_authority after DNS expand on plaintext; emit an outage log when a rebuild replacement never becomes READY; throttle per-lookup DNS errors in BackendAddressResolver. --- .../core/remote/BackendAddressResolver.ts | 8 ++-- src/agent/core/remote/GRPCChannelManager.ts | 31 ++++++++++--- tests/remote/GRPCChannelManager.test.ts | 45 ++++++++++++++++++- 3 files changed, 73 insertions(+), 11 deletions(-) diff --git a/src/agent/core/remote/BackendAddressResolver.ts b/src/agent/core/remote/BackendAddressResolver.ts index d905837f..5217d09c 100644 --- a/src/agent/core/remote/BackendAddressResolver.ts +++ b/src/agent/core/remote/BackendAddressResolver.ts @@ -20,9 +20,11 @@ import * as dns from 'dns'; import * as net from 'net'; import * as grpc from '@grpc/grpc-js'; -import { createLogger } from '../../../logging'; +import { createLogger, throttled } from '../../../logging'; const logger = createLogger(__filename); +const logDnsLookupEmpty = throttled(logger, 'error', 30_000); +const logDnsLookupFailed = throttled(logger, 'error', 30_000); const SW_STATIC_SCHEME = 'sw-static'; @@ -197,7 +199,7 @@ export async function expandBackendAddresses( if (!records.length) { // Same as throw/timeout: incomplete expand must not drop prior endpoints. hadLookupFailure = true; - logger.error(`DNS lookup for backend [${host}] returned no addresses`); + logDnsLookupEmpty(`DNS lookup for backend [${host}] returned no addresses`); const previous = previousByConfigured.get(entry); if (previous?.length) { byConfigured.set(entry, [...previous]); @@ -213,7 +215,7 @@ export async function expandBackendAddresses( appendUnique(endpoints); } catch (error) { hadLookupFailure = true; - logger.error(`Failed to resolve backend [${host}]: ${error}`); + logDnsLookupFailed(`Failed to resolve backend [${host}]`, error); const previous = previousByConfigured.get(entry); if (previous?.length) { byConfigured.set(entry, [...previous]); diff --git a/src/agent/core/remote/GRPCChannelManager.ts b/src/agent/core/remote/GRPCChannelManager.ts index 85c45248..30255613 100644 --- a/src/agent/core/remote/GRPCChannelManager.ts +++ b/src/agent/core/remote/GRPCChannelManager.ts @@ -135,13 +135,16 @@ function nativeChannelOptions(authorityHostname?: string): ChannelOptions { }), }; - // After DNS expand, endpoints are IP literals — under TLS keep SNI/authority on the - // configured hostname unless the operator already set sslTargetNameOverride - // (TLSChannelBuilder wins then). Plaintext does not need an authority override. + // After DNS expand, endpoints are IP literals. Preserve HTTP/2 :authority on the + // configured hostname (plaintext and TLS) so virtual-host proxies still route by name. + // Under TLS also set SNI / ssl_target_name_override unless the operator already set + // sslTargetNameOverride (TLSChannelBuilder wins then). const override = config.sslTargetNameOverride?.trim(); - if (config.secure && !override && authorityHostname) { + if (authorityHostname && !override) { options['grpc.default_authority'] = authorityHostname; - options['grpc.ssl_target_name_override'] = authorityHostname; + if (config.secure) { + options['grpc.ssl_target_name_override'] = authorityHostname; + } } return options; @@ -532,9 +535,14 @@ export default class GRPCChannelManager implements BootService { return; } // Rebuild quiet window ends if the new channel leaves CONNECTING without READY - // (IDLE / TRANSIENT_FAILURE / SHUTDOWN) so later recover logs are not muted forever. + // (IDLE / TRANSIENT_FAILURE / SHUTDOWN). The intentional rebuild already set + // lastStatus=DISCONNECT with logs suppressed; notify(DISCONNECT) would no-op, so + // emit the real outage diagnostic here. if (this.suppressDnsRebuildStatusLog) { this.suppressDnsRebuildStatusLog = false; + if (this.lastStatus === GRPCChannelStatus.DISCONNECT) { + this.logDnsRebuildFailedToConnect(); + } } // READY→IDLE is grpc-js's normal path after the active connection drops. if (state === grpc.connectivityState.IDLE) { @@ -590,4 +598,15 @@ export default class GRPCChannelManager implements BootService { logChannelRecovered(`gRPC channel recovered; connected to backends [${backends}]`); } } + + /** Outage log when a DNS rebuild replacement never becomes READY (status already DISCONNECT). */ + private logDnsRebuildFailedToConnect(): void { + if (this.closed) { + return; + } + const backends = this.configuredServers.join(',') || this.grpcServers.join(',') || config.collectorAddress || ''; + logChannelDisconnected( + `gRPC channel not connected to backends [${backends}] after DNS rebuild; connecting with exponential backoff`, + ); + } } diff --git a/tests/remote/GRPCChannelManager.test.ts b/tests/remote/GRPCChannelManager.test.ts index 8a64cfcc..bdbb428e 100644 --- a/tests/remote/GRPCChannelManager.test.ts +++ b/tests/remote/GRPCChannelManager.test.ts @@ -264,7 +264,7 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.shutdown(); }); - it('does not set TLS authority overrides when secure is false', async () => { + it('preserves HTTP/2 default_authority on plaintext after DNS expand', async () => { jest .spyOn(BackendAddressResolver, 'expandBackendAddresses') .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); @@ -275,7 +275,7 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.boot(); await flushAsyncWork(); const options = mockWithChannelOptions.mock.calls[0][0]; - expect(options['grpc.default_authority']).toBeUndefined(); + expect(options['grpc.default_authority']).toBe('oap-a.svc'); expect(options['grpc.ssl_target_name_override']).toBeUndefined(); manager.shutdown(); }); @@ -801,6 +801,47 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.shutdown(); }); + it('logs an outage when DNS rebuild replacement stays in TRANSIENT_FAILURE', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])); + + const watchCallbacks: Array<(error?: Error) => void> = []; + mockWatchConnectivityState.mockImplementation((_state, _deadline, cb: (error?: Error) => void) => { + watchCallbacks.push(cb); + }); + + const outageSpy = jest.spyOn( + GRPCChannelManager.prototype as unknown as { logDnsRebuildFailedToConnect: () => void }, + 'logDnsRebuildFailedToConnect', + ); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.READY); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.CONNECTING); + watchCallbacks.length = 0; + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(true); + expect(outageSpy).not.toHaveBeenCalled(); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.TRANSIENT_FAILURE); + watchCallbacks[watchCallbacks.length - 1]!(); + await flushAsyncWork(); + + expect(outageSpy).toHaveBeenCalled(); + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(false); + outageSpy.mockRestore(); + manager.shutdown(); + }); + it('honors SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS for the refresh timer', async () => { jest.useFakeTimers(); const previousInterval = process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; From 737f745043c61fe9ff6b88989d899e6a849dc62c Mon Sep 17 00:00:00 2001 From: songzhendong12315 Date: Thu, 17 Sep 2026 15:34:43 +0800 Subject: [PATCH 3/6] fix(grpc): close DNS expand authority and rebuild-log edge cases Keep plaintext default_authority when a TLS-only sslTargetNameOverride is set; retain rebuild status-log suppress across consecutive rebuilds while already DISCONNECT so failed replacements still emit an outage log. --- src/agent/core/remote/GRPCChannelManager.ts | 18 ++++-- tests/remote/GRPCChannelManager.test.ts | 66 +++++++++++++++++++++ 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/src/agent/core/remote/GRPCChannelManager.ts b/src/agent/core/remote/GRPCChannelManager.ts index 30255613..9acb38cf 100644 --- a/src/agent/core/remote/GRPCChannelManager.ts +++ b/src/agent/core/remote/GRPCChannelManager.ts @@ -138,12 +138,17 @@ function nativeChannelOptions(authorityHostname?: string): ChannelOptions { // After DNS expand, endpoints are IP literals. Preserve HTTP/2 :authority on the // configured hostname (plaintext and TLS) so virtual-host proxies still route by name. // Under TLS also set SNI / ssl_target_name_override unless the operator already set - // sslTargetNameOverride (TLSChannelBuilder wins then). + // sslTargetNameOverride (TLSChannelBuilder wins then). A TLS-only override must not + // skip plaintext default_authority — TLSChannelBuilder ignores it when secure=false. const override = config.sslTargetNameOverride?.trim(); - if (authorityHostname && !override) { - options['grpc.default_authority'] = authorityHostname; + if (authorityHostname) { if (config.secure) { - options['grpc.ssl_target_name_override'] = authorityHostname; + if (!override) { + options['grpc.default_authority'] = authorityHostname; + options['grpc.ssl_target_name_override'] = authorityHostname; + } + } else { + options['grpc.default_authority'] = authorityHostname; } } @@ -476,6 +481,11 @@ export default class GRPCChannelManager implements BootService { this.suppressDnsRebuildStatusLog = false; throw error; } + } else if (this.lastStatus === GRPCChannelStatus.DISCONNECT) { + // Already DISCONNECT (e.g. prior rebuild still CONNECTING). Keep the quiet window so + // a later TRANSIENT_FAILURE can emit logDnsRebuildFailedToConnect instead of a + // deduped no-op notify(DISCONNECT). + this.suppressDnsRebuildStatusLog = true; } else { this.suppressDnsRebuildStatusLog = false; } diff --git a/tests/remote/GRPCChannelManager.test.ts b/tests/remote/GRPCChannelManager.test.ts index bdbb428e..16b65ec7 100644 --- a/tests/remote/GRPCChannelManager.test.ts +++ b/tests/remote/GRPCChannelManager.test.ts @@ -280,6 +280,23 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.shutdown(); }); + it('keeps plaintext default_authority even when a TLS-only sslTargetNameOverride is set', async () => { + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValue(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + config.secure = false; + config.sslTargetNameOverride = 'custom.oap.example'; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + const options = mockWithChannelOptions.mock.calls[0][0]; + expect(options['grpc.default_authority']).toBe('oap-a.svc'); + expect(options['grpc.ssl_target_name_override']).toBeUndefined(); + manager.shutdown(); + }); + it('uses sw-static even when DNS expand yields a single IP', async () => { jest.spyOn(BackendAddressResolver, 'expandBackendAddresses').mockResolvedValue(dnsExpand(['10.0.0.1:11800'])); config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; @@ -842,6 +859,55 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.shutdown(); }); + it('logs an outage when a second DNS rebuild fails while already DISCONNECT', async () => { + jest.useFakeTimers(); + jest + .spyOn(BackendAddressResolver, 'expandBackendAddresses') + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.2:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.3:11800'])) + .mockResolvedValueOnce(dnsExpand(['10.0.0.1:11800', '10.0.0.4:11800'])); + + const watchCallbacks: Array<(error?: Error) => void> = []; + mockWatchConnectivityState.mockImplementation((_state, _deadline, cb: (error?: Error) => void) => { + watchCallbacks.push(cb); + }); + + const outageSpy = jest.spyOn( + GRPCChannelManager.prototype as unknown as { logDnsRebuildFailedToConnect: () => void }, + 'logDnsRebuildFailedToConnect', + ); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.READY); + config.collectorAddress = 'oap-a.svc:11800,oap-b.svc:11800'; + config.isResolveDnsPeriodically = true; + const manager = new GRPCChannelManager(); + manager.boot(); + await flushAsyncWork(); + + // First rebuild: CONNECTED → quiet DISCONNECT, stuck in CONNECTING. + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.CONNECTING); + watchCallbacks.length = 0; + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + expect((manager as unknown as { lastStatus: GRPCChannelStatus }).lastStatus).toBe(GRPCChannelStatus.DISCONNECT); + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(true); + expect(outageSpy).not.toHaveBeenCalled(); + + // Second rebuild while still DISCONNECT/CONNECTING; replacement then fails. + watchCallbacks.length = 0; + jest.advanceTimersByTime(30_000); + await flushAsyncWork(); + expect((manager as unknown as { suppressDnsRebuildStatusLog: boolean }).suppressDnsRebuildStatusLog).toBe(true); + + mockGetConnectivityState.mockReturnValue(grpc.connectivityState.TRANSIENT_FAILURE); + watchCallbacks[watchCallbacks.length - 1]!(); + await flushAsyncWork(); + + expect(outageSpy).toHaveBeenCalled(); + outageSpy.mockRestore(); + manager.shutdown(); + }); + it('honors SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS for the refresh timer', async () => { jest.useFakeTimers(); const previousInterval = process.env.SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS; From a11b7a8c8f55c25396fd3315998a83a81aad37e0 Mon Sep 17 00:00:00 2001 From: songzhendong12315 Date: Thu, 17 Sep 2026 23:01:51 +0800 Subject: [PATCH 4/6] fix(grpc): keep host:port in HTTP/2 authority after DNS expand Split DnsAuthority into host:port for grpc.default_authority and hostname-only for TLS SNI, matching sw-static pre-expand authority. --- .../core/remote/BackendAddressResolver.ts | 21 +++++++++--- src/agent/core/remote/GRPCChannelManager.ts | 32 +++++++++---------- tests/remote/BackendAddressResolver.test.ts | 12 +++++-- tests/remote/GRPCChannelManager.test.ts | 8 ++--- 4 files changed, 45 insertions(+), 28 deletions(-) diff --git a/src/agent/core/remote/BackendAddressResolver.ts b/src/agent/core/remote/BackendAddressResolver.ts index 5217d09c..e44d713c 100644 --- a/src/agent/core/remote/BackendAddressResolver.ts +++ b/src/agent/core/remote/BackendAddressResolver.ts @@ -243,14 +243,25 @@ export function sameAddressSet(a: string[], b: string[]): boolean { } /** - * First non-IP hostname in the configured list — used as TLS authority after - * expanding backends to IP literals (e.g. `10.0.0.1:11800,oap-b.svc:11800`). + * First non-IP hostname in the configured list — used after expanding backends to IP + * literals (e.g. `10.0.0.1:11800,oap-b.svc:11800`). + * + * `authority` keeps host:port for HTTP/2 `:authority` (proxies may match on port). + * `serverName` is hostname-only for TLS SNI / ssl_target_name_override. */ -export function firstHostnameAuthority(addresses: string[]): string | undefined { +export type DnsAuthority = { + authority: string; + serverName: string; +}; + +export function firstHostnameAuthority(addresses: string[]): DnsAuthority | undefined { for (const entry of addresses) { const parsed = grpc.experimental.splitHostPort(entry); - if (parsed?.host && !isIpLiteral(parsed.host)) { - return parsed.host; + if (parsed?.host && parsed.port != null && !isIpLiteral(parsed.host)) { + return { + authority: formatHostPort(parsed.host, parsed.port), + serverName: parsed.host, + }; } } return undefined; diff --git a/src/agent/core/remote/GRPCChannelManager.ts b/src/agent/core/remote/GRPCChannelManager.ts index 9acb38cf..5aa63530 100644 --- a/src/agent/core/remote/GRPCChannelManager.ts +++ b/src/agent/core/remote/GRPCChannelManager.ts @@ -25,6 +25,7 @@ import AgentIDDecorator from './AgentIDDecorator'; import AuthenticationDecorator from './AuthenticationDecorator'; import { buildNativeGrpcTarget, + DnsAuthority, expandBackendAddresses, firstHostnameAuthority, parseStaticBackendAddresses, @@ -99,7 +100,7 @@ function isGrpcNetworkError(error: unknown): boolean { ); } -function nativeChannelOptions(authorityHostname?: string): ChannelOptions { +function nativeChannelOptions(dnsAuthority?: DnsAuthority): ChannelOptions { // No gRPC keepalive: stock OAP (grpc-java) rejects frequent idle pings with GOAWAY // ENHANCE_YOUR_CALM. Agent traffic (trace/heartbeat/metrics) provides liveness. // @@ -135,20 +136,19 @@ function nativeChannelOptions(authorityHostname?: string): ChannelOptions { }), }; - // After DNS expand, endpoints are IP literals. Preserve HTTP/2 :authority on the - // configured hostname (plaintext and TLS) so virtual-host proxies still route by name. - // Under TLS also set SNI / ssl_target_name_override unless the operator already set - // sslTargetNameOverride (TLSChannelBuilder wins then). A TLS-only override must not - // skip plaintext default_authority — TLSChannelBuilder ignores it when secure=false. + // After DNS expand, endpoints are IP literals. Preserve HTTP/2 :authority as host:port + // (plaintext and TLS) so virtual-host proxies that match on port still route correctly. + // TLS SNI uses hostname-only. Operator sslTargetNameOverride (TLSChannelBuilder) wins + // for both when set under secure=true; a TLS-only override must not skip plaintext authority. const override = config.sslTargetNameOverride?.trim(); - if (authorityHostname) { + if (dnsAuthority) { if (config.secure) { if (!override) { - options['grpc.default_authority'] = authorityHostname; - options['grpc.ssl_target_name_override'] = authorityHostname; + options['grpc.default_authority'] = dnsAuthority.authority; + options['grpc.ssl_target_name_override'] = dnsAuthority.serverName; } } else { - options['grpc.default_authority'] = authorityHostname; + options['grpc.default_authority'] = dnsAuthority.authority; } } @@ -182,8 +182,8 @@ export default class GRPCChannelManager implements BootService { * next tick even if the resolved address set is unchanged. */ private dnsOpenNeedsRetry = false; - /** Hostname authority when dialing expanded IPs under TLS. */ - private dnsAuthorityHostname: string | undefined; + /** HTTP/2 authority + TLS SNI when dialing DNS-expanded IP endpoints. */ + private dnsAuthority: DnsAuthority | undefined; /** True while dialing addresses produced by expandBackendAddresses (always sw-static). */ private dialingExpandedAddresses = false; /** Skip status transition logs for intentional DISCONNECT→CONNECTED during DNS rebuild. */ @@ -272,7 +272,7 @@ export default class GRPCChannelManager implements BootService { this.closed = false; this.lastConnectivityState = null; this.stopDnsRefreshTimer(); - this.dnsAuthorityHostname = undefined; + this.dnsAuthority = undefined; this.dnsRefreshInFlight = false; this.dnsOpenNeedsRetry = false; this.dialingExpandedAddresses = false; @@ -296,7 +296,7 @@ export default class GRPCChannelManager implements BootService { this.grpcServers = [...parsed]; if (config.isResolveDnsPeriodically && shouldExpandBackendDns(parsed)) { - this.dnsAuthorityHostname = firstHostnameAuthority(parsed); + this.dnsAuthority = firstHostnameAuthority(parsed); // Start the timer immediately so a hung initial lookup cannot block later retries. this.startDnsRefreshTimer(); void this.refreshResolvedBackends(true).catch((error) => { @@ -321,7 +321,7 @@ export default class GRPCChannelManager implements BootService { this.configuredServers = []; this.grpcServers = []; this.lastResolvedByConfigured = new Map(); - this.dnsAuthorityHostname = undefined; + this.dnsAuthority = undefined; this.dialingExpandedAddresses = false; this.dnsOpenNeedsRetry = false; this.suppressDnsRebuildStatusLog = false; @@ -443,7 +443,7 @@ export default class GRPCChannelManager implements BootService { let built: GRPCChannel; try { built = GRPCChannel.newBuilder(target) - .withChannelOptions(nativeChannelOptions(this.dnsAuthorityHostname)) + .withChannelOptions(nativeChannelOptions(this.dnsAuthority)) .addManagedChannelBuilder(new StandardChannelBuilder()) .addManagedChannelBuilder(new TLSChannelBuilder()) .addChannelDecorator(new AgentIDDecorator()) diff --git a/tests/remote/BackendAddressResolver.test.ts b/tests/remote/BackendAddressResolver.test.ts index 7c0047b1..224b7b9a 100644 --- a/tests/remote/BackendAddressResolver.test.ts +++ b/tests/remote/BackendAddressResolver.test.ts @@ -89,9 +89,15 @@ describe('BackendAddressResolver (comma-separated static backends)', () => { expect(sameAddressSet(['a:1'], ['a:1', 'b:1'])).toBe(false); }); - it('firstHostnameAuthority returns the first non-IP host in the list', () => { - expect(firstHostnameAuthority(['oap-a.svc:11800', 'oap-b.svc:11800'])).toBe('oap-a.svc'); - expect(firstHostnameAuthority(['10.0.0.1:11800', 'oap-b.svc:11800'])).toBe('oap-b.svc'); + it('firstHostnameAuthority returns host:port authority and hostname-only SNI name', () => { + expect(firstHostnameAuthority(['oap-a.svc:11800', 'oap-b.svc:11800'])).toEqual({ + authority: 'oap-a.svc:11800', + serverName: 'oap-a.svc', + }); + expect(firstHostnameAuthority(['10.0.0.1:11800', 'oap-b.svc:11800'])).toEqual({ + authority: 'oap-b.svc:11800', + serverName: 'oap-b.svc', + }); expect(firstHostnameAuthority(['10.0.0.1:11800', '10.0.0.2:11800'])).toBeUndefined(); }); diff --git a/tests/remote/GRPCChannelManager.test.ts b/tests/remote/GRPCChannelManager.test.ts index 16b65ec7..88e402a1 100644 --- a/tests/remote/GRPCChannelManager.test.ts +++ b/tests/remote/GRPCChannelManager.test.ts @@ -259,7 +259,7 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { expect(mockNewBuilder).toHaveBeenCalled(); expect(mockNewBuilder.mock.calls[0][0]).toBe('sw-static:///10.0.0.1:11800,10.0.0.2:11800'); const options = mockWithChannelOptions.mock.calls[0][0]; - expect(options['grpc.default_authority']).toBe('oap-a.svc'); + expect(options['grpc.default_authority']).toBe('oap-a.svc:11800'); expect(options['grpc.ssl_target_name_override']).toBe('oap-a.svc'); manager.shutdown(); }); @@ -275,7 +275,7 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.boot(); await flushAsyncWork(); const options = mockWithChannelOptions.mock.calls[0][0]; - expect(options['grpc.default_authority']).toBe('oap-a.svc'); + expect(options['grpc.default_authority']).toBe('oap-a.svc:11800'); expect(options['grpc.ssl_target_name_override']).toBeUndefined(); manager.shutdown(); }); @@ -292,7 +292,7 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.boot(); await flushAsyncWork(); const options = mockWithChannelOptions.mock.calls[0][0]; - expect(options['grpc.default_authority']).toBe('oap-a.svc'); + expect(options['grpc.default_authority']).toBe('oap-a.svc:11800'); expect(options['grpc.ssl_target_name_override']).toBeUndefined(); manager.shutdown(); }); @@ -526,7 +526,7 @@ describe('GRPCChannelManager (native grpc-js multi-backend failover)', () => { manager.boot(); await flushAsyncWork(); const options = mockWithChannelOptions.mock.calls[0][0]; - expect(options['grpc.default_authority']).toBe('oap-b.svc'); + expect(options['grpc.default_authority']).toBe('oap-b.svc:11800'); expect(options['grpc.ssl_target_name_override']).toBe('oap-b.svc'); manager.shutdown(); }); From bd4bc2dad835bbd425305da9a7dc57e517a93654 Mon Sep 17 00:00:00 2001 From: songzhendong12315 Date: Thu, 17 Sep 2026 23:19:08 +0800 Subject: [PATCH 5/6] fix(grpc): drop sw-static resolver results after channel destroy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ignore updateResolution and pending nextTick deliveries once destroy() runs so boot→immediate shutdown cannot reconnect a closed channel. --- .../core/remote/BackendAddressResolver.ts | 11 +++++++-- tests/remote/BackendAddressResolver.test.ts | 24 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/agent/core/remote/BackendAddressResolver.ts b/src/agent/core/remote/BackendAddressResolver.ts index e44d713c..0252c84b 100644 --- a/src/agent/core/remote/BackendAddressResolver.ts +++ b/src/agent/core/remote/BackendAddressResolver.ts @@ -297,6 +297,7 @@ function ensureSwStaticResolverRegistered(): void { private readonly endpoints: grpc.experimental.Endpoint[]; private readonly error: { code: number; details: string; metadata: grpc.Metadata } | null; private hasReturnedResult = false; + private destroyed = false; constructor( target: grpc.experimental.GrpcUri, @@ -337,11 +338,17 @@ function ensureSwStaticResolverRegistered(): void { } updateResolution(): void { - if (this.hasReturnedResult) { + // Channel.close() calls destroy() then may still invoke updateResolution; ignore both. + if (this.destroyed || this.hasReturnedResult) { return; } this.hasReturnedResult = true; process.nextTick(() => { + // Drop results scheduled before destroy — otherwise grpc-js reconnects after close + // (boot→immediate shutdown race) while the manager has already dropped the channel. + if (this.destroyed) { + return; + } if (this.error) { this.listener(statusOrFromError(this.error), {}, null, ''); } else { @@ -351,7 +358,7 @@ function ensureSwStaticResolverRegistered(): void { } destroy(): void { - this.hasReturnedResult = false; + this.destroyed = true; } static getDefaultAuthority(target: grpc.experimental.GrpcUri): string { diff --git a/tests/remote/BackendAddressResolver.test.ts b/tests/remote/BackendAddressResolver.test.ts index 224b7b9a..07ae6a56 100644 --- a/tests/remote/BackendAddressResolver.test.ts +++ b/tests/remote/BackendAddressResolver.test.ts @@ -19,6 +19,8 @@ /* eslint-env jest */ +import * as net from 'net'; +import * as grpc from '@grpc/grpc-js'; import { buildNativeGrpcTarget, expandBackendAddresses, @@ -70,6 +72,28 @@ describe('BackendAddressResolver (comma-separated static backends)', () => { expect(buildNativeGrpcTarget(['10.0.0.1:11800'], { forceStatic: true })).toBe('sw-static:///10.0.0.1:11800'); }); + it('sw-static does not reconnect after channel close before resolver nextTick', async () => { + let accepts = 0; + const server = net.createServer((socket) => { + accepts += 1; + socket.end(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const port = (server.address() as net.AddressInfo).port; + const target = buildNativeGrpcTarget([`127.0.0.1:${port}`, `127.0.0.1:${port}`]); + + const channel = new grpc.Channel(target, grpc.credentials.createInsecure(), {}); + // Kick resolution, then close before the resolver's process.nextTick delivers endpoints. + channel.getConnectivityState(true); + channel.close(); + expect(channel.getConnectivityState(false)).toBe(grpc.connectivityState.SHUTDOWN); + + await new Promise((resolve) => setTimeout(resolve, 150)); + expect(accepts).toBe(0); + expect(channel.getConnectivityState(false)).toBe(grpc.connectivityState.SHUTDOWN); + await new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve()))); + }); + it('detects IP literals', () => { expect(isIpLiteral('10.0.0.1')).toBe(true); expect(isIpLiteral('::1')).toBe(true); From 3098e7e66e7967d2304e628170cd9d09590995eb Mon Sep 17 00:00:00 2001 From: songzhendong12315 Date: Thu, 17 Sep 2026 23:23:24 +0800 Subject: [PATCH 6/6] fix(grpc): dedupe in-flight DNS lookups across expand ticks Reuse the pending getaddrinfo promise per hostname so a 5s wait timeout cannot stack another libc query on every periodic tick. --- .../core/remote/BackendAddressResolver.ts | 41 +++++++++++++++++-- tests/remote/BackendAddressResolver.test.ts | 22 ++++++++++ 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/src/agent/core/remote/BackendAddressResolver.ts b/src/agent/core/remote/BackendAddressResolver.ts index 0252c84b..dcbd79f5 100644 --- a/src/agent/core/remote/BackendAddressResolver.ts +++ b/src/agent/core/remote/BackendAddressResolver.ts @@ -38,16 +38,49 @@ const defaultDnsLookupAll: DnsLookupAll = (hostname) => dns.promises.lookup(host /** Per-hostname DNS lookup deadline (ms). Hung lookups fail open to the next name / tick. */ export const DNS_LOOKUP_TIMEOUT_MS = 5_000; +/** + * In-flight getaddrinfo cannot be cancelled after the wait timeout. Deduplicate by + * (lookup, hostname) so periodic ticks reuse the same pending query instead of + * stacking libc/thread-pool work under slow DNS. + */ +const inflightLookups = new WeakMap< + DnsLookupAll, + Map>> +>(); + +function inflightMapFor( + lookup: DnsLookupAll, +): Map>> { + let map = inflightLookups.get(lookup); + if (!map) { + map = new Map(); + inflightLookups.set(lookup, map); + } + return map; +} + async function lookupWithTimeout( hostname: string, lookup: DnsLookupAll, timeoutMs: number = DNS_LOOKUP_TIMEOUT_MS, ): Promise> { + const inflight = inflightMapFor(lookup); + let lookupPromise = inflight.get(hostname); + if (!lookupPromise) { + lookupPromise = lookup(hostname); + inflight.set(hostname, lookupPromise); + // Keep a rejection handler so a late failure after timeout does not surface as + // an unhandledRejection; drop the map entry once the underlying query settles. + void lookupPromise + .finally(() => { + if (inflight.get(hostname) === lookupPromise) { + inflight.delete(hostname); + } + }) + .catch(() => undefined); + } + let timer: NodeJS.Timeout | undefined; - // Keep a rejection handler so a late failure after timeout does not surface as - // an unhandledRejection (dns.lookup/getaddrinfo cannot be cancelled). - const lookupPromise = lookup(hostname); - void lookupPromise.catch(() => undefined); try { return await Promise.race([ lookupPromise, diff --git a/tests/remote/BackendAddressResolver.test.ts b/tests/remote/BackendAddressResolver.test.ts index 07ae6a56..90dd1985 100644 --- a/tests/remote/BackendAddressResolver.test.ts +++ b/tests/remote/BackendAddressResolver.test.ts @@ -201,6 +201,28 @@ describe('BackendAddressResolver (comma-separated static backends)', () => { expect(lookup).toHaveBeenCalledWith('hung'); }, 20000); + it('reuses an in-flight hung lookup across expand ticks instead of stacking queries', async () => { + const lookup = jest.fn( + () => + new Promise>(() => { + /* never resolves */ + }), + ); + + const first = await expandBackendAddresses(['hung:11800'], lookup); + expect(first.hadLookupFailure).toBe(true); + expect(lookup).toHaveBeenCalledTimes(1); + + const second = await expandBackendAddresses(['hung:11800'], lookup); + expect(second.hadLookupFailure).toBe(true); + // getaddrinfo cannot be cancelled; still must not start a second libc query. + expect(lookup).toHaveBeenCalledTimes(1); + + const third = await expandBackendAddresses(['hung:11800'], lookup); + expect(third.hadLookupFailure).toBe(true); + expect(lookup).toHaveBeenCalledTimes(1); + }, 30000); + it('does not surface unhandledRejection when lookup fails after timeout', async () => { const unhandled: unknown[] = []; const onUnhandled = (reason: unknown) => {