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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,22 @@ of servers -- that is, when deploying clusters of servers.
connect and sync to a leader. Increased this value as needed, if
the amount of data managed by ZooKeeper is large.

* *leaderElection.skipStartupSnapshot* :
(Java system property: **zookeeper.leaderElection.skipStartupSnapshot**)
Defaults to **false**. When true, skips the final synchronous snapshot
in leader startup so a large data tree does not delay quorum formation.
Set this before starting the server, using the system property or
`leaderElection.skipStartupSnapshot=true` in `zoo.cfg`.
The value is read when the quorum peer is constructed, not dynamically
reloaded from configuration.

Database initialization and recovery, dead-session cleanup, transaction-log
durability, periodic snapshots, and snapshots required for follower
synchronization remain unchanged. Standalone startup still takes its
snapshot. Until another snapshot is taken, a restart may replay more
transactions and repeat dead-session cleanup; this option does not disable
snapshots globally or change backup/restore behavior.

* *connectToLearnerMasterLimit* :
(Java system property: zookeeper.**connectToLearnerMasterLimit**)
Amount of time, in ticks (see [tickTime](#id_tickTime)), to allow followers to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,22 @@ public void setZKDatabase(ZKDatabase zkDb) {
* Restore sessions and data
*/
public void loadData() throws IOException, InterruptedException {
loadData(false);
}

/**
* Restore sessions and data, optionally skipping the final startup snapshot.
*
* <p>During leader startup, this snapshot can delay quorum formation. Dead
* session cleanup is repeated on recovery, follower synchronization uses the
* in-memory tree, and periodic snapshots persist state as transactions arrive.
* Database initialization and transaction-log recovery are not skipped.
*
* @param skipSnapshot whether to skip the final startup snapshot
* @see <a href="https://issues.apache.org/jira/browse/ZOOKEEPER-1558">ZOOKEEPER-1558</a>
* @see <a href="https://issues.apache.org/jira/browse/ZOOKEEPER-4766">ZOOKEEPER-4766</a>
*/
public void loadData(boolean skipSnapshot) throws IOException, InterruptedException {
/*
* When a new leader starts executing Leader#lead, it
* invokes this method. The database, however, has been
Expand All @@ -553,12 +569,23 @@ public void loadData() throws IOException, InterruptedException {
}

// Clean up dead sessions
AtomicInteger deadSessionCount = new AtomicInteger();
zkDb.getSessions().stream()
.filter(session -> zkDb.getSessionWithTimeOuts().get(session) == null)
.forEach(session -> killSession(session, zkDb.getDataTreeLastProcessedZxid()));

// Make a clean snapshot
takeSnapshot();
.forEach(session -> {
killSession(session, zkDb.getDataTreeLastProcessedZxid());
deadSessionCount.incrementAndGet();
});

if (skipSnapshot) {
LOG.info("Skipping startup snapshot (periodic snapshot will persist state). "
+ "lastProcessedZxid: 0x{}, dead sessions cleaned: {}",
Long.toHexString(zkDb.getDataTreeLastProcessedZxid()),
deadSessionCount.get());
} else {
// Make a clean snapshot
takeSnapshot();
}
}

public void takeSnapshot() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,7 @@ void lead() throws IOException, InterruptedException {
try {
self.setZabState(QuorumPeer.ZabState.DISCOVERY);
self.tick.set(0);
zk.loadData();
zk.loadData(self.isSkipLeaderStartupSnapshot());

leaderStateSummary = new StateSummary(self.getCurrentEpoch(), zk.getLastProcessedZxid());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,15 @@ public synchronized void setCurrentVote(Vote v) {
*/
protected volatile int initLimit;

/**
* Whether to skip the final synchronous snapshot in leader startup.
* Defaults to false; database recovery and learner snapshots are unaffected.
*/
public static final String SKIP_LEADER_STARTUP_SNAPSHOT =
"zookeeper.leaderElection.skipStartupSnapshot";
private volatile boolean skipLeaderStartupSnapshot =
Boolean.getBoolean(SKIP_LEADER_STARTUP_SNAPSHOT);

/**
* The number of ticks that can pass between sending a request and getting
* an acknowledgment
Expand Down Expand Up @@ -1898,6 +1907,14 @@ public void setInitLimit(int initLimit) {
this.initLimit = initLimit;
}

public boolean isSkipLeaderStartupSnapshot() {
return skipLeaderStartupSnapshot;
}

public void setSkipLeaderStartupSnapshot(boolean skip) {
this.skipLeaderStartupSnapshot = skip;
}

/**
* Get the current tick
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,49 @@

package org.apache.zookeeper.server;

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.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.persistence.FileTxnLog;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.SnapStream;
import org.apache.zookeeper.server.persistence.Util;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.util.QuotaMetricsUtils;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.LoggerTestTool;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.TxnHeader;
import org.junit.jupiter.api.Test;

import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;

@Execution(ExecutionMode.SAME_THREAD)
@ResourceLock(Resources.SYSTEM_PROPERTIES)
public class ZooKeeperServerTest extends ZKTestCase {

@Test
Expand Down Expand Up @@ -230,4 +250,147 @@ public void testUpdateQuotaExceededMetrics() {
public void testUpdateQuotaExceededMetrics_nullNamespace() {
assertDoesNotThrow(() -> ZooKeeperServer.updateQuotaExceededMetrics(null));
}

@ParameterizedTest
@NullSource
@ValueSource(strings = {"false", "true"})
public void testLoadDataStartupSnapshotPolicy(String skipSnapshot, @TempDir File directory) throws Exception {
FileTxnSnapLog snapLog = new FileTxnSnapLog(directory, directory);
String prior = System.getProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT);
try {
System.setProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT, "true");
ZooKeeperServer server = new ZooKeeperServer(snapLog, 2000, null);
ZKDatabase database = server.getZKDatabase();
assertEquals(0, database.loadDataBase());
byte[] data = {1, 2, 3};
TxnHeader header = new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create);
CreateTxn transaction = new CreateTxn("/policy", data, ZooDefs.Ids.READ_ACL_UNSAFE, false, 1);
assertTrue(snapLog.append(new Request(1, 1, ZooDefs.OpCode.create, header, transaction, 1)));
snapLog.commit();
assertEquals(0, database.processTxn(header, transaction, null).err);
File snapshot = new File(snapLog.getSnapDir(), Util.makeSnapshotName(1));
assertFalse(snapshot.exists());

if (skipSnapshot == null) {
database.clear();
server.startdata();
} else {
server.loadData(Boolean.parseBoolean(skipSnapshot));
}

assertEquals(!Boolean.parseBoolean(skipSnapshot), snapshot.isFile());
assertEquals(1, server.getZxid());
assertArrayEquals(data, database.getData("/policy", new Stat(), null));
assertEquals(ZooDefs.Ids.READ_ACL_UNSAFE, database.getACL("/policy", new Stat()));

// An explicit snapshot is never suppressed by the startup policy.
server.takeSnapshot(true);
assertTrue(snapshot.isFile());
} finally {
if (prior == null) {
System.clearProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT);
} else {
System.setProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT, prior);
}
snapLog.close();
}
}

@Test
public void testSkippedStartupSnapshotRetainsInitialSnapshot(@TempDir File directory) throws Exception {
FileTxnSnapLog snapLog = new FileTxnSnapLog(directory, directory);
try {
ZooKeeperServer server = new ZooKeeperServer(snapLog, 2000, null);
assertFalse(server.getZKDatabase().isInitialized());
server.loadData(true);
assertTrue(server.getZKDatabase().isInitialized());
assertEquals(0, server.getZxid());
assertTrue(new File(snapLog.getSnapDir(), Util.makeSnapshotName(0)).isFile(),
"Database initialization must still write the initial snapshot");
} finally {
snapLog.close();
}
}

@Test
public void testSkippedStartupSnapshotRecoversDataAndSessionsOnRestart(@TempDir File directory) throws Exception {
long deadSession = 11;
long liveSession = 22;
byte[] data = {4, 5, 6};
FileTxnSnapLog snapLog = new FileTxnSnapLog(directory, directory);
try {
ZKDatabase database = new ZKDatabase(snapLog);
database.loadDataBase();
assertEquals(0, database.processTxn(
new TxnHeader(deadSession, 1, 1, 1, ZooDefs.OpCode.create),
new CreateTxn("/dead", data, ZooDefs.Ids.READ_ACL_UNSAFE, true, 1), null).err);
assertEquals(0, database.processTxn(
new TxnHeader(liveSession, 2, 2, 2, ZooDefs.OpCode.create),
new CreateTxn("/live", data, ZooDefs.Ids.READ_ACL_UNSAFE, true, 2), null).err);
database.getSessionWithTimeOuts().put(liveSession, 30000);
snapLog.save(database.getDataTree(), database.getSessionWithTimeOuts(), true);
TxnHeader header = new TxnHeader(liveSession, 3, 3, 3, ZooDefs.OpCode.create);
CreateTxn transaction = new CreateTxn("/durable", data, ZooDefs.Ids.READ_ACL_UNSAFE, false, 3);
assertTrue(snapLog.append(new Request(liveSession, 3, ZooDefs.OpCode.create, header, transaction, 3)));
snapLog.commit();
} finally {
snapLog.close();
}

for (int restart = 0; restart < 2; restart++) {
snapLog = new FileTxnSnapLog(directory, directory);
try {
ZooKeeperServer server = new ZooKeeperServer(snapLog, 2000, null);
ZKDatabase database = server.getZKDatabase();
if (restart == 1) {
database.loadDataBase();
assertNotNull(database.getNode("/dead"), "The previous startup did not rewrite the snapshot");
}
server.loadData(true);
assertEquals(3, server.getZxid());
assertNull(database.getNode("/dead"));
assertFalse(database.getSessions().contains(deadSession));
assertArrayEquals(data, database.getData("/live", new Stat(), null));
assertEquals(Integer.valueOf(30000), database.getSessionWithTimeOuts().get(liveSession));
assertArrayEquals(data, database.getData("/durable", new Stat(), null));
assertEquals(ZooDefs.Ids.READ_ACL_UNSAFE, database.getACL("/durable", new Stat()));
assertEquals(ZooDefs.Ids.READ_ACL_UNSAFE, database.getACL("/live", new Stat()));
assertFalse(new File(snapLog.getSnapDir(), Util.makeSnapshotName(3)).exists());
} finally {
snapLog.close();
}
}

}

@ParameterizedTest
@ValueSource(ints = {0, 2})
public void testSkippedStartupSnapshotLogsDeadSessionCount(int deadSessionCount, @TempDir File directory) throws Exception {
FileTxnSnapLog snapLog = new FileTxnSnapLog(directory, directory);
try (LoggerTestTool logger = new LoggerTestTool(ZooKeeperServer.class)) {
ZooKeeperServer server = new ZooKeeperServer(snapLog, 2000, null);
ZKDatabase database = server.getZKDatabase();
database.loadDataBase();
for (int i = 0; i <= deadSessionCount; i++) {
long session = i + 1;
assertEquals(0, database.processTxn(
new TxnHeader(session, 1, session, 1, ZooDefs.OpCode.create),
new CreateTxn("/session-" + session, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, true, i + 1), null).err);
}
database.getSessionWithTimeOuts().put(1L, 30000);

server.loadData(true);
String log = logger.readLogLine("Skipping startup snapshot");
assertNotNull(log);
assertTrue(log.endsWith(", dead sessions cleaned: " + deadSessionCount), log);
assertEquals(Collections.singleton(1L), database.getSessions());

server.loadData(true);
log = logger.readLogLine("Skipping startup snapshot");
assertNotNull(log);
assertTrue(log.endsWith(", dead sessions cleaned: 0"), log);
} finally {
snapLog.close();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,22 @@
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.test.ClientBase;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

@Execution(ExecutionMode.SAME_THREAD)
@ResourceLock(Resources.SYSTEM_PROPERTIES)
public class QuorumPeerTest {

private int electionAlg = 3;
Expand Down Expand Up @@ -107,4 +117,52 @@ public void testIsNotLeaderBecauseNoVote() throws Exception {
assertFalse(peer.isLeader(localPeerId));
}

@ParameterizedTest
@CsvSource(value = {"<unset>,false", "true,true", "TrUe,true", "false,false", "yes,false", "' true ',false", "'',false"},
nullValues = "<unset>")
public void testSkipLeaderStartupSnapshotConfiguration(String value, boolean expected) throws Exception {
String prior = System.getProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT);
try {
restoreStartupSnapshotProperty(value);
QuorumPeer peer = new QuorumPeer();
assertEquals(expected, peer.isSkipLeaderStartupSnapshot());

System.setProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT, Boolean.toString(!expected));
assertEquals(expected, peer.isSkipLeaderStartupSnapshot(), "Existing peers retain their startup configuration");
assertEquals(!expected, new QuorumPeer().isSkipLeaderStartupSnapshot());

peer.setSkipLeaderStartupSnapshot(!expected);
assertEquals(!expected, peer.isSkipLeaderStartupSnapshot(), "An explicit setter overrides the startup value");
peer.setSkipLeaderStartupSnapshot(expected);
assertEquals(expected, peer.isSkipLeaderStartupSnapshot());
} finally {
restoreStartupSnapshotProperty(prior);
}
}

@Test
public void testStartupSnapshotPropertyFromQuorumConfiguration(@TempDir File directory) throws Exception {
String prior = System.getProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT);
try {
System.clearProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT);
Properties properties = new Properties();
properties.setProperty("dataDir", directory.getAbsolutePath());
properties.setProperty("tickTime", "2000");
properties.setProperty("leaderElection.skipStartupSnapshot", "true");
new QuorumPeerConfig().parseProperties(properties);
assertEquals("true", System.getProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT));
assertTrue(new QuorumPeer().isSkipLeaderStartupSnapshot());
} finally {
restoreStartupSnapshotProperty(prior);
}
}

private static void restoreStartupSnapshotProperty(String value) {
if (value == null) {
System.clearProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT);
} else {
System.setProperty(QuorumPeer.SKIP_LEADER_STARTUP_SNAPSHOT, value);
}
}

}
Loading