From 050634fd1990136c382a8747ed063c75453382b4 Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Mon, 23 Nov 2026 13:09:17 +0530 Subject: [PATCH 1/6] Add ACL dry-run mode with identity-aware diagnostics Port PR163 behavior from branch-3.6 onto the reviewed P09 identity APIs. Preserve enforcing and bypass modes; test isolated configuration parsing, ACL evaluation, credential-safe warnings, and forwarded request identity/session context. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../main/resources/markdown/zookeeperAdmin.md | 13 + .../zookeeper/server/ZooKeeperServer.java | 48 ++- .../test/ClientSkipACLDryRunTest.java | 335 ++++++++++++++++++ .../org/apache/zookeeper/test/ClientTest.java | 42 ++- 4 files changed, 432 insertions(+), 6 deletions(-) create mode 100644 zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md index 092a2963b65..a7d60f9c695 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md @@ -2092,6 +2092,19 @@ the variable does. (Java system property: **zookeeper.skipACL**) Skips ACL checks. This results in a boost in throughput, but opens up full access to the data tree to everyone. + Supported values are **yes** (skip ACL checks), **dryrun** and + **no** (default, enforce ACL checks). In **dryrun** mode the ACL checks are + still evaluated, but a request that would have been rejected with + NOAUTH is allowed and a warning is logged instead (path, requested permission, + session id, client address, client authentication identities and node ACL). + Identities are logged as scheme:user, omitting digest password hashes. + This can be used to audit the impact of enforcing ACLs before turning them on. + Note that dryrun does not provide the throughput boost of **yes** and, like + **yes**, leaves the data tree open to everyone. + Values are case-sensitive and are not trimmed: any value other than + **yes** or **dryrun**, including an invalid value, enforces ACL checks. + The property is read when the server class is initialized; changing it + requires a server restart. * *quorumListenOnAllIPs* : When set to true the ZooKeeper server will listen diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java index 64986d85066..60370ddbb6b 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ZooKeeperServer.java @@ -81,6 +81,7 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import org.apache.zookeeper.server.quorum.ReadOnlyZooKeeperServer; +import org.apache.zookeeper.server.util.AuthUtil; import org.apache.zookeeper.server.util.JvmPauseMonitor; import org.apache.zookeeper.server.util.OSMXBean; import org.apache.zookeeper.server.util.QuotaMetricsUtils; @@ -106,6 +107,7 @@ 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 SKIP_ACL_DRYRUN = "dryrun"; 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; @@ -118,6 +120,9 @@ public class ZooKeeperServer implements SessionExpirer, ServerStats.Provider { static final boolean skipACL; + // When zookeeper.skipACL=dryrun, evaluate ACL checks but only log failures. + static final boolean skipACLDryRun; + public static final boolean enforceQuota; public static final String SASL_SUPER_USER = "zookeeper.superUser"; @@ -143,9 +148,14 @@ public class ZooKeeperServer implements SessionExpirer, ServerStats.Provider { enableEagerACLCheck = Boolean.getBoolean(ENABLE_EAGER_ACL_CHECK); LOG.info("{} = {}", ENABLE_EAGER_ACL_CHECK, enableEagerACLCheck); - skipACL = System.getProperty(SKIP_ACL, "no").equals("yes"); + String skipACLValue = System.getProperty(SKIP_ACL, "no"); + skipACL = skipACLValue.equals("yes"); + skipACLDryRun = skipACLValue.equals(SKIP_ACL_DRYRUN); if (skipACL) { LOG.info("{}==\"yes\", ACL checks will be skipped", SKIP_ACL); + } else if (skipACLDryRun) { + LOG.info("{}==\"{}\", ACL checks will be evaluated but failures will only be logged, requests will not be rejected", + SKIP_ACL, SKIP_ACL_DRYRUN); } enforceQuota = Boolean.parseBoolean(System.getProperty(ENFORCE_QUOTA, "false")); @@ -2026,18 +2036,20 @@ public void dumpMonitorValues(BiConsumer response) { * @param setAcls : for set ACL operations, the list of ACLs being set. Otherwise null. */ public void checkACL(ServerCnxn cnxn, List acl, int perm, List ids, String path, List setAcls) throws KeeperException.NoAuthException { - checkACLWithContext(new ServerAuthenticationProvider.ServerObjs(this, cnxn), acl, perm, ids, path, setAcls); + checkACLWithContext(new ServerAuthenticationProvider.ServerObjs(this, cnxn), + cnxn == null ? -1 : cnxn.getSessionId(), acl, perm, ids, path, setAcls); } public void checkACL(Request request, List acl, int perm, String path, List setAcls) throws KeeperException.NoAuthException { checkACLWithContext( new ServerAuthenticationProvider.ServerObjs(this, request.cnxn, request.getX509ClientIdentity()), - acl, perm, request.authInfo, path, setAcls); + request.sessionId, acl, perm, request.authInfo, path, setAcls); } - private void checkACLWithContext(ServerAuthenticationProvider.ServerObjs serverObjs, List acl, int perm, - List ids, String path, List setAcls) throws KeeperException.NoAuthException { + private void checkACLWithContext(ServerAuthenticationProvider.ServerObjs serverObjs, long sessionId, + List acl, int perm, List ids, String path, List setAcls) + throws KeeperException.NoAuthException { if (skipACL) { return; } @@ -2073,9 +2085,35 @@ private void checkACLWithContext(ServerAuthenticationProvider.ServerObjs serverO } } } + if (skipACLDryRun) { + ServerCnxn cnxn = serverObjs.getCnxn(); + List clientAuth = new ArrayList<>(); + for (Id authId : ids) { + clientAuth.add(describeIdForLog(authId)); + } + List nodeACL = new ArrayList<>(); + for (ACL a : acl) { + nodeACL.add(describeIdForLog(a.getId()) + ":" + a.getPerms()); + } + LOG.warn("{}=\"{}\": ACL check would have failed, request is allowed. path={}, requestedPerm={}, " + + "sessionId=0x{}, clientAddress={}, clientAuth={}, nodeACL={}", + SKIP_ACL, SKIP_ACL_DRYRUN, path, perm, Long.toHexString(sessionId), + cnxn == null ? null : cnxn.getRemoteSocketAddress(), clientAuth, nodeACL); + return; + } throw new KeeperException.NoAuthException(); } + // Format as scheme:user so that credentials (e.g. digest password hashes) are not logged. + private static String describeIdForLog(Id id) { + String scheme = id.getScheme(); + if ("world".equals(scheme) || "auth".equals(scheme)) { + return scheme + ":" + id.getId(); + } + String user = id.getId() == null ? null : AuthUtil.getUser(id); + return user == null ? scheme : scheme + ":" + user; + } + /** * check a path whether exceeded the quota. * diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java new file mode 100644 index 00000000000..07030c10ed5 --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java @@ -0,0 +1,335 @@ +/* + * 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.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooDefs.Perms; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.common.SpiffeAuthTestUtil; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Id; +import org.apache.zookeeper.server.MockServerCnxn; +import org.apache.zookeeper.server.Request; +import org.apache.zookeeper.server.ServerCnxn; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.apache.zookeeper.server.auth.AuthenticationProvider; +import org.apache.zookeeper.server.auth.DigestAuthenticationProvider; +import org.apache.zookeeper.server.auth.ProviderRegistry; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; +import org.apache.zookeeper.server.auth.X509AuthenticationProvider; +import org.apache.zookeeper.server.auth.X509QuorumAuthInfo; +import org.apache.zookeeper.server.auth.znode.groupacl.X509ZNodeGroupAclProvider; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Like skipACL=yes, dryrun allows unauthorized operations, but it still evaluates + * the ACL and warns on failure. Surefire runs each ClientTest subclass in its own JVM. + */ +public class ClientSkipACLDryRunTest extends ClientTest { + + private static final String FAILURE = "ACL check would have failed, request is allowed."; + private static final long SESSION_ID = 0x1234abcdL; + private static String originalSkipACL; + + @BeforeAll + public static void setup() { + originalSkipACL = System.getProperty(ZooKeeperServer.SKIP_ACL); + System.setProperty(ZooKeeperServer.SKIP_ACL, ZooKeeperServer.SKIP_ACL_DRYRUN); + SpiffeAuthTestUtil.registerBouncyCastle(); + } + + @AfterAll + public static void teardown() { + restoreProperty(ZooKeeperServer.SKIP_ACL, originalSkipACL); + } + + @Test + public void testFailedACLCheckIsLoggedAndAllowed() throws Exception { + try (ZooKeeper owner = createClient(); ZooKeeper other = createClient(); + LoggerTestTool logger = new LoggerTestTool(ZooKeeperServer.class)) { + owner.addAuthInfo("digest", "owner:password".getBytes(StandardCharsets.UTF_8)); + other.addAuthInfo("digest", "owner:wrong-password".getBytes(StandardCharsets.UTF_8)); + owner.create("/dryruntest", new byte[]{1}, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); + assertArrayEquals(new byte[]{1}, owner.getData("/dryruntest", false, null)); + owner.setData("/dryruntest", new byte[]{2}, -1); + assertFalse(logger.getOutputStream().toString().contains(FAILURE)); + logger.getOutputStream().reset(); + + assertArrayEquals(new byte[]{2}, other.getData("/dryruntest", false, null)); + other.setData("/dryruntest", new byte[]{3}, -1); + assertArrayEquals(new byte[]{3}, owner.getData("/dryruntest", false, null)); + String log = logger.getOutputStream().toString(); + for (int permission : Arrays.asList(Perms.READ, Perms.WRITE)) { + assertDiagnostic(log, "/dryruntest", permission, other.getSessionId()); + } + assertTrue(log.contains("clientAddress=/127.0.0.1:")); + assertTrue(log.contains("digest:owner")); + assertTrue(log.contains("nodeACL=[digest:owner:" + Perms.ALL + "]")); + assertFalse(log.contains(DigestAuthenticationProvider.generateDigest("owner:password"))); + assertFalse(log.contains(DigestAuthenticationProvider.generateDigest("owner:wrong-password"))); + } + } + + @Test + public void testIdentityAwareChecksAndForwardedDiagnostics() throws Exception { + String providerProperty = ProviderRegistry.AUTHPROVIDER_PROPERTY_PREFIX + "x509"; + String originalProvider = System.getProperty(providerProperty); + String typeProperty = X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE; + String originalType = System.getProperty(typeProperty); + String matchTypeProperty = X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE; + String originalMatchType = System.getProperty(matchTypeProperty); + try { + System.setProperty(typeProperty, "SAN"); + System.setProperty(matchTypeProperty, "6"); + X509AuthenticationConfig.reset(); + ZooKeeperServer server = new ZooKeeperServer(); + MockServerCnxn spiffe = authenticate("spiffe://example.org/v2/application/example-mp/orders"); + MockServerCnxn legacy = authenticate("urn:li:servicePrincipal(orders)"); + for (Class provider : Arrays.asList( + X509AuthenticationProvider.class, X509ZNodeGroupAclProvider.class)) { + System.setProperty(providerProperty, provider.getName()); + ProviderRegistry.reset(); + for (boolean forwarded : Arrays.asList(false, true)) { + Request request = request(spiffe, forwarded); + Request legacyRequest = request(legacy, forwarded); + for (int permission : Arrays.asList(Perms.READ, Perms.WRITE, Perms.CREATE, Perms.DELETE, Perms.ADMIN)) { + assertIdentityCheck(server, request, "servicePrincipal(orders", permission, false); + assertIdentityCheck(server, request, legacy.getX509ClientIdentity().getId(), permission, false); + assertIdentityCheck(server, request, "servicePrincipal(other", permission, true); + assertIdentityCheck(server, legacyRequest, legacy.getX509ClientIdentity().getId(), permission, false); + assertIdentityCheck(server, legacyRequest, spiffe.getX509ClientIdentity().getId(), permission, true); + } + Request missing = new Request(null, SESSION_ID, 1, ZooDefs.OpCode.setData, null, spiffe.getAuthInfo()); + assertIdentityCheck(server, missing, "servicePrincipal(orders", Perms.WRITE, true); + assertIdentityCheck(server, missing, spiffe.getX509ClientIdentity().getId(), Perms.WRITE, false); + } + try (LoggerTestTool logger = new LoggerTestTool(ZooKeeperServer.class)) { + server.checkACL(spiffe, acl("x509", "servicePrincipal(orders", Perms.ALL), + Perms.WRITE, spiffe.getAuthInfo(), "/direct", null); + assertFalse(logger.getOutputStream().toString().contains(FAILURE)); + server.checkACL(spiffe, acl("x509", "servicePrincipal(other", Perms.ALL), + Perms.WRITE, spiffe.getAuthInfo(), "/direct", null); + assertDiagnostic(logger.getOutputStream().toString(), "/direct", Perms.WRITE, spiffe.getSessionId()); + } + } + } finally { + restoreProperty(providerProperty, originalProvider); + restoreProperty(typeProperty, originalType); + restoreProperty(matchTypeProperty, originalMatchType); + ProviderRegistry.reset(); + X509AuthenticationConfig.reset(); + } + } + + @Test + public void testDiagnosticDescriptionsDoNotExposeUnknownCredentials() throws Exception { + List ids = Arrays.asList(new Id("unknown", "private-credential"), new Id("x509", null)); + List acls = Arrays.asList( + new ACL(0, new Id("world", "anyone")), + new ACL(0, new Id("auth", "")), + new ACL(Perms.WRITE, new Id("unknown", "private-acl")), + new ACL(0, new Id("x509", null))); + try (LoggerTestTool logger = new LoggerTestTool(ZooKeeperServer.class)) { + new ZooKeeperServer().checkACL((ServerCnxn) null, acls, Perms.WRITE, ids, "/descriptions", null); + String log = logger.getOutputStream().toString(); + assertDiagnostic(log, "/descriptions", Perms.WRITE, -1); + assertTrue(log.contains("clientAuth=[unknown, x509]"), log); + assertTrue(log.contains("nodeACL=[world:anyone:0, auth::0, unknown:2, x509:0]"), log); + assertFalse(log.contains("private-credential"), log); + assertFalse(log.contains("private-acl"), log); + } + } + + @ParameterizedTest + @MethodSource("configurations") + public void testConfigurationInFreshJvm(String value, String mode) throws Exception { + // skipACL is static final: changing properties in this test JVM cannot test initialization. + List command = new ArrayList<>(); + command.add(Paths.get(System.getProperty("java.home"), "bin", "java").toString()); + command.add("-Djava.io.tmpdir=" + System.getProperty("java.io.tmpdir")); + command.add("-cp"); + command.add(System.getProperty("surefire.test.class.path", System.getProperty("java.class.path"))); + command.add(ConfigurationProbe.class.getName()); + command.add(mode); + if (value != null) { + command.add(value); + } + Path output = Paths.get("target", "surefire-reports", "skip-acl-config-" + + (value == null ? "default" : Integer.toHexString(value.hashCode())) + ".log"); + Files.createDirectories(output.getParent()); + Process process = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()).start(); + try { + assertTrue(process.waitFor(60, TimeUnit.SECONDS), "Configuration probe timed out: " + command); + String log = new String(Files.readAllBytes(output), StandardCharsets.UTF_8); + assertEquals(0, process.exitValue(), log); + assertTrue(log.contains("CONFIGURATION PASS: " + mode), log); + } finally { + if (process.isAlive()) { + process.destroyForcibly(); + assertTrue(process.waitFor(10, TimeUnit.SECONDS), "Configuration probe failed to stop"); + } + } + } + + private static Stream configurations() { + return Stream.of( + Arguments.of(null, "ENFORCE"), + Arguments.of("no", "ENFORCE"), + Arguments.of("yes", "BYPASS"), + Arguments.of("dryrun", "DRYRUN"), + Arguments.of("", "ENFORCE"), + Arguments.of("YES", "ENFORCE"), + Arguments.of("DRYRUN", "ENFORCE"), + Arguments.of("true", "ENFORCE"), + Arguments.of(" yes", "ENFORCE"), + Arguments.of("dryrun ", "ENFORCE"), + Arguments.of("invalid", "ENFORCE")); + } + + private static void assertIdentityCheck(ZooKeeperServer server, Request request, String id, int permission, + boolean denied) throws Exception { + try (LoggerTestTool logger = new LoggerTestTool(ZooKeeperServer.class)) { + server.checkACL(request, acl("x509", id, permission), permission, "/identity", null); + String log = logger.getOutputStream().toString(); + assertEquals(denied, log.contains(FAILURE), log); + if (denied) { + assertDiagnostic(log, "/identity", permission, SESSION_ID); + if (request.cnxn == null) { + assertTrue(log.contains("clientAddress=null"), log); + } + assertTrue(log.contains("clientAuth=[x509:" + request.authInfo.get(0).getId() + "]"), log); + assertTrue(log.contains("nodeACL=[x509:" + id + ":" + permission + "]"), log); + } + } + } + + private static MockServerCnxn authenticate(String uri) throws Exception { + X509Certificate cert = SpiffeAuthTestUtil.buildClientCertWithUriSans(uri); + X509AuthenticationProvider provider = new X509AuthenticationProvider( + new X509AuthTest.TestTrustManager(cert), new SpiffeAuthTestUtil.NoopKeyManager()); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{cert}; + assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null)); + return cnxn; + } + + private static Request request(MockServerCnxn cnxn, boolean forwarded) throws Exception { + if (!forwarded) { + return new Request(cnxn, SESSION_ID, 1, ZooDefs.OpCode.setData, null, cnxn.getAuthInfo()); + } + X509QuorumAuthInfo auth = X509QuorumAuthInfo.decode( + X509QuorumAuthInfo.encode(cnxn.getAuthInfo(), cnxn.getX509ClientIdentity())); + return new Request(null, SESSION_ID, 1, ZooDefs.OpCode.setData, null, auth.getAuthInfo(), auth.getClientIdentity()); + } + + private static void assertDiagnostic(String log, String path, int permission, long sessionId) { + assertTrue(log.contains("WARN"), log); + assertTrue(log.contains("zookeeper.skipACL=\"dryrun\": " + FAILURE + + " path=" + path + ", requestedPerm=" + permission + + ", sessionId=0x" + Long.toHexString(sessionId) + ", clientAddress="), log); + } + + private static List acl(String scheme, String id, int permissions) { + return Collections.singletonList(new ACL(permissions, new Id(scheme, id))); + } + + private static void restoreProperty(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + public static class CountingDigestProvider extends DigestAuthenticationProvider { + private static int checks; + + @Override + public boolean matches(String id, String aclExpr) { + checks++; + return super.matches(id, aclExpr); + } + } + + public static class ConfigurationProbe { + + public static void main(String[] args) throws Exception { + String mode = args[0]; + restoreProperty(ZooKeeperServer.SKIP_ACL, args.length == 1 ? null : args[1]); + System.setProperty(ProviderRegistry.AUTHPROVIDER_PROPERTY_PREFIX + "digest", CountingDigestProvider.class.getName()); + try (LoggerTestTool logger = new LoggerTestTool(ZooKeeperServer.class)) { + ZooKeeperServer server = new ZooKeeperServer(); + String startup = logger.getOutputStream().toString(); + assertEquals("BYPASS".equals(mode), startup.contains("zookeeper.skipACL==\"yes\", ACL checks will be skipped")); + assertEquals("DRYRUN".equals(mode), startup.contains("zookeeper.skipACL==\"dryrun\", ACL checks will be evaluated" + + " but failures will only be logged, requests will not be rejected")); + List acl = acl("digest", DigestAuthenticationProvider.generateDigest("owner:password"), Perms.ALL); + List owner = Collections.singletonList(acl.get(0).getId()); + List other = Collections.singletonList( + new Id("digest", DigestAuthenticationProvider.generateDigest("owner:wrong-password"))); + for (int attempt = 0; attempt < 2; attempt++) { + CountingDigestProvider.checks = 0; + logger.getOutputStream().reset(); + server.checkACL((ServerCnxn) null, acl, Perms.WRITE, owner, "/config", null); + assertFalse(logger.getOutputStream().toString().contains(FAILURE)); + if ("ENFORCE".equals(mode)) { + assertThrows(KeeperException.NoAuthException.class, + () -> server.checkACL((ServerCnxn) null, acl, Perms.WRITE, other, "/config", null)); + } else { + server.checkACL((ServerCnxn) null, acl, Perms.WRITE, other, "/config", null); + } + assertEquals("BYPASS".equals(mode) ? 0 : 2, CountingDigestProvider.checks); + String log = logger.getOutputStream().toString(); + assertEquals("DRYRUN".equals(mode), log.contains(FAILURE), log); + if ("DRYRUN".equals(mode)) { + assertDiagnostic(log, "/config", Perms.WRITE, -1); + assertTrue(log.contains("clientAddress=null, clientAuth=[digest:owner], nodeACL=[digest:owner:31]"), log); + assertFalse(log.contains(acl.get(0).getId().getId()), log); + assertFalse(log.contains(other.get(0).getId()), log); + } + System.setProperty(ZooKeeperServer.SKIP_ACL, "ENFORCE".equals(mode) ? "dryrun" : "no"); + } + System.out.println("CONFIGURATION PASS: " + mode); + } + } + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java index 5ee50f19a34..950efc2d258 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java @@ -18,14 +18,19 @@ package org.apache.zookeeper.test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; +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.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -36,6 +41,7 @@ import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.Code; import org.apache.zookeeper.KeeperException.InvalidACLException; +import org.apache.zookeeper.Op; import org.apache.zookeeper.TestableZooKeeper; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; @@ -54,13 +60,15 @@ import org.apache.zookeeper.server.PrepRequestProcessor; import org.apache.zookeeper.server.util.OSMXBean; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClientTest extends ClientBase { protected static final Logger LOG = LoggerFactory.getLogger(ClientTest.class); - private boolean skipACL = System.getProperty("zookeeper.skipACL", "no").equals("yes"); + // dryrun allows requests that fail the ACL check, just like skipACL=yes. + private boolean skipACL = Arrays.asList("yes", "dryrun").contains(System.getProperty("zookeeper.skipACL", "no")); /** Verify that pings are sent, keeping the "idle" client alive */ @Test @@ -198,6 +206,38 @@ public void testACLs() throws Exception { } } + @Test + public void testACLsAcrossOperations() throws Exception { + try (ZooKeeper owner = createClient(); ZooKeeper other = createClient()) { + owner.addAuthInfo("digest", "owner:password".getBytes(StandardCharsets.UTF_8)); + other.addAuthInfo("digest", "owner:wrong-password".getBytes(StandardCharsets.UTF_8)); + owner.create("/acl-modes", new byte[]{1}, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); + owner.create("/acl-modes/child", new byte[]{2}, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); + assertArrayEquals(new byte[]{1}, owner.getData("/acl-modes", true, null)); + assertEquals(Collections.singletonList("child"), owner.getChildren("/acl-modes", true)); + owner.setData("/acl-modes", new byte[]{3}, -1); + List acl = owner.getACL("/acl-modes", null); + owner.setACL("/acl-modes", acl, -1); + + for (Executable operation : Arrays.asList( + () -> other.getData("/acl-modes", true, null), + () -> other.getChildren("/acl-modes", true), + () -> other.setData("/acl-modes", new byte[]{4}, -1), + () -> other.create("/acl-modes/new", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), + () -> other.setACL("/acl-modes", acl, -1), + () -> other.multi(Collections.singletonList(Op.setData("/acl-modes", new byte[]{5}, -1))), + () -> other.delete("/acl-modes/child", -1))) { + if (skipACL) { + assertDoesNotThrow(operation); + } else { + assertThrows(KeeperException.NoAuthException.class, operation); + } + } + assertArrayEquals(new byte[]{(byte) (skipACL ? 5 : 3)}, owner.getData("/acl-modes", false, null)); + assertEquals(Collections.singletonList(skipACL ? "new" : "child"), owner.getChildren("/acl-modes", false)); + } + } + @Test public void testNullAuthId() throws Exception { ZooKeeper zk = null; From 5fddb7c0aaed48609028c77aa00625450a2ed683 Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Mon, 23 Nov 2026 13:25:09 +0530 Subject: [PATCH 2/6] Clarify skipACL whitespace handling for zoo.cfg The JVM property is compared literally, while the existing configuration parser trims values before setting it. No runtime or test changes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/main/resources/markdown/zookeeperAdmin.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md index a7d60f9c695..329fb25b223 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md @@ -2101,8 +2101,10 @@ the variable does. This can be used to audit the impact of enforcing ACLs before turning them on. Note that dryrun does not provide the throughput boost of **yes** and, like **yes**, leaves the data tree open to everyone. - Values are case-sensitive and are not trimmed: any value other than - **yes** or **dryrun**, including an invalid value, enforces ACL checks. + The Java system-property value is case-sensitive and is not trimmed. + Any value other than **yes** or **dryrun**, including an invalid value, + enforces ACL checks. When configured through **zoo.cfg**, the configuration + parser trims surrounding whitespace before setting this property. The property is read when the server class is initialized; changing it requires a server restart. From 59a53e4682f602ecfe73564d20ec50b7fb81054a Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Thu, 3 Dec 2026 10:11:16 +0530 Subject: [PATCH 3/6] Document exists ACL dry-run warning volume Clarify the READ permission check for existing znodes when upgrading from 3.6.3-35 to 3.8.7. Describe the conditional WARN-volume risk without claiming a measured operation mix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/main/resources/markdown/zookeeperAdmin.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md index 329fb25b223..28d8bdf42c7 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md @@ -2108,6 +2108,12 @@ the variable does. The property is read when the server class is initialized; changing it requires a server restart. + Compared with 3.6.3-35, ZooKeeper 3.8.7 checks READ permission for + `exists()` on existing znodes. In **dryrun** mode, high-frequency + `exists()` requests that would be denied can therefore generate additional + WARN log volume. Assess logging throughput and storage before enabling + **dryrun** for such workloads. + * *quorumListenOnAllIPs* : When set to true the ZooKeeper server will listen for connections from its peers on all available IP addresses, From 946334027d758cc9dca26285b3079213aebef94d Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Thu, 3 Dec 2026 10:23:45 +0530 Subject: [PATCH 4/6] Cover exists ACL behavior across skipACL modes Exercise existing-node exists requests in enforcing, bypass and dry-run mode. Isolate the dry-run READ warning and verify authorized and missing-node requests do not emit it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../org/apache/zookeeper/test/ClientSkipACLDryRunTest.java | 7 +++++++ .../test/java/org/apache/zookeeper/test/ClientTest.java | 2 ++ 2 files changed, 9 insertions(+) diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java index 07030c10ed5..222033579fe 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLDryRunTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; @@ -91,9 +92,15 @@ public void testFailedACLCheckIsLoggedAndAllowed() throws Exception { owner.create("/dryruntest", new byte[]{1}, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); assertArrayEquals(new byte[]{1}, owner.getData("/dryruntest", false, null)); owner.setData("/dryruntest", new byte[]{2}, -1); + assertEquals(1, owner.exists("/dryruntest", false).getVersion()); + assertNull(other.exists("/dryruntest/missing", false)); assertFalse(logger.getOutputStream().toString().contains(FAILURE)); logger.getOutputStream().reset(); + assertEquals(1, other.exists("/dryruntest", false).getVersion()); + assertDiagnostic(logger.getOutputStream().toString(), "/dryruntest", Perms.READ, other.getSessionId()); + logger.getOutputStream().reset(); + assertArrayEquals(new byte[]{2}, other.getData("/dryruntest", false, null)); other.setData("/dryruntest", new byte[]{3}, -1); assertArrayEquals(new byte[]{3}, owner.getData("/dryruntest", false, null)); diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java index 950efc2d258..ec287136cfe 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java @@ -213,6 +213,7 @@ public void testACLsAcrossOperations() throws Exception { other.addAuthInfo("digest", "owner:wrong-password".getBytes(StandardCharsets.UTF_8)); owner.create("/acl-modes", new byte[]{1}, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); owner.create("/acl-modes/child", new byte[]{2}, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); + assertEquals(0, owner.exists("/acl-modes", false).getVersion()); assertArrayEquals(new byte[]{1}, owner.getData("/acl-modes", true, null)); assertEquals(Collections.singletonList("child"), owner.getChildren("/acl-modes", true)); owner.setData("/acl-modes", new byte[]{3}, -1); @@ -220,6 +221,7 @@ public void testACLsAcrossOperations() throws Exception { owner.setACL("/acl-modes", acl, -1); for (Executable operation : Arrays.asList( + () -> assertEquals(1, other.exists("/acl-modes", false).getVersion()), () -> other.getData("/acl-modes", true, null), () -> other.getChildren("/acl-modes", true), () -> other.setData("/acl-modes", new byte[]{4}, -1), From 281f05e126efbd01fa42353761fea0573a6398ee Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Thu, 3 Dec 2026 15:10:12 +0530 Subject: [PATCH 5/6] Fail compatibility checks on unsuccessful sync and retain logs Require an explicit successful sync as well as a zero client exit status. Preserve per-direction client/server diagnostics and upload them on failures. Add hermetic harness regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/e2e.yaml | 21 +++++- tools/ci/test-connectivity.py | 26 ++++++-- tools/ci/test_connectivity.py | 117 ++++++++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 8 deletions(-) create mode 100644 tools/ci/test_connectivity.py diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index c73c351765f..8564416aad4 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -32,6 +32,8 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - name: Test connectivity harness + run: python3 -B -m unittest discover -s tools/ci -p 'test_*.py' - name: Set up JDK ${{ matrix.jdk }} uses: actions/setup-java@ad2b38190b15e4d6bdf0c97fb4fca8412226d287 # v5.3.0 with: @@ -64,16 +66,29 @@ jobs: run: tar -xzvf apache-zookeeper-${{ matrix.zk }}-bin.tar.gz - name: Test ZooKeeper nightly server and ${{ matrix.zk }} client if: matrix.zk != 'nightly' - run: tools/ci/test-connectivity.py --server . --client apache-zookeeper-${{ matrix.zk }}-bin + run: >- + tools/ci/test-connectivity.py --server . --client apache-zookeeper-${{ matrix.zk }}-bin + --log-dir connectivity-logs/nightly-server-${{ matrix.zk }}-client env: ZOOCFG: zoo_sample.cfg - name: Test ZooKeeper ${{ matrix.zk }} server and nightly client if: matrix.zk != 'nightly' - run: tools/ci/test-connectivity.py --server apache-zookeeper-${{ matrix.zk }}-bin --client . + run: >- + tools/ci/test-connectivity.py --server apache-zookeeper-${{ matrix.zk }}-bin --client . + --log-dir connectivity-logs/${{ matrix.zk }}-server-nightly-client env: ZOOCFG: zoo_sample.cfg - name: Test ZooKeeper nightly server and client if: matrix.zk == 'nightly' - run: tools/ci/test-connectivity.py --server . --client . + run: >- + tools/ci/test-connectivity.py --server . --client . + --log-dir connectivity-logs/nightly-server-nightly-client env: ZOOCFG: zoo_sample.cfg + - name: Upload compatibility logs + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: compatibility-logs-${{ matrix.jdk }}-${{ matrix.zk }}-attempt-${{ github.run_attempt }} + path: connectivity-logs/ + if-no-files-found: warn diff --git a/tools/ci/test-connectivity.py b/tools/ci/test-connectivity.py index 2ad837571c0..53db598c661 100755 --- a/tools/ci/test-connectivity.py +++ b/tools/ci/test-connectivity.py @@ -17,23 +17,29 @@ # limitations under the License. import argparse +import os import subprocess from pathlib import Path class Server(): - def __init__(self, binpath): + def __init__(self, binpath, log_dir): self.binpath = binpath + self.log_dir = log_dir / "server" + self.env = dict(os.environ, ZOO_LOG_DIR=str(self.log_dir)) def __enter__(self): - subprocess.run([f'{self.binpath}', 'start'], check=True) + self.log_dir.mkdir(parents=True, exist_ok=True) + subprocess.run([f'{self.binpath}', 'start'], check=True, env=self.env) return self def __exit__(self, type, value, traceback): - subprocess.run([f'{self.binpath}', 'stop'], check=True) + subprocess.run([f'{self.binpath}', 'stop'], check=True, env=self.env) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--server', help="basepath to zk server", required=True) parser.add_argument('--client', help="basepath to zk client", required=True) + parser.add_argument('--log-dir', help="directory for client and server logs", + type=Path, default=Path("connectivity-logs")) args = parser.parse_args() @@ -44,5 +50,15 @@ def __exit__(self, type, value, traceback): client_binpath = client_basepath / "bin" / "zkCli.sh" assert client_binpath.exists(), f"client binpath not exist: {client_binpath}" - with Server(server_binpath): - subprocess.run([f'{client_binpath}', 'sync', '/'], check=True) + log_dir = args.log_dir.absolute() + with Server(server_binpath, log_dir): + client_log = log_dir / "client.log" + with client_log.open("w") as output: + result = subprocess.run([f'{client_binpath}', 'sync', '/'], + stdout=output, stderr=subprocess.STDOUT) + output = client_log.read_text() + print(output, end="", flush=True) + result.check_returncode() + lines = output.splitlines() + if "Sync is OK" not in lines or any(line.startswith("Sync has failed.") for line in lines): + raise RuntimeError(f"ZooKeeper sync did not report success; see {client_log}") diff --git a/tools/ci/test_connectivity.py b/tools/ci/test_connectivity.py new file mode 100644 index 00000000000..c5372b51553 --- /dev/null +++ b/tools/ci/test_connectivity.py @@ -0,0 +1,117 @@ +# 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. + +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +class ConnectivityTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.server = self.root / "server" + self.client = self.root / "client" + self.env = dict(os.environ, TEST_SYNC_OUTPUT="Sync is OK\n", + TEST_SYNC_EXIT="0", TEST_SERVER_START_EXIT="0", + TEST_SERVER_STOP_EXIT="0", + ZOO_LOG_DIR=str(self.root / "ambient-logs")) + self.attempt = 0 + self.write_launcher(self.server, "zkServer.sh", """#!/usr/bin/env python3 +import os +import sys +from pathlib import Path +logs = Path(os.environ["ZOO_LOG_DIR"]) +logs.mkdir(parents=True, exist_ok=True) +with (logs / "server.log").open("a") as output: + print(sys.argv[1], file=output) +sys.exit(int(os.environ["TEST_SERVER_" + sys.argv[1].upper() + "_EXIT"])) +""") + self.write_launcher(self.client, "zkCli.sh", """#!/usr/bin/env python3 +import os +import sys +assert sys.argv[1:] == ["sync", "/"] +sys.stdout.write(os.environ["TEST_SYNC_OUTPUT"]) +sys.stderr.write("client stderr\\n") +sys.exit(int(os.environ["TEST_SYNC_EXIT"])) +""") + + def write_launcher(self, base, name, source): + path = base / "bin" / name + path.parent.mkdir(parents=True) + path.write_text(source) + path.chmod(0o755) + + def run_connectivity(self): + self.attempt += 1 + logs = self.root / f"logs {self.attempt}" + result = subprocess.run( + [sys.executable, str(Path(__file__).with_name("test-connectivity.py")), + "--server", str(self.server), "--client", str(self.client), + "--log-dir", str(logs)], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + env=self.env, timeout=10) + return result, logs + + def assert_logs_and_stop(self, result, logs): + client_output = (logs / "client.log").read_text() + self.assertIn(self.env["TEST_SYNC_OUTPUT"], client_output) + self.assertIn("client stderr", client_output) + self.assertIn(client_output, result.stdout) + self.assertEqual("start\nstop\n", (logs / "server" / "server.log").read_text()) + + def test_success_preserves_logs_and_stops_server(self): + result, logs = self.run_connectivity() + self.assertEqual(0, result.returncode, result.stdout) + self.assert_logs_and_stop(result, logs) + + def test_rejects_failed_missing_or_conflicting_sync_with_zero_exit(self): + for output in ("Sync has failed. rc=-4\n", "", + "Sync is OK\nSync has failed. rc=-4\n"): + with self.subTest(output=output): + self.env["TEST_SYNC_OUTPUT"] = output + result, logs = self.run_connectivity() + self.assertNotEqual(0, result.returncode) + self.assertIn("sync did not report success", result.stdout) + self.assert_logs_and_stop(result, logs) + + def test_nonzero_client_exit_is_not_masked_by_success_output(self): + self.env["TEST_SYNC_EXIT"] = "7" + result, logs = self.run_connectivity() + self.assertNotEqual(0, result.returncode) + self.assert_logs_and_stop(result, logs) + + def test_start_failure_preserves_server_log(self): + self.env["TEST_SERVER_START_EXIT"] = "8" + result, logs = self.run_connectivity() + self.assertNotEqual(0, result.returncode) + self.assertEqual("start\n", (logs / "server" / "server.log").read_text()) + self.assertFalse((logs / "client.log").exists()) + + def test_stop_failure_is_not_masked_by_successful_sync(self): + self.env["TEST_SERVER_STOP_EXIT"] = "9" + result, logs = self.run_connectivity() + self.assertNotEqual(0, result.returncode) + self.assert_logs_and_stop(result, logs) + + +if __name__ == "__main__": + unittest.main() From aa77c518be6dd32c070a33797fe0f165bc798908 Mon Sep 17 00:00:00 2001 From: Aditi Bansal Date: Thu, 3 Dec 2026 15:55:49 +0530 Subject: [PATCH 6/6] Revert "Fail compatibility checks on unsuccessful sync and retain logs" This reverts commit 281f05e126efbd01fa42353761fea0573a6398ee at the user request. Restore the prior CI harness and workflow; keep the retained diagnostic evidence outside the repository. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/e2e.yaml | 21 +----- tools/ci/test-connectivity.py | 26 ++------ tools/ci/test_connectivity.py | 117 ---------------------------------- 3 files changed, 8 insertions(+), 156 deletions(-) delete mode 100644 tools/ci/test_connectivity.py diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 8564416aad4..c73c351765f 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -32,8 +32,6 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - - name: Test connectivity harness - run: python3 -B -m unittest discover -s tools/ci -p 'test_*.py' - name: Set up JDK ${{ matrix.jdk }} uses: actions/setup-java@ad2b38190b15e4d6bdf0c97fb4fca8412226d287 # v5.3.0 with: @@ -66,29 +64,16 @@ jobs: run: tar -xzvf apache-zookeeper-${{ matrix.zk }}-bin.tar.gz - name: Test ZooKeeper nightly server and ${{ matrix.zk }} client if: matrix.zk != 'nightly' - run: >- - tools/ci/test-connectivity.py --server . --client apache-zookeeper-${{ matrix.zk }}-bin - --log-dir connectivity-logs/nightly-server-${{ matrix.zk }}-client + run: tools/ci/test-connectivity.py --server . --client apache-zookeeper-${{ matrix.zk }}-bin env: ZOOCFG: zoo_sample.cfg - name: Test ZooKeeper ${{ matrix.zk }} server and nightly client if: matrix.zk != 'nightly' - run: >- - tools/ci/test-connectivity.py --server apache-zookeeper-${{ matrix.zk }}-bin --client . - --log-dir connectivity-logs/${{ matrix.zk }}-server-nightly-client + run: tools/ci/test-connectivity.py --server apache-zookeeper-${{ matrix.zk }}-bin --client . env: ZOOCFG: zoo_sample.cfg - name: Test ZooKeeper nightly server and client if: matrix.zk == 'nightly' - run: >- - tools/ci/test-connectivity.py --server . --client . - --log-dir connectivity-logs/nightly-server-nightly-client + run: tools/ci/test-connectivity.py --server . --client . env: ZOOCFG: zoo_sample.cfg - - name: Upload compatibility logs - if: ${{ always() }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: compatibility-logs-${{ matrix.jdk }}-${{ matrix.zk }}-attempt-${{ github.run_attempt }} - path: connectivity-logs/ - if-no-files-found: warn diff --git a/tools/ci/test-connectivity.py b/tools/ci/test-connectivity.py index 53db598c661..2ad837571c0 100755 --- a/tools/ci/test-connectivity.py +++ b/tools/ci/test-connectivity.py @@ -17,29 +17,23 @@ # limitations under the License. import argparse -import os import subprocess from pathlib import Path class Server(): - def __init__(self, binpath, log_dir): + def __init__(self, binpath): self.binpath = binpath - self.log_dir = log_dir / "server" - self.env = dict(os.environ, ZOO_LOG_DIR=str(self.log_dir)) def __enter__(self): - self.log_dir.mkdir(parents=True, exist_ok=True) - subprocess.run([f'{self.binpath}', 'start'], check=True, env=self.env) + subprocess.run([f'{self.binpath}', 'start'], check=True) return self def __exit__(self, type, value, traceback): - subprocess.run([f'{self.binpath}', 'stop'], check=True, env=self.env) + subprocess.run([f'{self.binpath}', 'stop'], check=True) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--server', help="basepath to zk server", required=True) parser.add_argument('--client', help="basepath to zk client", required=True) - parser.add_argument('--log-dir', help="directory for client and server logs", - type=Path, default=Path("connectivity-logs")) args = parser.parse_args() @@ -50,15 +44,5 @@ def __exit__(self, type, value, traceback): client_binpath = client_basepath / "bin" / "zkCli.sh" assert client_binpath.exists(), f"client binpath not exist: {client_binpath}" - log_dir = args.log_dir.absolute() - with Server(server_binpath, log_dir): - client_log = log_dir / "client.log" - with client_log.open("w") as output: - result = subprocess.run([f'{client_binpath}', 'sync', '/'], - stdout=output, stderr=subprocess.STDOUT) - output = client_log.read_text() - print(output, end="", flush=True) - result.check_returncode() - lines = output.splitlines() - if "Sync is OK" not in lines or any(line.startswith("Sync has failed.") for line in lines): - raise RuntimeError(f"ZooKeeper sync did not report success; see {client_log}") + with Server(server_binpath): + subprocess.run([f'{client_binpath}', 'sync', '/'], check=True) diff --git a/tools/ci/test_connectivity.py b/tools/ci/test_connectivity.py deleted file mode 100644 index c5372b51553..00000000000 --- a/tools/ci/test_connectivity.py +++ /dev/null @@ -1,117 +0,0 @@ -# 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. - -import os -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - - -class ConnectivityTest(unittest.TestCase): - def setUp(self): - directory = tempfile.TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.root = Path(directory.name) - self.server = self.root / "server" - self.client = self.root / "client" - self.env = dict(os.environ, TEST_SYNC_OUTPUT="Sync is OK\n", - TEST_SYNC_EXIT="0", TEST_SERVER_START_EXIT="0", - TEST_SERVER_STOP_EXIT="0", - ZOO_LOG_DIR=str(self.root / "ambient-logs")) - self.attempt = 0 - self.write_launcher(self.server, "zkServer.sh", """#!/usr/bin/env python3 -import os -import sys -from pathlib import Path -logs = Path(os.environ["ZOO_LOG_DIR"]) -logs.mkdir(parents=True, exist_ok=True) -with (logs / "server.log").open("a") as output: - print(sys.argv[1], file=output) -sys.exit(int(os.environ["TEST_SERVER_" + sys.argv[1].upper() + "_EXIT"])) -""") - self.write_launcher(self.client, "zkCli.sh", """#!/usr/bin/env python3 -import os -import sys -assert sys.argv[1:] == ["sync", "/"] -sys.stdout.write(os.environ["TEST_SYNC_OUTPUT"]) -sys.stderr.write("client stderr\\n") -sys.exit(int(os.environ["TEST_SYNC_EXIT"])) -""") - - def write_launcher(self, base, name, source): - path = base / "bin" / name - path.parent.mkdir(parents=True) - path.write_text(source) - path.chmod(0o755) - - def run_connectivity(self): - self.attempt += 1 - logs = self.root / f"logs {self.attempt}" - result = subprocess.run( - [sys.executable, str(Path(__file__).with_name("test-connectivity.py")), - "--server", str(self.server), "--client", str(self.client), - "--log-dir", str(logs)], - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, - env=self.env, timeout=10) - return result, logs - - def assert_logs_and_stop(self, result, logs): - client_output = (logs / "client.log").read_text() - self.assertIn(self.env["TEST_SYNC_OUTPUT"], client_output) - self.assertIn("client stderr", client_output) - self.assertIn(client_output, result.stdout) - self.assertEqual("start\nstop\n", (logs / "server" / "server.log").read_text()) - - def test_success_preserves_logs_and_stops_server(self): - result, logs = self.run_connectivity() - self.assertEqual(0, result.returncode, result.stdout) - self.assert_logs_and_stop(result, logs) - - def test_rejects_failed_missing_or_conflicting_sync_with_zero_exit(self): - for output in ("Sync has failed. rc=-4\n", "", - "Sync is OK\nSync has failed. rc=-4\n"): - with self.subTest(output=output): - self.env["TEST_SYNC_OUTPUT"] = output - result, logs = self.run_connectivity() - self.assertNotEqual(0, result.returncode) - self.assertIn("sync did not report success", result.stdout) - self.assert_logs_and_stop(result, logs) - - def test_nonzero_client_exit_is_not_masked_by_success_output(self): - self.env["TEST_SYNC_EXIT"] = "7" - result, logs = self.run_connectivity() - self.assertNotEqual(0, result.returncode) - self.assert_logs_and_stop(result, logs) - - def test_start_failure_preserves_server_log(self): - self.env["TEST_SERVER_START_EXIT"] = "8" - result, logs = self.run_connectivity() - self.assertNotEqual(0, result.returncode) - self.assertEqual("start\n", (logs / "server" / "server.log").read_text()) - self.assertFalse((logs / "client.log").exists()) - - def test_stop_failure_is_not_masked_by_successful_sync(self): - self.env["TEST_SERVER_STOP_EXIT"] = "9" - result, logs = self.run_connectivity() - self.assertNotEqual(0, result.returncode) - self.assert_logs_and_stop(result, logs) - - -if __name__ == "__main__": - unittest.main()