-
Notifications
You must be signed in to change notification settings - Fork 209
dns-discovery-netty: Add support for DNS hedging requests #2918
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
bryce-anderson
wants to merge
10
commits into
apple:main
from
bryce-anderson:bl_anderson/DNS-hedging-requests
+650
−8
Closed
Changes from 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6523df8
Add the bones of a hedging system
bryce-anderson 0227d18
Work with the Dns interface
bryce-anderson 8f10df5
Use the io executor as the time source for easy testing
bryce-anderson 06c9037
Cleanup;
bryce-anderson e59eed2
Add some tests
bryce-anderson e7b7fff
Cleanup and make it easier to indirect
bryce-anderson 32e6ead
Start hacking together tests
bryce-anderson b1859c7
WIP
bryce-anderson d66b1d0
Merge remote-tracking branch 'origin/main' into bl_anderson/DNS-hedgi…
bryce-anderson 3fdd86c
Add a moving variance computation
bryce-anderson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
289 changes: 289 additions & 0 deletions
289
...covery-netty/src/main/java/io/servicetalk/dns/discovery/netty/HedgingDnsNameResolver.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,289 @@ | ||
| /* | ||
| * Copyright © 2024 Apple Inc. and the ServiceTalk project authors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package io.servicetalk.dns.discovery.netty; | ||
|
|
||
| import io.servicetalk.concurrent.Cancellable; | ||
|
|
||
| import io.netty.handler.codec.dns.DnsQuestion; | ||
| import io.netty.handler.codec.dns.DnsRecord; | ||
| import io.netty.resolver.dns.DnsNameResolver; | ||
| import io.netty.util.concurrent.Future; | ||
| import io.netty.util.concurrent.Promise; | ||
| import io.servicetalk.transport.api.IoExecutor; | ||
| import io.servicetalk.transport.netty.internal.EventLoopAwareNettyIoExecutor; | ||
|
|
||
| import java.net.InetAddress; | ||
| import java.util.List; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.function.Function; | ||
|
|
||
| import static io.servicetalk.transport.netty.internal.EventLoopAwareNettyIoExecutors.toEventLoopAwareNettyIoExecutor; | ||
| import static io.servicetalk.utils.internal.NumberUtils.ensurePositive; | ||
| import static java.lang.Math.max; | ||
| import static java.lang.Math.min; | ||
|
|
||
| final class HedgingDnsNameResolver implements UnderlyingDnsResolver { | ||
|
|
||
| private final UnderlyingDnsResolver delegate; | ||
| private final EventLoopAwareNettyIoExecutor executor; | ||
| private final PercentileTracker percentile; | ||
| private final Budget budget; | ||
|
|
||
| HedgingDnsNameResolver(DnsNameResolver delegate, IoExecutor executor) { | ||
| this(new NettyDnsNameResolver(delegate), executor); | ||
| } | ||
|
|
||
| HedgingDnsNameResolver(UnderlyingDnsResolver delegate, IoExecutor executor) { | ||
| this(delegate, executor, defaultTracker(), defaultBudget()); | ||
| } | ||
|
|
||
| HedgingDnsNameResolver(UnderlyingDnsResolver delegate, IoExecutor executor, | ||
| PercentileTracker percentile, Budget budget) { | ||
| this.delegate = delegate; | ||
| this.executor = toEventLoopAwareNettyIoExecutor(executor).next(); | ||
| this.percentile = percentile; | ||
| this.budget = budget; | ||
| } | ||
|
|
||
| @Override | ||
| public Future<List<DnsRecord>> resolveAllQuestion(DnsQuestion t) { | ||
| return setupHedge(delegate::resolveAllQuestion, t); | ||
| } | ||
|
|
||
| @Override | ||
| public Future<List<InetAddress>> resolveAll(String t) { | ||
| return setupHedge(delegate::resolveAll, t); | ||
| } | ||
|
|
||
| @Override | ||
| public void close() { | ||
| delegate.close(); | ||
| } | ||
|
|
||
| private long currentTimeMillis() { | ||
| return executor.currentTime(TimeUnit.MILLISECONDS); | ||
| } | ||
|
|
||
| private <T, R> Future<R> setupHedge(Function<T, Future<R>> computation, T t) { | ||
| // Only add tokens for organic requests and not retries. | ||
| budget.deposit(); | ||
| Future<R> underlyingResult = computation.apply(t); | ||
| final long delay = percentile.getValue(); | ||
| if (delay == Long.MAX_VALUE) { | ||
| // basically forever: just return the value. | ||
| return underlyingResult; | ||
| } else { | ||
| final long startTimeMs = currentTimeMillis(); | ||
| Promise<R> promise = executor.eventLoopGroup().next().newPromise(); | ||
| Cancellable hedgeTimer = executor.schedule(() -> tryHedge(computation, t, underlyingResult, promise), | ||
| delay, TimeUnit.MILLISECONDS); | ||
| underlyingResult.addListener(completedFuture -> { | ||
| measureRequest(currentTimeMillis() - startTimeMs, completedFuture); | ||
| if (complete(underlyingResult, promise)) { | ||
| hedgeTimer.cancel(); | ||
| } | ||
| }); | ||
| return promise; | ||
| } | ||
| } | ||
|
|
||
| private <T, R> void tryHedge( | ||
| Function<T, Future<R>> computation, T t, Future<R> original, Promise<R> promise) { | ||
| if (!original.isDone() && budget.withdraw()) { | ||
| System.out.println("" + System.currentTimeMillis() + ": sending backup request."); | ||
| Future<R> backupResult = computation.apply(t); | ||
| final long startTime = currentTimeMillis(); | ||
| backupResult.addListener(done -> { | ||
| if (complete(backupResult, promise)) { | ||
| original.cancel(true); | ||
| measureRequest(currentTimeMillis() - startTime, done); | ||
| } | ||
| }); | ||
| promise.addListener(complete -> backupResult.cancel(true)); | ||
| } | ||
| } | ||
|
|
||
| private void measureRequest(long durationMs, Future<?> future) { | ||
| // Cancelled responses don't count but we do consider failed responses because failure | ||
| // is a legitimate response. | ||
| if (!future.isCancelled()) { | ||
| percentile.addSample(durationMs); | ||
| } | ||
| } | ||
|
|
||
| private <T, R> boolean complete(Future<R> f, Promise<R> p) { | ||
| assert f.isDone(); | ||
| if (f.isSuccess()) { | ||
| return p.trySuccess(f.getNow()); | ||
| } else { | ||
| return p.tryFailure(f.cause()); | ||
| } | ||
| } | ||
|
|
||
| interface PercentileTracker { | ||
| void addSample(long sample); | ||
|
|
||
| long getValue(); | ||
| } | ||
|
|
||
| interface Budget { | ||
| void deposit(); | ||
|
|
||
| boolean withdraw(); | ||
| } | ||
|
|
||
| // TODO: both these implementations are un-synchronized and rely on netty using only a single event loop. | ||
| private static final class DefaultBudgetImpl implements Budget { | ||
|
|
||
| private final int depositAmount; | ||
| private final int withDrawAmount; | ||
| private final int maxTokens; | ||
| private int tokens; | ||
|
|
||
| DefaultBudgetImpl(int depositAmount, int withDrawAmount, int maxTokens) { | ||
| this(depositAmount, withDrawAmount, maxTokens, 0); | ||
| } | ||
|
|
||
| DefaultBudgetImpl(int depositAmount, int withDrawAmount, int maxTokens, int initialTokens) { | ||
| this.depositAmount = depositAmount; | ||
| this.withDrawAmount = withDrawAmount; | ||
| this.maxTokens = maxTokens; | ||
| this.tokens = initialTokens; | ||
| } | ||
|
|
||
| @Override | ||
| public void deposit() { | ||
| tokens = max(maxTokens, tokens + depositAmount); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean withdraw() { | ||
| if (tokens < withDrawAmount) { | ||
| return false; | ||
| } else { | ||
| tokens -= withDrawAmount; | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // TODO: we shouldn't need to worry about concurrency if this is all happening in the same netty channel. | ||
| private static final class DefaultPercentileTracker implements PercentileTracker { | ||
|
|
||
| // TODO: we need to make the buckets grow exponentially to save space. | ||
| private final int[] buckets; | ||
| private final double percentile; | ||
| private final int sampleThreshold; | ||
| private long lastValue; | ||
| private int sampleCount; | ||
|
|
||
| DefaultPercentileTracker(int buckets, double percentile, int sampleThreshold) { | ||
| if (percentile < 0 || percentile > 1) { | ||
| throw new IllegalArgumentException("Unexpected percentile value: " + percentile); | ||
| } | ||
| this.buckets = new int[ensurePositive(buckets, "buckets")]; | ||
| this.percentile = percentile; | ||
| this.sampleThreshold = ensurePositive(sampleThreshold, "sampleThreshold"); | ||
| lastValue = Long.MAX_VALUE; | ||
| } | ||
|
|
||
| @Override | ||
| public void addSample(long value) { | ||
| maybeSwap(); | ||
| int bucket = valueToBucket(value); | ||
| buckets[bucket]++; | ||
| sampleCount++; | ||
| } | ||
|
|
||
| @Override | ||
| public long getValue() { | ||
| maybeSwap(); | ||
| return lastValue; | ||
| } | ||
|
|
||
| private void maybeSwap() { | ||
| if (shouldSwap()) { | ||
| lastValue = compute(); | ||
| } | ||
| } | ||
|
|
||
| private boolean shouldSwap() { | ||
| return sampleCount >= sampleThreshold; | ||
| } | ||
|
|
||
| private long compute() { | ||
| long targetCount = (long) (sampleCount * percentile); | ||
| sampleCount = 0; | ||
| long result = -1; | ||
| for (int i = 0; i < buckets.length; i++) { | ||
| if (result != -1) { | ||
| targetCount -= buckets[i]; | ||
| if (targetCount <= 0) { | ||
| result = bucketToValue(i); | ||
| } | ||
| } | ||
| buckets[i] = 0; | ||
| } | ||
| assert result != -1; // we should have found a bucket. | ||
| return max(1, result); | ||
| } | ||
|
|
||
| private long bucketToValue(int bucket) { | ||
| return bucket; | ||
| } | ||
|
|
||
| private int valueToBucket(long value) { | ||
| return (int) max(0, min(buckets.length, value)); | ||
| } | ||
| } | ||
|
|
||
| private static PercentileTracker defaultTracker() { | ||
| return new DefaultPercentileTracker(128, 0.98, 200); | ||
| } | ||
|
|
||
| private static Budget defaultBudget() { | ||
| // 5% extra load and a max burst of 5 hedges. | ||
| return new DefaultBudgetImpl(1, 20, 100); | ||
| } | ||
|
|
||
| static PercentileTracker constantTracker(int value) { | ||
| return new PercentileTracker() { | ||
| @Override | ||
| public void addSample(long sample) { | ||
| // noop | ||
| } | ||
|
|
||
| @Override | ||
| public long getValue() { | ||
| return value; | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| static Budget alwaysBudget() { | ||
| return new Budget() { | ||
| @Override | ||
| public void deposit() { | ||
| // noop | ||
| } | ||
|
|
||
| @Override | ||
| public boolean withdraw() { | ||
| return true; | ||
| } | ||
| }; | ||
| } | ||
| } | ||
43 changes: 43 additions & 0 deletions
43
...scovery-netty/src/main/java/io/servicetalk/dns/discovery/netty/UnderlyingDnsResolver.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| package io.servicetalk.dns.discovery.netty; | ||
|
|
||
| import io.netty.handler.codec.dns.DnsQuestion; | ||
| import io.netty.handler.codec.dns.DnsRecord; | ||
| import io.netty.resolver.dns.DnsNameResolver; | ||
| import io.netty.util.concurrent.Future; | ||
|
|
||
| import java.io.Closeable; | ||
| import java.net.InetAddress; | ||
| import java.util.List; | ||
|
|
||
| interface UnderlyingDnsResolver extends Closeable { | ||
|
|
||
| Future<List<DnsRecord>> resolveAllQuestion(DnsQuestion t); | ||
|
|
||
| Future<List<InetAddress>> resolveAll(String t); | ||
|
|
||
| @Override | ||
| void close(); | ||
|
|
||
| static final class NettyDnsNameResolver implements UnderlyingDnsResolver { | ||
| private final DnsNameResolver resolver; | ||
|
|
||
| NettyDnsNameResolver(final DnsNameResolver resolver) { | ||
| this.resolver = resolver; | ||
| } | ||
|
|
||
| @Override | ||
| public Future<List<DnsRecord>> resolveAllQuestion(DnsQuestion t) { | ||
| return resolver.resolveAll(t); | ||
| } | ||
|
|
||
| @Override | ||
| public Future<List<InetAddress>> resolveAll(String t) { | ||
| return resolver.resolveAll(t); | ||
| } | ||
|
|
||
| @Override | ||
| public void close() { | ||
| resolver.close(); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.