-
Notifications
You must be signed in to change notification settings - Fork 203
feat: add jitter to max lifetime in connection pool #1496
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
Open
priyanshu-d11
wants to merge
4
commits into
eclipse-vertx:master
Choose a base branch
from
priyanshu-d11:feat/jitter-in-maxlifetime
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
61d0455
feat: add jitter to max lifetime in connection pool
priyanshu-d11 204faa9
test: improve connection jitter test with timing verification and ass…
priyanshu-d11 cbb4fad
Added timeunit for jitter
priyanshu-d11 f9dc3c8
Addded test case for jitter
priyanshu-d11 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,8 +18,11 @@ | |
package io.vertx.tests.pgclient; | ||
|
||
import io.netty.channel.EventLoop; | ||
import io.vertx.core.Future; | ||
import io.vertx.core.Handler; | ||
import io.vertx.core.Promise; | ||
import io.vertx.core.VertxOptions; | ||
import io.vertx.core.json.JsonObject; | ||
import io.vertx.ext.unit.Async; | ||
import io.vertx.ext.unit.TestContext; | ||
import io.vertx.ext.unit.junit.Repeat; | ||
|
@@ -34,21 +37,31 @@ | |
import io.vertx.tests.sqlclient.ProxyServer; | ||
import org.junit.Rule; | ||
import org.junit.Test; | ||
import org.testcontainers.shaded.com.trilead.ssh2.ConnectionInfo; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.HashMap; | ||
import java.util.HashSet; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Set; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.ConcurrentMap; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.atomic.AtomicBoolean; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
import java.util.concurrent.atomic.AtomicLong; | ||
import java.util.concurrent.atomic.AtomicReference; | ||
import java.util.stream.Collector; | ||
import java.util.function.Consumer; | ||
import java.util.stream.Collectors; | ||
|
||
import static java.util.stream.Collectors.mapping; | ||
import static java.util.stream.Collectors.toList; | ||
|
||
import java.time.OffsetDateTime; | ||
|
||
/** | ||
* @author <a href="mailto:[email protected]">Julien Viet</a> | ||
*/ | ||
|
@@ -619,4 +632,184 @@ public void testConnectionClosedInHook(TestContext ctx) { | |
})); | ||
})); | ||
} | ||
|
||
@Test | ||
public void testConnectionJitter(TestContext ctx) { | ||
PoolOptions poolOptions = new PoolOptions() | ||
.setMaxSize(1) | ||
.setMaxLifetime(3000) | ||
.setMaxLifetimeUnit(TimeUnit.MILLISECONDS) | ||
.setJitter(1) | ||
.setJitterUnit(TimeUnit.SECONDS) | ||
.setPoolCleanerPeriod(50); | ||
|
||
Pool pool = createPool(options, poolOptions); | ||
Async latch = ctx.async(); | ||
|
||
List<Integer> pids = Collections.synchronizedList(new ArrayList<>()); | ||
List<Long> times = Collections.synchronizedList(new ArrayList<>()); | ||
AtomicInteger lastPid = new AtomicInteger(-1); | ||
AtomicLong timerId = new AtomicLong(); | ||
|
||
Consumer<TestContext> checkPid = testCtx -> { | ||
pool.query("SELECT pg_backend_pid() as pid") | ||
.execute() | ||
.onComplete(testCtx.asyncAssertSuccess(rs -> { | ||
int currentPid = rs.iterator().next().getInteger("pid"); | ||
if (lastPid.get() != currentPid) { | ||
pids.add(currentPid); | ||
times.add(System.currentTimeMillis()); | ||
lastPid.set(currentPid); | ||
|
||
if (pids.size() == 3) { | ||
vertx.cancelTimer(timerId.get()); | ||
long diff1to2 = times.get(1) - times.get(0); | ||
long diff2to3 = times.get(2) - times.get(1); | ||
|
||
// Verify time ranges | ||
int maxLifetime = 3000; | ||
int jitter = 1000; | ||
int buffer = 100; | ||
int lowerBound = maxLifetime - jitter + buffer; | ||
int upperBound = maxLifetime + jitter + buffer; | ||
|
||
ctx.assertTrue(diff1to2 >= lowerBound && diff1to2 <= upperBound, | ||
String.format("Time between PIDs %d->%d (%dms) should be between %dms and %dms", | ||
pids.get(0), pids.get(1), diff1to2, lowerBound, upperBound)); | ||
|
||
ctx.assertTrue(diff2to3 >= lowerBound && diff2to3 <= upperBound, | ||
String.format("Time between PIDs %d->%d (%dms) should be between %dms and %dms", | ||
pids.get(1), pids.get(2), diff2to3, lowerBound, upperBound)); | ||
|
||
pool.close().onComplete(ctx.asyncAssertSuccess(v -> latch.complete())); | ||
} | ||
} | ||
})); | ||
}; | ||
|
||
timerId.set(vertx.setPeriodic(30, id -> checkPid.accept(ctx))); | ||
latch.awaitSuccess(20000); | ||
} | ||
|
||
@Test | ||
public void testConnectionCloseTimingParallel(TestContext ctx) { | ||
// Configure pool options. | ||
PoolOptions poolOptions = new PoolOptions() | ||
.setMaxSize(20) // Allow parallel tasks. | ||
.setMaxLifetime(5000) // Maximum lifetime = 5000 ms. | ||
.setMaxLifetimeUnit(TimeUnit.MILLISECONDS) | ||
.setJitter(1) // Jitter = 1 second. | ||
.setJitterUnit(TimeUnit.SECONDS) | ||
.setPoolCleanerPeriod(50); | ||
|
||
Pool pool = createPool(options, poolOptions); | ||
Async latch = ctx.async(); | ||
int totalConnections = 50; | ||
List<Future<JsonObject>> futures = new ArrayList<>(); | ||
List<Integer> pids = Collections.synchronizedList(new ArrayList<>()); | ||
ConcurrentMap<Integer, Long> startTimes = new ConcurrentHashMap<>(); | ||
ConcurrentMap<Integer, Long> endTimes = new ConcurrentHashMap<>(); | ||
|
||
// Launch connection tasks in parallel. | ||
for (int i = 0; i < totalConnections; i++) { | ||
futures.add(processSingleConnection(pool, i, ctx, pids, startTimes, endTimes)); | ||
} | ||
|
||
Future.all(futures).onComplete(ctx.asyncAssertSuccess(ar -> { | ||
pool.close().onComplete(ctx.asyncAssertSuccess(v -> { | ||
// Wait 3 seconds after pool closure. | ||
vertx.setTimer(3000, timerId -> { | ||
PgConnection.connect(vertx, options).onComplete(ctx.asyncAssertSuccess(conn -> { | ||
// (Optional) Query to verify that none of our recorded PIDs are still active. | ||
String pidList = pids.stream().map(String::valueOf).collect(Collectors.joining(",")); | ||
String sql = "SELECT pid FROM pg_stat_activity WHERE pid IN (" + pidList + ")"; | ||
conn.query(sql).execute().onComplete(ctx.asyncAssertSuccess(rs2 -> { | ||
// Compute durations for each PID. | ||
List<Long> durations = pids.stream() | ||
.map(pid -> endTimes.get(pid) - startTimes.get(pid)) | ||
.collect(Collectors.toList()); | ||
long maxLifetime = 5000; | ||
long jitterMs = 1000; | ||
long bucketWidth = jitterMs / 5; | ||
// Bucket the durations based on an offset of maxLifetime. | ||
Map<Integer, List<Integer>> bucketMap = new HashMap<>(); | ||
for (Integer pid : pids) { | ||
long duration = endTimes.get(pid) - startTimes.get(pid); | ||
int bucket = (int) ((duration - maxLifetime) / bucketWidth); | ||
bucketMap.computeIfAbsent(bucket, k -> new ArrayList<>()).add(pid); | ||
} | ||
|
||
ctx.assertTrue(bucketMap.size() >= 5, "Bucket Size should be 5"); | ||
bucketMap.forEach((bucket, bucketPids) -> { | ||
ctx.assertTrue(!bucketPids.isEmpty(), "Bucket " + bucket + " should not be empty"); | ||
}); | ||
// Print one line per PID with its duration. | ||
for (Integer pid : pids) { | ||
long duration = endTimes.get(pid) - startTimes.get(pid); | ||
} | ||
conn.close(); | ||
latch.complete(); | ||
})); | ||
})); | ||
}); | ||
})); | ||
})); | ||
latch.awaitSuccess(60000); | ||
} | ||
|
||
/** | ||
* Acquires a connection, retrieves its PID and backend_start time, | ||
* closes the connection, and polls for its closure. | ||
* Returns a Future with a JsonObject containing the PID, start time, and end time. | ||
*/ | ||
private Future<JsonObject> processSingleConnection(Pool pool, int index, TestContext ctx, | ||
List<Integer> pids, | ||
ConcurrentMap<Integer, Long> startTimes, | ||
ConcurrentMap<Integer, Long> endTimes) { | ||
Promise<JsonObject> promise = Promise.promise(); | ||
pool.getConnection().onComplete(ctx.asyncAssertSuccess(conn -> { | ||
conn.query("SELECT pg_backend_pid() AS pid") | ||
.execute() | ||
.onComplete(ctx.asyncAssertSuccess(rs -> { | ||
int pid = rs.iterator().next().getInteger("pid"); | ||
pids.add(pid); | ||
String sql = "SELECT backend_start FROM pg_stat_activity WHERE pid = " + pid; | ||
conn.query(sql).execute().onComplete(ctx.asyncAssertSuccess(rs2 -> { | ||
Row row = rs2.iterator().next(); | ||
OffsetDateTime backendStart = row.getOffsetDateTime("backend_start"); | ||
long startMillis = backendStart.toInstant().toEpochMilli(); | ||
startTimes.put(pid, startMillis); | ||
pollForClose(pool, pid, closeTime -> { | ||
endTimes.put(pid, closeTime); | ||
JsonObject res = new JsonObject() | ||
.put("pid", pid) | ||
.put("start", startMillis) | ||
.put("end", closeTime); | ||
promise.complete(res); | ||
}); | ||
conn.close().onComplete(x -> {}); | ||
})); | ||
})); | ||
})); | ||
return promise.future(); | ||
} | ||
|
||
/** | ||
* Polls pg_stat_activity periodically for the given PID. | ||
* Once the PID is no longer found (i.e. the connection is closed), | ||
* returns the current system time via the resultHandler. | ||
*/ | ||
private void pollForClose(Pool pool, int pid, Handler<Long> resultHandler) { | ||
long timerId = vertx.setPeriodic(50, id -> { | ||
pool.query("SELECT 1 FROM pg_stat_activity WHERE pid = " + pid) | ||
.execute() | ||
.onComplete(ar -> { | ||
if (ar.succeeded() && !ar.result().iterator().hasNext()) { | ||
long closeTime = System.currentTimeMillis(); | ||
vertx.cancelTimer(id); | ||
resultHandler.handle(closeTime); | ||
} | ||
}); | ||
}); | ||
} | ||
} |
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
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
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
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we also need a
jitterTimeUnit
property which should be by default WillisThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
added