From 0e0b03faa480bfa6ee79106b5d6b003e9150b158 Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Thu, 19 Nov 2026 13:02:46 +0530 Subject: [PATCH 1/4] Port per-session ephemeral path-byte budget to 3.8.7 Adds the opt-in zookeeper.ephemeralNodes.total.byte.limit system property (default -1, disabled). When set, the leader's request preparation rejects an ephemeral create whose serialized full path (4-byte length prefix plus encoded bytes) would push the session's committed total above the limit, logs the rejection, increments ephemeral_node_limit_violation and returns TOTALEPHEMERALLIMITEXCEEDED. DataTree keeps the per-session total on create, delete and close. The check uses committed state only, so concurrent or batched creates can exceed the configured value. The error code is -128 because -125 is QUOTAEXCEEDED in 3.8. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../main/resources/markdown/zookeeperAdmin.md | 7 + .../org/apache/jute/BinaryOutputArchive.java | 23 ++ .../apache/jute/BinaryOutputArchiveTest.java | 59 +++ .../org/apache/zookeeper/KeeperException.java | 16 +- .../org/apache/zookeeper/server/DataTree.java | 26 +- .../server/PrepRequestProcessor.java | 9 + .../zookeeper/server/ServerMetrics.java | 2 + .../zookeeper/server/ZooKeeperServer.java | 11 + .../apache/zookeeper/server/DataTreeTest.java | 12 + ...phemeralNodeThrottlingMultithreadTest.java | 136 +++++++ .../quorum/EphemeralNodeThrottlingTest.java | 180 +++++++++ .../test/EphemeralNodeByteLimitTest.java | 356 ++++++++++++++++++ 12 files changed, 835 insertions(+), 2 deletions(-) create mode 100644 zookeeper-jute/src/test/java/org/apache/jute/BinaryOutputArchiveTest.java create mode 100644 zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingMultithreadTest.java create mode 100644 zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java create mode 100644 zookeeper-server/src/test/java/org/apache/zookeeper/test/EphemeralNodeByteLimitTest.java diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md index 4b3cc243bd5..48f23721404 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md @@ -1153,6 +1153,13 @@ property, when available, is noted below. **New in 3.6.0:** The size threshold after which a request is considered a large request. If it is -1, then all requests are considered small, effectively turning off large request throttling. The default is -1. +* *ephemeralNodes.total.byte.limit* : + (Java system property: **zookeeper.ephemeralNodes.total.byte.limit**) + This property set a limit on the amount of ephemeral nodes that can be created in one session. The limit is the number + of bytes it takes to store the serialized path strings for all the session's ephemeral nodes. + This limit should always be under the jute maxbuffer, as exceeding will cause the server to crash when the connection is closed + and a transaction to delete all the ephemeral nodes for that session are deleted. This limit will be ignored if not explicitly set. + * *outstandingHandshake.limit* (Java system property only: **zookeeper.netty.server.outstandingHandshake.limit**) The maximum in-flight TLS handshake connections could have in ZooKeeper, diff --git a/zookeeper-jute/src/main/java/org/apache/jute/BinaryOutputArchive.java b/zookeeper-jute/src/main/java/org/apache/jute/BinaryOutputArchive.java index 4752d8461ab..1a1749d8645 100644 --- a/zookeeper-jute/src/main/java/org/apache/jute/BinaryOutputArchive.java +++ b/zookeeper-jute/src/main/java/org/apache/jute/BinaryOutputArchive.java @@ -102,6 +102,29 @@ private ByteBuffer stringToByteBuffer(CharSequence s) { return bb; } + public static int getSerializedStringByteSize(String s) throws ArithmeticException { + if (s == null) { + return 0; + } + + // Always add 4 bytes to size as we call writeInt(bb.remaining(), "len") when writing to DataOutput + int lengthDescriptorSize = 4; + + int size = 0; + final int len = s.length(); + for (int i = 0; i < len; i++) { + char c = s.charAt(i); + if (c < 0x80) { + size = Math.addExact(size, 1); + } else if (c < 0x800) { + size = Math.addExact(size, 2); + } else { + size = Math.addExact(size, 3); + } + } + return Math.addExact(size, lengthDescriptorSize); + } + public void writeString(String s, String tag) throws IOException { if (s == null) { writeInt(-1, "len"); diff --git a/zookeeper-jute/src/test/java/org/apache/jute/BinaryOutputArchiveTest.java b/zookeeper-jute/src/test/java/org/apache/jute/BinaryOutputArchiveTest.java new file mode 100644 index 00000000000..ad2cad77251 --- /dev/null +++ b/zookeeper-jute/src/test/java/org/apache/jute/BinaryOutputArchiveTest.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.jute; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +public class BinaryOutputArchiveTest { + + private static int writtenSize(String s) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + BinaryOutputArchive.getArchive(new DataOutputStream(bytes)).writeString(s, "s"); + return bytes.size(); + } + + @Test + public void testSerializedStringByteSizeMatchesWriteString() throws IOException { + String[] values = { + "", + "/", + "/ephemeral-0000000001", + "/caf\u00e9/\u00df", + "/\u4e2d\u6587/\u0800\uffef", + "/surrogate-\ud83d\ude00", + }; + for (String value : values) { + assertEquals(writtenSize(value), BinaryOutputArchive.getSerializedStringByteSize(value), value); + } + } + + @Test + public void testSerializedStringByteSizeCountsUtf8BytesNotChars() { + String path = "/\u00e9\u4e2d"; + assertEquals(3, path.length()); + assertEquals(4 + 1 + 2 + 3, BinaryOutputArchive.getSerializedStringByteSize(path)); + assertEquals(path.getBytes(StandardCharsets.UTF_8).length + 4, + BinaryOutputArchive.getSerializedStringByteSize(path)); + } +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java b/zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java index ef38763f41e..dd89707ee40 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java @@ -152,6 +152,8 @@ public static KeeperException create(Code code) { return new QuotaExceededException(); case THROTTLEDOP: return new ThrottledOpException(); + case TOTALEPHEMERALLIMITEXCEEDED: + return new TotalEphemeralLimitExceeded(); case OK: default: throw new IllegalArgumentException("Invalid exception code:" + code.code); @@ -415,7 +417,10 @@ public enum Code implements CodeDeprecated { /** Operation was throttled and not executed at all. This error code indicates that zookeeper server * is under heavy load and can't process incoming requests at full speed; please retry with back off. */ - THROTTLEDOP (-127); + THROTTLEDOP (-127), + /** Request to create ephemeral node was rejected because the total byte limit for the session was exceeded. + * This limit is manually set through the "zookeeper.ephemeralNodes.total.byte.limit" system property. */ + TOTALEPHEMERALLIMITEXCEEDED(-128); private static final Map lookup = new HashMap(); @@ -514,6 +519,8 @@ static String getCodeMessage(Code code) { return "Quota has exceeded"; case THROTTLEDOP: return "Op throttled due to high load"; + case TOTALEPHEMERALLIMITEXCEEDED: + return "Ephemeral count exceeded for session"; default: return "Unknown error " + code; } @@ -980,4 +987,11 @@ public ThrottledOpException() { super(Code.THROTTLEDOP); } } + + public static class TotalEphemeralLimitExceeded extends KeeperException { + public TotalEphemeralLimitExceeded() { + super(Code.TOTALEPHEMERALLIMITEXCEEDED); + } + } + } diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/DataTree.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/DataTree.java index e545664ff74..d16298aefad 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/DataTree.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/DataTree.java @@ -35,8 +35,10 @@ import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.jute.BinaryInputArchive; +import org.apache.jute.BinaryOutputArchive; import org.apache.jute.InputArchive; import org.apache.jute.OutputArchive; import org.apache.jute.Record; @@ -161,6 +163,7 @@ public class DataTree { * This hashtable lists the paths of the ephemeral nodes of a session. */ private final Map> ephemerals = new ConcurrentHashMap>(); + private final Map ephemeralsByteSizeMap = new ConcurrentHashMap(); /** * This set contains the paths of all container nodes @@ -223,6 +226,11 @@ public Set getEphemerals(long sessionId) { return cloned; } + public int getTotalEphemeralsByteSize(long sessionID) { + AtomicInteger byteSize = ephemeralsByteSizeMap.get(sessionID); + return byteSize != null ? byteSize.get() : 0; + } + public Set getContainers() { return new HashSet(containers); } @@ -535,6 +543,7 @@ public void createNode(final String path, byte[] data, List acl, long ephem ttls.add(path); } else if (ephemeralOwner != 0) { HashSet list = ephemerals.get(ephemeralOwner); + AtomicInteger totalEphemeralsByteSize = ephemeralsByteSizeMap.get(ephemeralOwner); if (list == null) { list = new HashSet(); ephemerals.put(ephemeralOwner, list); @@ -542,6 +551,14 @@ public void createNode(final String path, byte[] data, List acl, long ephem synchronized (list) { list.add(path); } + // Only store sum of ephemeral node byte sizes if we're enforcing a limit + if (ZooKeeperServer.getEphemeralNodesTotalByteLimit() != -1) { + if (totalEphemeralsByteSize == null) { + totalEphemeralsByteSize = new AtomicInteger(); + ephemeralsByteSizeMap.put(ephemeralOwner, totalEphemeralsByteSize); + } + totalEphemeralsByteSize.addAndGet(BinaryOutputArchive.getSerializedStringByteSize(path)); + } } if (outputStat != null) { child.copyStat(outputStat); @@ -631,9 +648,15 @@ public void deleteNode(String path, long zxid) throws KeeperException.NoNodeExce ttls.remove(path); } else if (eowner != 0) { Set nodes = ephemerals.get(eowner); + AtomicInteger totalEphemeralsByteSize = ephemeralsByteSizeMap.get(eowner); if (nodes != null) { + Boolean nodeExisted; synchronized (nodes) { - nodes.remove(path); + nodeExisted = nodes.remove(path); + } + // Only store sum of ephemeral node byte sizes if we're enforcing a limit + if (ZooKeeperServer.getEphemeralNodesTotalByteLimit() != -1 && nodeExisted && totalEphemeralsByteSize != null) { + totalEphemeralsByteSize.addAndGet(-(BinaryOutputArchive.getSerializedStringByteSize(path))); } } } @@ -1200,6 +1223,7 @@ public ProcessTxnResult processTxn(TxnHeader header, Record txn, boolean isSubTx case OpCode.closeSession: long sessionId = header.getClientId(); if (txn != null) { + ephemeralsByteSizeMap.remove(sessionId); killSession(sessionId, header.getZxid(), ephemerals.remove(sessionId), ((CloseSessionTxn) txn).getPaths2Delete()); diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java index 0a9231091dd..b6b631ca0d1 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java @@ -725,6 +725,15 @@ private void pRequest2TxnCreate(int type, Request request, Record record, boolea ephemeralOwner = EphemeralType.TTL.toEphemeralOwner(ttl); } else if (createMode.isEphemeral()) { ephemeralOwner = request.sessionId; + int currentByteSize = zks.getZKDatabase().getDataTree().getTotalEphemeralsByteSize(ephemeralOwner); + int proposedByteSize = currentByteSize + BinaryOutputArchive.getSerializedStringByteSize(path); + if (ZooKeeperServer.getEphemeralNodesTotalByteLimit() != -1 && proposedByteSize + > ZooKeeperServer.getEphemeralNodesTotalByteLimit()) { + LOG.error(String.format("Rejecting ephemeral node creation for session %s, zxid %s, path %s.", + request.sessionId, request.getHdr().getZxid(), path)); + ServerMetrics.getMetrics().EPHEMERAL_NODE_LIMIT_VIOLATION.inc(); + throw new KeeperException.TotalEphemeralLimitExceeded(); + } } StatPersisted s = DataTree.createStat(hdr.getZxid(), hdr.getTime(), ephemeralOwner); parentRecord = parentRecord.duplicate(request.getHdr().getZxid()); diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerMetrics.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerMetrics.java index af156542f03..8effff1e4a6 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerMetrics.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerMetrics.java @@ -163,6 +163,7 @@ private ServerMetrics(MetricsProvider metricsProvider) { COMMITS_QUEUED = metricsContext.getCounter("request_commit_queued"); READS_ISSUED_IN_COMMIT_PROC = metricsContext.getSummary("read_commit_proc_issued", DetailLevel.BASIC); WRITES_ISSUED_IN_COMMIT_PROC = metricsContext.getSummary("write_commit_proc_issued", DetailLevel.BASIC); + EPHEMERAL_NODE_LIMIT_VIOLATION = metricsContext.getCounter("ephemeral_node_limit_violation"); THROTTLED_OPS = metricsContext.getCounter("throttled_ops"); @@ -420,6 +421,7 @@ private ServerMetrics(MetricsProvider metricsProvider) { public final Counter COMMITS_QUEUED; public final Summary READS_ISSUED_IN_COMMIT_PROC; public final Summary WRITES_ISSUED_IN_COMMIT_PROC; + public final Counter EPHEMERAL_NODE_LIMIT_VIOLATION; // Request op throttling related public final Counter THROTTLED_OPS; diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java index f1cc6752c79..292fd8864b3 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java @@ -106,6 +106,10 @@ public class ZooKeeperServer implements SessionExpirer, ServerStats.Provider { public static final String ENABLE_EAGER_ACL_CHECK = "zookeeper.enableEagerACLCheck"; public static final String SKIP_ACL = "zookeeper.skipACL"; + public static final String EPHEMERAL_NODES_TOTAL_BYTE_LIMIT_KEY = "zookeeper.ephemeralNodes.total.byte.limit"; + public static final int DEFAULT_EPHEMERAL_NODES_TOTAL_BYTE_LIMIT = -1; + private static int ephemeralCountLimit; + private static int ephemeralNodesTotalByteLimit; public static final String ENFORCE_QUOTA = "zookeeper.enforceQuota"; // When enabled, will check ACL constraints appertained to the requests first, @@ -155,6 +159,9 @@ public class ZooKeeperServer implements SessionExpirer, ServerStats.Provider { closeSessionTxnEnabled = Boolean.parseBoolean( System.getProperty(CLOSE_SESSION_TXN_ENABLED, "true")); LOG.info("{} = {}", CLOSE_SESSION_TXN_ENABLED, closeSessionTxnEnabled); + + ephemeralNodesTotalByteLimit = Integer.getInteger(EPHEMERAL_NODES_TOTAL_BYTE_LIMIT_KEY, DEFAULT_EPHEMERAL_NODES_TOTAL_BYTE_LIMIT); + LOG.info("{} = {}", EPHEMERAL_NODES_TOTAL_BYTE_LIMIT_KEY, ephemeralNodesTotalByteLimit); } // @VisibleForTesting @@ -178,6 +185,10 @@ public static void setCloseSessionTxnEnabled(boolean enabled) { ZooKeeperServer.closeSessionTxnEnabled); } + public static int getEphemeralNodesTotalByteLimit() { + return ephemeralNodesTotalByteLimit; + } + protected ZooKeeperServerBean jmxServerBean; protected DataTreeBean jmxDataTreeBean; diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java index 6396e376436..82c73b86824 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java @@ -116,6 +116,18 @@ private void createEphemeralNode(long session, final DataTree dataTree, int coun } } + @Test + public void testEphemeralByteSizeNotTrackedWhenLimitDisabled() throws Exception { + assertEquals(-1, ZooKeeperServer.getEphemeralNodesTotalByteLimit()); + DataTree dataTree = new DataTree(); + long session = 1000; + createEphemeralNode(session, dataTree, 1); + assertEquals(1, dataTree.getEphemerals(session).size()); + assertEquals(0, dataTree.getTotalEphemeralsByteSize(session)); + dataTree.deleteNode("/test0", 2); + assertEquals(0, dataTree.getTotalEphemeralsByteSize(session)); + } + @Test @Timeout(value = 60) public void testRootWatchTriggered() throws Exception { diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingMultithreadTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingMultithreadTest.java new file mode 100644 index 00000000000..29baa638f09 --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingMultithreadTest.java @@ -0,0 +1,136 @@ +/* + * 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. + */ + +package org.apache.zookeeper.server.quorum; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.apache.jute.BinaryOutputArchive; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooKeeper; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +public class EphemeralNodeThrottlingMultithreadTest extends QuorumPeerTestBase { + + public static final String EPHEMERAL_BYTE_LIMIT_KEY = "zookeeper.ephemeralNodes.total.byte.limit"; + static final String TEST_PATH = "/ephemeral-throttling-multithread-test"; + static final int DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT = (int) Math.pow(2d, 15d); + static final int NUM_SERVERS = 5; + + @BeforeAll + public static void setUpClass() { + System.setProperty(EPHEMERAL_BYTE_LIMIT_KEY, Integer.toString(DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT)); + } + + @AfterAll + public static void tearDownClass() { + System.clearProperty(EPHEMERAL_BYTE_LIMIT_KEY); + } + + // Tests multithreaded creates and deletes against the leader and a follower server + @Test + public void multithreadedRequestsTest() throws Exception { + // 32 KiB, so that the create threads can reach the budget within their time window + int totalEphemeralNodesByteLimit = DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT; + System.setProperty("zookeeper.ephemeralNodes.total.byte.limit", Integer.toString(totalEphemeralNodesByteLimit)); + + servers = LaunchServers(NUM_SERVERS); + ZooKeeper leaderServer = servers.zk[servers.findLeader()]; + ZooKeeper followerServer = servers.zk[servers.findAnyFollower()]; + + runMultithreadedRequests(leaderServer); + runMultithreadedRequests(followerServer); + + int leaderSessionEphemeralsByteSum = 0; + for (String nodePath : leaderServer.getEphemerals()) { + leaderSessionEphemeralsByteSum += BinaryOutputArchive.getSerializedStringByteSize(nodePath); + } + // TODO: What % delta do we want to allow here? + assertEquals(totalEphemeralNodesByteLimit, leaderSessionEphemeralsByteSum, totalEphemeralNodesByteLimit / 20d); + + int followerSessionEphemeralsByteSum = 0; + for (String nodePath : followerServer.getEphemerals()) { + followerSessionEphemeralsByteSum += BinaryOutputArchive.getSerializedStringByteSize(nodePath); + } + assertEquals(totalEphemeralNodesByteLimit, followerSessionEphemeralsByteSum, totalEphemeralNodesByteLimit / 20d); + + servers.shutDownAllServers(); + } + + private void runMultithreadedRequests(ZooKeeper server) { + int threadPoolCount = 8; + int deleteRequestThreads = 2; + int createRequestThreads = threadPoolCount - deleteRequestThreads; + // Spin up threads to repeatedly send CREATE requests to server + ExecutorService executor = Executors.newFixedThreadPool(threadPoolCount); + for (int i = 0; i < createRequestThreads; i++) { + final int threadID = i; + executor.submit(() ->{ + long startTime = System.currentTimeMillis(); + while (System.currentTimeMillis() - startTime < 10000) { + try { + server.create(TEST_PATH + "_" + threadID + "_", new byte[512], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); + } catch (KeeperException.TotalEphemeralLimitExceeded expectedException) { + // Ignore Ephemeral Count exceeded exception, as this is expected to occur + } catch (Exception e) { + LOG.warn("Thread encountered an exception but ignored it:\n" + e.getMessage()); + } + } + }); + } + + // Spin up threads to repeatedly send DELETE requests to server + // After a 1-second sleep, this should run concurrently with the create threads, but then end before create threads end + // so that we still have time to hit the limit and can then assert that limit was upheld correctly + for (int i = 0; i < deleteRequestThreads; i++) { + executor.submit(() -> { + long startTime = System.currentTimeMillis(); + try { + // Brief sleep to reduce chance that ephemeral nodes not yet created + Thread.sleep(1000); + while (System.currentTimeMillis() - startTime < 4000) { + for (String ephemeralNode : server.getEphemerals()) { + server.delete(ephemeralNode, -1); + } + } + } catch (KeeperException.TotalEphemeralLimitExceeded expectedException) { + // Ignore Ephemeral Count exceeded exception, as this is expected to occur + } catch (Exception e) { + LOG.warn("Thread encountered an exception but ignored it:\n" + e.getMessage()); + } + }); + } + + executor.shutdown(); + try { + if (!executor.awaitTermination(12000, TimeUnit.MILLISECONDS)) { + LOG.warn("Threads did not finish in the given time!"); + executor.shutdownNow(); + } + } catch (InterruptedException e) { + LOG.error(e.getMessage()); + executor.shutdownNow(); + } + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java new file mode 100644 index 00000000000..08756ef7086 --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java @@ -0,0 +1,180 @@ +/* + * 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. + */ + +package org.apache.zookeeper.server.quorum; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.apache.jute.BinaryOutputArchive; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.metrics.MetricsUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class EphemeralNodeThrottlingTest extends QuorumPeerTestBase { + + protected static final Logger LOG = LoggerFactory.getLogger(EphemeralNodeThrottlingTest.class); + + public static final String EPHEMERAL_BYTE_LIMIT_KEY = "zookeeper.ephemeralNodes.total.byte.limit"; + public static final String EPHEMERAL_BYTE_LIMIT_VIOLATION_KEY = "ephemeral_node_limit_violation"; + static final int DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT = 2000; + static final int NUM_SERVERS = 5; + static final String TEST_PATH = "/ephemeral-throttling-test"; + + @BeforeAll + public static void setUpClass() { + System.setProperty(EPHEMERAL_BYTE_LIMIT_KEY, Integer.toString(DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT)); + } + + @AfterAll + public static void tearDownClass() { + System.clearProperty(EPHEMERAL_BYTE_LIMIT_KEY); + } + + @BeforeEach + public void setUpMethod() throws Exception { + servers = LaunchServers(NUM_SERVERS); + } + + @AfterEach + public void tearDownMethod() throws Exception { + servers.shutDownAllServers(); + } + + @Test + public void byteSizeTest() { + System.setProperty(EPHEMERAL_BYTE_LIMIT_KEY, Integer.toString(DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT)); + ZooKeeper leaderServer = servers.zk[servers.findLeader()]; + int cumulativeBytes = 0; + int i = 0; + while (cumulativeBytes <= DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT) { + cumulativeBytes += BinaryOutputArchive.getSerializedStringByteSize(TEST_PATH + i); + try { + leaderServer.create(TEST_PATH + i++, new byte[512], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); + } catch (Exception e) { + break; + } + } + long actual = (long) MetricsUtils.currentServerMetrics().get(EPHEMERAL_BYTE_LIMIT_VIOLATION_KEY); + System.out.println("byte limit property is: " + Integer.getInteger(EPHEMERAL_BYTE_LIMIT_KEY)); + assertEquals(1, actual); + } + + @Test + public void limitingEphemeralsTest() throws Exception { + System.setProperty(EPHEMERAL_BYTE_LIMIT_KEY, Integer.toString(DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT)); + ZooKeeper leaderServer = servers.zk[servers.findLeader()]; + String leaderSubPath = TEST_PATH + "-leader-"; + assertTrue(checkLimitEnforcedForServer(leaderServer, leaderSubPath, CreateMode.EPHEMERAL)); + + ZooKeeper followerServer = servers.zk[servers.findAnyFollower()]; + String followerSubPath = TEST_PATH + "-follower-"; + assertTrue(checkLimitEnforcedForServer(followerServer, followerSubPath, CreateMode.EPHEMERAL)); + + // Assert both servers emitted failure metric + long actual = (long) MetricsUtils.currentServerMetrics().get(EPHEMERAL_BYTE_LIMIT_VIOLATION_KEY); + assertEquals(2, actual); + } + + @Test + public void limitingSequentialEphemeralsTest() throws Exception { + System.setProperty(EPHEMERAL_BYTE_LIMIT_KEY, Integer.toString(DEFAULT_EPHEMERALNODES_TOTAL_BYTE_LIMIT)); + ZooKeeper leaderServer = servers.zk[servers.findLeader()]; + String leaderSubPath = TEST_PATH + "-leader-"; + assertTrue(checkLimitEnforcedForServer(leaderServer, leaderSubPath, CreateMode.EPHEMERAL_SEQUENTIAL)); + + ZooKeeper followerServer = servers.zk[servers.findAnyFollower()]; + String followerSubPath = TEST_PATH + "-follower-"; + assertTrue(checkLimitEnforcedForServer(followerServer, followerSubPath, CreateMode.EPHEMERAL_SEQUENTIAL)); + + // Assert both servers emitted failure metric + long actual = (long) MetricsUtils.currentServerMetrics().get(EPHEMERAL_BYTE_LIMIT_VIOLATION_KEY); + assertEquals(2, actual); + } + + public boolean checkLimitEnforcedForServer(ZooKeeper server, String subPath, CreateMode mode) throws Exception { + if (!mode.isEphemeral()) { + return false; + } + + int limit = Integer.getInteger(EPHEMERAL_BYTE_LIMIT_KEY); + int cumulativeBytes = 0; + + if (mode.isSequential()) { + int lastPathBytes = 0; + while (cumulativeBytes + lastPathBytes <= limit) { + String path = server.create(TEST_PATH + "-leader-", new byte[512], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); + lastPathBytes = BinaryOutputArchive.getSerializedStringByteSize(path); + cumulativeBytes += lastPathBytes; + } + + try { + server.create(TEST_PATH + "-leader-", new byte[512], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); + } catch (KeeperException.TotalEphemeralLimitExceeded e) { + return true; + } + return false; + } else { + int i = 0; + while (cumulativeBytes + BinaryOutputArchive.getSerializedStringByteSize(subPath + i) + <= limit) { + server.create(subPath + i, new byte[512], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); + cumulativeBytes += BinaryOutputArchive.getSerializedStringByteSize(subPath + i); + i++; + } + try { + server.create(subPath + "-follower-" + i, new byte[512], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); + } catch (KeeperException.TotalEphemeralLimitExceeded e) { + return true; + } + return false; + } + } + + @Test + public void rejectedEphemeralMetricsTest() throws Exception { + ZooKeeper leaderServer = servers.zk[servers.findLeader()]; + int expectedLimitExceededAttempts = 10; + int i = expectedLimitExceededAttempts; + int limit = Integer.getInteger(EPHEMERAL_BYTE_LIMIT_KEY); + int cumulativeBytes = 0; + int lastPathBytes = 0; + while (i > 0 || cumulativeBytes + lastPathBytes <= limit) { + try { + String path = leaderServer.create(TEST_PATH + "-leader-", new byte[512], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); + lastPathBytes = BinaryOutputArchive.getSerializedStringByteSize(path); + cumulativeBytes += lastPathBytes; + } catch (KeeperException.TotalEphemeralLimitExceeded e) { + LOG.info("Encountered TotalEphemeralLimitExceeded as expected, continuing..."); + i--; + } + } + + long actual = (long) MetricsUtils.currentServerMetrics().get(EPHEMERAL_BYTE_LIMIT_VIOLATION_KEY); + assertEquals(expectedLimitExceededAttempts, actual); + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/EphemeralNodeByteLimitTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EphemeralNodeByteLimitTest.java new file mode 100644 index 00000000000..30b24227c39 --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EphemeralNodeByteLimitTest.java @@ -0,0 +1,356 @@ +/* + * 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. + */ + +package org.apache.zookeeper.test; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Arrays; +import java.util.List; +import org.apache.jute.BinaryOutputArchive; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.KeeperException.Code; +import org.apache.zookeeper.Op; +import org.apache.zookeeper.OpResult; +import org.apache.zookeeper.TestableZooKeeper; +import org.apache.zookeeper.ZooDefs.Ids; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.metrics.MetricsUtils; +import org.apache.zookeeper.server.DataTree; +import org.apache.zookeeper.server.PrepRequestProcessor; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * Exercises the per-session ephemeral path-byte budget configured through + * {@code zookeeper.ephemeralNodes.total.byte.limit}. Each ephemeral node costs + * the serialized size of its full path (4-byte length prefix plus the UTF-8 + * bytes of the path). The budget is checked against committed state, so these + * tests issue requests serially unless they explicitly characterize a batch. + */ +public class EphemeralNodeByteLimitTest extends ClientBase { + + private static final int LIMIT = 60; + private static final String VIOLATION_METRIC = "ephemeral_node_limit_violation"; + private static final String EXTENDED_TYPES = "zookeeper.extendedTypesEnabled"; + + @BeforeAll + public static void setUpLimit() { + System.setProperty(ZooKeeperServer.EPHEMERAL_NODES_TOTAL_BYTE_LIMIT_KEY, Integer.toString(LIMIT)); + System.setProperty(EXTENDED_TYPES, "true"); + } + + @AfterAll + public static void clearLimit() { + System.clearProperty(ZooKeeperServer.EPHEMERAL_NODES_TOTAL_BYTE_LIMIT_KEY); + System.clearProperty(EXTENDED_TYPES); + } + + // 15 bytes each: 11 ASCII bytes plus the 4-byte length prefix. + private static String asciiPath(int i) { + return String.format("/node-%05d", i); + } + + private static int cost(String path) { + return path.getBytes(UTF_8).length + 4; + } + + private DataTree dataTree() { + return serverFactory.getZooKeeperServer().getZKDatabase().getDataTree(); + } + + private int accounted(ZooKeeper zk) { + return dataTree().getTotalEphemeralsByteSize(zk.getSessionId()); + } + + private static long violations() { + Object value = MetricsUtils.currentServerMetrics().get(VIOLATION_METRIC); + assertNotNull(value, VIOLATION_METRIC + " is not registered"); + return (Long) value; + } + + private static void assertBudgetExceeded(KeeperException e) { + assertTrue(e instanceof KeeperException.TotalEphemeralLimitExceeded, e.toString()); + assertEquals(Code.TOTALEPHEMERALLIMITEXCEEDED, e.code()); + assertEquals(-128, e.code().intValue()); + } + + private static void createEphemeralRejected(ZooKeeper zk, String path) { + KeeperException e = assertThrows(KeeperException.class, + () -> zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)); + assertBudgetExceeded(e); + } + + private static void createEphemeral(ZooKeeper zk, String path) throws Exception { + zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); + } + + @Test + public void testExactBoundaryAndRejection() throws Exception { + try (ZooKeeper zk = createClient()) { + for (int i = 0; i < 3; i++) { + createEphemeral(zk, asciiPath(i)); + } + assertEquals(45, accounted(zk)); + + long before = violations(); + String oneByteOver = "/node-00003x"; + assertEquals(16, cost(oneByteOver)); + try (LoggerTestTool log = new LoggerTestTool(PrepRequestProcessor.class)) { + createEphemeralRejected(zk, oneByteOver); + String logged = log.readLogLine("Rejecting ephemeral node creation"); + assertNotNull(logged); + assertTrue(logged.contains("Rejecting ephemeral node creation for session " + zk.getSessionId() + ", zxid "), logged); + assertTrue(logged.contains("path " + oneByteOver + "."), logged); + } + assertEquals(before + 1, violations()); + assertNull(zk.exists(oneByteOver, false)); + assertEquals(45, accounted(zk)); + + // 45 + 15 = 60 == limit is accepted + createEphemeral(zk, asciiPath(3)); + assertEquals(LIMIT, accounted(zk)); + + createEphemeralRejected(zk, "/a"); + assertEquals(before + 2, violations()); + assertEquals(LIMIT, accounted(zk)); + assertEquals(4, zk.getEphemerals().size()); + } + } + + @Test + public void testSerializedSizeUsesUtf8Bytes() throws Exception { + String threeCjk = "/\u4e2d\u4e2d\u4e2d"; + String fourCjk = "/\u4e2d\u4e2d\u4e2d\u4e2d"; + String twoByte = "/\u00e9\u00e9"; + assertEquals(14, cost(threeCjk)); + assertEquals(17, cost(fourCjk)); + assertEquals(9, cost(twoByte)); + assertEquals(cost(threeCjk), BinaryOutputArchive.getSerializedStringByteSize(threeCjk)); + assertEquals(cost(twoByte), BinaryOutputArchive.getSerializedStringByteSize(twoByte)); + + try (ZooKeeper zk = createClient()) { + for (int i = 0; i < 3; i++) { + createEphemeral(zk, asciiPath(i)); + } + // 15 bytes remain: fourCjk has only 5 chars but costs 17 bytes. + createEphemeralRejected(zk, fourCjk); + createEphemeral(zk, threeCjk); + assertEquals(59, accounted(zk)); + assertEquals(threeCjk, zk.getEphemerals("/\u4e2d").get(0)); + + zk.delete(threeCjk, -1); + createEphemeral(zk, twoByte); + assertEquals(54, accounted(zk)); + } + } + + @Test + public void testSequentialNodesAreChargedForFinalPath() throws Exception { + try (ZooKeeper zk = createClient()) { + String first = zk.create("/seq-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); + assertEquals("/seq-0000000000", first); + assertEquals(19, accounted(zk)); + zk.create("/seq-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); + zk.create("/seq-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); + assertEquals(57, accounted(zk)); + + // The 9-byte prefix would fit, the 19-byte final path does not. + KeeperException e = assertThrows(KeeperException.class, + () -> zk.create("/seq-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL)); + assertBudgetExceeded(e); + assertEquals(57, accounted(zk)); + } + } + + @Test + public void testOnlySessionEphemeralsAreCharged() throws Exception { + try (ZooKeeper zk = createClient()) { + for (int i = 0; i < 4; i++) { + createEphemeral(zk, asciiPath(i)); + } + assertEquals(LIMIT, accounted(zk)); + createEphemeralRejected(zk, "/a"); + + zk.create("/persistent", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + zk.create("/persistent/seq-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); + zk.create("/container", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER); + zk.create("/ttl", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, null, 60000); + assertEquals(LIMIT, accounted(zk)); + assertEquals(4, zk.getEphemerals().size()); + } + } + + @Test + public void testSessionsHaveIndependentBudgets() throws Exception { + try (ZooKeeper first = createClient(); ZooKeeper second = createClient()) { + for (int i = 0; i < 4; i++) { + createEphemeral(first, asciiPath(i)); + } + createEphemeralRejected(first, "/a"); + + for (int i = 4; i < 8; i++) { + createEphemeral(second, asciiPath(i)); + } + createEphemeralRejected(second, "/b"); + assertEquals(LIMIT, accounted(first)); + assertEquals(LIMIT, accounted(second)); + } + } + + @Test + public void testDeleteReleasesBudget() throws Exception { + try (ZooKeeper zk = createClient()) { + for (int i = 0; i < 4; i++) { + createEphemeral(zk, asciiPath(i)); + } + createEphemeralRejected(zk, asciiPath(4)); + + zk.delete(asciiPath(0), -1); + assertEquals(45, accounted(zk)); + createEphemeral(zk, asciiPath(4)); + assertEquals(LIMIT, accounted(zk)); + + // A failed delete does not change the accounting. + assertThrows(KeeperException.BadVersionException.class, () -> zk.delete(asciiPath(1), 100)); + assertEquals(LIMIT, accounted(zk)); + } + } + + @Test + public void testCloseAndExpiryClearAccounting() throws Exception { + ZooKeeper closed = createClient(); + long closedId = closed.getSessionId(); + createEphemeral(closed, asciiPath(0)); + assertEquals(15, dataTree().getTotalEphemeralsByteSize(closedId)); + closed.close(); + assertEquals(0, dataTree().getTotalEphemeralsByteSize(closedId)); + + try (ZooKeeper observer = createClient()) { + ZooKeeper expired = createClient(); + long expiredId = expired.getSessionId(); + createEphemeral(expired, asciiPath(1)); + createEphemeral(expired, asciiPath(2)); + assertEquals(30, dataTree().getTotalEphemeralsByteSize(expiredId)); + + serverFactory.getZooKeeperServer().expire(expiredId); + waitForNodeRemoval(observer, asciiPath(2)); + assertEquals(0, dataTree().getTotalEphemeralsByteSize(expiredId)); + expired.close(); + + // The budget of a new session is not affected by the previous ones. + for (int i = 3; i < 7; i++) { + createEphemeral(observer, asciiPath(i)); + } + assertEquals(LIMIT, accounted(observer)); + } + } + + private static void waitForNodeRemoval(ZooKeeper zk, String path) throws Exception { + long deadline = System.currentTimeMillis() + CONNECTION_TIMEOUT; + while (zk.exists(path, false) != null) { + assertTrue(System.currentTimeMillis() < deadline, path + " still exists"); + Thread.sleep(50); + } + } + + @Test + public void testReconnectKeepsSessionBudget() throws Exception { + CountdownWatcher watcher = new CountdownWatcher(); + try (TestableZooKeeper zk = createClient(watcher)) { + long sessionId = zk.getSessionId(); + for (int i = 0; i < 4; i++) { + createEphemeral(zk, asciiPath(i)); + } + + watcher.reset(); + zk.testableConnloss(); + watcher.waitForConnected(CONNECTION_TIMEOUT); + assertEquals(sessionId, zk.getSessionId()); + + createEphemeralRejected(zk, "/a"); + assertEquals(LIMIT, accounted(zk)); + zk.delete(asciiPath(3), -1); + createEphemeral(zk, "/a"); + assertEquals(51, accounted(zk)); + } + } + + @Test + public void testRejectedOrFailedMultiDoesNotChangeAccounting() throws Exception { + try (ZooKeeper zk = createClient()) { + for (int i = 0; i < 3; i++) { + createEphemeral(zk, asciiPath(i)); + } + long before = violations(); + + List rejected = Arrays.asList( + Op.create("/persistent", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), + Op.create("/node-00003x", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)); + KeeperException e = assertThrows(KeeperException.class, () -> zk.multi(rejected)); + assertBudgetExceeded(e); + List results = e.getResults(); + assertEquals(Code.TOTALEPHEMERALLIMITEXCEEDED.intValue(), ((OpResult.ErrorResult) results.get(1)).getErr()); + assertEquals(before + 1, violations()); + assertNull(zk.exists("/persistent", false)); + assertEquals(45, accounted(zk)); + + List failed = Arrays.asList( + Op.create(asciiPath(3), new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL), + Op.check(asciiPath(0), 100)); + assertThrows(KeeperException.BadVersionException.class, () -> zk.multi(failed)); + assertNull(zk.exists(asciiPath(3), false)); + assertEquals(45, accounted(zk)); + assertEquals(before + 1, violations()); + } + } + + /** + * The budget is best effort: each create is checked against the committed + * per-session total only, so creates in the same multi (or otherwise in + * flight together) are not counted against each other and the committed + * total can end up above the configured value. + */ + @Test + public void testCreatesInOneMultiAreCheckedAgainstCommittedTotal() throws Exception { + try (ZooKeeper zk = createClient()) { + for (int i = 0; i < 3; i++) { + createEphemeral(zk, asciiPath(i)); + } + zk.multi(Arrays.asList( + Op.create(asciiPath(3), new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL), + Op.create(asciiPath(4), new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL))); + assertEquals(75, accounted(zk)); + assertFalse(accounted(zk) <= LIMIT); + + createEphemeralRejected(zk, "/a"); + zk.delete(asciiPath(0), -1); + zk.delete(asciiPath(1), -1); + createEphemeral(zk, "/a"); + assertEquals(51, accounted(zk)); + } + } +} From 32a4c412e5024cf1ba6579bf6c4a723a3989baa3 Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Thu, 19 Nov 2026 13:03:34 +0530 Subject: [PATCH 2/4] Fix import order in ported ephemeral throttling test Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../zookeeper/server/quorum/EphemeralNodeThrottlingTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java index 08756ef7086..af4721a24ec 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeThrottlingTest.java @@ -26,10 +26,10 @@ import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.metrics.MetricsUtils; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; From 110310908159a88e60b88f27932c040d4f7bd207 Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Sun, 22 Nov 2026 21:25:58 +0530 Subject: [PATCH 3/4] Document ephemeral-budget compatibility and enforcement limits Describe the custom -128 client requirement, the published fork client that recognizes it, and the inherited committed-state and snapshot accounting limitations. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/main/resources/markdown/zookeeperAdmin.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md index 48f23721404..d16f8af8f67 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md @@ -1160,6 +1160,21 @@ property, when available, is noted below. This limit should always be under the jute maxbuffer, as exceeding will cause the server to crash when the connection is closed and a transaction to delete all the ephemeral nodes for that session are deleted. This limit will be ignored if not explicitly set. + This is a best-effort check against committed state: concurrent requests and + creates within one multi operation can exceed the configured value. Snapshot + loading does not rebuild the byte totals, so this is not a strict bound across + recovery or snapshot synchronization. + + **Client compatibility:** Exceeding an enabled limit returns the custom error code + `-128` (`TOTALEPHEMERALLIMITEXCEEDED`). Before enabling it, use clients that recognize + this code; an Apache ZooKeeper version number alone does not establish support. + The published fork client `com.linkedin.zookeeper:zookeeper:3.8.4-0` recognizes + this error code; this alone does not qualify other aspects of client compatibility. + The default value, `-1`, disables this limit. Keep it disabled when incompatible + clients are present. Older fork servers return `-125` for the same restriction, + which newer clients interpret as `QUOTAEXCEEDED`; mixed-version rollouts must + also account for this ambiguity. + * *outstandingHandshake.limit* (Java system property only: **zookeeper.netty.server.outstandingHandshake.limit**) The maximum in-flight TLS handshake connections could have in ZooKeeper, From 55f79df820e82ea586e9ef4257df8d5ac9524b4b Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Tue, 1 Dec 2026 17:43:48 +0530 Subject: [PATCH 4/4] Clarify ephemeral-budget upgrade compatibility Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../main/resources/markdown/zookeeperAdmin.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md index d16f8af8f67..75b3796efa3 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md @@ -1168,12 +1168,24 @@ property, when available, is noted below. **Client compatibility:** Exceeding an enabled limit returns the custom error code `-128` (`TOTALEPHEMERALLIMITEXCEEDED`). Before enabling it, use clients that recognize this code; an Apache ZooKeeper version number alone does not establish support. + In particular, `3.6.3-35` Java clients receiving `-128` throw + `NullPointerException` on synchronous calls instead of a `KeeperException`. The published fork client `com.linkedin.zookeeper:zookeeper:3.8.4-0` recognizes this error code; this alone does not qualify other aspects of client compatibility. The default value, `-1`, disables this limit. Keep it disabled when incompatible clients are present. Older fork servers return `-125` for the same restriction, - which newer clients interpret as `QUOTAEXCEEDED`; mixed-version rollouts must - also account for this ambiguity. + which newer clients interpret as `QUOTAEXCEEDED`. In the reverse direction, + `3.6.3-35` clients receiving a newer server's native `QUOTAEXCEEDED` (`-125`) + error report `TotalEphemeralLimitExceeded`. + + **Mixed-version rollouts:** Keep this limit disabled (`-1`) on all participating + servers, and keep native quota enforcement disabled + (`zookeeper.enforceQuota=false`) on newer servers. These are separate controls: + disabling only this limit does not prevent the native-quota `-125` collision. + These settings mitigate the affected error paths; they do not make the error + codes backward-compatible. Enable either enforcement feature only after + qualifying the actual server/client matrix, including rollback. If either + protection must remain enabled, establish a compatible rollout before upgrading. * *outstandingHandshake.limit* (Java system property only: **zookeeper.netty.server.outstandingHandshake.limit**)