Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md
Original file line number Diff line number Diff line change
Expand Up @@ -1153,6 +1153,40 @@ 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.

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.
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`. 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**)
The maximum in-flight TLS handshake connections could have in ZooKeeper,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
@@ -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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Comment thread
bellatrix007 marked this conversation as resolved.
Resolved

private static final Map<Integer, Code> lookup = new HashMap<Integer, Code>();

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -980,4 +987,11 @@ public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}

public static class TotalEphemeralLimitExceeded extends KeeperException {
public TotalEphemeralLimitExceeded() {
super(Code.TOTALEPHEMERALLIMITEXCEEDED);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -161,6 +163,7 @@ public class DataTree {
* This hashtable lists the paths of the ephemeral nodes of a session.
*/
private final Map<Long, HashSet<String>> ephemerals = new ConcurrentHashMap<Long, HashSet<String>>();
private final Map<Long, AtomicInteger> ephemeralsByteSizeMap = new ConcurrentHashMap<Long, AtomicInteger>();

/**
* This set contains the paths of all container nodes
Expand Down Expand Up @@ -223,6 +226,11 @@ public Set<String> getEphemerals(long sessionId) {
return cloned;
}

public int getTotalEphemeralsByteSize(long sessionID) {
AtomicInteger byteSize = ephemeralsByteSizeMap.get(sessionID);
return byteSize != null ? byteSize.get() : 0;
}

public Set<String> getContainers() {
return new HashSet<String>(containers);
}
Expand Down Expand Up @@ -535,13 +543,22 @@ public void createNode(final String path, byte[] data, List<ACL> acl, long ephem
ttls.add(path);
} else if (ephemeralOwner != 0) {
HashSet<String> list = ephemerals.get(ephemeralOwner);
AtomicInteger totalEphemeralsByteSize = ephemeralsByteSizeMap.get(ephemeralOwner);
if (list == null) {
list = new HashSet<String>();
ephemerals.put(ephemeralOwner, list);
}
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);
Expand Down Expand Up @@ -631,9 +648,15 @@ public void deleteNode(String path, long zxid) throws KeeperException.NoNodeExce
ttls.remove(path);
} else if (eowner != 0) {
Set<String> 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)));
}
}
}
Expand Down Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -178,6 +185,10 @@ public static void setCloseSessionTxnEnabled(boolean enabled) {
ZooKeeperServer.closeSessionTxnEnabled);
}

public static int getEphemeralNodesTotalByteLimit() {
return ephemeralNodesTotalByteLimit;
}

protected ZooKeeperServerBean jmxServerBean;
protected DataTreeBean jmxDataTreeBean;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,18 @@ private void createEphemeralNode(long session, final DataTree dataTree, int coun
}
}

@Test
public void testEphemeralByteSizeNotTrackedWhenLimitDisabled() throws Exception {
assertEquals(-1, ZooKeeperServer.getEphemeralNodesTotalByteLimit());
Comment thread
bellatrix007 marked this conversation as resolved.
Resolved
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 {
Expand Down
Loading