diff --git a/zookeeper-jute/src/main/resources/zookeeper.jute b/zookeeper-jute/src/main/resources/zookeeper.jute index 796ea396755..5e1f734489f 100644 --- a/zookeeper-jute/src/main/resources/zookeeper.jute +++ b/zookeeper-jute/src/main/resources/zookeeper.jute @@ -51,6 +51,10 @@ module org.apache.zookeeper.data { long ephemeralOwner; // owner id if ephemeral, 0 otw long pzxid; // last modified children } + class PathWithStat { + ustring path; + org.apache.zookeeper.data.Stat stat; + } class ClientInfo { ustring authScheme; // Authentication scheme @@ -162,6 +166,13 @@ module org.apache.zookeeper.proto { ustring path; boolean watch; } + class GetChildrenPaginatedRequest { + ustring path; + int maxReturned; + long minCzxid; + int czxidOffset; + boolean watch; + } class CheckVersionRequest { ustring path; int version; @@ -233,6 +244,12 @@ module org.apache.zookeeper.proto { vector children; org.apache.zookeeper.data.Stat stat; } + class GetChildrenPaginatedResponse { + vector children; + org.apache.zookeeper.data.Stat stat; + long nextPageCzxid; + int nextPageCzxidOffset; + } class GetACLResponse { vector acl; org.apache.zookeeper.data.Stat stat; diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/ChildrenBatchIterator.java b/zookeeper-server/src/main/java/org/apache/zookeeper/ChildrenBatchIterator.java new file mode 100644 index 00000000000..572928452eb --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/ChildrenBatchIterator.java @@ -0,0 +1,95 @@ +/** + * 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; + +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; + +/** + * Iterator over children nodes of a given path. + *

+ * Note: the final collection of children may not be strongly consistent with the server. + * If there are concurrent writes to the children during iteration, the final collection could + * miss some children or contain some duplicate children. + * + * @see ZooKeeper#getAllChildrenPaginated(String, boolean) + */ +class ChildrenBatchIterator implements RemoteIterator { + + private final ZooKeeper zooKeeper; + private final String path; + private final Watcher watcher; + private final int batchSize; + private final LinkedList childrenQueue; + private final PaginationNextPage nextPage; + private long nextBatchMinZxid; + private int nextBatchZxidOffset; + + + ChildrenBatchIterator(ZooKeeper zooKeeper, String path, Watcher watcher, int batchSize, long minZxid) + throws KeeperException, InterruptedException { + this.zooKeeper = zooKeeper; + this.path = path; + this.watcher = watcher; + this.batchSize = batchSize; + this.nextBatchZxidOffset = 0; + this.nextBatchMinZxid = minZxid; + + this.childrenQueue = new LinkedList<>(); + this.nextPage = new PaginationNextPage(); + + batchGetChildren(); + } + + @Override + public boolean hasNext() { + // next() never lets childrenQueue empty unless we iterated over all children + return !childrenQueue.isEmpty(); + } + + @Override + public String next() throws KeeperException, InterruptedException { + if (!hasNext()) { + throw new NoSuchElementException("No more children"); + } + + // If we're down to the last element, backfill before returning it + if (childrenQueue.size() == 1 && nextBatchMinZxid != ZooDefs.GetChildrenPaginated.lastPageMinCzxid) { + batchGetChildren(); + } + + return childrenQueue.pop(); + } + + /** + * Prepare minZxid and zxidOffset for the next batch request + */ + private void updateOffsetsForNextBatch() { + nextBatchMinZxid = nextPage.getMinCzxid(); + nextBatchZxidOffset = nextPage.getMinCzxidOffset(); + } + + private void batchGetChildren() throws KeeperException, InterruptedException { + List childrenBatch = + zooKeeper.getChildren(path, watcher, batchSize, nextBatchMinZxid, nextBatchZxidOffset, null, nextPage); + childrenQueue.addAll(childrenBatch); + updateOffsetsForNextBatch(); + } +} \ No newline at end of file diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/PaginationNextPage.java b/zookeeper-server/src/main/java/org/apache/zookeeper/PaginationNextPage.java new file mode 100644 index 00000000000..6726412b49f --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/PaginationNextPage.java @@ -0,0 +1,53 @@ +/* + * 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; + +import org.apache.yetus.audience.InterfaceAudience; + +/** + * Represents the info used to fetch the next page of data for pagination. + */ +@InterfaceAudience.Public +public class PaginationNextPage { + private long minCzxid; + private int minCzxidOffset; + + public long getMinCzxid() { + return minCzxid; + } + + public void setMinCzxid(long minCzxid) { + this.minCzxid = minCzxid; + } + + public int getMinCzxidOffset() { + return minCzxidOffset; + } + + public void setMinCzxidOffset(int minCzxidOffset) { + this.minCzxidOffset = minCzxidOffset; + } + + @Override + public String toString() { + return "PaginationNextPage{" + + "minCzxid=" + minCzxid + + ", minCzxidOffset=" + minCzxidOffset + + '}'; + } +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/RemoteIterator.java b/zookeeper-server/src/main/java/org/apache/zookeeper/RemoteIterator.java new file mode 100644 index 00000000000..af25b71b748 --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/RemoteIterator.java @@ -0,0 +1,44 @@ +/** + * 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; + +import java.util.NoSuchElementException; + +/** + * An iterator over a collection whose elements need to be fetched remotely. + */ +public interface RemoteIterator { + + /** + * Returns true if the iterator has more elements. + * + * @return true if the iterator has more elements, false otherwise. + */ + boolean hasNext(); + + /** + * Returns the next element in the iteration. + * + * @return the next element in the iteration. + * @throws InterruptedException if the thread is interrupted + * @throws KeeperException if an error is encountered server-side + * @throws NoSuchElementException if the iteration has no more elements + */ + E next() throws InterruptedException, KeeperException; +} \ No newline at end of file diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/ZooDefs.java b/zookeeper-server/src/main/java/org/apache/zookeeper/ZooDefs.java index 9cf70787668..12d1ff21d72 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/ZooDefs.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/ZooDefs.java @@ -79,6 +79,8 @@ public interface OpCode { int multiRead = 22; + int getChildrenPaginated = 71; + int auth = 100; int setWatches = 101; @@ -161,6 +163,13 @@ public interface AddWatchModes { int persistentRecursive = 1; // matches AddWatchMode.PERSISTENT_RECURSIVE } + @InterfaceAudience.Public + public interface GetChildrenPaginated { + // Represents the current fetched page is the final page, no more children left to fetch. + long lastPageMinCzxid = -1L; + int lastPageCzxidOffset = -1; + } + public static final String[] opNames = {"notification", "create", "delete", "exists", "getData", "setData", "getACL", "setACL", "getChildren", "getChildren2", "getMaxChildren", "setMaxChildren", "ping", "reconfig", "getConfig"}; } diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java b/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java index 127f5a2a3f3..9da67879c4b 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java @@ -66,6 +66,8 @@ import org.apache.zookeeper.proto.GetAllChildrenNumberResponse; import org.apache.zookeeper.proto.GetChildren2Request; import org.apache.zookeeper.proto.GetChildren2Response; +import org.apache.zookeeper.proto.GetChildrenPaginatedRequest; +import org.apache.zookeeper.proto.GetChildrenPaginatedResponse; import org.apache.zookeeper.proto.GetChildrenRequest; import org.apache.zookeeper.proto.GetChildrenResponse; import org.apache.zookeeper.proto.GetDataRequest; @@ -2368,6 +2370,220 @@ public List getChildren(final String path, Watcher watcher) throws Keepe return response.getChildren(); } + /** + * Returns the a subset (a "page") of the children node of the given path. + * + *

+ * The returned list contains children names up to {@code maxReturned}. The max number of returned children + * is limited by {@code jute.maxbuffer}. If the packet length of {@code maxReturned} children exceeds the limit, + * there will be less children returned, within the limit range. {@code outputNextPage} can be used in the next + * page to fetch the remaining children. + *

+ * + *

+ * If {@code watcher} is non-null, a watch on children creation/deletion is set when reaching the end of pagination + *

+ * + * @param path + * - the path of the node + * @param watcher + * - a concrete watcher or null + * @param maxReturned + * - the maximum number of children returned + * @param minCzxId + * - only return children whose creation zxid is equal or greater than {@code minCzxId} + * @param czxidOffset + * - how many children with zxid == minCzxId to skip server-side, as they were returned in previous pages + * @param outputStat + * - output stat of the znode designated by path. It is the stat of the znode when the znode's single + * page of children are returned. The {@code cversion} in stat could be used to validate data consistency + * for multiple pages of children fetched. + * @param outputNextPage + * - if not null, {@link PaginationNextPage} info returned from server will be copied to + * {@code outputNextPage}. The info can be used for fetching the next page of remaining children, + * or checking whether the returned page is the last page by comparing + * {@link PaginationNextPage#getMinCzxid()} with + * {@link org.apache.zookeeper.ZooDefs.GetChildrenPaginated#lastPageMinCzxid} + * @return + * a list of children nodes, up to {@code maxReturned}. + *

When params are set {@code maxReturned} = {@code Integer.MAX_VALUE}, {@code minCzxid} <= 0: + * the children list is unordered if all the children can be returned in a page; + *

Otherwise, the children list is ordered by czxid. + * @throws KeeperException + * if the server signals an error with a non-zero error code. + * @throws IllegalArgumentException + * if any of the following is true: + *

    + *
  • {@code path} is invalid + *
  • {@code maxReturned} is less than 1 + *
+ * + * @throws InterruptedException + * if the server transaction is interrupted. + * + * @since 3.6.2 + */ + public List getChildren(final String path, + Watcher watcher, + int maxReturned, + long minCzxId, + int czxidOffset, + Stat outputStat, + PaginationNextPage outputNextPage) + throws KeeperException, InterruptedException { + PathUtils.validatePath(path); + if (maxReturned <= 0) { + throw new IllegalArgumentException("Cannot return less than 1 children"); + } + + // the watch contains the un-chroot path + WatchRegistration wcb = null; + if (watcher != null) { + wcb = new ChildWatchRegistration(watcher, path); + } + + final String serverPath = prependChroot(path); + + RequestHeader h = new RequestHeader(); + h.setType(ZooDefs.OpCode.getChildrenPaginated); + GetChildrenPaginatedRequest request = new GetChildrenPaginatedRequest(); + request.setPath(serverPath); + request.setWatch(watcher != null); + request.setMaxReturned(maxReturned); + request.setMinCzxid(minCzxId); + request.setCzxidOffset(czxidOffset); + + GetChildrenPaginatedResponse response = new GetChildrenPaginatedResponse(); + ReplyHeader r = cnxn.submitRequest(h, request, response, wcb); + if (r.getErr() != 0) { + throw KeeperException.create(KeeperException.Code.get(r.getErr()), + path); + } + if (outputStat != null) { + DataTree.copyStat(response.getStat(), outputStat); + } + updateNextPage(outputNextPage, response.getNextPageCzxid(), response.getNextPageCzxidOffset()); + + return response.getChildren(); + } + + /** + * Returns a list of all the children given the path. + *

+ * The difference between this API and {@link #getChildren(String, boolean)} is: + * when there are lots of children and the network buffer exceeds {@code jute.maxbuffer}, + * this API will fetch the children using pagination and be able to return all children; + * while {@link #getChildren(String, boolean)} will fail. + *

+ * The final list of children returned is NOT strongly consistent with the server's data: + * the list might contain some deleted children if some children are deleted before the last page is fetched. + *

+ * If the watch is true and the call is successful (no exception is thrown), + # a watch will be left on the node with the given path. The watch will be + * triggered by a successful operation that deletes the node of the given + * path or creates/deletes a child under the node. + * + * @param path the path of the parent node + * @param watch whether or not leave a watch on the given node + * @return a unordered list of all children of the given path + * @throws IllegalStateException if watch this node with a null default watcher + * @throws KeeperException if the server signals an error with a non-zero error code. + * @throws InterruptedException if the server transaction is interrupted. + */ + public List getAllChildrenPaginated(String path, boolean watch) + throws KeeperException, InterruptedException { + PaginationNextPage nextPage = new PaginationNextPage(); + Watcher watcher = getDefaultWatcher(watch); + List childrenPaginated = getChildren(path, watcher, Integer.MAX_VALUE, 0L, 0, null, nextPage); + if (nextPage.getMinCzxid() == ZooDefs.GetChildrenPaginated.lastPageMinCzxid) { + return childrenPaginated; + } + + Set childrenSet = getChildrenRemainingPages(path, watcher, nextPage, childrenPaginated); + + return new ArrayList<>(childrenSet); + } + + private Set getChildrenRemainingPages(String path, + Watcher watcher, + PaginationNextPage nextPage, + List childrenPage) + throws KeeperException, InterruptedException { + Set allChildrenSet = new HashSet<>(childrenPage); + int retryCount = 0; + + do { + long minCzxid = nextPage.getMinCzxid(); + if (nextPage.getMinCzxidOffset() == 0) { + childrenPage = getChildren(path, watcher, Integer.MAX_VALUE, minCzxid, + nextPage.getMinCzxidOffset(), null, nextPage); + } else { + // If a child with the same czxid is returned in the previous page, and then deleted + // on the server, the children not in the previous page but offset is less than czxidOffset + // would be missed in the next page. Use the last child in the previous page to determine whether or not + // the deletion case happens. If it happens, retry fetching the page starting from offset 0. + String lastChild = childrenPage.isEmpty() ? "" : childrenPage.get(childrenPage.size() - 1); + childrenPage = getChildren(path, watcher, Integer.MAX_VALUE, minCzxid, + nextPage.getMinCzxidOffset() - 1, null, nextPage); + if (!lastChild.equals(childrenPage.get(0))) { + if (retryCount++ >= 5) { + LOG.warn("Failed to fetch children pages because of znode deletion and retries exceeding 5"); + throw KeeperException.create(KeeperException.Code.OPERATIONTIMEOUT); + } + LOG.info("Due to znode deletion, retry fetching children from offset 0 for minCzxid={}, retries={}", + minCzxid, retryCount); + childrenPage = getChildren(path, watcher, Integer.MAX_VALUE, minCzxid, 0, null, nextPage); + } + } + allChildrenSet.addAll(childrenPage); + } while (nextPage.getMinCzxid() != ZooDefs.GetChildrenPaginated.lastPageMinCzxid); + + return allChildrenSet; + } + + private void updateNextPage(PaginationNextPage nextPage, long minCzxId, int czxIdOffset) { + if (nextPage != null) { + nextPage.setMinCzxid(minCzxId); + nextPage.setMinCzxidOffset(czxIdOffset); + } + } + + /** + * Returns the a RemoteIterator over the children nodes of the given path. + * + *

+ * If {@code watcher} is non-null, a watch on children creation/deletion is set when reaching the end the iterator + *

+ * + * @param path + * - the path of the node + * @param watcher + * - a concrete watcher or null + * @param batchSize + * - the maximum number of children returned by each background call to the server + * @param minCzxId + * - only return children whose creation zkid is equal or greater than {@code minCzxId} + * + * @return + * an iterator on children node, ordered by czxid + * @throws KeeperException + * if the server signals an error with a non-zero error code. + * @throws IllegalArgumentException + * if any of the following is true: + *
    + *
  • {@code path} is invalid + *
  • {@code maxReturned} is less than 1 + *
+ * @throws InterruptedException + * if the server transaction is interrupted. + * + * @since 3.6.2 + */ + public RemoteIterator getChildrenIterator(String path, Watcher watcher, int batchSize, long minCzxId) + throws KeeperException, InterruptedException { + return new ChildrenBatchIterator(this, path, watcher, batchSize, minCzxId); + } + /** * Return the list of the children of the node of the given path. *

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 265c44e4101..e545664ff74 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 @@ -21,10 +21,12 @@ import java.io.EOFException; import java.io.IOException; import java.io.PrintWriter; +import java.io.Serializable; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; @@ -34,6 +36,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import org.apache.jute.BinaryInputArchive; import org.apache.jute.InputArchive; import org.apache.jute.OutputArchive; import org.apache.jute.Record; @@ -42,6 +45,7 @@ import org.apache.zookeeper.KeeperException.Code; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NodeExistsException; +import org.apache.zookeeper.PaginationNextPage; import org.apache.zookeeper.Quotas; import org.apache.zookeeper.StatsTrack; import org.apache.zookeeper.WatchedEvent; @@ -58,8 +62,12 @@ import org.apache.zookeeper.common.PathTrie; import org.apache.zookeeper.common.PathUtils; import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.PathWithStat; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.data.StatPersisted; +import org.apache.zookeeper.proto.GetChildrenPaginatedResponse; +import org.apache.zookeeper.proto.ReplyHeader; +import org.apache.zookeeper.server.util.SerializeUtils; import org.apache.zookeeper.server.watch.IWatchManager; import org.apache.zookeeper.server.watch.WatchManagerFactory; import org.apache.zookeeper.server.watch.WatcherMode; @@ -173,6 +181,18 @@ public class DataTree { // to align and compare between servers. public static final int DIGEST_LOG_INTERVAL = 128; + // Constants used to calculate response packet length for the paginated children list. + // packetLength = (childNameLength + PAGINATION_PACKET_CHILD_EXTRA_BYTES) * numChildren + // + PAGINATION_PACKET_BASE_BYTES + public static final int PAGINATION_PACKET_BASE_BYTES; + public static final int PAGINATION_PACKET_CHILD_EXTRA_BYTES; + + static { + PAGINATION_PACKET_BASE_BYTES = getPaginationPacketLength(Collections.emptyList()); + PAGINATION_PACKET_CHILD_EXTRA_BYTES = + getPaginationPacketLength(Collections.singletonList("")) - PAGINATION_PACKET_BASE_BYTES; + } + // If this is not null, we are actively looking for a target zxid that we // want to validate the digest for private ZxidDigest digestFromLoadedSnapshot; @@ -258,6 +278,19 @@ private static long getNodeSize(String path, byte[] data) { return (path == null ? 0 : path.length()) + (data == null ? 0 : data.length); } + private static int getPaginationPacketLength(List children) { + try { + Record record = new GetChildrenPaginatedResponse(children, new Stat(), 0, 0); + ReplyHeader header = new ReplyHeader(); + byte[] recordBytes = SerializeUtils.serializeRecord(record); + byte[] headerBytes = SerializeUtils.serializeRecord(header); + return recordBytes.length + headerBytes.length; + } catch (IOException e) { + LOG.warn("Unexpected exception. Destruction averted.", e); + return 0; + } + } + public long cachedApproximateDataSize() { return nodeDataSize.get(); } @@ -308,6 +341,9 @@ public DataTree() { LOG.error("Unexpected exception when creating WatchManager, exiting abnormally", e); ServiceUtils.requestSystemExit(ExitCode.UNEXPECTED_ERROR.getValue()); } + + LOG.info("Pagination packet length formula constants: child extra = {} bytes, base = {} bytes", + PAGINATION_PACKET_CHILD_EXTRA_BYTES, PAGINATION_PACKET_BASE_BYTES); } /** @@ -767,6 +803,211 @@ public int getAllChildrenNumber(String path) { return (int) nodes.entrySet().parallelStream().filter(entry -> entry.getKey().startsWith(path + "/")).count(); } + /** + * Comparator used to sort children by creation time (older to newer) compare lexicographically to break ties + */ + private static class NodeCreationComparator implements Comparator, Serializable { + @Override + public int compare(PathWithStat left, PathWithStat right) { + final long leftCzxId = left.getStat().getCzxid(); + final long rightCzxId = right.getStat().getCzxid(); + + if (leftCzxId < rightCzxId) { + return -1; + } else if (leftCzxId > rightCzxId) { + return 1; + } else { + // For nodes with the same creation time (created with multi()), use name to order + return left.getPath().compareTo(right.getPath()); + } + } + } + + /** + * Static comparator instance, avoids creating and destroying a new one at each invocation of the method below + */ + private static NodeCreationComparator staticNodeCreationComparator = new NodeCreationComparator(); + + /** + * Produces a paginated list of the children of a given path + * @param path path of node node to list + * @param stat stat of the node to list + * @param watcher an optional watcher to attach to the node. The watcher is added only once + * when reaching the end of pagination + * @param maxReturned maximum number of children to return. + * @param minCzxId only return children whose creation zxid equal or greater than minCzxId + * @param czxIdOffset how many children with zxid == minCzxId to skip (as returned in previous pages) + * @param outputNextPage info to be used for the next page call + * @return A list of child names of the given path + * @throws NoNodeException if the path does not exist + */ + public List getPaginatedChildren(String path, Stat stat, Watcher watcher, int maxReturned, + long minCzxId, int czxIdOffset, PaginationNextPage outputNextPage) + throws NoNodeException { + DataNode n = nodes.get(path); + if (n == null) { + throw new KeeperException.NoNodeException(); + } + + if (maxReturned == Integer.MAX_VALUE && minCzxId <= 0) { + List allChildren; + boolean canFitInMaxBuffer = false; + // Need to lock the parent node for the whole block between reading children list and adding watch + synchronized (n) { + if (stat != null) { + n.copyStat(stat); + } + allChildren = new ArrayList<>(n.getChildren()); + if (canPacketFitInMaxBuffer(computeChildrenPacketLength(allChildren))) { + // If all children can be returned in the first page, just return them without sorting. + canFitInMaxBuffer = true; + if (watcher != null) { + childWatches.addWatch(path, watcher); + } + } + } + if (canFitInMaxBuffer) { + updateReadStat(path, countReadChildrenBytes(allChildren)); + if (outputNextPage != null) { + outputNextPage.setMinCzxid(ZooDefs.GetChildrenPaginated.lastPageMinCzxid); + outputNextPage.setMinCzxidOffset(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset); + } + return allChildren; + } + } + + return getSortedPaginatedChildren(n, path, stat, watcher, maxReturned, minCzxId, czxIdOffset, outputNextPage); + } + + private List getSortedPaginatedChildren(DataNode node, String path, Stat stat, Watcher watcher, + int maxReturned, long minCzxId, int czxIdOffset, + PaginationNextPage outputNextPage) { + int index = 0; + List targetChildren = new ArrayList(); + List paginatedChildren = new ArrayList(); + + // Need to lock the parent node for the whole block between reading children list and adding watch + synchronized (node) { + buildChildrenPathWithStat(node, path, stat, minCzxId, targetChildren); + + targetChildren.sort(staticNodeCreationComparator); + + // Go over the ordered list of children and skip the first czxIdOffset + // that have czxid equal to minCzxId, if any + while (index < targetChildren.size() && index < czxIdOffset) { + if (targetChildren.get(index).getStat().getCzxid() > minCzxId) { + // We moved past the minCzxId, no point in looking further + break; + } + index++; + } + + // Return as list preserving older-to-newer order + // Add children up to maxReturned and just below the max network buffer + for (int packetLength = PAGINATION_PACKET_BASE_BYTES; + index < targetChildren.size() && paginatedChildren.size() < maxReturned; + index++) { + String child = targetChildren.get(index).getPath(); + packetLength += child.length() + PAGINATION_PACKET_CHILD_EXTRA_BYTES; + if (!canPacketFitInMaxBuffer(packetLength)) { + // Stop adding more children to ensure packet is below max buffer + break; + } + paginatedChildren.add(child); + } + + // Decrement index as it was incremented once before exiting the for-loop. + index--; + + if (index == targetChildren.size() - 1 && watcher != null) { + // All children are added so this is the last page, set the watch + childWatches.addWatch(path, watcher); + } + } + + updateNextPage(outputNextPage, targetChildren, index); + updateReadStat(path, countReadChildrenBytes(paginatedChildren)); + + return paginatedChildren; + } + + private boolean canPacketFitInMaxBuffer(int packetLength) { + return packetLength <= BinaryInputArchive.maxBuffer; + } + + private int countReadChildrenBytes(Collection children) { + return children.stream().mapToInt(String::length).sum(); + } + + private void buildChildrenPathWithStat(DataNode n, String path, Stat stat, long minCzxId, + List targetChildren) { + synchronized (n) { + if (stat != null) { + n.copyStat(stat); + } + // The root's children are keyed as "/child", not "//child" + final String prefix = "/".equals(path) ? path : path + "/"; + for (String child : n.getChildren()) { + DataNode childNode = nodes.get(prefix + child); + if (null != childNode) { + final long czxId = childNode.stat.getCzxid(); + + if (czxId < minCzxId) { + // Filter out nodes that are below minCzxId + continue; + } + + Stat childStat = new Stat(); + childNode.copyStat(childStat); + + // Cannot discard before having sorted and removed offset + targetChildren.add(new PathWithStat(child, childStat)); + } + } + } + } + + /* + * totalLength = (PAGINATION_PACKET_CHILD_EXTRA_BYTES + childLength) * numChildren + PAGINATION_PACKET_BASE_BYTES + */ + private int computeChildrenPacketLength(Collection children) { + int length = children.stream().mapToInt(child -> PAGINATION_PACKET_CHILD_EXTRA_BYTES + child.length()).sum(); + return length + PAGINATION_PACKET_BASE_BYTES; + } + + private void updateNextPage(PaginationNextPage nextPage, List children, int lastAddedIndex) { + if (nextPage == null) { + return; + } + if (lastAddedIndex == children.size() - 1) { + // All children are added, so this is the last page + nextPage.setMinCzxid(ZooDefs.GetChildrenPaginated.lastPageMinCzxid); + nextPage.setMinCzxidOffset(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset); + return; + } + + long lastCzxid = children.get(lastAddedIndex).getStat().getCzxid(); + long nextCzxid = children.get(lastAddedIndex + 1).getStat().getCzxid(); + int nextCzixdOffset = 0; + + if (nextCzxid == lastCzxid) { + // Find the minCzxidOffset next next page by searching the index (startIndex) of czxid + // that is not equal to current czxid. + // minCzxidOffset of next page = lastAddedIndex - startIndex + int startIndex = lastAddedIndex; + while (startIndex >= 0) { + if (children.get(startIndex).getStat().getCzxid() != lastCzxid) { + break; + } + startIndex--; + } + nextCzixdOffset = lastAddedIndex - startIndex; + } + + nextPage.setMinCzxid(nextCzxid); + nextPage.setMinCzxidOffset(nextCzixdOffset); + } + public Stat setACL(String path, List acl, int version) throws KeeperException.NoNodeException { Stat stat = new Stat(); DataNode n = nodes.get(path); diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/FinalRequestProcessor.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/FinalRequestProcessor.java index d90f1084801..67c51ef5d88 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/FinalRequestProcessor.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/FinalRequestProcessor.java @@ -42,6 +42,7 @@ import org.apache.zookeeper.OpResult.GetChildrenResult; import org.apache.zookeeper.OpResult.GetDataResult; import org.apache.zookeeper.OpResult.SetDataResult; +import org.apache.zookeeper.PaginationNextPage; import org.apache.zookeeper.Watcher.WatcherType; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooDefs.OpCode; @@ -63,6 +64,8 @@ import org.apache.zookeeper.proto.GetAllChildrenNumberResponse; import org.apache.zookeeper.proto.GetChildren2Request; import org.apache.zookeeper.proto.GetChildren2Response; +import org.apache.zookeeper.proto.GetChildrenPaginatedRequest; +import org.apache.zookeeper.proto.GetChildrenPaginatedResponse; import org.apache.zookeeper.proto.GetChildrenRequest; import org.apache.zookeeper.proto.GetChildrenResponse; import org.apache.zookeeper.proto.GetDataRequest; @@ -582,6 +585,35 @@ public void processRequest(Request request) { rsp = new GetEphemeralsResponse(ephemerals); break; } + case OpCode.getChildrenPaginated: { + lastOp = "GETC"; + GetChildrenPaginatedRequest getChildrenPaginatedRequest = new GetChildrenPaginatedRequest(); + ByteBufferInputStream.byteBuffer2Record(request.request, + getChildrenPaginatedRequest); + Stat stat = new Stat(); + path = getChildrenPaginatedRequest.getPath(); + DataNode n = zks.getZKDatabase().getNode(path); + if (n == null) { + throw new KeeperException.NoNodeException(); + } + zks.checkACL( + request.cnxn, + zks.getZKDatabase().aclForNode(n), + ZooDefs.Perms.READ, + request.authInfo, path, + null); + final int maxReturned = getChildrenPaginatedRequest.getMaxReturned(); + final PaginationNextPage nextPage = new PaginationNextPage(); + List list = zks.getZKDatabase().getPaginatedChildren( + getChildrenPaginatedRequest.getPath(), stat, + getChildrenPaginatedRequest.getWatch() ? cnxn : null, + maxReturned, + getChildrenPaginatedRequest.getMinCzxid(), + getChildrenPaginatedRequest.getCzxidOffset(), + nextPage); + rsp = new GetChildrenPaginatedResponse(list, stat, nextPage.getMinCzxid(), nextPage.getMinCzxidOffset()); + break; + } } } catch (SessionMovedException e) { // session moved is a connection level error, we need to tear 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 b7e90e930b1..0a9231091dd 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 @@ -920,6 +920,7 @@ private void pRequestHelper(Request request) throws RequestProcessorException { case OpCode.getChildren: case OpCode.getAllChildrenNumber: case OpCode.getChildren2: + case OpCode.getChildrenPaginated: case OpCode.ping: case OpCode.setWatches: case OpCode.setWatches2: diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/Request.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/Request.java index 943303be014..28b97db1934 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/Request.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/Request.java @@ -273,6 +273,7 @@ static boolean isValid(int type) { case OpCode.removeWatches: case OpCode.addWatch: case OpCode.whoAmI: + case OpCode.getChildrenPaginated: return true; default: return false; diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZKDatabase.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZKDatabase.java index 05ada8ceebe..ecd5743aa24 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZKDatabase.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZKDatabase.java @@ -41,6 +41,7 @@ import org.apache.jute.Record; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; +import org.apache.zookeeper.PaginationNextPage; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.WatcherType; import org.apache.zookeeper.ZooDefs; @@ -572,6 +573,22 @@ public int getAllChildrenNumber(String path) throws KeeperException.NoNodeExcept return dataTree.getAllChildrenNumber(path); } + /** + * Get a subset (a page) of the children of the given node + * @param path the path of the node + * @param stat the stat of the node + * @param watcher an optional watcher for this node children + * @param maxReturned the maximum number of nodes to be returned + * @param minCzxId only return children whose creation zxid greater than minCzxId + * @param czxIdOffset how many children with zxid == minCzxId to skip (as returned in previous pages) + * @return A list of children. Size is bound to maxReturned (maxReturned+1 indicates truncation) + * @throws NoNodeException if the given path does not exist + */ + public List getPaginatedChildren(String path, Stat stat, Watcher watcher, int maxReturned, + long minCzxId, int czxIdOffset, PaginationNextPage nextPage) throws NoNodeException { + return dataTree.getPaginatedChildren(path, stat, watcher, maxReturned, minCzxId, czxIdOffset, nextPage); + } + /** * check if the path is special or not * @param path the input path diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/SerializeUtils.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/SerializeUtils.java index fcc5c8f4b70..85f294c44a1 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/SerializeUtils.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/SerializeUtils.java @@ -19,12 +19,14 @@ package org.apache.zookeeper.server.util; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; 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; @@ -184,4 +186,17 @@ public static byte[] serializeRequest(Request request) { return data; } + /** + * Serializes a {@link Record} into a byte array. + * + * @param record the {@link Record} to be serialized + * @return a new byte array + * @throws IOException if there is an error during serialization + */ + public static byte[] serializeRecord(Record record) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(ZooKeeperServer.intBufferStartingSizeBytes); + BinaryOutputArchive bos = BinaryOutputArchive.getArchive(baos); + bos.writeRecord(record, null); + return baos.toByteArray(); + } } 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 7095aae117c..6396e376436 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 @@ -33,6 +33,9 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Semaphore; @@ -44,7 +47,10 @@ import org.apache.jute.Record; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NodeExistsException; +import org.apache.zookeeper.PaginationNextPage; import org.apache.zookeeper.Quotas; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZKTestCase; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.common.PathTrie; @@ -308,6 +314,301 @@ public void run() { assertTrue(ranTestCase.get(), "Didn't find the expected node"); } + @Test + @Timeout(value = 60) + public void testGetChildrenPaginated() throws NodeExistsException, NoNodeException { + final String rootPath = "/children"; + final int firstCzxId = 1000; + final int countNodes = 10; + + // Create the parent node + DataTree dt = new DataTree(); + dt.createNode(rootPath, new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1); + + // Create 10 child nodes + List childrenCreated = new ArrayList<>(countNodes); + for (int i = 0; i < countNodes; ++i) { + dt.createNode(rootPath + "/test-" + i, new byte[0], null, 0, dt.getNode(rootPath).stat.getCversion() + i + 1, firstCzxId + i, 1); + childrenCreated.add("test-" + i); + } + + // Asking from a negative for 5 nodes should return the 5, and not set the watch + int curWatchCount = dt.getWatchCount(); + PaginationNextPage nextPage = new PaginationNextPage(); + List result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 5, -1, 0, nextPage); + assertEquals(5, result.size()); + assertEquals(firstCzxId + 5, nextPage.getMinCzxid()); + assertEquals(0, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount, dt.getWatchCount(), "The watch not should have been set"); + // Verify that the list is sorted + String before = ""; + for (final String path : result) { + assertTrue(path.compareTo(before) > 0, String.format("The next path (%s) should be > previous (%s)", path, before)); + before = path; + } + + // Asking from a negative would give me all children, and set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), countNodes, -1, 0, nextPage); + assertEquals(countNodes, result.size()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + // Verify that the list is sorted + before = ""; + for (final String path : result) { + assertTrue(path.compareTo(before) > 0, String.format("The next path (%s) should be > previous (%s)", path, before)); + before = path; + } + + // Asking with maxReturned = MAX_INT would give me all children with no sorting, and set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), Integer.MAX_VALUE, 0, 0, nextPage); + assertEquals(countNodes, result.size()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + // Verify that the list is not sorted + assertNotEquals(childrenCreated, result, "The returned list of children should not be sorted"); + + // Passing a null watch when fetching all children should not set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, null, Integer.MAX_VALUE, 0, 0, nextPage); + assertEquals(countNodes, result.size()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount, dt.getWatchCount(), "The watch should have been set"); + + // Passing a null watch when fetching all children should not set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, null, countNodes, 0, 0, nextPage); + // Returned result is ordered + assertEquals(childrenCreated, result); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount, dt.getWatchCount(), "The watch should have been set"); + + // Asking from the last one should return only one node + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 2, 1000 + countNodes - 1, 0, nextPage); + assertEquals(1, result.size()); + assertEquals("test-" + (countNodes - 1), result.get(0)); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + + // Asking from the last created node+1 should return an empty list and set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 2, 1000 + countNodes, 0, nextPage); + assertTrue(result.isEmpty(), "The result should be an empty list"); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + + // Asking from -1 for one node should return two, and NOT set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 1, -1, 0, nextPage); + assertEquals(curWatchCount, dt.getWatchCount(), "No watch should be set"); + assertEquals(1, result.size(), "We only return up to "); + // Check that we ordered correctly + assertEquals("test-0", result.get(0)); + // Check next page info is returned correctly + assertEquals(firstCzxId + 1, nextPage.getMinCzxid()); + assertEquals(0, nextPage.getMinCzxidOffset()); + } + + @Test + @Timeout(value = 60) + public void testGetChildrenPaginatedOnRoot() throws NodeExistsException, NoNodeException { + final int firstCzxId = 1000; + final int countNodes = 10; + + DataTree dt = new DataTree(); + // Create the children in reverse lexical order so that ordering by czxid (correct) and + // ordering by name (incorrect) produce different results, and the test can tell them apart. + List childrenCreated = new ArrayList<>(countNodes); + for (int i = 0; i < countNodes; ++i) { + final String name = "test-" + (countNodes - 1 - i); + dt.createNode("/" + name, new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, firstCzxId + i, 1); + childrenCreated.add(name); + } + + // "/zookeeper" has czxid 0, so it sorts ahead of everything created above. + List expected = new ArrayList<>(); + expected.add("zookeeper"); + expected.addAll(childrenCreated); + + // Bounded pages on "/" must return every child, in creation order + List collected = new ArrayList<>(); + PaginationNextPage nextPage = new PaginationNextPage(); + long minCzxid = -1; + int offset = 0; + final int watchCount = dt.getWatchCount(); + boolean reachedLastPage = false; + for (int i = 0; i < countNodes + 2; ++i) { + List page = dt.getPaginatedChildren("/", null, new DummyWatcher(), 3, minCzxid, offset, nextPage); + collected.addAll(page); + if (nextPage.getMinCzxid() == ZooDefs.GetChildrenPaginated.lastPageMinCzxid) { + reachedLastPage = true; + assertEquals(watchCount + 1, dt.getWatchCount(), "The watch must be set on the last page"); + break; + } + // Asserting this on every intermediate page is what catches the "//child" bug: with the + // bug the very first page looks like a last page and registers the watch immediately. + assertEquals(watchCount, dt.getWatchCount(), "The watch must not be set before the last page"); + minCzxid = nextPage.getMinCzxid(); + offset = nextPage.getMinCzxidOffset(); + } + assertTrue(reachedLastPage, "Pagination never reported a last page"); + assertEquals(expected, collected); + + // minCzxId > 0 skips the fast path even with an unbounded page size + List result = dt.getPaginatedChildren("/", null, null, Integer.MAX_VALUE, firstCzxId + countNodes - 2, 0, nextPage); + assertEquals(Arrays.asList("test-1", "test-0"), result); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid(), "The remainder fits in one page, so it is the last page"); + } + + @Test + @Timeout(value = 60) + public void testGetChildrenPaginatedWithOffset() throws NodeExistsException, NoNodeException { + final String rootPath = "/children"; + final int childrenCzxId = 1000; + final int countNodes = 9; + final int allNodes = countNodes + 2; + + // Create the parent node + DataTree dt = new DataTree(); + dt.createNode(rootPath, new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1); + + int parentVersion = dt.getNode(rootPath).stat.getCversion(); + + // Create a children sometimes "before" + dt.createNode(rootPath + "/test-0", new byte[0], null, 0, parentVersion + 1, childrenCzxId - 100, 1); + + // Create 10 child nodes, all with the same + for (int i = 1; i <= countNodes; ++i) { + dt.createNode(rootPath + "/test-" + i, new byte[0], null, 0, parentVersion + 2, childrenCzxId, 1); + } + + // Create a children sometimes "after" + dt.createNode(rootPath + "/test-999", new byte[0], null, 0, parentVersion + 3, childrenCzxId + 100, 1); + + // Asking from a negative would give me all children, and set the watch + int curWatchCount = dt.getWatchCount(); + PaginationNextPage nextPage = new PaginationNextPage(); + List result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 1000, -1, 0, nextPage); + assertEquals(allNodes, result.size()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + // Verify that the list is sorted + String before = ""; + for (final String path : result) { + assertTrue(path.compareTo(before) > 0, String.format("The next path (%s) should be > previous (%s)", path, before)); + before = path; + } + + // Asking with minCzxid = 0, offset = 0 should not skip anything. + // maxReturned = 1, the returned nextPage should be: minCzxid = next czxid, offset = 0. + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 1, 0, 0, nextPage); + assertEquals(1, result.size()); + assertEquals("test-0", result.get(0)); + assertEquals(childrenCzxId, nextPage.getMinCzxid()); + assertEquals(0, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount, dt.getWatchCount(), "The watch should not have been set"); + + // Asking with offset minCzxId below childrenCzxId should not skip anything, regardless of offset + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 2, childrenCzxId - 1, 3, nextPage); + assertEquals(2, result.size()); + assertEquals("test-1", result.get(0)); + assertEquals("test-2", result.get(1)); + assertEquals(childrenCzxId, nextPage.getMinCzxid()); + assertEquals(2, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount, dt.getWatchCount(), "The watch should not have been set"); + + // Asking with offset 5 should skip nodes 1, 2, 3, 4, 5 + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 2, childrenCzxId, 5, nextPage); + assertEquals(2, result.size()); + assertEquals("test-6", result.get(0)); + assertEquals("test-7", result.get(1)); + assertEquals(childrenCzxId, nextPage.getMinCzxid()); + assertEquals(7, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount, dt.getWatchCount(), "The watch should not have been set"); + + // Asking with offset 5 for more nodes than are there should skip nodes 1, 2, 3, 4, 5 (plus 0 due to zxid) + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 10, childrenCzxId, 5, nextPage); + + assertEquals(5, result.size()); + assertEquals("test-6", result.get(0)); + assertEquals("test-7", result.get(1)); + assertEquals("test-8", result.get(2)); + assertEquals("test-9", result.get(3)); + assertEquals("test-999", result.get(4)); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + + // Asking with offset 5 for fewer nodes than are there should skip nodes 1, 2, 3, 4, 5 (plus 0 due to zxid) + // Returned next page should be: minCzxid = next czxid, offset = 0 + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 4, childrenCzxId, 5, nextPage); + + assertEquals(4, result.size()); + assertEquals("test-6", result.get(0)); + assertEquals("test-7", result.get(1)); + assertEquals("test-8", result.get(2)); + assertEquals("test-9", result.get(3)); + assertEquals(childrenCzxId + 100, nextPage.getMinCzxid()); + assertEquals(0, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount, dt.getWatchCount(), "The watch should not have been set"); + + // Asking from the last created node+1 should return an empty list and set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 2, 1000 + childrenCzxId, 0, nextPage); + assertTrue(result.isEmpty(), "The result should be an empty list"); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + } + + @Test + @Timeout(value = 60) + public void testGetChildrenPaginatedEmpty() throws NodeExistsException, NoNodeException { + final String rootPath = "/children"; + + // Create the parent node + DataTree dt = new DataTree(); + dt.createNode(rootPath, new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1); + + // Asking from a negative would give me all children, and set the watch + // This goes to the pagination branch. + int curWatchCount = dt.getWatchCount(); + PaginationNextPage nextPage = new PaginationNextPage(); + List result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), 100, -1, 0, nextPage); + assertTrue(result.isEmpty(), "The result should be empty"); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + + // Specify max int to fetch all children - trying to return all without sorting, and set the watch + curWatchCount = dt.getWatchCount(); + result = dt.getPaginatedChildren(rootPath, null, new DummyWatcher(), Integer.MAX_VALUE, 0, 0, nextPage); + assertTrue(result.isEmpty(), "The result should be empty"); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + assertEquals(curWatchCount + 1, dt.getWatchCount(), "The watch should have been set"); + } + + private class DummyWatcher implements Watcher { + @Override + public void process(WatchedEvent ignored) { + } + } + /* ZOOKEEPER-3531 - similarly for aclCache.deserialize, we should not hold lock either */ @Test diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildrenPaginatedTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildrenPaginatedTest.java new file mode 100644 index 00000000000..6eabaf5e894 --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildrenPaginatedTest.java @@ -0,0 +1,920 @@ +/** + * 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 org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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 static org.junit.jupiter.api.Assertions.fail; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Random; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import org.apache.jute.BinaryInputArchive; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.OpResult; +import org.apache.zookeeper.PaginationNextPage; +import org.apache.zookeeper.RemoteIterator; +import org.apache.zookeeper.Transaction; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooDefs.Ids; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Id; +import org.apache.zookeeper.data.Stat; +import org.apache.zookeeper.server.DataTree; +import org.apache.zookeeper.server.auth.DigestAuthenticationProvider; +import org.apache.zookeeper.server.quorum.BufferStats; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +public class GetChildrenPaginatedTest extends ClientBase { + private ZooKeeper zk; + private final Random random = new Random(); + + + @BeforeEach + @Override + public void setUp() throws Exception { + super.setUp(); + + zk = createClient(); + } + + @AfterEach + @Override + public void tearDown() throws Exception { + super.tearDown(); + + zk.close(); + } + + @Test + @Timeout(value = 30) + public void testPagination() throws Exception { + + final String testId = UUID.randomUUID().toString(); + final String basePath = "/testPagination-" + testId; + + Map createdChildrenMetadata = createChildren(basePath, 10, 1); + + // Create child 0 out of order (to make sure paths are not ordered lexicographically). + { + String childPath = basePath + "/" + 0; + zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + final Stat stat = zk.exists(childPath, null); + + createdChildrenMetadata.put(String.valueOf(0), stat); + + LOG.info("Created: " + childPath + " czxId: " + stat.getCzxid()); + } + + long minCzxId = -1; + Set readChildrenMetadata = new HashSet(); + final int pageSize = 3; + + RemoteIterator it = zk.getChildrenIterator(basePath, null, pageSize, minCzxId); + + while (it.hasNext()) { + final String nodePath = it.next(); + + LOG.info("Read: " + nodePath); + readChildrenMetadata.add(nodePath); + + assertTrue(createdChildrenMetadata.get(nodePath).getCzxid() > minCzxId); + minCzxId = createdChildrenMetadata.get(nodePath).getCzxid(); + } + + assertEquals(createdChildrenMetadata.keySet(), readChildrenMetadata); + } + + @Test + @Timeout(value = 30) + public void testPaginationIterator() throws Exception { + + final String testId = UUID.randomUUID().toString(); + final String basePath = "/testPagination-" + testId; + + Map createdChildrenMetadata = createChildren(basePath, random.nextInt(50) + 1, 0); + + Set readChildrenMetadata = new HashSet(); + + final int batchSize = random.nextInt(3) + 1; + + RemoteIterator childrenIterator = zk.getChildrenIterator(basePath, null, batchSize, -1); + + + while (childrenIterator.hasNext()) { + String nodePath = childrenIterator.next(); + + LOG.info("Read: " + nodePath); + readChildrenMetadata.add(nodePath); + } + + assertEquals(createdChildrenMetadata.keySet(), readChildrenMetadata); + } + + @Test + @Timeout(value = 30) + public void testPaginationIteratorOnRoot() throws Exception { + final String prefix = "/testPaginationRoot-" + UUID.randomUUID(); + List expected = new ArrayList(); + for (int i = 0; i < 10; i++) { + zk.create(prefix + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + expected.add(prefix.substring(1) + i); + } + + // Collect into a List (not a Set) so duplicated or out-of-order pages are caught. + List actual = new ArrayList(); + RemoteIterator childrenIterator = zk.getChildrenIterator("/", null, 3, -1); + while (childrenIterator.hasNext()) { + actual.add(childrenIterator.next()); + } + + assertEquals(new HashSet(actual).size(), actual.size(), "Root pagination returned duplicates: " + actual); + assertTrue(actual.containsAll(expected), "Missing children of root: " + expected + " vs " + actual); + assertTrue(actual.contains("zookeeper"), "Missing /zookeeper: " + actual); + + // The nodes were created in order, so they must come back in that order. Other tests may + // leave unrelated nodes at the root, so compare only the ones this test created. + List actualOurs = new ArrayList(); + for (String child : actual) { + if (child.startsWith(prefix.substring(1))) { + actualOurs.add(child); + } + } + assertEquals(expected, actualOurs, "Root children returned out of creation order"); + } + + /* + * This test validates a known list of children is returned by the iterator despite server failures. + * After the iterator is created successfully, the following logic drives the rest of the test: + *

    + *
  • Randomly change the server state (down to up or up to down)
  • + *
  • Try to fetch the next element, swallowing exception produced by the server being down
  • + *
+ * Eventually, all children should be returned regardless of the number of times the server was unavailable. + */ + @Test + @Timeout(value = 60) + public void testPaginationWithServerDown() throws Exception { + + final String testId = UUID.randomUUID().toString(); + final String basePath = "/testPagination-" + testId; + + Map createdChildrenMetadata = createChildren(basePath, random.nextInt(15) + 10, 0); + + Set readChildrenMetadata = new HashSet(); + + final int batchSize = random.nextInt(3) + 1; + + RemoteIterator childrenIterator = zk.getChildrenIterator(basePath, null, batchSize, -1); + + boolean serverDown = false; + + while (childrenIterator.hasNext()) { + + // Randomly change the up/down state of the server + if (random.nextBoolean()) { + if (serverDown) { + LOG.info("Bringing server UP"); + startServer(); + waitForServerUp(hostPort, 5000); + serverDown = false; + } else { + LOG.info("Taking server DOWN"); + stopServer(); + serverDown = true; + } + } + + String child = null; + + boolean exception = false; + try { + child = childrenIterator.next(); + } catch (InterruptedException | KeeperException e) { + LOG.info("Exception in #next(): " + e.getMessage()); + exception = true; + } + + if (!exception) { + // next() returned (either more elements in current batch or server is up) + assertNotNull(child); + + LOG.info("Read: " + child); + readChildrenMetadata.add(child); + } + } + + assertEquals(createdChildrenMetadata.keySet(), readChildrenMetadata); + } + + + class FireOnlyOnceWatcher implements Watcher { + int watchFiredCount = 0; + + @Override + public void process(WatchedEvent event) { + + synchronized (this) { + watchFiredCount += 1; + this.notify(); + } + } + } + + @Test + @Timeout(value = 30) + public void testPaginationWatch() throws Exception { + + final String testId = UUID.randomUUID().toString(); + final String basePath = "/testPaginationWatch-" + testId; + + createChildren(basePath, 10, 0); + + long minCzxId = -1; + final int pageSize = 3; + + FireOnlyOnceWatcher fireOnlyOnceWatcher = new FireOnlyOnceWatcher(); + + RemoteIterator it = zk.getChildrenIterator(basePath, fireOnlyOnceWatcher, pageSize, minCzxId); + + int childrenIndex = 0; + + while (it.hasNext()) { + + ++childrenIndex; + + final String nodePath = it.next(); + LOG.info("Read: " + nodePath); + + // Create more children before pagination is completed -- should NOT trigger watch + if (childrenIndex < 6) { + String childPath = basePath + "/" + "before-pagination-" + childrenIndex; + zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + + // Modify the first child of each page. + // This should not trigger additional watches or create duplicates in the set of children returned + if (childrenIndex % pageSize == 0) { + zk.setData(basePath + "/" + nodePath, new byte[3], -1); + } + + synchronized (fireOnlyOnceWatcher) { + assertEquals(0, fireOnlyOnceWatcher.watchFiredCount, "Watch should not have fired yet"); + } + } + + // Create another children after pagination is completed -- should trigger watch + { + String childPath = basePath + "/" + "after-pagination"; + zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + + + // Test eventually times out and fails if watches does not fire + while (true) { + synchronized (fireOnlyOnceWatcher) { + if (fireOnlyOnceWatcher.watchFiredCount > 0) { + assertEquals(1, fireOnlyOnceWatcher.watchFiredCount, "Watch should have fired once"); + break; + } + fireOnlyOnceWatcher.wait(1000); + } + } + + // Watch fired once. + + // Give it another chance to fire (i.e. a duplicate) which would make the test fail + synchronized (fireOnlyOnceWatcher) { + fireOnlyOnceWatcher.wait(1000); + assertEquals(1, fireOnlyOnceWatcher.watchFiredCount, "Watch should have fired once"); + } + } + + @Test + @Timeout(value = 60) + public void testPaginationWithNoChildren() throws Exception { + + final String testId = UUID.randomUUID().toString(); + final String basePath = "/testPagination-" + testId; + + Map createdChildrenMetadata = createChildren(basePath, 0, 0); + + final int batchSize = 10; + + RemoteIterator childrenIterator = zk.getChildrenIterator(basePath, null, batchSize, -1); + + assertFalse(childrenIterator.hasNext()); + + assertThrows(NoSuchElementException.class, childrenIterator::next); + } + + private Map createChildren(String basePath, int numChildren, int firstChildrenNameOffset) throws KeeperException, InterruptedException { + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + Map createdChildrenMetadata = new HashMap(); + + for (int i = firstChildrenNameOffset; i < (firstChildrenNameOffset + numChildren); i++) { + String childPath = basePath + "/" + i; + zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + final Stat stat = zk.exists(childPath, null); + + createdChildrenMetadata.put(String.valueOf(i), stat); + + LOG.info("Created: " + childPath + " czxid: " + stat.getCzxid()); + } + return createdChildrenMetadata; + } + + @Test + @Timeout(value = 60) + public void testPaginationWithMulti() throws Exception { + + final String testId = UUID.randomUUID().toString(); + final String basePath = "/testPagination-" + testId; + + final int numChildren = 10; + final int batchSize = 3; + + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + Transaction transaction = zk.transaction(); + for (int i = 0; i < numChildren; i++) { + String childPath = basePath + "/" + i; + transaction.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + + List transactionOpResults = transaction.commit(); + + assertEquals(numChildren, transactionOpResults.size()); + + Map createdChildrenMetadata = new HashMap<>(); + + for (int i = 0; i < numChildren; i++) { + String childPath = basePath + "/" + i; + final Stat stat = zk.exists(childPath, null); + createdChildrenMetadata.put(String.valueOf(i), stat); + LOG.info("Created: " + childPath + " zkId: " + stat.getCzxid()); + } + + Set readChildrenMetadata = new HashSet(); + + RemoteIterator childrenIterator = zk.getChildrenIterator(basePath, null, batchSize, -1); + + while (childrenIterator.hasNext()) { + + String children = childrenIterator.next(); + + LOG.info("Read: " + children); + readChildrenMetadata.add(children); + } + + assertEquals(numChildren, readChildrenMetadata.size()); + + assertEquals(createdChildrenMetadata.keySet(), readChildrenMetadata); + } + + /* + * Tests if all children can be fetched in one page, the children are + * in the same order(no sorting by czxid) as the non-paginated result. + */ + @Test + @Timeout(value = 60) + public void testGetAllChildrenPaginatedOnePage() throws KeeperException, InterruptedException { + final String basePath = "/testPagination-" + UUID.randomUUID().toString(); + createChildren(basePath, 100, 0); + + List expected = zk.getChildren(basePath, false); + List actual = zk.getAllChildrenPaginated(basePath, false); + + assertEquals(expected, actual); + } + + /* + * Tests if all children's packet exceeds jute.maxbuffer, the paginated API can still successfully fetch them. + */ + @Test + @Timeout(value = 60) + public void testGetAllChildrenPaginatedMultiPages() throws InterruptedException, KeeperException { + // Get the number of children that would definitely exceed 1 MB. + int numChildren = BinaryInputArchive.maxBuffer / UUID.randomUUID().toString().length() + 1; + final String basePath = "/testPagination-" + UUID.randomUUID().toString(); + + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + Set expectedChildren = new HashSet<>(); + + for (int i = 0; i < numChildren; i += 1000) { + Transaction transaction = zk.transaction(); + for (int j = i; j < i + 1000 && j < numChildren; j++) { + String child = UUID.randomUUID().toString(); + String childPath = basePath + "/" + child; + transaction.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + expectedChildren.add(child); + } + transaction.commit(); + } + + try { + zk.getChildren(basePath, false); + fail("Should not succeed to get children because packet length is out of range"); + } catch (KeeperException.ConnectionLossException expected) { + // ConnectionLossException is expected because packet length exceeds jute.maxbuffer + } + + // Paginated API can successfully fetch all the children with pagination. + // If ConnectionLossException is thrown from this method, it possibly means + // the packet length computing formula in DataTree#getPaginatedChildren needs modification. + List actualChildren = zk.getAllChildrenPaginated(basePath, false); + + assertEquals(numChildren, actualChildren.size()); + assertEquals(expectedChildren, new HashSet<>(actualChildren)); + } + + /* + * Tests the packet length formula in DataTree as expected. The packet length calculated + * is equal to the actual buffer size of the client response. + */ + @Test + @Timeout(value = 60) + public void testPacketLengthFormula() throws KeeperException, InterruptedException { + final String basePath = "/testPagination-" + UUID.randomUUID().toString(); + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + Set expectedChildren = new HashSet<>(); + int numChildren = 50 + random.nextInt(50); + + for (int i = 0; i < numChildren; i++) { + String child = UUID.randomUUID().toString(); + String childPath = basePath + "/" + child; + zk.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + expectedChildren.add(child); + } + + // Fetch max number of children that can fit into one page. The client response stat should record the same + // buffer size as the packet length calculated by the formula in DataTree. + PaginationNextPage nextPage = new PaginationNextPage(); + + // First page + List firstPage = zk.getChildren(basePath, null, numChildren, 0, 0, null, nextPage); + BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats(); + int expectedPacketLength = + (DataTree.PAGINATION_PACKET_CHILD_EXTRA_BYTES + UUID.randomUUID().toString().length()) + * firstPage.size() + DataTree.PAGINATION_PACKET_BASE_BYTES; + int actualBufferSize = clientResponseStats.getLastBufferSize(); + + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid(), "The page should be the last page."); + assertEquals(expectedPacketLength, actualBufferSize, "The client response buffer size should be equal to the packet length calculated by " + + "pagination formula in DataTree."); + assertTrue(actualBufferSize <= BinaryInputArchive.maxBuffer); + + assertEquals(expectedChildren, new HashSet<>(firstPage)); + } + + /* + * Tests below logic: + * 1. the packet length formula is as expected. The calculated length is equal to the actual + * client response's buffer size. + * 2. logic of adding children on server side is correct. It does not miss the last child. + * 3. watch is only added in the last page. + */ + @Test + @Timeout(value = 60) + public void testMaxNumChildrenPageWatch() throws KeeperException, InterruptedException { + // Get the max number of UUID children that can return in a page. + int numChildren = (BinaryInputArchive.maxBuffer - DataTree.PAGINATION_PACKET_BASE_BYTES) + / (UUID.randomUUID().toString().length() + DataTree.PAGINATION_PACKET_CHILD_EXTRA_BYTES); + // The packet will exceed 1 MB. + numChildren++; + + final String basePath = "/testPagination-" + UUID.randomUUID().toString(); + + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + Set expectedChildren = new HashSet<>(); + + for (int i = 0; i < numChildren; i += 1000) { + Transaction transaction = zk.transaction(); + for (int j = i; j < i + 1000 && j < numChildren; j++) { + String child = UUID.randomUUID().toString(); + String childPath = basePath + "/" + child; + transaction.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + expectedChildren.add(child); + } + transaction.commit(); + } + + // Fetch max number of children that can fit into one page. The client response stat should record the same + // buffer size as the packet length calculated by the formula in DataTree. + PaginationNextPage nextPage = new PaginationNextPage(); + FireOnlyOnceWatcher fireOnlyOnceWatcher = new FireOnlyOnceWatcher(); + + // First page + List firstPage = zk.getChildren(basePath, fireOnlyOnceWatcher, numChildren, 0, 0, null, nextPage); + BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats(); + int expectedPacketLength = + (DataTree.PAGINATION_PACKET_CHILD_EXTRA_BYTES + UUID.randomUUID().toString().length()) + * firstPage.size() + DataTree.PAGINATION_PACKET_BASE_BYTES; + int actualBufferSize = clientResponseStats.getLastBufferSize(); + + assertNotEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid(), "The page should not be the last page."); + assertEquals(expectedPacketLength, actualBufferSize, "The client response buffer size should be equal to the packet length calculated by " + + "pagination formula in DataTree."); + assertTrue(actualBufferSize <= BinaryInputArchive.maxBuffer); + + // Verify the index on server is correct: not adding the last child in the first page. + assertEquals(numChildren - 1, firstPage.size()); + + // Modify the first child of each page. + // This should not trigger additional watches or create duplicates in the set of children returned + zk.setData(basePath + "/" + firstPage.get(0), new byte[3], -1); + + synchronized (fireOnlyOnceWatcher) { + assertEquals(0, fireOnlyOnceWatcher.watchFiredCount, "Watch should not have fired yet"); + } + + // Second page + List secondPage = zk.getChildren(basePath, fireOnlyOnceWatcher, numChildren, nextPage.getMinCzxid(), + nextPage.getMinCzxidOffset(), null, nextPage); + + // Verify the logic of adding children to page in DataTree is correct. + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(1, secondPage.size(), "Should expect only 1 child left in the second page"); + + zk.setData(basePath + "/" + secondPage.get(0), new byte[3], -1); + + synchronized (fireOnlyOnceWatcher) { + assertEquals(0, fireOnlyOnceWatcher.watchFiredCount, "Watch has fired"); + } + + Set actualSet = new HashSet<>(firstPage); + actualSet.addAll(secondPage); + assertEquals(expectedChildren, actualSet); + } + + /* + * Pages over a stable child list of size 0, 1, page-1, page, page+1 and several pages. Every child is returned + * exactly once, in creation order, and only the page holding the last child reports the last-page marker. + */ + @Test + @Timeout(value = 60) + public void testStablePageBoundaries() throws Exception { + final int pageSize = 3; + for (int numChildren : new int[]{0, 1, pageSize - 1, pageSize, pageSize + 1, 3 * pageSize + 1}) { + final String basePath = "/testStablePageBoundaries-" + numChildren + "-" + UUID.randomUUID(); + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + List created = new ArrayList<>(); + List czxids = new ArrayList<>(); + for (int i = 0; i < numChildren; i++) { + // Names sort in the reverse of creation order, so name ordering would be detected. + String child = "child-" + (numChildren - i); + zk.create(basePath + "/" + child, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + created.add(child); + czxids.add(zk.exists(basePath + "/" + child, false).getCzxid()); + } + + List collected = new ArrayList<>(); + PaginationNextPage nextPage = new PaginationNextPage(); + long minCzxid = -1; + int offset = 0; + int pages = 0; + while (true) { + Stat stat = new Stat(); + List page = zk.getChildren(basePath, null, pageSize, minCzxid, offset, stat, nextPage); + pages++; + assertEquals(numChildren, stat.getNumChildren()); + assertTrue(page.size() <= pageSize); + collected.addAll(page); + if (nextPage.getMinCzxid() == ZooDefs.GetChildrenPaginated.lastPageMinCzxid) { + assertEquals(ZooDefs.GetChildrenPaginated.lastPageCzxidOffset, nextPage.getMinCzxidOffset()); + break; + } + assertEquals(pageSize, page.size(), "Only the last page may be partial"); + assertEquals((long) czxids.get(collected.size()), nextPage.getMinCzxid(), + "The next page starts at the first child not yet returned"); + assertEquals(0, nextPage.getMinCzxidOffset()); + minCzxid = nextPage.getMinCzxid(); + offset = nextPage.getMinCzxidOffset(); + assertTrue(pages <= numChildren, "Pagination did not terminate"); + } + assertEquals(created, collected, "numChildren=" + numChildren); + assertEquals(Math.max(1, (numChildren + pageSize - 1) / pageSize), pages, "numChildren=" + numChildren); + + List iterated = new ArrayList<>(); + RemoteIterator it = zk.getChildrenIterator(basePath, null, pageSize, -1); + while (it.hasNext()) { + iterated.add(it.next()); + } + assertEquals(created, iterated, "numChildren=" + numChildren); + assertEquals(new HashSet<>(created), new HashSet<>(zk.getAllChildrenPaginated(basePath, false))); + } + } + + /* + * A child list larger than jute.maxbuffer is returned over several pages, each response staying within the + * buffer limit, with every child returned exactly once. + */ + @Test + @Timeout(value = 120) + public void testLargeChildSetPagesStayWithinMaxBuffer() throws Exception { + final int childNameLength = UUID.randomUUID().toString().length(); + final int numChildren = BinaryInputArchive.maxBuffer / childNameLength + 1; + final String basePath = "/testLargeChildSet-" + UUID.randomUUID(); + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + Set expectedChildren = new HashSet<>(); + for (int i = 0; i < numChildren; i += 1000) { + Transaction transaction = zk.transaction(); + for (int j = i; j < i + 1000 && j < numChildren; j++) { + String child = UUID.randomUUID().toString(); + transaction.create(basePath + "/" + child, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + expectedChildren.add(child); + } + transaction.commit(); + } + + BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats(); + clientResponseStats.reset(); + + List collected = new ArrayList<>(); + PaginationNextPage nextPage = new PaginationNextPage(); + long minCzxid = 0; + int offset = 0; + int pages = 0; + do { + List page = zk.getChildren(basePath, null, Integer.MAX_VALUE, minCzxid, offset, null, nextPage); + pages++; + assertFalse(page.isEmpty()); + assertTrue(clientResponseStats.getLastBufferSize() <= BinaryInputArchive.maxBuffer); + collected.addAll(page); + minCzxid = nextPage.getMinCzxid(); + offset = nextPage.getMinCzxidOffset(); + } while (minCzxid != ZooDefs.GetChildrenPaginated.lastPageMinCzxid && pages <= numChildren); + + assertTrue(pages >= 2, "Expected several pages, got " + pages); + assertTrue(clientResponseStats.getMaxBufferSize() <= BinaryInputArchive.maxBuffer); + assertEquals(numChildren, collected.size(), "No child may be returned twice"); + assertEquals(expectedChildren, new HashSet<>(collected)); + + Set iterated = new HashSet<>(); + int iteratedCount = 0; + RemoteIterator it = zk.getChildrenIterator(basePath, null, 5000, -1); + while (it.hasNext()) { + iterated.add(it.next()); + iteratedCount++; + } + assertEquals(numChildren, iteratedCount); + assertEquals(expectedChildren, iterated); + } + + /* + * The paginated read requires READ permission on the parent, like getChildren. A denied request returns no + * child names and leaves no watch behind. + */ + @Test + @Timeout(value = 60) + public void testPaginationRequiresReadPermission() throws Exception { + final String basePath = "/testPaginationAcl-" + UUID.randomUUID(); + final String readerAuth = "reader:password"; + ZooKeeper reader = createClient(); + reader.addAuthInfo("digest", readerAuth.getBytes()); + List readerOnly = Collections.singletonList(new ACL(ZooDefs.Perms.READ | ZooDefs.Perms.CREATE + | ZooDefs.Perms.ADMIN, new Id("digest", DigestAuthenticationProvider.generateDigest(readerAuth)))); + List noRead = Collections.singletonList(new ACL(ZooDefs.Perms.ALL & ~ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE)); + + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + zk.create(basePath + "/child-a", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + zk.create(basePath + "/child-b", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + zk.setACL(basePath, readerOnly, -1); + + DataTree dataTree = serverFactory.getZooKeeperServer().getZKDatabase().getDataTree(); + final int watchCount = dataTree.getWatchCount(); + FireOnlyOnceWatcher deniedWatcher = new FireOnlyOnceWatcher(); + PaginationNextPage nextPage = new PaginationNextPage(); + Stat stat = new Stat(); + assertThrows(KeeperException.NoAuthException.class, + () -> zk.getChildren(basePath, deniedWatcher, 10, -1, 0, stat, nextPage)); + assertThrows(KeeperException.NoAuthException.class, + () -> zk.getChildren(basePath, deniedWatcher, Integer.MAX_VALUE, 0, 0, stat, nextPage)); + assertThrows(KeeperException.NoAuthException.class, () -> zk.getAllChildrenPaginated(basePath, false)); + assertThrows(KeeperException.NoAuthException.class, () -> zk.getChildrenIterator(basePath, deniedWatcher, 1, -1)); + assertThrows(KeeperException.NoAuthException.class, () -> zk.getChildren(basePath, false)); + assertEquals(0, nextPage.getMinCzxid(), "A denied request must not return page information"); + assertEquals(0, stat.getCzxid(), "A denied request must not return the parent stat"); + assertEquals(watchCount, dataTree.getWatchCount(), "A denied request must not leave a watch"); + + FireOnlyOnceWatcher allowedWatcher = new FireOnlyOnceWatcher(); + List page = reader.getChildren(basePath, allowedWatcher, 10, -1, 0, null, nextPage); + assertEquals(Arrays.asList("child-a", "child-b"), page); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(watchCount + 1, dataTree.getWatchCount()); + + reader.create(basePath + "/child-c", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + synchronized (allowedWatcher) { + while (allowedWatcher.watchFiredCount == 0) { + allowedWatcher.wait(1000); + } + } + reader.setACL(basePath, noRead, -1); + assertThrows(KeeperException.NoAuthException.class, + () -> reader.getChildren(basePath, null, 10, -1, 0, null, nextPage)); + synchronized (deniedWatcher) { + assertEquals(0, deniedWatcher.watchFiredCount, "The denied watcher must never fire"); + } + + KeeperException.NoNodeException noNode = assertThrows(KeeperException.NoNodeException.class, + () -> zk.getChildren(basePath + "/missing", null, 10, -1, 0, null, null)); + assertEquals(basePath + "/missing", noNode.getPath()); + assertThrows(IllegalArgumentException.class, () -> zk.getChildren(basePath, null, 0, -1, 0, null, null)); + assertThrows(IllegalArgumentException.class, () -> zk.getChildren("no-slash", null, 1, -1, 0, null, null)); + } + + /* + * Paginated reads through a chrooted client address the chrooted parent, including its root, and report + * client-relative paths in errors and watch events. + */ + @Test + @Timeout(value = 60) + public void testPaginationWithChroot() throws Exception { + final String chroot = "/testPaginationChroot-" + UUID.randomUUID(); + zk.create(chroot, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + List created = new ArrayList<>(); + for (int i = 0; i < 7; i++) { + String child = "child-" + (7 - i); + zk.create(chroot + "/" + child, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + created.add(child); + } + + ZooKeeper chrooted = createClient(hostPort + chroot); + List collected = new ArrayList<>(); + RemoteIterator it = chrooted.getChildrenIterator("/", null, 2, -1); + while (it.hasNext()) { + collected.add(it.next()); + } + assertEquals(created, collected); + assertEquals(new HashSet<>(created), new HashSet<>(chrooted.getAllChildrenPaginated("/", false))); + + final BlockingQueue events = new LinkedBlockingQueue<>(); + Watcher childWatcher = event -> { + if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) { + events.add(event); + } + }; + PaginationNextPage nextPage = new PaginationNextPage(); + Stat stat = new Stat(); + List page = chrooted.getChildren("/", childWatcher, 10, -1, 0, stat, nextPage); + assertEquals(created, page); + assertEquals(zk.exists(chroot, false).getCzxid(), stat.getCzxid()); + zk.create(chroot + "/after-watch", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + WatchedEvent event = events.poll(10, TimeUnit.SECONDS); + assertNotNull(event); + assertEquals("/", event.getPath()); + + KeeperException.NoNodeException noNode = assertThrows(KeeperException.NoNodeException.class, + () -> chrooted.getChildren("/missing", null, 10, -1, 0, null, null)); + assertEquals("/missing", noNode.getPath()); + } + + /* + * Documents the continuation contract under concurrent mutation. Pages are ordered by (czxid, name) and the + * continuation is (next czxid, offset within that czxid). This is not a snapshot: children created before the + * last page is read are returned, deleted children not yet returned are not, and deleting an already returned + * child that shares its czxid with later children shifts the offset so a later child can be skipped. + */ + @Test + @Timeout(value = 60) + public void testConcurrentMutationContract() throws Exception { + final String basePath = "/testPaginationMutation-" + UUID.randomUUID(); + zk.create(basePath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + for (int i = 0; i < 6; i++) { + zk.create(basePath + "/c" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + + PaginationNextPage nextPage = new PaginationNextPage(); + List collected = new ArrayList<>(zk.getChildren(basePath, null, 2, -1, 0, null, nextPage)); + assertEquals(Arrays.asList("c0", "c1"), collected); + assertEquals(zk.exists(basePath + "/c2", false).getCzxid(), nextPage.getMinCzxid()); + + zk.create(basePath + "/n0", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + // Delete the child the continuation points at, and a child that was already returned. + zk.delete(basePath + "/c2", -1); + zk.delete(basePath + "/c0", -1); + collected.addAll(zk.getChildren(basePath, null, 2, nextPage.getMinCzxid(), nextPage.getMinCzxidOffset(), null, + nextPage)); + collected.addAll(zk.getChildren(basePath, null, 2, nextPage.getMinCzxid(), nextPage.getMinCzxidOffset(), null, + nextPage)); + assertEquals(ZooDefs.GetChildrenPaginated.lastPageMinCzxid, nextPage.getMinCzxid()); + assertEquals(Arrays.asList("c0", "c1", "c3", "c4", "c5", "n0"), collected); + + // Children created by one multi share a czxid and are ordered by name. + final String multiPath = "/testPaginationMutationMulti-" + UUID.randomUUID(); + zk.create(multiPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + Transaction transaction = zk.transaction(); + for (int i = 0; i < 5; i++) { + transaction.create(multiPath + "/m" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + transaction.commit(); + final long multiCzxid = zk.exists(multiPath + "/m0", false).getCzxid(); + + List firstPage = zk.getChildren(multiPath, null, 2, -1, 0, null, nextPage); + assertEquals(Arrays.asList("m0", "m1"), firstPage); + assertEquals(multiCzxid, nextPage.getMinCzxid()); + assertEquals(2, nextPage.getMinCzxidOffset()); + + zk.delete(multiPath + "/m0", -1); + // Re-reading from offset - 1 no longer starts with the last returned child, which is how + // getAllChildrenPaginated detects the deletion and restarts the czxid group from offset 0. + List overlap = zk.getChildren(multiPath, null, 2, multiCzxid, nextPage.getMinCzxidOffset() - 1, null, + new PaginationNextPage()); + assertNotEquals(firstPage.get(firstPage.size() - 1), overlap.get(0)); + List secondPage = zk.getChildren(multiPath, null, 2, multiCzxid, nextPage.getMinCzxidOffset(), null, + nextPage); + assertEquals(Arrays.asList("m3", "m4"), secondPage, "The plain offset continuation skips m2"); + assertEquals(new HashSet<>(Arrays.asList("m1", "m2", "m3", "m4")), + new HashSet<>(zk.getAllChildrenPaginated(multiPath, false))); + + zk.delete(multiPath + "/m1", -1); + zk.delete(multiPath + "/m2", -1); + zk.delete(multiPath + "/m3", -1); + zk.delete(multiPath + "/m4", -1); + zk.delete(multiPath, -1); + assertThrows(KeeperException.NoNodeException.class, + () -> zk.getChildren(multiPath, null, 2, multiCzxid, 2, null, new PaginationNextPage())); + } + + /* + * A child watch left by the last page is an ordinary child watch: it is re-registered after reconnecting and + * fires once for a later child change. + */ + @Test + @Timeout(value = 60) + public void testPaginatedWatchSurvivesReconnect() throws Exception { + final String basePath = "/testPaginationReconnect-" + UUID.randomUUID(); + createChildren(basePath, 4, 0); + final BlockingQueue events = new LinkedBlockingQueue<>(); + Watcher childWatcher = event -> { + if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) { + events.add(event); + } + }; + PaginationNextPage nextPage = new PaginationNextPage(); + List collected = new ArrayList<>(); + long minCzxid = -1; + int offset = 0; + do { + collected.addAll(zk.getChildren(basePath, childWatcher, 3, minCzxid, offset, null, nextPage)); + minCzxid = nextPage.getMinCzxid(); + offset = nextPage.getMinCzxidOffset(); + } while (minCzxid != ZooDefs.GetChildrenPaginated.lastPageMinCzxid); + assertEquals(4, collected.size()); + + stopServer(); + startServer(); + assertTrue(waitForServerUp(hostPort, CONNECTION_TIMEOUT)); + ZooKeeper other = createClient(); + other.create(basePath + "/after-reconnect", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + WatchedEvent event = events.poll(30, TimeUnit.SECONDS); + assertNotNull(event, "The watch set by the last page must survive reconnect"); + assertEquals(basePath, event.getPath()); + other.create(basePath + "/second", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + assertNull(events.poll(1, TimeUnit.SECONDS), "A child watch fires only once"); + } +}