Skip to content

feat(grpc): optional multi-backend DNS expand and periodic re-resolve - #147

Open
songzhendong wants to merge 6 commits into
apache:masterfrom
songzhendong:feature/multi-backend-dns-re-resolve
Open

songzhendong wants to merge 6 commits into
apache:masterfrom
songzhendong:feature/multi-backend-dns-re-resolve

Conversation

@songzhendong

@songzhendong songzhendong commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add optional multi-backend DNS expand and periodic re-resolve for comma-separated OAP collector addresses.

  • Opt-in via SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY / isResolveDnsPeriodically (default false). Also accepts SW_AGENT_COLLECTOR_IS_RESOLVE_DNS_PERIODICALLY.
  • When enabled and the collector list has multiple entries including hostnames: expand each name to A/AAAA (5s per-name lookup timeout), dial via sw-static, re-resolve on an interval (default 30s; override with SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS, also accepts SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL).
  • Rebuild the gRPC channel only when the merged dial set changes; retry open on later ticks if no channel is installed yet.
  • Failed names keep last-known endpoints so partial DNS outages neither shrink a healthy channel nor block recovery when another name's IPs change.
  • Single-address targets and all-IP multi-address lists are unchanged (no new timer). Default path is unaffected when the flag is off.
  • Unit tests + remote e2e (tests/remote-e2e/dns-periodic/) + CI job TestRemoteE2EDnsPeriodic.

New / related configuration

Environment variable agent.start() option Default Description
SW_AGENT_IS_RESOLVE_DNS_PERIODICALLY isResolveDnsPeriodically false Enable multi-name DNS expand + periodic re-resolve
SW_AGENT_DNS_RE_RESOLVE_INTERVAL_SECONDS — 30 Re-resolve interval (seconds); invalid / overflow → 30

Bugs fixed during review (by severity)

No P0 defects were left open on tip. Issues below were found in review of this feature and fixed before merge.

P1

ID Issue Fix
P1-1 DNS rebuild while status stayed CONNECTED did not force listener teardown; Trace/Meter/Management kept stubs on the shut-down channel Force DISCONNECT → CONNECTED on rebuild so listeners recreate stubs

P2

ID Issue Fix
P2-1 Overlapping timer ticks could queue concurrent resolves / busy-loop under slow DNS Skip ticks while a resolve is already in flight
P2-2 Empty expand could tear down a working channel Keep previous channel when expand returns no addresses
P2-3 Channel build/target failure on rebuild notified DISCONNECT even with a usable prior channel Keep prior channel; retry open on the next tick
P2-4 Partial DNS (timeout / ENOTFOUND) used success-only endpoints and could shrink the dial set / flap Track per-configured-name last-known endpoints; merge into dial set
P2-5 Empty A/AAAA ([], no throw) did not count as incomplete expand → same shrink/flap class Treat empty records like lookup failure and keep previous endpoints for that name
P2-6 Skipping rebuild whenever a channel object existed under incomplete DNS blocked recovery while the channel was in TRANSIENT_FAILURE and another name's IP changed Rebuild when the merged set changes (keeps last-known for failed names)
P2-7 Intentional rebuild DISCONNECT→CONNECTED spam / mute window wrong for async READY Suppress status logs until CONNECTED (or clear if CONNECTING → non-READY)
P2-8 Hung DNS lookup could stall forever; late rejection after timeout → unhandledRejection 5s per-name timeout; swallow late rejection
P2-9 Sustained incomplete/empty DNS logged every tick at default warn/error Throttle incomplete/empty DNS logs (30s)

P3

ID Issue Fix
P3-1 Very large re-resolve interval overflows Node's 32-bit timer → effective 1ms refresh Fall back to 30s when seconds * 1000 > 2^31-1
P3-2 parseInt accepted 1.5 / 1e3 / 10junk despite docs saying invalid → 30 Require the whole value to match /^\d+$/
P3-3 Docs unit-test command omitted /tests/remote-e2e/ ignore (would pull in Docker e2e) Align build-and-test.md with CI ignore patterns
P3-4 Single-address docs said "periodically re-resolved" (easy to confuse with the new timer) Clarify grpc-js re-resolves on demand, not on a fixed agent timer

Test plan

  • Unit: tests/remote/BackendAddressResolver.test.ts, tests/remote/GRPCChannelManager.test.ts
  • Remote e2e: tests/remote-e2e/dns-periodic/ (multi-IP via socat; interval / rebuild proof)
  • CI: TestRemoteE2EDnsPeriodic on Node 20/22/24
  • Default path: flag unset → no expand timer; single host:port still grpc-js dns:
  • Partial DNS: one name fails, other changes IP → merged set rebuilds; healthy channel does not shrink on blip
  • Interval: overflow / 1.5 / 1e3 / 10junk → stay 30s

Notes for reviewers

  • Feature is opt-in; stock single-backend and flag-off multi-backend behavior is unchanged.
  • Periodic re-resolve runs while the channel is connected so multi-name sw-static targets can pick up DNS changes without waiting for a disconnect.
  • TLS authority after expand: first hostname in the configured list (not an earlier IP literal).

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.
@wu-sheng wu-sheng added this to the 0.10.0 milestone Sep 16, 2026
@wu-sheng wu-sheng added the enhancement New feature or request label Sep 16, 2026
@wu-sheng

Copy link
Copy Markdown
Member

Reviewed commit 168d7d0063bdf82e83cd8be6a3b66aca4f74d8bc. I found three issues in the opt-in multi-address DNS path:

  1. [P2] Preserve HTTP/2 authority for plaintext connections. In GRPCChannelManager.ts:138–145, grpc.default_authority is preserved only when TLS is enabled. Plaintext HTTP/2 also uses :authority for virtual-host routing. With DNS expansion enabled, it changes from the configured hostname to the first resolved IP, so a proxy routing by hostname can reject all reporting RPCs. A local gRPC reproduction with authority-based routing succeeded with expansion disabled (localhost:port) and returned UNIMPLEMENTED when enabled (127.0.0.1:port). Please preserve the configured HTTP/2 authority independently of the TLS/SNI override.

  2. [P2] Log actual connection failure after a DNS rebuild. In GRPCChannelManager.ts:534–551, clearing suppressDnsRebuildStatusLog does not restore outage logging. The intentional rebuild already set lastStatus to DISCONNECT while suppressing its log. If the replacement subsequently reaches TRANSIENT_FAILURE, notify(DISCONNECT) returns at the deduplication check without logging. I reproduced a working connection being replaced with an unreachable endpoint, reaching TRANSIENT_FAILURE with zero warning/error logs. Please emit the actual failure diagnostic even when the listener status is already DISCONNECT.

  3. [P3] Throttle the resolver-level DNS errors too. BackendAddressResolver.ts:195–216 logs each failed or empty lookup directly through logger.error. The manager's throttled incomplete/empty summary does not suppress these messages. With a one-second refresh interval, a persistently failing hostname still generates 60 errors per minute. Repeated failed lookups reproduced one error per invocation. Please throttle these messages as well.

Validation: all 81 remote unit tests passed, and the changed source files passed ESLint. The local gRPC checks above reproduced the routing and missing-outage-log issues; an active streaming RPC survived channel replacement in the focused check. Docker/OAP e2e was not validated locally.

…NS 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.
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.
Split DnsAuthority into host:port for grpc.default_authority and
hostname-only for TLS SNI, matching sw-static pre-expand authority.
Ignore updateResolution and pending nextTick deliveries once destroy()
runs so boot→immediate shutdown cannot reconnect a closed channel.
Reuse the pending getaddrinfo promise per hostname so a 5s wait timeout
cannot stack another libc query on every periodic tick.
@songzhendong

Copy link
Copy Markdown
Contributor Author

Thanks for the review. We verified the reported issues and fixed them, plus a few follow-up edge cases found while hardening the same paths.

Fixes for review comments

Severity Issue Fix
P2 Plaintext DNS expand omitted grpc.default_authority (only set under TLS) Set HTTP/2 default_authority for plaintext and TLS; ssl_target_name_override only when secure
P2 DNS rebuild quiet DISCONNECT + status dedupe hid a real outage when the replacement stayed in TRANSIENT_FAILURE Emit an explicit outage log when clearing rebuild suppress if status is already DISCONNECT
P3 Per-lookup DNS errors in BackendAddressResolver were unthrottled Throttle empty/failed lookup logs (30s)

Follow-up bugs found and fixed

Severity Issue Fix
P2 Leftover sslTargetNameOverride with secure=false skipped plaintext default_authority TLS-only override no longer gates plaintext authority
P2 A second DNS rebuild while already DISCONNECT/CONNECTING cleared suppress and could miss the outage log Keep rebuild suppress across consecutive rebuilds while already DISCONNECT
P2 After DNS expand, plaintext :authority dropped the port (oap-a.svc:11800 → oap-a.svc) Split DnsAuthority: host:port for grpc.default_authority, hostname-only for TLS SNI
P2 boot() → immediate shutdown(): sw-static nextTick still delivered endpoints after destroy(), channel left SHUTDOWN and reconnected destroyed flag; ignore updateResolution / pending nextTick after destroy
P2 DNS wait timeout (5s) cannot cancel getaddrinfo; each tick stacked another libc query under hung DNS Dedupe in-flight lookups per hostname; reuse the pending promise across expand ticks

Notes

  • Feature remains opt-in; default / flag-off paths are unchanged.
  • Unit coverage added/updated for the above cases.
  • Fixes are pushed to this PR branch (validated on our internal CI).

@wu-sheng

Copy link
Copy Markdown
Member

Re-reviewed at 3098e7e. The three issues from the previous round are fixed: plaintext :authority is preserved (host:port, SNI hostname-only), a failed rebuild replacement now emits an outage log, and per-lookup DNS errors are throttled. One new blocking issue and a few smaller ones:

  1. [P1, blocking] After an OAP outage longer than the channel idle timeout (30 min by default), an agent with a multi-address collector list never reconnects until the process restarts. In BackendAddressResolver.ts:373–395, bd4bc2d replaced destroy() { this.hasReturnedResult = false; } with a permanent destroyed = true, and updateResolution() returns early once it is set. grpc-js calls destroy() on idle, not only on close. enterIdle() destroys the resolving load balancer, and the next exitIdle() calls updateResolution() on the same resolver instance. The grpc-js Resolver interface documents this: "A later call to updateResolution should reinitialize those resources." The agent sends no RPCs while DISCONNECT, because heartbeat and trace reporting are gated on CONNECTED. Any OAP outage longer than the idle timeout therefore reaches this path. After that, the channel never receives endpoints again, even when OAP comes back on the same address. This affects every comma-separated collector list, because sw-static is also used with isResolveDnsPeriodically off.

    Reproduction: the real GRPCChannelManager against a local grpc-js server, flag off, two addresses, grpc.client_idle_timeout_ms reduced to 1 s. I stopped the server long enough for the channel to go idle, then restarted it on the same port. On master the channel returns to READY/CONNECTED. On this branch it stays IDLE/DISCONNECT.

    Suggested fix: keep resetting hasReturnedResult in destroy(), as grpc-js's own IP resolver does, and drop only deliveries scheduled before the latest destroy():

    updateResolution(): void {
      if (this.hasReturnedResult) return;
      this.hasReturnedResult = true;
      const generation = this.generation;
      process.nextTick(() => {
        if (generation !== this.generation) return; // destroyed after scheduling
        // ... deliver endpoints / error as before
      });
    }
    destroy(): void {
      this.hasReturnedResult = false;
      this.generation += 1;
    }

    With this change, all remote unit tests pass (including the new close-race test) and the idle reproduction reconnects. Please add a regression test for idle → reconnect.

  2. [P3] A rebuild during an already-logged outage suppresses the recovery log. GRPCChannelManager.ts:484–488 starts the quiet window for every DISCONNECT, not only when one is already active from a previous rebuild. Scenario: OAP pods reschedule, "gRPC channel disconnected" is logged, the next tick sees new IPs and rebuilds, and the replacement becomes READY. Listeners receive CONNECTED, but "gRPC channel recovered" is never logged. That is the main use case for this feature. Carrying over only an existing window (this.lastStatus === GRPCChannelStatus.DISCONNECT && this.suppressDnsRebuildStatusLog) keeps the consecutive-rebuild fix and restores the recovery log.

  3. [P3] The per-lookup DNS throttles are shared across hostnames. In BackendAddressResolver.ts:26–27, lookups run in configuration order. When two names fail, the first takes every 30 s window and the second is never named. Over 61 one-second ticks, [first] was logged three times and [second] zero times. Keying the throttle by hostname, or listing the failed names in the manager's "DNS expand incomplete" message, would fix this.

  4. [Nit] The close-race test depends on proxy environment variables. BackendAddressResolver.test.ts:85 creates its channel with {}. With http_proxy set, grpc-js routes the target through the proxy's dns: resolver instead of sw-static, and the test fails (SHUTDOWN → CONNECTING). Production already sets grpc.enable_http_proxy: 0. Please pass the same option in the test.

Validation: all 86 remote unit tests pass with proxy variables unset (85/86 with http_proxy set; see 4). The changed source files pass ESLint. Docker/OAP e2e was not run locally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants