diff --git a/zookeeper-server/pom.xml b/zookeeper-server/pom.xml
index 1595b940d09..3ba376f21ba 100755
--- a/zookeeper-server/pom.xml
+++ b/zookeeper-server/pom.xml
@@ -183,6 +183,11 @@
commons-io
compile
+
+ com.google.guava
+ guava
+ 27.0.1-jre
+
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliParseException.java b/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliParseException.java
index 7311210a651..f1846c33320 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliParseException.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliParseException.java
@@ -31,4 +31,7 @@ public CliParseException(String message) {
super(message);
}
+ public CliParseException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CommandFactory.java b/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CommandFactory.java
index 681eabad512..2a17b395d12 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CommandFactory.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/cli/CommandFactory.java
@@ -33,6 +33,7 @@ public enum Command {
CREATE(CreateCommand::new),
DELETE(DeleteCommand::new),
DELETE_ALL(DeleteAllCommand::new),
+ RESTORE(RestoreCommand::new),
SET(SetCommand::new),
GET(GetCommand::new),
LS(LsCommand::new),
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/cli/RestoreCommand.java b/zookeeper-server/src/main/java/org/apache/zookeeper/cli/RestoreCommand.java
new file mode 100644
index 00000000000..ef406404401
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/cli/RestoreCommand.java
@@ -0,0 +1,257 @@
+/*
+ * 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.cli;
+
+import java.util.Scanner;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.zookeeper.server.backup.RestoreFromBackupTool;
+
+/**
+ * Restore command for ZkCli.
+ */
+public class RestoreCommand extends CliCommand {
+
+ private RestoreFromBackupTool tool;
+ private CommandLine cl;
+ private static Options options = new Options();
+ private static final String RESTORE_CMD_STR = "restore";
+ private static final String OPTION_STR =
+ "[" + OptionFullCommand.RESTORE_ZXID + "]/[" + OptionFullCommand.RESTORE_TIMESTAMP + "] ["
+ + OptionFullCommand.BACKUP_STORE + "] [" + OptionFullCommand.SNAP_DESTINATION + "] ["
+ + OptionFullCommand.LOG_DESTINATION + "] [" + OptionFullCommand.TIMETABLE_STORAGE_PATH
+ + "](needed if restore to a timestamp) [" + OptionFullCommand.LOCAL_RESTORE_TEMP_DIR_PATH
+ + "](optional) [" + OptionFullCommand.DRY_RUN + "](optional) ["
+ + OptionFullCommand.OVERWRITE + "](optional)\n Options for spot restoration: \n["
+ + OptionFullCommand.ZNODE_PATH_TO_RESTORE + "] ["
+ + OptionFullCommand.ZK_SERVER_CONNECTION_STRING + "] ["
+ + OptionFullCommand.RECURSIVE_SPOT_RESTORE + "](optional)";
+
+ public static final class OptionLongForm {
+ /* Required if no restore timestamp is specified */
+ public static final String RESTORE_ZXID = "restore_zxid";
+ /* Required if no restore zxid is specified */
+ public static final String RESTORE_TIMESTAMP = "restore_timestamp";
+ /* Required */
+ public static final String BACKUP_STORE = "backup_store";
+ /* Required */
+ public static final String SNAP_DESTINATION = "snap_destination";
+ /* Required */
+ public static final String LOG_DESTINATION = "log_destination";
+ /* Optional. If not set, default to backup storage path */
+ public static final String TIMETABLE_STORAGE_PATH = "timetable_storage_path";
+ /* Optional. If not set, default to the log destination dir */
+ public static final String LOCAL_RESTORE_TEMP_DIR_PATH = "local_restore_temp_dir_path";
+ /* Optional. Default value false */
+ public static final String DRY_RUN = "dry_run";
+ /* Optional. Default value false */
+ public static final String OVERWRITE = "overwrite";
+
+ //For spot restoration
+ /* Required */
+ public static final String ZNODE_PATH_TO_RESTORE = "znode_path_to_restore";
+ /* Required */
+ public static final String ZK_SERVER_CONNECTION_STRING = "zk_server_connection_string";
+ /* Optional. Default value false */
+ public static final String RECURSIVE_SPOT_RESTORE = "recursive_spot_restore";
+
+ // Create a private constructor so it can't be instantiated
+ private OptionLongForm() {
+ }
+ }
+
+ public static final class OptionShortForm {
+ public static final String RESTORE_ZXID = "z";
+ public static final String RESTORE_TIMESTAMP = "t";
+ public static final String BACKUP_STORE = "b";
+ public static final String SNAP_DESTINATION = "s";
+ public static final String LOG_DESTINATION = "l";
+ public static final String TIMETABLE_STORAGE_PATH = "m";
+ public static final String LOCAL_RESTORE_TEMP_DIR_PATH = "r";
+ public static final String DRY_RUN = "n";
+ public static final String HELP = "h";
+ public static final String OVERWRITE = "f";
+
+ //For spot restoration
+ public static final String ZNODE_PATH_TO_RESTORE = "p";
+ public static final String ZK_SERVER_CONNECTION_STRING = "c";
+ public static final String RECURSIVE_SPOT_RESTORE = "a";
+
+ // Create a private constructor so it can't be instantiated
+ private OptionShortForm() {
+ }
+ }
+
+ public static final class OptionFullCommand {
+ public static final String RESTORE_ZXID =
+ "-" + OptionShortForm.RESTORE_ZXID + " " + OptionLongForm.RESTORE_ZXID;
+ public static final String RESTORE_TIMESTAMP =
+ "-" + OptionShortForm.RESTORE_TIMESTAMP + " " + OptionLongForm.RESTORE_TIMESTAMP;
+ public static final String BACKUP_STORE =
+ "-" + OptionShortForm.BACKUP_STORE + " " + OptionLongForm.BACKUP_STORE;
+ public static final String SNAP_DESTINATION =
+ "-" + OptionShortForm.SNAP_DESTINATION + " " + OptionLongForm.SNAP_DESTINATION;
+ public static final String LOG_DESTINATION =
+ "-" + OptionShortForm.LOG_DESTINATION + " " + OptionLongForm.LOG_DESTINATION;
+ public static final String TIMETABLE_STORAGE_PATH =
+ "-" + OptionShortForm.TIMETABLE_STORAGE_PATH + " " + OptionLongForm.TIMETABLE_STORAGE_PATH;
+ public static final String LOCAL_RESTORE_TEMP_DIR_PATH =
+ "-" + OptionShortForm.LOCAL_RESTORE_TEMP_DIR_PATH + " "
+ + OptionLongForm.LOCAL_RESTORE_TEMP_DIR_PATH;
+ public static final String DRY_RUN = "-" + OptionShortForm.DRY_RUN;
+ public static final String OVERWRITE = "-" + OptionShortForm.OVERWRITE;
+
+ //For spot restoration
+ public static final String ZNODE_PATH_TO_RESTORE =
+ "-" + OptionShortForm.ZNODE_PATH_TO_RESTORE + " " + OptionLongForm.ZNODE_PATH_TO_RESTORE;
+ public static final String ZK_SERVER_CONNECTION_STRING =
+ "-" + OptionShortForm.ZK_SERVER_CONNECTION_STRING + " "
+ + OptionLongForm.ZK_SERVER_CONNECTION_STRING;
+ public static final String RECURSIVE_SPOT_RESTORE =
+ "-" + OptionShortForm.RECURSIVE_SPOT_RESTORE;
+
+ // Create a private constructor so it can't be instantiated
+ private OptionFullCommand() {
+ }
+ }
+
+ static {
+ options.addOption(new Option(OptionShortForm.RESTORE_ZXID, true, OptionLongForm.RESTORE_ZXID));
+ options.addOption(
+ new Option(OptionShortForm.RESTORE_TIMESTAMP, true, OptionLongForm.RESTORE_TIMESTAMP));
+ options.addOption(new Option(OptionShortForm.BACKUP_STORE, true, OptionLongForm.BACKUP_STORE));
+ options.addOption(
+ new Option(OptionShortForm.SNAP_DESTINATION, true, OptionLongForm.SNAP_DESTINATION));
+ options.addOption(
+ new Option(OptionShortForm.LOG_DESTINATION, true, OptionLongForm.LOG_DESTINATION));
+ options.addOption(new Option(OptionShortForm.TIMETABLE_STORAGE_PATH, true,
+ OptionLongForm.TIMETABLE_STORAGE_PATH));
+ options.addOption(new Option(OptionShortForm.LOCAL_RESTORE_TEMP_DIR_PATH, true,
+ OptionLongForm.LOCAL_RESTORE_TEMP_DIR_PATH));
+ options.addOption(new Option(OptionShortForm.DRY_RUN, false, OptionLongForm.DRY_RUN));
+ options.addOption(new Option(OptionShortForm.OVERWRITE, false, OptionLongForm.OVERWRITE));
+
+ //For spot restoration
+ options.addOption(new Option(OptionShortForm.ZNODE_PATH_TO_RESTORE, true,
+ OptionLongForm.ZNODE_PATH_TO_RESTORE));
+ options.addOption(new Option(OptionShortForm.ZK_SERVER_CONNECTION_STRING, true,
+ OptionLongForm.ZK_SERVER_CONNECTION_STRING));
+ options.addOption(new Option(OptionShortForm.RECURSIVE_SPOT_RESTORE, false,
+ OptionLongForm.RECURSIVE_SPOT_RESTORE));
+ }
+
+ public RestoreCommand() {
+ super(RESTORE_CMD_STR, OPTION_STR);
+ tool = new RestoreFromBackupTool();
+ }
+
+ @Override
+ public String getUsageStr() {
+ return "Usage: RestoreFromBackupTool " + RESTORE_CMD_STR + " " + OPTION_STR
+ + "\n Options for both offline restoration and spot restoration:\n "
+ + OptionFullCommand.RESTORE_ZXID
+ + ": the point to restore to, either the string 'latest' or a zxid in hex format. "
+ + "Choose one between this option or " + OptionFullCommand.RESTORE_TIMESTAMP
+ + ", if both are specified, this option will be prioritized. "
+ + "Required for both offline restoration and spot restoration.\n "
+ + OptionFullCommand.RESTORE_TIMESTAMP
+ + ": the point to restore to, a timestamp in long format. Choose one between this option or "
+ + OptionFullCommand.RESTORE_ZXID
+ + ". Required for both offline restoration and spot restoration.\n "
+ + OptionFullCommand.BACKUP_STORE
+ + ": the connection information for the backup store\n "
+ + "For GPFS the format is: gpfs:::\n "
+ + "Required for both offline restoration and spot restoration.\n "
+ + OptionFullCommand.SNAP_DESTINATION + ": local destination path for restored snapshots. "
+ + "Required for offline restoration.\n " + OptionFullCommand.LOG_DESTINATION
+ + ": local destination path for restored txlogs. "
+ + "Required for offline restoration.\n " + OptionFullCommand.TIMETABLE_STORAGE_PATH
+ + ": Needed if restore to a timestamp. Backup storage path for timetable files. "
+ + "For GPFS the format is: gpfs:::. "
+ + "If not set, default to be same as backup storage path\n "
+ + OptionFullCommand.LOCAL_RESTORE_TEMP_DIR_PATH
+ + ": Required for spot restoration, and optional for offline restoration. "
+ + "The restore tool will use this local path to stage temporary files needed for restoration work, "
+ + "this directory will be deleted after restoration is done\n "
+ + OptionFullCommand.DRY_RUN + " " + OptionLongForm.DRY_RUN
+ + ": Optional, no files will be actually copied in a dry run\n "
+ + OptionFullCommand.OVERWRITE + " " + OptionLongForm.OVERWRITE
+ + ": Optional, default false. If true, all existing files will be wiped out and the directories "
+ + "be populated with restored files\n " + "Options for spot restoration only:\n "
+ + OptionFullCommand.ZNODE_PATH_TO_RESTORE
+ + ": The znode path to restore in the zk server\n "
+ + OptionFullCommand.ZK_SERVER_CONNECTION_STRING
+ + ": The connection string used to establish a client to server connection "
+ + "in order to do spot restoration on zk server. "
+ + "The format of this string should be host:port, " + "for example: 127.0.0.1:3000\n "
+ + OptionFullCommand.RECURSIVE_SPOT_RESTORE
+ + ": Optional, default false. If false, the spot restoration will be done on one single node only; "
+ + "if true, it will be done recursively on all of its descendants as well";
+ }
+
+ @Override
+ public CliCommand parse(String[] cmdArgs) throws CliParseException {
+ DefaultParser parser = new DefaultParser();
+ try {
+ cl = parser.parse(options, cmdArgs);
+ } catch (ParseException ex) {
+ throw new CliParseException(getUsageStr(), ex);
+ }
+ if ((!cl.hasOption(OptionShortForm.RESTORE_ZXID) && !cl
+ .hasOption(OptionShortForm.RESTORE_TIMESTAMP)) || !cl
+ .hasOption(OptionShortForm.BACKUP_STORE)) {
+ throw new CliParseException("Missing required argument(s).\n" + getUsageStr());
+ }
+ return this;
+ }
+
+ @Override
+ public boolean exec() throws CliException {
+ if (cl.hasOption(OptionShortForm.HELP)) {
+ out.println(getUsageStr());
+ return true;
+ }
+ if (cl.hasOption(OptionShortForm.OVERWRITE)) {
+ Scanner scanner = new Scanner(System.in);
+ boolean repeat = true;
+ while (repeat) {
+ out.println(
+ "Are you sure you want to overwrite the destination directories? Please enter \"yes/no\".");
+ String input = scanner.nextLine().toLowerCase();
+ switch (input) {
+ case "yes":
+ repeat = false;
+ break;
+ case "no":
+ out.println(
+ "Exiting restoration. Please remove the \"-f\" (overwrite) option from the command, and try again.");
+ return false;
+ default:
+ out.println("Could not recognize the input: " + input + ". Please try again.");
+ break;
+ }
+ }
+ }
+ return tool.runWithRetries(cl);
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/common/ConfigException.java b/zookeeper-server/src/main/java/org/apache/zookeeper/common/ConfigException.java
new file mode 100644
index 00000000000..43706e06a4a
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/common/ConfigException.java
@@ -0,0 +1,29 @@
+/*
+ * 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.common;
+
+public class ConfigException extends Exception {
+ public ConfigException(String msg) {
+ super(msg);
+ }
+
+ public ConfigException(String msg, Exception exception) {
+ super(msg, exception);
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupConfig.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupConfig.java
new file mode 100644
index 00000000000..34c4d436752
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupConfig.java
@@ -0,0 +1,445 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import java.io.File;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import org.apache.zookeeper.common.ConfigException;
+import org.apache.zookeeper.server.util.VerifyingFileFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Backup-related configurations.
+ */
+public class BackupConfig {
+ private static final Logger LOG = LoggerFactory.getLogger(BackupConfig.class);
+
+ /*
+ * Default constants
+ */
+ private static final boolean DEFAULT_BACKUP_ENABLED = false;
+ public static final int DEFAULT_RETENTION_DAYS = 20;
+ public static final int DEFAULT_BACKUP_INTERVAL_MINUTES = 30; // 30 minutes
+ /*
+ * For retention maintenance, -1 indicates no maintenance by default.
+ * Some storage backends support TTL natively.
+ */
+ public static final int DEFAULT_RETENTION_MAINTENANCE_INTERVAL_HOURS = -1;
+
+ private final BackupConfig.Builder builder;
+ private final File statusDir;
+ private final File tmpDir;
+ private final int backupIntervalInMinutes;
+ private final int retentionPeriodInDays;
+ private final int retentionMaintenanceIntervalInHours;
+ /*
+ * Fully-qualified Java class name for the storage implementation. See BackupStorageType.java
+ * for example.
+ */
+ private final String storageProviderClassName;
+ /*
+ * Storage config file (optional).
+ * E.g.) HDFS config
+ */
+ private final File storageConfig;
+ /*
+ * The custom path under which the backup files will be stored in.
+ */
+ private final String backupStoragePath;
+ /*
+ * The custom namespace string under which the backup files will be stored in.
+ * E.g.) //snapshot-123456
+ * //translog-123456
+ */
+ private final String namespace;
+ private static final String UNKNOWN_NAMESPACE = "UNKNOWN";
+
+ /*
+ * Optional timetable configs
+ */
+ private boolean timetableEnabled = false;
+ private String timetableStoragePath;
+ private long timetableBackupIntervalInMs = -1L;
+
+ public BackupConfig(Builder builder) {
+ this.builder = builder;
+ this.statusDir = builder.statusDir.orElse(null);
+ this.tmpDir = builder.tmpDir.orElse(null);
+ this.backupIntervalInMinutes = builder.backupIntervalInMinutes.orElse(
+ DEFAULT_BACKUP_INTERVAL_MINUTES);
+ this.retentionPeriodInDays = builder.retentionPeriodInDays.orElse(DEFAULT_RETENTION_DAYS);
+ this.retentionMaintenanceIntervalInHours =
+ builder.retentionMaintenanceIntervalInHours.orElse(
+ DEFAULT_RETENTION_MAINTENANCE_INTERVAL_HOURS);
+ this.storageProviderClassName = builder.storageProviderClassName.get();
+ this.storageConfig = builder.storageConfig.orElse(null);
+ this.backupStoragePath = builder.backupStoragePath.orElse("");
+ this.namespace = builder.namespace.orElse(UNKNOWN_NAMESPACE);
+ this.timetableEnabled = builder.timetableEnabled.orElse(false);
+ // If timetable storage path is not given, use the backup storage path
+ this.timetableStoragePath = builder.timetableStoragePath.orElse(backupStoragePath);
+ // If timetable backup interval is not given, use the regular backup interval
+ this.timetableBackupIntervalInMs = builder.timetableBackupIntervalInMs
+ .orElse(TimeUnit.MINUTES.toMillis(backupIntervalInMinutes));
+ }
+
+ public BackupConfig.Builder getBuilder() {
+ return builder;
+ }
+
+ public File getStatusDir() {
+ return statusDir;
+ }
+
+ public File getTmpDir() {
+ return tmpDir;
+ }
+
+ public int getBackupIntervalInMinutes() {
+ return backupIntervalInMinutes;
+ }
+
+ public int getRetentionPeriod() {
+ return retentionPeriodInDays;
+ }
+
+ public long getRetentionMaintenanceIntervalInHours() {
+ return retentionMaintenanceIntervalInHours;
+ }
+
+ public String getStorageProviderClassName() {
+ return storageProviderClassName;
+ }
+
+ public File getStorageConfig() {
+ return storageConfig;
+ }
+
+ public String getBackupStoragePath() {
+ return backupStoragePath;
+ }
+
+ public String getNamespace() {
+ return namespace;
+ }
+
+ public boolean isTimetableEnabled() {
+ return timetableEnabled;
+ }
+
+ public String getTimetableStoragePath() {
+ return timetableStoragePath;
+ }
+
+ public long getTimetableBackupIntervalInMs() {
+ return timetableBackupIntervalInMs;
+ }
+
+ public static class Builder {
+ private static final VerifyingFileFactory vff =
+ new VerifyingFileFactory.Builder(LOG).warnForRelativePath().build();
+
+ private Optional enabled = Optional.empty();
+ private Optional statusDir = Optional.empty();
+ private Optional tmpDir = Optional.empty();
+ private Optional backupIntervalInMinutes =
+ Optional.of(DEFAULT_BACKUP_INTERVAL_MINUTES);
+ private Optional retentionPeriodInDays = Optional.of(DEFAULT_RETENTION_DAYS);
+ private Optional retentionMaintenanceIntervalInHours =
+ Optional.of(DEFAULT_RETENTION_MAINTENANCE_INTERVAL_HOURS);
+ protected Optional storageProviderClassName = Optional.empty();
+ protected Optional storageConfig = Optional.empty();
+ protected Optional backupStoragePath = Optional.empty();
+ protected Optional namespace = Optional.empty();
+ private Optional timetableEnabled = Optional.empty();
+ private Optional timetableStoragePath = Optional.empty();
+ private Optional timetableBackupIntervalInMs = Optional.empty();
+
+ public Builder setEnabled(boolean enabled) {
+ this.enabled = Optional.of(enabled);
+ return this;
+ }
+
+ public Builder setStatusDir(File dir) {
+ this.statusDir = Optional.of(dir);
+ return this;
+ }
+
+ public Builder setTmpDir(File dir) {
+ this.tmpDir = Optional.of(dir);
+ return this;
+ }
+
+ public Builder setBackupIntervalInMinutes(int intervalInMinutes) {
+ this.backupIntervalInMinutes = Optional.of(intervalInMinutes);
+ return this;
+ }
+
+ public Builder setRetentionPeriodInDays(int retentionPeriodInDays) {
+ this.retentionPeriodInDays = Optional.of(retentionPeriodInDays);
+ return this;
+ }
+
+ public Builder setRetentionMaintenanceIntervalInHours(int retentionMaintenanceIntervalInHours) {
+ this.retentionMaintenanceIntervalInHours = Optional.of(retentionMaintenanceIntervalInHours);
+ return this;
+ }
+
+ public Builder setStorageProviderClassName(String storageProviderClassName) {
+ this.storageProviderClassName = Optional.of(storageProviderClassName);
+ return this;
+ }
+
+ public Builder setStorageConfig(File storageConfig) {
+ this.storageConfig = Optional.of(storageConfig);
+ return this;
+ }
+
+ public Builder setBackupStoragePath(String backupStoragePath) {
+ this.backupStoragePath = Optional.of(backupStoragePath);
+ return this;
+ }
+
+ public Builder setNamespace(String namespace) {
+ this.namespace = Optional.of(namespace);
+ return this;
+ }
+
+ public Builder setTimetableEnabled(boolean timetableEnabled) {
+ this.timetableEnabled = Optional.of(timetableEnabled);
+ return this;
+ }
+
+ public Builder setTimetableStoragePath(String timetableStoragePath) {
+ this.timetableStoragePath = Optional.of(timetableStoragePath);
+ return this;
+ }
+
+ public Builder setTimetableBackupIntervalInMs(long timetableBackupIntervalInMs) {
+ this.timetableBackupIntervalInMs = Optional.of(timetableBackupIntervalInMs);
+ return this;
+ }
+
+ public Builder withProperties(Properties properties) throws ConfigException {
+ return withProperties(properties, "");
+ }
+
+ public Builder withProperties(Properties properties, String prefix) throws ConfigException {
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_ENABLED;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.enabled = Optional.of(parseBoolean(key, prop));
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_STATUS_DIR;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.statusDir = Optional.of(vff.create(prop));
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_TMP_DIR;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.tmpDir = Optional.of(vff.create(prop));
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_INTERVAL_MINUTES;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ int minutes = parseInt(key, prop);
+ this.backupIntervalInMinutes = Optional.of(minutes);
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_STORAGE_CONFIG;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.storageConfig = Optional.of(vff.create(prop));
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_STORAGE_PATH;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.backupStoragePath = Optional.of(prop);
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_RETENTION_DAYS;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.retentionPeriodInDays = Optional.of(parseInt(key, prop));
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_RETENTION_MAINTENANCE_INTERVAL_HOURS;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ int hours = parseInt(key, prop);
+ this.retentionMaintenanceIntervalInHours = Optional.of(hours);
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_STORAGE_PROVIDER_CLASS_NAME;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.storageProviderClassName = Optional.of(prop);
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_NAMESPACE;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.namespace = Optional.of(prop);
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_TIMETABLE_ENABLED;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.timetableEnabled = Optional.of(parseBoolean(key, prop));
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_TIMETABLE_STORAGE_PATH;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.timetableStoragePath = Optional.of(prop);
+ }
+ }
+ {
+ String key = prefix + BackupSystemProperty.BACKUP_TIMETABLE_BACKUP_INTERVAL_MS;
+ String prop = properties.getProperty(key);
+ if (prop != null) {
+ this.timetableBackupIntervalInMs = Optional.of(parseLong(key, prop));
+ }
+ }
+ return this;
+ }
+
+ protected Builder withProperty(String key, String val) throws ConfigException {
+ Properties properties = new Properties();
+ properties.setProperty(key, val);
+ return withProperties(properties);
+ }
+
+ private static long parseLong(String key, String value) throws ConfigException {
+ try {
+ return Long.parseLong(value);
+ } catch (NumberFormatException exc) {
+ throw new ConfigException(String.format("parsing %s", key), exc);
+ }
+ }
+
+ private static int parseInt(String key, String value) throws ConfigException {
+ try {
+ return Integer.parseInt(value);
+ } catch (NumberFormatException exc) {
+ throw new ConfigException(String.format("parsing %s", key), exc);
+ }
+ }
+
+ private static boolean parseBoolean(String key, String value) {
+ boolean result;
+ switch (value.toLowerCase()) {
+ case "yes":
+ result = true;
+ break;
+ case "no":
+ result = false;
+ break;
+ default:
+ result = Boolean.parseBoolean(value);
+ break;
+ }
+ return result;
+ }
+
+ public Optional build() throws ConfigException {
+ final Optional result;
+ if (enabled.orElse(DEFAULT_BACKUP_ENABLED)) {
+ validate();
+ result = Optional.of(new BackupConfig(this));
+ } else {
+ result = Optional.empty();
+ }
+ return result;
+ }
+
+ /**
+ * Validates the backup config. Makes sure that required fields are present.
+ * @throws ConfigException
+ */
+ private void validate() throws ConfigException {
+ if (!statusDir.isPresent()) {
+ throw new ConfigException("BackupConfig statusDir not specified");
+ }
+ if (!tmpDir.isPresent()) {
+ throw new ConfigException("BackupConfig tmpDir not specified");
+ }
+ if (!storageProviderClassName.isPresent() || storageProviderClassName.get().equals("")) {
+ throw new ConfigException("Please specify a valid storage provider class name.");
+ }
+ }
+ }
+
+ public static class RestorationConfigBuilder extends Builder {
+ public RestorationConfigBuilder setStorageProviderClassName(
+ String storageProviderClassName) {
+ this.storageProviderClassName = Optional.of(storageProviderClassName);
+ return this;
+ }
+
+ public RestorationConfigBuilder setStorageConfig(File storageConfig) {
+ this.storageConfig = Optional.of(storageConfig);
+ return this;
+ }
+
+ public RestorationConfigBuilder setBackupStoragePath(String backupStoragePath) {
+ this.backupStoragePath = Optional.of(backupStoragePath);
+ return this;
+ }
+
+ public RestorationConfigBuilder setNamespace(String namespace) {
+ this.namespace = Optional.of(namespace);
+ return this;
+ }
+
+ @Override
+ public Optional build() throws ConfigException {
+ if (!storageProviderClassName.isPresent() || storageProviderClassName.get().isEmpty()) {
+ throw new ConfigException("Please specify a valid storage provider class name.");
+ }
+ if (!backupStoragePath.isPresent()) {
+ throw new ConfigException("Please specify a valid backup storage path..");
+ }
+ if (!namespace.isPresent()) {
+ throw new ConfigException("Please specify a valid namespace.");
+ }
+ return Optional.of(new BackupConfig(this));
+ }
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupFileInfo.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupFileInfo.java
new file mode 100644
index 00000000000..ce1cd477fd7
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupFileInfo.java
@@ -0,0 +1,163 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import com.google.common.collect.Range;
+import java.io.File;
+import org.apache.zookeeper.server.backup.BackupUtil.BackupFileType;
+import org.apache.zookeeper.server.backup.BackupUtil.IntervalEndpoint;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+import org.apache.zookeeper.server.backup.timetable.TimetableBackup;
+import org.apache.zookeeper.server.persistence.SnapStream;
+import org.apache.zookeeper.server.persistence.Util;
+
+/**
+ * Metadata for a file that has been backed-up
+ * Assumes that the name of the backed up file uses the format:
+ * prefix.lowzxid-highzxid where prefix is one of the standard snap or log file prefixes, or
+ * "lostLog".
+ * In the case of timetable backup file, it takes a format of timetable.lowTimestamp-highTimestamp.
+ */
+public class BackupFileInfo {
+ public static final long NOT_SET = -1L;
+ private static final String DASH_DELIMITER = "-";
+
+ private final File backupFile;
+ private final File standardFile;
+ private final Range range;
+ private final BackupFileType fileType;
+ private final long modificationTime;
+ private final long size;
+
+ /**
+ * Constructor that pulls backup metadata based on the backed-up filename
+ * @param backedupFile the backed-up file with the name in the form prefix.lowzxid-highzxid
+ * for example snapshot.9a0000a344-9a0000b012.
+ * if timetable backup, ranges are decimal longs (posix timestamps)
+ * @param modificationTime the file modification time
+ * @param size the size of the file in bytes
+ */
+ public BackupFileInfo(File backedupFile, long modificationTime, long size) {
+ this.backupFile = backedupFile;
+ this.modificationTime = modificationTime;
+ this.size = size;
+
+ String backedupFilename = this.backupFile.getName();
+
+ if (backedupFilename.startsWith(BackupUtil.LOST_LOG_PREFIX)) {
+ this.fileType = BackupFileType.LOSTLOG;
+ this.standardFile = this.backupFile;
+ } else if (backedupFilename.startsWith(Util.SNAP_PREFIX)) {
+ this.fileType = BackupFileType.SNAPSHOT;
+ // For snapshot backup files, we need to consider the case of snapshot compression
+ String streamMode = SnapStream.getStreamMode(backedupFilename).getName();
+ String standardFileName;
+ if (streamMode.isEmpty()) {
+ // No compression was used, so simply drop the end part
+ standardFileName = backedupFilename.split(DASH_DELIMITER)[0];
+ } else {
+ // Snapshot compression is enabled; standardName looks like "snapshot.."
+ // Need to remove the ending zxid
+ String[] nameParts = backedupFilename.split("\\.");
+ if (nameParts.length != 3) {
+ throw new BackupException(
+ "BackupFileInfo: unable to create standardFile reference! backedupFilename: "
+ + backedupFilename + " StreamMode: " + streamMode);
+ }
+ String zxidPartWithoutEnd = nameParts[1].split(DASH_DELIMITER)[0];
+ // Combine all parts to generate a backup name
+ standardFileName = nameParts[0] + "." + zxidPartWithoutEnd + "." + nameParts[2];
+ }
+ this.standardFile = new File(this.backupFile.getParentFile(), standardFileName);
+ } else if (backedupFilename.startsWith(Util.TXLOG_PREFIX)) {
+ this.fileType = BackupFileType.TXNLOG;
+ this.standardFile =
+ new File(this.backupFile.getParentFile(), backedupFilename.split(DASH_DELIMITER)[0]);
+ } else if (backedupFilename.startsWith(TimetableBackup.TIMETABLE_PREFIX)) {
+ this.fileType = BackupFileType.TIMETABLE;
+ this.standardFile = this.backupFile;
+ } else {
+ throw new IllegalArgumentException("Not a known backup file type: " + backedupFilename);
+ }
+
+ this.range = BackupUtil.getRangeFromName(
+ backedupFilename,
+ BackupUtil.getPrefix(this.fileType));
+ }
+
+ /**
+ * Get the zxid range for the backed up file.
+ * @return the zxid range
+ */
+ public Range getRange() {
+ return this.range;
+ }
+
+ /**
+ * Convenience method for getting a specific interval endpoint (e.g. zxid, timestamp, etc.)
+ * @param whichIntervalEndpoint which range part to get
+ * @return the value of the requested range endpoint
+ */
+ public long getIntervalEndpoint(IntervalEndpoint whichIntervalEndpoint) {
+ return whichIntervalEndpoint == IntervalEndpoint.START
+ ? this.range.lowerEndpoint()
+ : this.range.upperEndpoint();
+ }
+
+ /**
+ * Get the backedup file
+ * @return the backedup file
+ */
+ public File getBackedUpFile() {
+ return this.backupFile;
+ }
+
+ /**
+ * Get the files corresponding to the standard name of the backed up file. I.e. removes the
+ * high zxid from the filename.
+ * @return the standard file corresponding to the backed up file
+ */
+ public File getStandardFile() {
+ return this.standardFile;
+ }
+
+ /**
+ * Get the type of the file (snap, log, lostLog)
+ * @return the type of file that was backed up
+ */
+ public BackupFileType getFileType() {
+ return this.fileType;
+ }
+
+ /**
+ * Get the modification time for the file
+ * @return the modification time
+ */
+ public long getModificationTime() {
+ return this.modificationTime;
+ }
+
+ /**
+ * Get the file size in bytes
+ * @return file size in bytes
+ */
+ public long getSize() {
+ return this.size;
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupManager.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupManager.java
new file mode 100644
index 00000000000..343d26a95aa
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupManager.java
@@ -0,0 +1,672 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.common.annotations.VisibleForTesting;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import javax.management.JMException;
+import org.apache.zookeeper.jmx.MBeanRegistry;
+import org.apache.zookeeper.server.backup.BackupUtil.BackupFileType;
+import org.apache.zookeeper.server.backup.BackupUtil.IntervalEndpoint;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+import org.apache.zookeeper.server.backup.monitoring.BackupBean;
+import org.apache.zookeeper.server.backup.monitoring.BackupStats;
+import org.apache.zookeeper.server.backup.monitoring.TimetableBackupBean;
+import org.apache.zookeeper.server.backup.monitoring.TimetableBackupStats;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.timetable.TimetableBackup;
+import org.apache.zookeeper.server.persistence.FileTxnLog;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.server.persistence.TxnLog;
+import org.apache.zookeeper.server.persistence.Util;
+import org.apache.zookeeper.server.persistence.ZxidRange;
+import org.apache.zookeeper.server.util.ZxidUtils;
+import org.apache.zookeeper.txn.TxnHeader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class manages the backing up of txnlog and snap files to remote
+ * storage for longer term and durable retention than is possible on
+ * an ensemble server
+ */
+public class BackupManager {
+ private static final Logger LOG = LoggerFactory.getLogger(BackupManager.class);
+
+ private final Logger logger;
+ private final File snapDir;
+ private final File dataLogDir;
+ private final File tmpDir;
+ private final BackupConfig backupConfig;
+ private final long backupIntervalInMilliseconds;
+ private BackupProcess logBackup = null;
+ private BackupProcess snapBackup = null;
+
+ // backupStatus, backupLogZxid and backedupSnapZxid need to be access while synchronized
+ // on backupStatus.
+ private final BackupStatus backupStatus;
+ private BackupPoint backupPoint;
+
+ private final BackupStorageProvider backupStorage;
+ private final long serverId;
+ private final String namespace;
+
+ @VisibleForTesting
+ protected BackupBean backupBean = null;
+ protected TimetableBackupBean timetableBackupBean = null;
+
+ private BackupStats backupStats = null;
+
+ // Optional timetable backup
+ private BackupProcess timetableBackup = null;
+
+ /**
+ * Tracks a file that needs to be backed up, including temporary copies of the file
+ */
+ public static class BackupFile {
+ private final File file;
+ private final boolean isTemporary;
+ private final ZxidRange zxidRange;
+
+ /**
+ * Create an instance of a BackupFile for the given initial file and zxid range
+ * @param backupFile the initial/original file
+ * @param isTemporaryFile whether the file is a temporary file
+ * @param fileMinZxid the min zxid associated with this file
+ * @param fileMaxZxid the max zxid associated with this file
+ */
+ public BackupFile(File backupFile, boolean isTemporaryFile, long fileMinZxid, long fileMaxZxid) {
+ this(backupFile, isTemporaryFile, new ZxidRange(fileMinZxid, fileMaxZxid));
+ }
+
+ /**
+ * Create an instance of a BackupFile for the given initial file and zxid range
+ * @param backupFile the initial/original file
+ * @param isTemporaryFile whether the file is a temporary file
+ * @param zxidRange the zxid range associated with this file
+ */
+ public BackupFile(File backupFile, boolean isTemporaryFile, ZxidRange zxidRange) {
+ checkNotNull(zxidRange);
+
+ if (!zxidRange.isHighPresent()) {
+ throw new IllegalArgumentException("ZxidRange must have a high value");
+ }
+
+ this.file = backupFile;
+ this.isTemporary = isTemporaryFile;
+ this.zxidRange = zxidRange;
+ }
+
+ /**
+ * Perform cleanup including deleting temporary files.
+ */
+ public void cleanup() {
+ if (isTemporary && exists()) {
+ if (!file.delete()) {
+ LOG.warn("Failed to delete file {}", file);
+ }
+ }
+ }
+
+ /**
+ * Whether the file representing the zxids exists
+ * @return whether the file represented exists
+ */
+ public boolean exists() {
+ return file != null && file.exists();
+ }
+
+ /**
+ * Get the current file (topmost on the stack)
+ * @return the current file
+ */
+ public File getFile() {
+ return file;
+ }
+
+ /**
+ * Get the zxid range associated with this file
+ * @return the zxid range
+ */
+ public ZxidRange getZxidRange() {
+ return zxidRange;
+ }
+
+ /**
+ * Get the min zxid associated with this file
+ * @return the min associated zxid
+ */
+ public long getMinZxid() {
+ return zxidRange.getLow();
+ }
+
+ /**
+ * Get the max zxid associated with this file
+ * @return the max associated zxid
+ */
+ public long getMaxZxid() {
+ return zxidRange.getHigh();
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s : %s : %d - %d",
+ file == null ? "[empty]" : file.getPath(),
+ isTemporary ? "temp" : "perm",
+ zxidRange.getLow(),
+ zxidRange.getHigh());
+ }
+ }
+
+ /**
+ * Implements txnlog specific logic for BackupProcess
+ */
+ protected class TxnLogBackup extends BackupProcess {
+ private long iterationEndPoint;
+ private final FileTxnSnapLog snapLog;
+
+ /**
+ * Constructor for TxnLogBackup
+ * @param snapLog the FileTxnSnapLog object to use
+ */
+ public TxnLogBackup(FileTxnSnapLog snapLog) {
+ super(LoggerFactory.getLogger(TxnLogBackup.class), BackupManager.this.backupStorage,
+ backupIntervalInMilliseconds);
+ this.snapLog = snapLog;
+ }
+
+ protected void initialize() throws IOException {
+ backupStorage.cleanupInvalidFiles(null);
+
+ BackupFileInfo latest =
+ BackupUtil.getLatest(backupStorage, BackupFileType.TXNLOG, IntervalEndpoint.START);
+
+ long rZxid = latest == null
+ ? BackupUtil.INVALID_LOG_ZXID
+ : latest.getIntervalEndpoint(IntervalEndpoint.END);
+
+ logger.info("Latest Zxid from storage: {} from status: {}",
+ ZxidUtils.zxidToString(rZxid), ZxidUtils.zxidToString(backupPoint.getLogZxid()));
+
+ if (rZxid != backupPoint.getLogZxid()) {
+ synchronized (backupStatus) {
+ backupPoint.setLogZxid(rZxid);
+ backupStatus.update(backupPoint);
+ }
+ }
+ }
+
+ protected void startIteration() {
+ // Store the current last logged zxid. This becomes the stopping point
+ // for the current iteration so we don't keep chasing our own tail as
+ // new transactions get written.
+ iterationEndPoint = snapLog.getLastLoggedZxid();
+ backupStats.setTxnLogBackupIterationStart();
+ }
+
+ protected void endIteration(boolean errorFree) {
+ backupStats.setTxnLogBackupIterationDone(errorFree);
+ iterationEndPoint = 0L;
+ }
+
+ /**
+ * Gets the next txnlog file to backup. This is a temporary file created by copying
+ * all transaction from the previous backup point until the end zxid for this iteration, or
+ * a file indicating that some log records were lost.
+ * @return the file that needs to be backed-up. The minZxid is the first
+ * zxid contained in the file. The maxZxid is the last zxid that is contained in the
+ * file.
+ * @throws IOException
+ */
+ protected BackupFile getNextFileToBackup() throws IOException {
+ long startingZxid = backupStatus.read().getLogZxid() + 1;
+
+ // Don't keep chasing the tail so stop if past the last zxid at the time
+ // this iteration started.
+ if (startingZxid > iterationEndPoint) {
+ return null;
+ }
+
+ TxnLog.TxnIterator iter = null;
+ FileTxnLog newFile = null;
+ long lastZxid = -1;
+ int txnCopied = 0;
+ BackupFile ret;
+
+ logger.info("Creating backup file from zxid {}.", ZxidUtils.zxidToString(startingZxid));
+
+ try {
+ iter = snapLog.readTxnLog(startingZxid, true);
+
+ // Use a temp directory to avoid conflicts with live txnlog files
+ newFile = new FileTxnLog(tmpDir);
+
+ // TODO: Ideally, we should have have a way to prevent lost TxLogs
+ // Check for lost txnlogs; <=1 indicates that no backups have been done before so
+ // nothing can be considered lost.
+ // If a lost sequence is found then return a file whose name encodes the lost
+ // sequence and back that up so the backup store has a record of the lost sequence
+ if (startingZxid > 1
+ && iter.getHeader() != null
+ && iter.getHeader().getZxid() > startingZxid) {
+
+ logger.error("TxnLog backups lost. Required starting zxid={} First available zxid={}",
+ ZxidUtils.zxidToString(startingZxid),
+ ZxidUtils.zxidToString(iter.getHeader().getZxid()));
+
+ String fileName = String.format("%s.%s",
+ BackupUtil.LOST_LOG_PREFIX,
+ Long.toHexString(startingZxid));
+ File lostZxidFile = new File(tmpDir, fileName);
+ if (!lostZxidFile.createNewFile()) {
+ logger.warn("Failed to create file");
+ }
+
+ return new BackupFile(lostZxidFile, true, startingZxid, iter.getHeader().getZxid() - 1);
+ }
+
+ while (iter.getHeader() != null) {
+ TxnHeader hdr = iter.getHeader();
+
+ if (hdr.getZxid() > iterationEndPoint) {
+ break;
+ }
+
+ newFile.append(hdr, iter.getTxn());
+
+ // update position and count only AFTER the record has been successfully
+ // copied
+ lastZxid = hdr.getZxid();
+ txnCopied++;
+
+ iter.next();
+ }
+
+ ret = makeBackupFileFromCopiedLog(newFile, lastZxid);
+
+ if (ret != null) {
+ logger.info("Copied {} records starting at {} and ending at zxid {}.",
+ txnCopied,
+ ZxidUtils.zxidToString(ret.getMinZxid()),
+ ZxidUtils.zxidToString(ret.getMaxZxid()));
+ }
+
+ } catch (IOException e) {
+ logger.warn("Hit exception after {} records. Exception: {} ", txnCopied, e.fillInStackTrace());
+
+ // If any records were copied return those and ignore the error. Otherwise
+ // rethrow the error to be handled by the caller as a failed backup iteration.
+ if (txnCopied <= 0) {
+ throw e;
+ }
+
+ ret = makeBackupFileFromCopiedLog(newFile, lastZxid);
+ } finally {
+ if (iter != null) {
+ iter.close();
+ }
+
+ if (newFile != null) {
+ newFile.close();
+ }
+ }
+
+ return ret;
+ }
+
+ private BackupFile makeBackupFileFromCopiedLog(FileTxnLog backupTxnLog, long lastZxid) {
+
+ if (backupTxnLog == null) {
+ return null;
+ }
+
+ // The logFile gets initialized with the first transaction's zxid
+ File logFile = backupTxnLog.getCurrentFile();
+
+ if (logFile == null) {
+ return null;
+ }
+
+ long firstZxid = Util.getZxidFromName(logFile.getName(), Util.TXLOG_PREFIX);
+
+ if (lastZxid == -1) {
+ lastZxid = firstZxid;
+ }
+
+ return new BackupFile(logFile, true, new ZxidRange(firstZxid, lastZxid));
+ }
+
+ protected void backupComplete(BackupFile file) throws IOException {
+ synchronized (backupStatus) {
+ backupPoint.setLogZxid(file.getMaxZxid());
+ backupStatus.update(backupPoint);
+ }
+
+ logger.info("Updated backedup tnxlog zxid to {}",
+ ZxidUtils.zxidToString(backupPoint.getLogZxid()));
+ }
+ }
+
+ /**
+ * Implements snapshot specific logic for BackupProcess
+ */
+ protected class SnapBackup extends BackupProcess {
+ private final FileTxnSnapLog snapLog;
+ private final List filesToBackup = new ArrayList<>();
+
+ /**
+ * Constructor for SnapBackup
+ * @param snapLog the FileTxnSnapLog object to use
+ */
+ public SnapBackup(FileTxnSnapLog snapLog) {
+ super(LoggerFactory.getLogger(SnapBackup.class), BackupManager.this.backupStorage,
+ backupIntervalInMilliseconds);
+ this.snapLog = snapLog;
+ }
+
+ protected void initialize() throws IOException {
+ backupStorage.cleanupInvalidFiles(null);
+
+ BackupFileInfo latest =
+ BackupUtil.getLatest(backupStorage, BackupFileType.SNAPSHOT, IntervalEndpoint.START);
+
+ long rZxid = latest == null
+ ? BackupUtil.INVALID_SNAP_ZXID
+ : latest.getIntervalEndpoint(IntervalEndpoint.START);
+
+ logger.info("Latest Zxid from storage: {} from status: {}",
+ ZxidUtils.zxidToString(rZxid), ZxidUtils.zxidToString(backupPoint.getSnapZxid()));
+
+ if (rZxid != backupPoint.getSnapZxid()) {
+ synchronized (backupStatus) {
+ backupPoint.setSnapZxid(rZxid);
+ backupStatus.update(backupPoint);
+ }
+ }
+ }
+
+ /**
+ * Prepares snapshot files to back up and populate filesToBackup.
+ * Note that this implementation persists all snapshots instead of only persisting the
+ * latest snapshot.
+ * @throws IOException
+ */
+ protected void startIteration() throws IOException {
+ backupStats.setSnapshotBackupIterationStart();
+ filesToBackup.clear();
+
+ // Get all available snapshots excluding the ones whose lastProcessedZxid falls into the
+ // zxid range [0, backedupSnapZxid]
+ List candidateSnapshots = snapLog.findValidSnapshots(0, backupPoint.getSnapZxid());
+ // Sort candidateSnapshots from oldest to newest
+ Collections.reverse(candidateSnapshots);
+
+ if (candidateSnapshots.size() == 0) {
+ // Either no snapshots or no newer snapshots to back up, so return
+ return;
+ }
+
+ for (int i = 0; i < candidateSnapshots.size(); i++) {
+ File f = candidateSnapshots.get(i);
+ ZxidRange zxidRange = Util.getZxidRangeFromName(f.getName(), Util.SNAP_PREFIX);
+
+ if (i == candidateSnapshots.size() - 1) {
+ // This is the most recent snapshot
+
+ // Handle backwards compatibility for snapshots that use old style naming where
+ // only the starting zxid is included.
+ // TODO: Can be removed after all snapshots being produced have ending zxid
+ if (!zxidRange.isHighPresent()) {
+ // Use the last logged zxid for the zxidRange for the latest snapshot as a best effort
+ // approach
+ // TODO: Because this is the best effort approach, the zxidRange will not be accurate
+ // TODO: Consider rewriting these latest snapshots to backup storage if necessary
+ // TODO: when we know the high zxid when we get a newer snapshot
+ long latestZxid = snapLog.getLastLoggedZxid();
+ long consistentAt = latestZxid == -1 ? zxidRange.getLow() : latestZxid;
+ zxidRange = new ZxidRange(zxidRange.getLow(), consistentAt);
+ }
+ } else {
+ // All newer snapshots that are not the most recent snapshot
+
+ // Handle backwards compatibility for snapshots that use old style naming where
+ // only the starting zxid is included.
+ // TODO: Can be removed after all snapshots being produced have ending zxid
+ if (!zxidRange.isHighPresent()) {
+ // ZxidRange will be [low, high] where high will be the zxid right before the next
+ // snapshot's lastProcessedZxid
+ long nextSnapshotStartZxid =
+ Util.getZxidFromName(candidateSnapshots.get(i + 1).getName(), Util.SNAP_PREFIX);
+ zxidRange = new ZxidRange(zxidRange.getLow(), nextSnapshotStartZxid - 1);
+ }
+ }
+
+ filesToBackup.add(new BackupFile(f, false, zxidRange));
+ }
+ }
+
+ protected void endIteration(boolean errorFree) {
+ backupStats.setSnapshotBackupIterationDone(errorFree);
+ filesToBackup.clear();
+ }
+
+ protected BackupFile getNextFileToBackup() {
+ if (filesToBackup.isEmpty()) {
+ return null;
+ }
+
+ return filesToBackup.remove(0);
+ }
+
+ protected void backupComplete(BackupFile file) throws IOException {
+ synchronized (backupStatus) {
+ backupPoint.setSnapZxid(file.getMinZxid());
+ backupStatus.update(backupPoint);
+ }
+ backupStats.incrementNumberOfSnapshotFilesBackedUpThisIteration();
+
+ logger.info("Updated backedup snap zxid to {}",
+ ZxidUtils.zxidToString(backupPoint.getSnapZxid()));
+ }
+ }
+
+ /**
+ * Constructor for the BackupManager.
+ * @param snapDir the snapshot directory
+ * @param dataLogDir the txnlog directory
+ * @param serverId the id of the zk server
+ * @param backupConfig the backup config object
+ * @throws IOException
+ */
+ public BackupManager(File snapDir, File dataLogDir, long serverId, BackupConfig backupConfig)
+ throws IOException {
+ logger = LoggerFactory.getLogger(BackupManager.class);
+ logger.info("snapDir={}", snapDir.getPath());
+ logger.info("dataLogDir={}", dataLogDir.getPath());
+ logger.info("backupStatusDir={}", backupConfig.getStatusDir().getPath());
+ logger.info("tmpDir={}", backupConfig.getTmpDir().getPath());
+ logger.info("backupIntervalInMinutes={}", backupConfig.getBackupIntervalInMinutes());
+ logger.info("serverId={}", serverId);
+ logger.info("namespace={}", backupConfig.getNamespace());
+
+ this.snapDir = snapDir;
+ this.dataLogDir = dataLogDir;
+ this.backupConfig = backupConfig;
+ this.tmpDir = backupConfig.getTmpDir();
+ this.backupStatus = new BackupStatus(backupConfig.getStatusDir());
+ this.backupIntervalInMilliseconds =
+ TimeUnit.MINUTES.toMillis(backupConfig.getBackupIntervalInMinutes());
+ this.serverId = serverId;
+ this.namespace = backupConfig.getNamespace() == null ? "UNKNOWN" : backupConfig.getNamespace();
+ try {
+ backupStorage = BackupUtil.createStorageProviderImpl(backupConfig);
+ } catch (ReflectiveOperationException e) {
+ throw new BackupException(e.getMessage(), e);
+ }
+ initialize();
+ }
+
+ /**
+ * Start the backup processes.
+ * @throws IOException
+ */
+ public synchronized void start() throws IOException {
+ logger.info("BackupManager starting.");
+
+ (new Thread(logBackup)).start();
+ (new Thread(snapBackup)).start();
+ if (timetableBackup != null) {
+ (new Thread(timetableBackup)).start();
+ }
+ }
+
+ /**
+ * Stop the backup processes.
+ */
+ public void stop() {
+ logger.info("BackupManager shutting down.");
+
+ synchronized (this) {
+ logBackup.shutdown();
+ snapBackup.shutdown();
+ logBackup = null;
+ snapBackup = null;
+
+ // Unregister MBeans so they can get GC-ed
+ if (backupBean != null) {
+ MBeanRegistry.getInstance().unregister(backupBean);
+ backupBean = null;
+ }
+ if (timetableBackupBean != null) {
+ MBeanRegistry.getInstance().unregister(timetableBackupBean);
+ timetableBackupBean = null;
+ }
+ }
+ }
+
+ public BackupProcess getLogBackup() {
+ return logBackup;
+ }
+
+ public BackupProcess getSnapBackup() {
+ return snapBackup;
+ }
+
+ public BackupProcess getTimetableBackup() {
+ return timetableBackup;
+ }
+
+ public long getBackedupLogZxid() {
+ synchronized (backupStatus) {
+ return backupPoint.getLogZxid();
+ }
+ }
+
+ public long getBackedupSnapZxid() {
+ synchronized (backupStatus) {
+ return backupPoint.getSnapZxid();
+ }
+ }
+
+ public synchronized void initialize() throws IOException {
+ try {
+ backupStats = new BackupStats();
+ backupBean = new BackupBean(backupStats, serverId);
+ MBeanRegistry.getInstance().register(backupBean, null);
+ LOG.info("Registered BackupBean {} with JMX.", backupBean.getName());
+ } catch (JMException e) {
+ LOG.error("Failed to register BackupBean with JMX for namespace {} on server {}.", namespace,
+ serverId, e);
+ backupBean = null;
+ }
+
+ synchronized (backupStatus) {
+ backupStatus.createIfNeeded();
+ // backupPoint is only to be initialized once via backupStatus.read() in initialize()
+ backupPoint = backupStatus.read();
+ }
+
+ if (!tmpDir.exists()) {
+ if (!tmpDir.mkdirs()) {
+ String errorMsg = "BackupManager::initialize(): failed to create tmpDir!";
+ logger.error(errorMsg);
+ throw new IOException(errorMsg);
+ }
+ }
+
+ logBackup = new TxnLogBackup(new FileTxnSnapLog(dataLogDir, snapDir));
+ snapBackup = new SnapBackup(new FileTxnSnapLog(dataLogDir, snapDir));
+
+ logBackup.initialize();
+ snapBackup.initialize();
+
+ // if timetable backup is enabled, initialize it as well
+ if (backupConfig.isTimetableEnabled()) {
+ LOG.info("BackupManager::initialize(): timetable is enabled!");
+ // Create a separate instance of BackupStorageProvider for timetable backup
+ // This is because we want the timetable backup to be stored in a different storage path
+ BackupStorageProvider timetableBackupStorage;
+ try {
+ timetableBackupStorage = BackupUtil.createStorageProviderImpl(
+ backupConfig.getBuilder().setBackupStoragePath(backupConfig.getTimetableStoragePath())
+ .build().get());
+ LOG.info(
+ "BackupManager::initialize(): timetable backup storage initialized! Timetable storage path: "
+ + backupConfig.getTimetableStoragePath());
+ } catch (Exception e) {
+ throw new BackupException(e.getMessage(), e);
+ }
+
+ // create metric-related classes for timetable backup
+ TimetableBackupStats timetableBackupStats = new TimetableBackupStats();
+ timetableBackupBean = new TimetableBackupBean(timetableBackupStats);
+ try {
+ // Put timetable backup bean under backup bean, so that they are coupled. this is
+ // consistent with the backup-timetable design where backup must be enabled in order for
+ // timetable to work
+ if (backupBean != null) {
+ MBeanRegistry.getInstance().register(timetableBackupBean, backupBean);
+ LOG.info("BackupManager::initialize(): registered TimetableBackupBean {} under BackupBean"
+ + " {}. Namespace: {}, ServerId: {}.", timetableBackupBean.getName(),
+ backupBean.getName(), namespace, serverId);
+ } else {
+ LOG.error("BackupManager::initialize(): Failed to register TimetableBackupBean with "
+ + "JMX because parent BackupBean is null!");
+ }
+ } catch (JMException e) {
+ LOG.error(
+ "BackupManager::initialize(): Failed to register TimetableBackupBean with JMX for "
+ + "namespace {} on server {}.", namespace, serverId, e);
+ }
+
+ // create an instance of TimetableBackup and initialize
+ timetableBackup = new TimetableBackup(new FileTxnSnapLog(dataLogDir, snapDir), tmpDir,
+ timetableBackupStorage, backupIntervalInMilliseconds,
+ backupConfig.getTimetableBackupIntervalInMs(), backupStatus, backupPoint,
+ timetableBackupStats);
+ timetableBackup.initialize();
+ }
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupPoint.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupPoint.java
new file mode 100644
index 00000000000..35a7f3992bc
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupPoint.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+/**
+ * Describes the point to which backups of log and snap files have been completed. It also includes
+ * a timestamp field to describe the last timestamp timetable has been backed up to (only
+ * applicable when timetable is enabled).
+ */
+public class BackupPoint {
+ private long logZxid;
+ private long snapZxid;
+ private long timestamp; // backup timetable is optional
+
+ /**
+ * Create an instance of a BackupPoint
+ * @param logZxid the highest log zxid that has been backed up
+ * @param snapZxid the start zxid of the latest snap that has been backedup
+ * @param timestamp the latest timestamp that was backed up into timetable
+ */
+ public BackupPoint(long logZxid, long snapZxid, long timestamp) {
+ this.logZxid = logZxid;
+ this.snapZxid = snapZxid;
+ this.timestamp = timestamp;
+ }
+
+ /**
+ * Get the zxid up to which the log has been backed up.
+ * @return the highest zxid that has been backed up
+ */
+ public long getLogZxid() {
+ return logZxid;
+ }
+
+ public void setLogZxid(long logZxid) {
+ this.logZxid = logZxid;
+ }
+
+ /**
+ * Get the starting zxid of the latest backed up snap
+ * @return the starting zxid of the latest backed up snap
+ */
+ public long getSnapZxid() {
+ return snapZxid;
+ }
+
+ public void setSnapZxid(long snapZxid) {
+ this.snapZxid = snapZxid;
+ }
+
+ /**
+ * Get the starting timestamp of the latest backed up timetable backup file
+ * @return the starting timestamp of the latest backed up timetable backup file
+ */
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ /**
+ * Set the ending timestamp of the latest backed up timetable backup file
+ * @param timestamp
+ * @return
+ */
+ public void setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupProcess.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupProcess.java
new file mode 100644
index 00000000000..3d8e722e257
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupProcess.java
@@ -0,0 +1,189 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import java.io.File;
+import java.io.IOException;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.slf4j.Logger;
+
+/**
+ * Base class for the txnlog and snap backup, and timetable backup processes.
+ * Provides the main backup loop and copying to remote storage (via HDFS, NFS, etc. APIs)
+ */
+public abstract class BackupProcess implements Runnable {
+ protected final Logger logger;
+ protected final BackupStorageProvider backupStorage;
+ private final long backupIntervalInMilliseconds;
+ protected volatile boolean isRunning = true;
+
+ /**
+ * Initialize starting backup point based on remote storage and backupStatus file
+ */
+ protected abstract void initialize() throws IOException;
+
+ /**
+ * Marks the start of a backup iteration. A backup iteration is run every
+ * backup.interval. This is called at the start of the iteration and before
+ * any calls to getNextFileToBackup
+ * @throws IOException
+ */
+ protected abstract void startIteration() throws IOException;
+
+ /**
+ * Marks the end of a backup iteration. After this call there will be no more
+ * calls to getNextFileToBackup or backupComplete until startIteration is
+ * called again.
+ * @param errorFree whether the iteration was error free
+ * @throws IOException
+ */
+ protected abstract void endIteration(boolean errorFree);
+
+ /**
+ * Get the next file to backup
+ * @return the next file to copy to backup storage.
+ * @throws IOException
+ */
+ protected abstract BackupManager.BackupFile getNextFileToBackup() throws IOException;
+
+ /**
+ * Marks that the copy of the specified file to backup storage has completed
+ * @param file the file to backup
+ * @throws IOException
+ */
+ protected abstract void backupComplete(BackupManager.BackupFile file) throws IOException;
+
+ /**
+ * Create an instance of the backup process
+ * @param logger the logger to use for this process.
+ */
+ public BackupProcess(Logger logger, BackupStorageProvider backupStorage,
+ long backupIntervalInMilliseconds) {
+ this.logger = logger;
+ this.backupStorage = backupStorage;
+ this.backupIntervalInMilliseconds = backupIntervalInMilliseconds;
+ }
+
+ /**
+ * Runs the main file based backup loop indefinitely.
+ */
+ public void run() {
+ run(0);
+ }
+
+ /**
+ * Runs the main file based backup loop the specified number of time.
+ * Calls methods implemented by derived classes to get the next file to copy.
+ */
+ public void run(int iterations) {
+ try {
+ boolean errorFree = true;
+ logger.debug("Thread starting.");
+
+ while (isRunning) {
+ BackupManager.BackupFile fileToCopy;
+ long startTime = System.currentTimeMillis();
+ try {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Starting iteration");
+ }
+
+ // Cleanup any invalid backups that may have been left behind by the
+ // previous failed iteration.
+ // NOTE: Not done on first iteration (errorFree initialized to true) since
+ // initialize already does this.
+ if (!errorFree) {
+ backupStorage.cleanupInvalidFiles(null);
+ }
+
+ startIteration();
+
+ while ((fileToCopy = getNextFileToBackup()) != null) {
+ // Consider: compress file before sending to remote storage
+ copyToRemoteStorage(fileToCopy);
+ backupComplete(fileToCopy);
+ fileToCopy.cleanup();
+ }
+
+ errorFree = true;
+ } catch (IOException e) {
+ errorFree = false;
+ logger.warn("Exception hit during backup", e);
+ }
+
+ endIteration(errorFree);
+
+ long elapsedTime = System.currentTimeMillis() - startTime;
+
+ logger.info("Completed backup iteration in {} milliseconds. ErrorFree: {}.",
+ elapsedTime, errorFree);
+
+ if (iterations != 0) {
+ iterations--;
+
+ if (iterations < 1) {
+ break;
+ }
+ }
+
+ // Count elapsed time towards the backup interval
+ long waitTime = backupIntervalInMilliseconds - elapsedTime;
+
+ synchronized (this) { // synchronized to get notification of termination
+ if (waitTime > 0) {
+ wait(waitTime);
+ }
+ }
+ }
+ } catch (InterruptedException e) {
+ logger.warn("Interrupted exception while waiting for backup interval.", e.fillInStackTrace());
+ } catch (Exception e) {
+ logger.error("Hit unexpected exception", e.fillInStackTrace());
+ }
+
+ logger.warn("BackupProcess thread exited loop!");
+ }
+
+ /**
+ * Copy given file to remote storage via Backup Storage (HDFS, NFS, etc.) APIs.
+ * @param fileToCopy the file to copy
+ * @throws IOException
+ */
+ private void copyToRemoteStorage(BackupManager.BackupFile fileToCopy) throws IOException {
+ if (fileToCopy.getFile() == null) {
+ return;
+ }
+
+ // Use the file name to encode the max included zxid
+ String backupName = BackupUtil.makeBackupName(
+ fileToCopy.getFile().getName(), fileToCopy.getMaxZxid());
+
+ backupStorage.copyToBackupStorage(fileToCopy.getFile(), new File(backupName));
+ }
+
+ /**
+ * Shutdown the backup process
+ */
+ public void shutdown() {
+ synchronized (this) {
+ isRunning = false;
+ notifyAll();
+ }
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupStatus.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupStatus.java
new file mode 100644
index 00000000000..b66e075d2f9
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupStatus.java
@@ -0,0 +1,167 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.channels.FileLock;
+import org.apache.jute.BinaryInputArchive;
+import org.apache.jute.BinaryOutputArchive;
+import org.apache.jute.InputArchive;
+import org.apache.jute.OutputArchive;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Coordinate the backup status among processes local to a server;
+ * coordination across servers is better served via either an extension
+ * to the ZAB protocol or by some external mechanism.
+ */
+public class BackupStatus {
+ private static final Logger LOG = LoggerFactory.getLogger(BackupStatus.class);
+
+ /**
+ * The name for the backup status file.
+ */
+ public static final String STATUS_FILENAME = "zkBackupStatus";
+
+ private static final String BACKEDUP_LOG_ZXID_TAG = "backedupLogZxid";
+ private static final String BACKEDUP_SNAP_ZXID_TAG = "backedupSnapZxid";
+ private static final String BACKEDUP_TIMETABLE_TIMESTAMP_TAG = "backedupTimetableTimestamp";
+ private File statusFile;
+
+ /**
+ * Create an instance of BackupStatus for reading and updating the
+ * status
+ * @param backupStatusDir the directory for the backup status file
+ * @throws IOException
+ */
+ public BackupStatus(File backupStatusDir) {
+ statusFile = null;
+
+ if (backupStatusDir != null) {
+ statusFile = new File(backupStatusDir, STATUS_FILENAME);
+ }
+ }
+
+ /**
+ * Create the backup status if it does not already exist; Initializes backup
+ * point to 0L, -1L, -1L. Otherwise returns the current backup point.
+ * @return the current backup point
+ * @throws IOException
+ */
+ public synchronized BackupPoint createIfNeeded() throws IOException {
+ if (statusFile == null) {
+ throw new IllegalArgumentException("A backup status directory has not been specified.");
+ }
+
+ if (!statusFile.getParentFile().exists()) {
+ if (!statusFile.getParentFile().mkdirs()) {
+ LOG.warn("Failed to create dirs");
+ }
+ }
+
+ if (!statusFile.exists()) {
+ update(new BackupPoint(BackupUtil.INVALID_LOG_ZXID, BackupUtil.INVALID_SNAP_ZXID,
+ BackupUtil.INVALID_TIMESTAMP));
+ }
+
+ return read();
+ }
+
+ /**
+ * Get the latest backup point
+ * @return the latest backup point, or MAX_VALUE, MAX_VALUE, MAX_VALUE if the backup
+ * status file does not exist
+ */
+ public synchronized BackupPoint read() throws IOException {
+ BackupPoint status = new BackupPoint(Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE);
+
+ if (statusFile != null && statusFile.exists()) {
+ FileInputStream is = null;
+ FileLock fileLock = null;
+
+ // Synchronize with writers from other processes
+ try {
+ is = new FileInputStream(statusFile);
+ InputArchive ia = BinaryInputArchive.getArchive(is);
+ fileLock = is.getChannel().lock(0L, Long.MAX_VALUE, true);
+ status =
+ new BackupPoint(ia.readLong(BACKEDUP_LOG_ZXID_TAG), ia.readLong(BACKEDUP_SNAP_ZXID_TAG),
+ ia.readLong(BACKEDUP_TIMETABLE_TIMESTAMP_TAG));
+ } finally {
+ if (fileLock != null) {
+ fileLock.release();
+ }
+
+ if (is != null) {
+ is.close();
+ }
+ }
+ }
+
+ return status;
+ }
+
+ /**
+ * Update the backup point in the status file. Creates the status file if needed.
+ * @param backupPoint the new backup point
+ * @throws IOException
+ */
+ public synchronized void update(BackupPoint backupPoint) throws IOException {
+ if (statusFile == null) {
+ throw new IllegalArgumentException("A backup status file has not been specified.");
+ }
+
+ if (!statusFile.exists()) {
+ LOG.info("BackupStatus::update(): BackupStatus file doesn't exist. Creating file at path: "
+ + statusFile.getAbsolutePath());
+ if (!statusFile.createNewFile()) {
+ LOG.warn("Failed to delete file: {}", statusFile);
+ }
+ }
+
+ FileOutputStream os = null;
+ FileLock fileLock = null;
+
+ try {
+ os = new FileOutputStream(statusFile, false);
+ OutputArchive oa = BinaryOutputArchive.getArchive(os);
+ // Synchronize with readers and writers from other processes
+ fileLock = os.getChannel().lock();
+ oa.writeLong(backupPoint.getLogZxid(), BACKEDUP_LOG_ZXID_TAG);
+ oa.writeLong(backupPoint.getSnapZxid(), BACKEDUP_SNAP_ZXID_TAG);
+ oa.writeLong(backupPoint.getTimestamp(), BACKEDUP_TIMETABLE_TIMESTAMP_TAG);
+ } finally {
+ if (os != null) {
+ os.flush();
+ }
+
+ if (fileLock != null) {
+ fileLock.release();
+ }
+
+ if (os != null) {
+ os.close();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupSystemProperty.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupSystemProperty.java
new file mode 100644
index 00000000000..b0f23bbfb4d
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupSystemProperty.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+/**
+ * System property Strings for ZooKeeper backup.
+ */
+public class BackupSystemProperty {
+ public static final String BACKUP_ENABLED = "backup.enabled";
+ public static final String BACKUP_STATUS_DIR = "backup.statusDir";
+ public static final String BACKUP_TMP_DIR = "backup.tmpDir";
+ public static final String BACKUP_INTERVAL_MINUTES = "backup.intervalMinutes";
+ public static final String BACKUP_RETENTION_DAYS = "backup.retentionDays";
+ public static final String BACKUP_RETENTION_MAINTENANCE_INTERVAL_HOURS =
+ "backup.retentionMaintenanceIntervalHours";
+ public static final String BACKUP_STORAGE_PROVIDER_CLASS_NAME = "backup.storageProviderClassName";
+ public static final String BACKUP_STORAGE_CONFIG = "backup.storageConfig";
+ public static final String BACKUP_STORAGE_PATH = "backup.storagePath";
+ public static final String BACKUP_NAMESPACE = "backup.namespace";
+
+ // Backup timetable properties
+ public static final String BACKUP_TIMETABLE_ENABLED = "backup.timetable.enabled";
+ public static final String BACKUP_TIMETABLE_STORAGE_PATH = "backup.timetable.storagePath";
+ public static final String BACKUP_TIMETABLE_BACKUP_INTERVAL_MS =
+ "backup.timetable.backupIntervalInMs";
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupUtil.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupUtil.java
new file mode 100644
index 00000000000..32d7333ec16
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/BackupUtil.java
@@ -0,0 +1,417 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Range;
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.timetable.TimetableBackup;
+import org.apache.zookeeper.server.persistence.SnapStream;
+import org.apache.zookeeper.server.persistence.Util;
+import org.apache.zookeeper.server.persistence.ZxidRange;
+
+/**
+ * Utility methods related to backups
+ */
+public class BackupUtil {
+ // first valid tnxlog zxid is 1 while first valid zxid for snapshots is 0
+ public static final long INVALID_LOG_ZXID = 0;
+ public static final long INVALID_SNAP_ZXID = -1;
+ // invalid timestamp is -1 by convention
+ public static final long INVALID_TIMESTAMP = -1L;
+ public static final String LOST_LOG_PREFIX = "lostLogs";
+ public static final String LATEST = "latest";
+
+ /**
+ * Identifiers for the two zxids in a backedup file name
+ */
+ public enum IntervalEndpoint {
+ START,
+ END
+ }
+
+ /**
+ * Identifiers for the backup file types
+ */
+ public enum BackupFileType {
+ SNAPSHOT(Util.SNAP_PREFIX),
+ TXNLOG(Util.TXLOG_PREFIX),
+ LOSTLOG(BackupUtil.LOST_LOG_PREFIX),
+ TIMETABLE(TimetableBackup.TIMETABLE_PREFIX);
+
+ private final String prefix;
+
+ BackupFileType(String prefix) {
+ this.prefix = prefix;
+ }
+
+ public String getPrefix() {
+ return prefix;
+ }
+
+ public static BackupFileType fromPrefix(String prefix) {
+ switch (prefix) {
+ case BackupUtil.LOST_LOG_PREFIX:
+ return LOSTLOG;
+ default:
+ return fromBaseFileType(Util.FileType.fromPrefix(prefix));
+ }
+ }
+
+ public static BackupFileType fromBaseFileType(Util.FileType type) {
+ switch (type) {
+ case SNAPSHOT:
+ return BackupFileType.SNAPSHOT;
+ case TXNLOG:
+ return BackupFileType.TXNLOG;
+ default:
+ throw new IllegalArgumentException("Unknown base file type: " + type);
+ }
+ }
+
+ public static Util.FileType toBaseFileType(BackupFileType type) {
+ switch (type) {
+ case SNAPSHOT:
+ return Util.FileType.SNAPSHOT;
+ case TXNLOG:
+ return Util.FileType.TXNLOG;
+ default:
+ throw new IllegalArgumentException("No matching base file type for: " + type);
+ }
+ }
+ }
+
+ /**
+ * Identifiers for sort direction
+ */
+ public enum SortOrder {
+ ASCENDING,
+ DESCENDING
+ }
+
+ private static class BackupFileComparator implements Comparator, Serializable {
+ private static final long serialVersionUID = -2648639884525140318L;
+
+ private SortOrder sortOrder;
+ private IntervalEndpoint whichIntervalEndpoint;
+
+ public BackupFileComparator(IntervalEndpoint whichIntervalEndpoint, SortOrder sortOrder) {
+ this.sortOrder = sortOrder;
+ this.whichIntervalEndpoint = whichIntervalEndpoint;
+ }
+
+ public int compare(BackupFileInfo o1, BackupFileInfo o2) {
+ long z1 = o1.getIntervalEndpoint(whichIntervalEndpoint);
+ long z2 = o2.getIntervalEndpoint(whichIntervalEndpoint);
+
+ int result = Long.compare(z1, z2);
+
+ if (result == 0) {
+ File f1 = o1.getBackedUpFile();
+ File f2 = o2.getBackedUpFile();
+
+ result = f1.compareTo(f2);
+ }
+
+ return sortOrder == SortOrder.ASCENDING ? result : -result;
+ }
+ }
+
+ private static Function> zxidRangeExtractor =
+ new Function>() {
+ public Range apply(BackupFileInfo fileInfo) {
+ if (fileInfo == null) {
+ throw new IllegalArgumentException("fileInfo is null");
+ }
+ return fileInfo.getRange();
+ }
+ };
+
+ /**
+ * Creates a file name string for a backup file by appending a high zxid/long in Hex if it
+ * doesn't already contain an ending zxid.
+ * It also adds the snapshot filename StreamMode extension in case snapshot compression is
+ * enabled. E.g.) snapshot.123.snappy -> snapshot.123-456.snappy
+ * @param standardName
+ * @param highZxid
+ * @return
+ */
+ public static String makeBackupName(String standardName, long highZxid) {
+ if (standardName.indexOf('-') >= 0) {
+ // standard name already contains the zxid interval endpoint and if snapshot compression
+ // is enabled, the standardName should already contain StreamMode extension, so just return
+ return standardName;
+ }
+ if (SnapStream.getStreamMode(standardName).getName().isEmpty()) {
+ // No snapshot compression is used for this snapshot, so just append the zxid interval
+ // endpoint
+ return String.format("%s-%x", standardName, highZxid);
+ } else {
+ // Snapshot compression is enabled; standardName looks like "snapshot.."
+ // Need to append the ending zxid
+ String[] nameParts = standardName.split("\\.");
+ if (nameParts.length != 3) {
+ throw new BackupException(
+ "BackupUtil::makeBackupName(): unable to make backup name! standardName: "
+ + standardName + " StreamMode: " + SnapStream.getStreamMode(standardName)
+ .getName());
+ }
+ String zxidPart = String.format("%s-%x", nameParts[1], highZxid);
+ // Combine all parts to generate a backup name
+ return nameParts[0] + "." + zxidPart + "." + nameParts[2];
+ }
+ }
+
+ /**
+ * Helper method for getting the proper file prefix for a backup file type.
+ * @param fileType the file type whose prefix to get
+ * @return the prefix for the file
+ */
+ public static String getPrefix(BackupFileType fileType) {
+ return fileType.getPrefix();
+ }
+
+ /**
+ * Sort a list of backup files based on the specified interval endpoint in the requested
+ * sort order
+ * @param files the files to sort
+ * @param whichIntervalEndpoint which interval endpoint to sort by
+ * @param sortOrder which direction in which to sort the files
+ */
+ public static void sort(List files, IntervalEndpoint whichIntervalEndpoint, SortOrder sortOrder) {
+ Collections.sort(files, new BackupFileComparator(whichIntervalEndpoint, sortOrder));
+ }
+
+ /**
+ * Get a range from the backup file name. This range is usually a zxid range, but in the case of
+ * timetable backup, it is a timestamp range.
+ * @param name the name of the file
+ * @param prefix the prefix to match
+ * @return return the range for the file
+ */
+ public static Range getRangeFromName(String name, String prefix) {
+ if (Util.SNAP_PREFIX.equals(prefix)) {
+ ZxidRange snapshotRange = Util.getZxidRangeFromName(name, prefix);
+ return snapshotRange.isHighPresent() ? snapshotRange.toRange() : Range.singleton(-1L);
+ }
+ Range range = Range.singleton(-1L);
+ String nameParts[] = name.split("[\\.-]");
+
+ if (nameParts.length == 3 && nameParts[0].equals(prefix)) {
+ try {
+ // timetable backup files contain decimal longs, not hex
+ int radix = prefix.equals(TimetableBackup.TIMETABLE_PREFIX) ? 10 : 16;
+ range =
+ Range.closed(Long.parseLong(nameParts[1], radix), Long.parseLong(nameParts[2], radix));
+ } catch (NumberFormatException e) {
+ }
+ }
+
+ return range;
+ }
+
+ /**
+ * Sort backup files by the starting point of the interval (min zxid part) in ascending order
+ * @param bsp the backup provide from which to get the files
+ * @param fileType the backup file to get
+ * @return the files listed in the specified order using the requested interval endpoint
+ */
+ public static List getBackupFilesByMin(BackupStorageProvider bsp, BackupFileType fileType)
+ throws IOException {
+ return getBackupFilesByMin(bsp, null, fileType);
+ }
+
+ /**
+ * Sort backup files by the starting point of the interval (min zxid part) in ascending order
+ * @param bsp the backup provide from which to get the files
+ * @param fileType the backup file to get
+ * @return the files listed in the specified order using the requested interval endpoint
+ */
+ public static List getBackupFilesByMin(
+ BackupStorageProvider bsp,
+ File path,
+ BackupFileType fileType) throws IOException {
+
+ return getBackupFiles(bsp, path, fileType, IntervalEndpoint.START, SortOrder.ASCENDING);
+ }
+
+ /**
+ * Sort backup files by the specified interval endpoint
+ * @param bsp the backup provide from which to get the files
+ * @param fileType the backup file to get
+ * @param whichIntervalEndpoint which interval part (min or max) to sort by
+ * @param sortOrder which direction to sort the values (e.g. zxid) in
+ * @return the file info for the matching files sorted by the requested interval endpoint
+ */
+ public static List getBackupFiles(
+ BackupStorageProvider bsp,
+ BackupFileType fileType,
+ IntervalEndpoint whichIntervalEndpoint,
+ SortOrder sortOrder) throws IOException {
+
+ return getBackupFiles(bsp, null, fileType, whichIntervalEndpoint, sortOrder);
+ }
+
+ /**
+ * Sort backup files by the specified interval endpoint
+ * @param bsp the backup provide from which to get the files
+ * @param fileType the backup file to get
+ * @param whichIntervalEndpoint which interval endpoint to sort by
+ * @param sortOrder which direction to sort the ranges in
+ * @return the file info for the matching files sorted by the requested interval endpoint
+ */
+ public static List getBackupFiles(
+ BackupStorageProvider bsp,
+ File path,
+ BackupFileType fileType,
+ IntervalEndpoint whichIntervalEndpoint, SortOrder
+ sortOrder) throws IOException {
+
+ return getBackupFiles(bsp, path, new BackupFileType[] { fileType }, whichIntervalEndpoint, sortOrder);
+ }
+
+ /**
+ * Sort the backup files of the requested types by the specified interval endpoint
+ * @param bsp the backup provide from which to get the files
+ * @param fileTypes the backup file types to get
+ * @param whichIntervalEndpoint which interval endpoint to sort by
+ * @param sortOrder which direction in which to sort based on the requested interval endpoint
+ * @return the file info for the matching files sorted by the requested interval endpoint
+ */
+ public static List getBackupFiles(
+ BackupStorageProvider bsp,
+ BackupFileType[] fileTypes,
+ IntervalEndpoint whichIntervalEndpoint,
+ SortOrder sortOrder) throws IOException {
+
+ return getBackupFiles(bsp, null, fileTypes, whichIntervalEndpoint, sortOrder);
+ }
+
+ /**
+ * Sort the backup files of the requested types by the specified interval endpoint
+ * @param bsp the backup provide from which to get the files
+ * @param fileTypes the backup file types to get
+ * @param whichIntervalEndpoint which interval endpoint to sort by
+ * @param sortOrder which direction in which to sort based on the requested interval endpoint
+ * @return the file info for the matching files sorted by the requested interval endpoint
+ */
+ public static List getBackupFiles(
+ BackupStorageProvider bsp,
+ File path,
+ BackupFileType[] fileTypes,
+ IntervalEndpoint whichIntervalEndpoint,
+ SortOrder sortOrder) throws IOException {
+
+ List files = new ArrayList();
+
+ if (fileTypes.length == 1) {
+ files = bsp.getBackupFileInfos(path, getPrefix(fileTypes[0]));
+ } else {
+ for (BackupFileType fileType : fileTypes) {
+ files.addAll(bsp.getBackupFileInfos(path, getPrefix(fileType)));
+ }
+ }
+
+ sort(files, whichIntervalEndpoint, sortOrder);
+ return files;
+ }
+
+ /**
+ * Get the latest backup file of the given type.
+ * @param bsp the backup storage provider
+ * @param fileType the file to get
+ * @param whichIntervalEndpoint sorted based on which interval endpoint
+ * @return the latest backup file if one exists, null otherwise
+ * @throws IOException
+ */
+ public static BackupFileInfo getLatest(
+ BackupStorageProvider bsp,
+ BackupFileType fileType,
+ IntervalEndpoint whichIntervalEndpoint) throws IOException {
+ List files = getBackupFiles(bsp, fileType, whichIntervalEndpoint, SortOrder.DESCENDING);
+
+ return files.isEmpty() ? null : files.get(0);
+ }
+
+ /**
+ * Get both interval endpoints (Range) for each of the files matching the prefix
+ * @param bsp the backup storage provide to get the files from
+ * @param fileType the backup file to get
+ * @return the list of interval endpoint pairs (ranges)
+ * @throws IOException
+ */
+ public static List> getRanges(BackupStorageProvider bsp, BackupFileType fileType)
+ throws IOException {
+
+ return getRanges(bsp, null, fileType);
+ }
+
+ /**
+ * Get the ranges for each of the files matching the prefix
+ * @param bsp the backup storage provide to get the files from
+ * @param fileType the backup file to get
+ * @return the list of zxid pairs
+ * @throws IOException
+ */
+ public static List> getRanges(
+ BackupStorageProvider bsp,
+ File path,
+ BackupFileType fileType) throws IOException {
+
+ return Lists.newArrayList(
+ Lists.transform(
+ getBackupFiles(bsp, path, fileType, IntervalEndpoint.START, SortOrder.ASCENDING),
+ zxidRangeExtractor));
+ }
+
+ /**
+ * Instantiates the storage provider implementation by reflection. This allows the user to
+ * choose which BackupStorageProvider implementation to use by specifying the fully-qualified
+ * class name in BackupConfig (read from Properties).
+ * @param backupConfig
+ * @return
+ * @throws ClassNotFoundException
+ * @throws NoSuchMethodException
+ * @throws IllegalAccessException
+ * @throws InvocationTargetException
+ * @throws InstantiationException
+ */
+ public static BackupStorageProvider createStorageProviderImpl(BackupConfig backupConfig)
+ throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
+ InvocationTargetException, InstantiationException {
+ Class> clazz = Class.forName(backupConfig.getStorageProviderClassName());
+ Constructor> constructor = clazz.getConstructor(BackupConfig.class);
+ Object storageProvider = constructor.newInstance(backupConfig);
+ return (BackupStorageProvider) storageProvider;
+ }
+
+ // Utility class
+ private BackupUtil() {}
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/RestoreFromBackupTool.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/RestoreFromBackupTool.java
new file mode 100644
index 00000000000..8a41aef6cbf
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/RestoreFromBackupTool.java
@@ -0,0 +1,728 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import static com.google.common.base.Preconditions.checkState;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Range;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.nio.file.Files;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import org.apache.commons.cli.CommandLine;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.cli.RestoreCommand;
+import org.apache.zookeeper.common.ConfigException;
+import org.apache.zookeeper.server.backup.BackupUtil.BackupFileType;
+import org.apache.zookeeper.server.backup.BackupUtil.IntervalEndpoint;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.storage.BackupStorageUtil;
+import org.apache.zookeeper.server.backup.timetable.TimetableBackup;
+import org.apache.zookeeper.server.backup.timetable.TimetableUtil;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.server.persistence.Util;
+import org.apache.zookeeper.server.util.ZxidUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This is a tool to restore, from backup storage, a snapshot and set of transaction log files
+ * that combine to represent a transactionally consistent image of a ZooKeeper ensemble at
+ * some zxid.
+ */
+public class RestoreFromBackupTool {
+ private static final Logger LOG = LoggerFactory.getLogger(RestoreFromBackupTool.class);
+
+ private static final int MAX_RETRIES = 10;
+ private static final String HEX_PREFIX = "0x";
+ private static final int CONNECTION_TIMEOUT = 300000;
+
+ BackupStorageProvider storage;
+ FileTxnSnapLog snapLog;
+ long zxidToRestore;
+ boolean dryRun;
+ File restoreTempDir;
+ boolean overwrite = false;
+
+ // Spot restoration
+ boolean isSpotRestoration = false;
+ String znodePathToRestore;
+ String zkServerConnectionStr;
+ boolean restoreRecursively = false;
+ ZooKeeper zk;
+ SpotRestorationTool spotRestorationTool;
+
+ List logs;
+ List snaps;
+ List filesToCopy;
+
+ int mostRecentLogNeededIndex;
+ int snapNeededIndex;
+ int oldestLogNeededIndex;
+
+ public enum BackupStorageOption {
+ GPFS("org.apache.zookeeper.server.backup.storage.impl.FileSystemBackupStorage"),
+ NFS("org.apache.zookeeper.server.backup.storage.impl.FileSystemBackupStorage");
+
+ private String storageProviderClassName;
+
+ BackupStorageOption(String className) {
+ this.storageProviderClassName = className;
+ }
+
+ public String getStorageProviderClassName() {
+ return storageProviderClassName;
+ }
+ }
+
+ /**
+ * Default constructor; requires using parseArgs to setup state.
+ */
+ public RestoreFromBackupTool() {
+ this(null, null, -1L, false, null);
+ }
+
+ /**
+ * Constructor
+ * @param storageProvider the backup provider from which to restore the backups
+ * @param snapLog the snap and log provider to use
+ * @param zxidToRestore the zxid upto which to restore, or Long.MAX to restore to the latest
+ * available transactionally consistent zxid.
+ * @param dryRun whether this is a dryrun in which case no files are actually copied
+ * @param restoreTempDir a temporary, local (not remote) directory to stage the backup files from
+ * remote backup storage for the processing stage of restoration. Note that
+ * this directory and the files in it will be removed after restoration.
+ */
+ RestoreFromBackupTool(BackupStorageProvider storageProvider, FileTxnSnapLog snapLog,
+ long zxidToRestore, boolean dryRun, File restoreTempDir) {
+
+ filesToCopy = new ArrayList<>();
+ snapNeededIndex = -1;
+ mostRecentLogNeededIndex = -1;
+ oldestLogNeededIndex = -1;
+
+ this.storage = storageProvider;
+ this.zxidToRestore = zxidToRestore;
+ this.snapLog = snapLog;
+ this.dryRun = dryRun;
+ this.restoreTempDir = restoreTempDir;
+ }
+
+ /**
+ * Parse and validate arguments to the tool
+ * @param cl the command line object with user inputs
+ * @return true if the arguments parse correctly; false in all other cases.
+ * @throws IOException if the backup provider cannot be instantiated correctly.
+ */
+ public void parseArgs(CommandLine cl) throws Exception {
+ String backupStoragePath = cl.getOptionValue(RestoreCommand.OptionShortForm.BACKUP_STORE);
+ createBackupStorageProvider(backupStoragePath);
+
+ // Read the restore point
+ if (cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_ZXID)) {
+ parseRestoreZxid(cl);
+ } else if (cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_TIMESTAMP)) {
+ parseRestoreTimestamp(cl, backupStoragePath);
+ }
+
+ parseAndValidateSpotRestorationArgs(cl);
+
+ parseAndValidateOfflineRestoreDestination(cl);
+
+ parseRestoreTempDir(cl);
+
+ // Check if overwriting the destination directories is allowed
+ if (cl.hasOption(RestoreCommand.OptionShortForm.OVERWRITE)) {
+ overwrite = true;
+ }
+
+ // Check if this is a dry-run
+ if (cl.hasOption(RestoreCommand.OptionShortForm.DRY_RUN)) {
+ dryRun = true;
+ }
+
+ System.out.println("parseArgs successful.");
+ }
+
+ private void createBackupStorageProvider(String backupStoragePath) throws Exception {
+ String[] backupStorageParams = backupStoragePath.split(":");
+ if (backupStorageParams.length != 4) {
+ System.err.println(
+ "Failed to parse backup storage connection information from the backup storage path provided, please check the input.");
+ System.err.println(
+ "For example: the format for a gpfs backup storage path should be \"gpfs:::\".");
+ throw new IllegalArgumentException("Failed to create backup storage provider");
+ }
+
+ String userProvidedStorageName = backupStorageParams[0].toUpperCase();
+ try {
+ BackupStorageOption storageOption = BackupStorageOption.valueOf(userProvidedStorageName);
+ String backupStorageProviderClassName = storageOption.getStorageProviderClassName();
+
+ BackupConfig.RestorationConfigBuilder configBuilder =
+ new BackupConfig.RestorationConfigBuilder()
+ .setStorageProviderClassName(backupStorageProviderClassName)
+ .setBackupStoragePath(backupStorageParams[2]).setNamespace(backupStorageParams[3]);
+ if (!backupStorageParams[1].isEmpty()) {
+ configBuilder = configBuilder.setStorageConfig(new File(backupStorageParams[1]));
+ }
+ storage = BackupUtil.createStorageProviderImpl(configBuilder.build().get());
+ } catch (IllegalArgumentException e) {
+ System.err.println("Could not find a valid backup storage option based on the input: "
+ + userProvidedStorageName + ". Error message: " + e.getMessage());
+ e.printStackTrace();
+ throw e;
+ } catch (ConfigException e) {
+ System.err.println(
+ "Could not generate a backup config based on the input, error message: " + e
+ .getMessage());
+ e.printStackTrace();
+ throw e;
+ } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) {
+ System.err.println(
+ "Could not generate a backup storage provider based on the input, error message: " + e
+ .getMessage());
+ e.printStackTrace();
+ throw e;
+ }
+ }
+
+ private void parseRestoreZxid(CommandLine cl) {
+ String zxidToRestoreStr = cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_ZXID);
+ if (zxidToRestoreStr.equalsIgnoreCase(BackupUtil.LATEST)) {
+ zxidToRestore = Long.MAX_VALUE;
+ } else {
+ int base = 10;
+ String numStr = zxidToRestoreStr;
+
+ if (zxidToRestoreStr.startsWith(HEX_PREFIX)) {
+ numStr = zxidToRestoreStr.substring(2);
+ base = 16;
+ }
+ try {
+ zxidToRestore = Long.parseLong(numStr, base);
+ } catch (NumberFormatException nfe) {
+ System.err
+ .println("Invalid number specified for restore zxid point, the input is: " + numStr);
+ throw nfe;
+ }
+ }
+ }
+
+ private void parseRestoreTimestamp(CommandLine cl, String backupStoragePath) {
+ String timestampStr = cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_TIMESTAMP);
+ String timetableStoragePath = backupStoragePath;
+ if (cl.hasOption(RestoreCommand.OptionShortForm.TIMETABLE_STORAGE_PATH)) {
+ timetableStoragePath =
+ cl.getOptionValue(RestoreCommand.OptionShortForm.TIMETABLE_STORAGE_PATH);
+ }
+ File[] timetableFiles = new File(timetableStoragePath)
+ .listFiles(file -> file.getName().startsWith(TimetableBackup.TIMETABLE_PREFIX));
+ if (timetableFiles == null || timetableFiles.length == 0) {
+ System.err.println("Could not find timetable files at the path: " + timetableStoragePath);
+ throw new IllegalArgumentException("Could not find timetable files.");
+ }
+ Map.Entry restorePoint;
+ String message;
+ try {
+ restorePoint = TimetableUtil.findLastZxidFromTimestamp(timetableFiles, timestampStr);
+ zxidToRestore = Long.parseLong(restorePoint.getValue(), 16);
+ String timeToRestore = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
+ .format(new java.util.Date(restorePoint.getKey()));
+ if (timestampStr.equalsIgnoreCase(BackupUtil.LATEST)) {
+ message = "Restoring to " + timeToRestore + ", original request was to restore to latest.";
+ } else {
+ String requestedTimeToRestore = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
+ .format(new java.util.Date(Long.decode(timestampStr)));
+ message = "Restoring to " + timeToRestore + ", original request was to restore to "
+ + requestedTimeToRestore + ".";
+ }
+ System.out.println(message);
+ LOG.info(message);
+ } catch (IllegalArgumentException | BackupException e) {
+ System.err.println(
+ "Could not find a valid zxid from timetable using the timestamp provided: " + timestampStr
+ + ". The error message is: " + e.getMessage());
+ e.printStackTrace();
+ throw e;
+ }
+ }
+
+ private void parseAndValidateOfflineRestoreDestination(CommandLine cl) throws IOException {
+ if (isSpotRestoration) {
+ return;
+ }
+ // Read restore destination: dataDir and logDir
+ try {
+ String snapDirPath = cl.getOptionValue(RestoreCommand.OptionShortForm.SNAP_DESTINATION);
+ String logDirPath = cl.getOptionValue(RestoreCommand.OptionShortForm.LOG_DESTINATION);
+
+ if (snapDirPath == null || logDirPath == null) {
+ throw new BackupException(
+ "Snap destination path and log destination path are not defined for offline restoration. SnapDirPath: "
+ + snapDirPath + ", logDirPath: " + logDirPath);
+ }
+
+ File snapDir = new File(snapDirPath);
+ File logDir = new File(logDirPath);
+ snapLog = new FileTxnSnapLog(logDir, snapDir);
+ checkSnapDataDirFileExistence();
+ } catch (IOException ioe) {
+ System.err.println("Could not setup transaction log utility." + ioe);
+ throw ioe;
+ }
+ }
+
+ private void parseRestoreTempDir(CommandLine cl) {
+ if (cl.hasOption(RestoreCommand.OptionShortForm.LOCAL_RESTORE_TEMP_DIR_PATH)) {
+ String localRestoreTempDirPath =
+ cl.getOptionValue(RestoreCommand.OptionShortForm.LOCAL_RESTORE_TEMP_DIR_PATH);
+ restoreTempDir = new File(localRestoreTempDirPath);
+ }
+
+ if (restoreTempDir == null) {
+ if (isSpotRestoration) {
+ throw new BackupException(
+ "Local restore temp dir path is not defined for spot restoration.");
+ } else {
+ // This is an offline restoration
+ // If the user hasn't provided the restore temp dir parameter,
+ //then the tool will just create a temporary folder inside snapLog and delete it afterwards.
+ this.restoreTempDir = new File(snapLog.getDataLogDir(), "RestoreTempDir_" + zxidToRestore);
+ }
+ }
+ }
+
+ private void parseAndValidateSpotRestorationArgs(CommandLine cl) {
+ if (cl.hasOption(RestoreCommand.OptionShortForm.ZNODE_PATH_TO_RESTORE)) {
+ znodePathToRestore = cl.getOptionValue(RestoreCommand.OptionShortForm.ZNODE_PATH_TO_RESTORE);
+ }
+ if (cl.hasOption(RestoreCommand.OptionShortForm.ZK_SERVER_CONNECTION_STRING)) {
+ zkServerConnectionStr =
+ cl.getOptionValue(RestoreCommand.OptionShortForm.ZK_SERVER_CONNECTION_STRING);
+ }
+ if (cl.hasOption(RestoreCommand.OptionShortForm.RECURSIVE_SPOT_RESTORE)) {
+ restoreRecursively = true;
+ }
+ if (znodePathToRestore != null && zkServerConnectionStr != null) {
+ isSpotRestoration = true;
+ } else if (znodePathToRestore == null && zkServerConnectionStr == null) {
+ isSpotRestoration = false;
+ } else {
+ throw new BackupException(
+ "Znode path and zk server connection string must be provided in order to do spot restoration. Provided znode path: "
+ + znodePathToRestore + ", provided zk server connection string: "
+ + zkServerConnectionStr);
+ }
+ }
+
+ /**
+ * Attempts to perform a restore with up to MAX_RETRIES retries.
+ * @return true if the restore completed successfully, false in all other cases.
+ */
+ public boolean runWithRetries(CommandLine cl) {
+ try {
+ parseArgs(cl);
+ } catch (Exception e) {
+ System.err.println(
+ "Restore attempt failed, could not parse arguments. "
+ + "Error message: " + e.getMessage());
+ return false;
+ }
+
+ int tries = 0;
+
+ if (dryRun) {
+ System.out.println("This is a DRYRUN, no files will actually be copied.");
+ }
+
+ while (tries < MAX_RETRIES) {
+ try {
+ run();
+ return true;
+ } catch (IllegalArgumentException re) {
+ System.err.println(
+ "Restore attempt failed, could not find all the required backup files to restore. "
+ + "Error message: " + re.getMessage());
+ re.printStackTrace();
+ return false;
+ } catch (BackupException be) {
+ System.err.println(
+ "Restoration attempt failed due to a backup exception, it's usually caused by required "
+ + "directories not existing or failure of creating directories, etc. Please check the message. "
+ + "Error message: " + be.getMessage());
+ be.printStackTrace();
+ return false;
+ } catch (Exception e) {
+ tries++;
+ System.err.println("Restore attempt failed; attempting again. " + tries + "/" + MAX_RETRIES
+ + ". Error message: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ System.err.println("Failed to restore after " + (tries + 1) + " attempts.");
+ return false;
+ }
+
+ /**
+ * Attempts to perform a restore.
+ */
+ public void run() throws IOException, InterruptedException {
+ try {
+ if (!findFilesToRestore()) {
+ throw new IllegalArgumentException("Failed to find valid snapshot and logs to restore.");
+ }
+
+ if (restoreTempDir == null || storage == null) {
+ throw new BackupException("The RestoreTempDir and BackupStorageProvider cannot be null.");
+ }
+
+ if (!restoreTempDir.exists() && !restoreTempDir.mkdirs()) {
+ throw new BackupException(
+ "Failed to create a temporary directory at path: " + restoreTempDir.getPath()
+ + " to store copied backup files.");
+ }
+
+ if (!dryRun) {
+ // This step will create a "version-2" directory inside restoreTempDir,
+ // all the selected backup files will be copied to version-2 directory
+ FileTxnSnapLog restoreTempSnapLog =
+ new FileTxnSnapLog(this.restoreTempDir, this.restoreTempDir);
+
+ copyBackupFilesToLocalTempDir(restoreTempSnapLog);
+ processCopiedBackupFiles(restoreTempSnapLog, zxidToRestore);
+ if (isSpotRestoration) {
+ performSpotRestoration(restoreTempDir);
+ } else {
+ // It is an offline restoration
+ copyProcessedRestoredFilesToDestination(restoreTempSnapLog);
+ }
+ }
+ } finally {
+ if (restoreTempDir != null && restoreTempDir.exists()) {
+ // Using recursive delete here because a "version-2" directory is created under restoreTempDir with FileTxnSnapLog
+ BackupStorageUtil.deleteDirectoryRecursively(restoreTempDir);
+ }
+ }
+ }
+
+ /**
+ * Finds the set of files (snapshot and txlog) that are required to restore to a transactionally
+ * consistent point for the requested zxid.
+ * Note that when restoring to the latest zxid, the transactionally consistent point may NOT
+ * be the latest backed up zxid if logs have been lost in between; or if there is no
+ * transactionally consistent point in which nothing will be restored but the restored will
+ * be considered successful.
+ * @return true if a transactionally consistent set of files could be found for the requested
+ * restore point; false in all other cases.
+ * @throws IOException
+ */
+ private boolean findFilesToRestore() throws IOException {
+ snaps = BackupUtil.getBackupFiles(storage, BackupFileType.SNAPSHOT, IntervalEndpoint.START,
+ BackupUtil.SortOrder.DESCENDING);
+ logs = BackupUtil.getBackupFiles(storage,
+ new BackupFileType[]{BackupFileType.TXNLOG, BackupFileType.LOSTLOG}, IntervalEndpoint.START,
+ BackupUtil.SortOrder.DESCENDING);
+ filesToCopy = new ArrayList<>();
+
+ snapNeededIndex = -1;
+
+ while (findNextPossibleSnapshot()) {
+ if (findLogRange()) {
+ filesToCopy.add(snaps.get(snapNeededIndex));
+ filesToCopy.addAll(logs.subList(mostRecentLogNeededIndex, oldestLogNeededIndex + 1));
+ return true;
+ }
+
+ if (zxidToRestore != Long.MAX_VALUE) {
+ break;
+ }
+ }
+
+ // Restoring to an empty data tree (i.e. no backup files) is valid for restoring to
+ // latest
+ if (zxidToRestore == Long.MAX_VALUE) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Find the next snapshot whose range is below the requested restore point.
+ * Note: in practice this only gets called once when zxidToRestore != Long.MAX
+ * @return true if a snapshot is found; false in all other cases.
+ */
+ private boolean findNextPossibleSnapshot() {
+ for (snapNeededIndex++; snapNeededIndex < snaps.size(); snapNeededIndex++) {
+ if (snaps.get(snapNeededIndex).getRange().upperEndpoint() <= zxidToRestore) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Find the range of log files needed to make the current proposed snapshot transactionally
+ * consistent to the requested zxid.
+ * When zxidToRestore == Long.MAX the transaction log range terminates either on the most
+ * recent backedup txnlog OR the last txnlog prior to a lost log range (assuming that log
+ * still makes the snapshot transactionally consistent).
+ * @return true if a valid log range is found; false in all other cases.
+ */
+ private boolean findLogRange() {
+ checkState(snapNeededIndex >= 0 && snapNeededIndex < snaps.size());
+
+ if (logs.size() == 0) {
+ return false;
+ }
+
+ BackupFileInfo snap = snaps.get(snapNeededIndex);
+ Range snapRange = snap.getRange();
+ oldestLogNeededIndex = logs.size() - 1;
+ mostRecentLogNeededIndex = 0;
+
+ // Find the first txlog that might make the snapshot valid, OR is a lost log
+ for (int i = 0; i < logs.size() - 1; i++) {
+ BackupFileInfo log = logs.get(i);
+ Range logRange = log.getRange();
+
+ if (logRange.lowerEndpoint() <= snapRange.lowerEndpoint()) {
+ oldestLogNeededIndex = i;
+ break;
+ }
+ }
+
+ // Starting if the oldest log that might allow the snapshot to be valid, find the txnlog
+ // that includes the restore point, OR is a lost log
+ for (int i = oldestLogNeededIndex; i > 0; i--) {
+ BackupFileInfo log = logs.get(i);
+ Range logRange = log.getRange();
+
+ if (log.getFileType() == BackupFileType.LOSTLOG
+ || logRange.upperEndpoint() >= zxidToRestore) {
+
+ mostRecentLogNeededIndex = i;
+ break;
+ }
+ }
+
+ return validateLogRange();
+ }
+
+ private boolean validateLogRange() {
+ checkState(oldestLogNeededIndex >= 0);
+ checkState(oldestLogNeededIndex < logs.size());
+ checkState(mostRecentLogNeededIndex >= 0);
+ checkState(mostRecentLogNeededIndex < logs.size());
+ checkState(oldestLogNeededIndex >= mostRecentLogNeededIndex);
+ checkState(snapNeededIndex >= 0);
+ checkState(snapNeededIndex < snaps.size());
+
+ BackupFileInfo snap = snaps.get(snapNeededIndex);
+ BackupFileInfo oldestLog = logs.get(oldestLogNeededIndex);
+ BackupFileInfo newestLog = logs.get(mostRecentLogNeededIndex);
+
+ if (oldestLog.getFileType() == BackupFileType.LOSTLOG) {
+ LOG.error("Could not find logs to make the snapshot '" + snap.getBackedUpFile()
+ + "' valid. Lost logs at " + logs.get(oldestLogNeededIndex).getRange());
+ return false;
+ }
+
+ if (newestLog.getFileType() == BackupFileType.LOSTLOG) {
+ if (zxidToRestore == Long.MAX_VALUE && oldestLogNeededIndex != mostRecentLogNeededIndex) {
+ // When restoring to the latest, we can use the last valid log prior to lost log
+ // range.
+ mostRecentLogNeededIndex++;
+ } else {
+ LOG.error("Could not find logs to make the snapshot '" + snap.getBackedUpFile()
+ + "' valid. Lost logs at " + logs.get(mostRecentLogNeededIndex).getRange() + ".");
+ return false;
+ }
+ }
+
+ Range fullRange = oldestLog.getRange().span(newestLog.getRange());
+
+ // The empty initial snapshot has zxid 0, but transaction logs start at zxid 1.
+ long firstRequiredZxid = Math.max(1, snap.getRange().lowerEndpoint());
+ if (fullRange.lowerEndpoint() > firstRequiredZxid) {
+ LOG.error("Could not find logs to make snap '" + snap.getBackedUpFile()
+ + "' valid. Logs start at zxid " + ZxidUtils.zxidToString(fullRange.lowerEndpoint())
+ + ".");
+ return false;
+ }
+
+ if (fullRange.upperEndpoint() < snap.getRange().upperEndpoint()) {
+ LOG.error("Could not find logs to make snap '" + snap.getBackedUpFile()
+ + "' valid. Logs end at zxid " + ZxidUtils.zxidToString(fullRange.upperEndpoint()) + ".");
+ return false;
+ }
+
+ if (zxidToRestore != Long.MAX_VALUE && fullRange.upperEndpoint() < zxidToRestore) {
+ LOG.error("Could not find logs to restore to zxid " + zxidToRestore + ". Logs end at zxid "
+ + ZxidUtils.zxidToString(fullRange.upperEndpoint()) + ".");
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Check if the specified snap dir and data dir already have files inside.
+ * If so, ask user to confirm if they want to overwrite these two directories with restored files,
+ * which means to wipe out all existing files and the directories be populated with restored files.
+ * Note : Supressing no null spotbugs warning because it's showing false positive thing and might be fixed in
+ * https://github.com/spotbugs/spotbugs/issues/456
+ */
+ @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
+ private void checkSnapDataDirFileExistence() {
+ File dataDir = snapLog.getDataLogDir();
+ File snapDir = snapLog.getSnapDir();
+ if (!dataDir.exists() && !dataDir.mkdirs()) {
+ throw new BackupException("Failed to create a data directory at path: " + dataDir.getPath()
+ + " to store restored txn logs.");
+ }
+ if (!snapDir.exists() && !snapDir.mkdirs()) {
+ throw new BackupException("Failed to create a snap directory at path: " + snapDir.getPath()
+ + " to store restored snapshot files.");
+ }
+ String[] dataDirFiles = dataDir.list();
+ String[] snapDirFiles = snapDir.list();
+ if (Objects.requireNonNull(dataDirFiles).length > 0
+ || Objects.requireNonNull(snapDirFiles).length > 0) {
+ if (overwrite) {
+ LOG.warn(
+ "Overwriting the destination directories for restoration, deleting all existing files. "
+ + "The files under dataDir: " + dataDir.getPath() + " are: " + Arrays
+ .toString(dataDirFiles) + "; and files under snapDir: " + snapDir.getPath()
+ + " are: " + Arrays.toString(snapDirFiles) + ".");
+ Arrays.stream(Objects.requireNonNull(dataDir.listFiles())).forEach(File::delete);
+ Arrays.stream(Objects.requireNonNull(snapDir.listFiles())).forEach(File::delete);
+ } else {
+ throw new BackupException(
+ "The destination directories are not empty, user chose not to overwrite the entire directory, "
+ + "exiting restoration. Please check the destination directory dataDir path: "
+ + dataDir.getPath() + ", and snapDir path" + snapDir.getPath());
+ }
+ }
+ }
+
+ /**
+ * Copy selected backup files from backup storage to a local restore temporary directory for further processing later
+ * @param restoreTempSnapLog A FileTxnSnapLog instance created on the specified local temporary directory path
+ * @throws IOException
+ */
+ private void copyBackupFilesToLocalTempDir(FileTxnSnapLog restoreTempSnapLog) throws IOException {
+ // Copy backup files to local temp directory
+ for (BackupFileInfo backedupFile : filesToCopy) {
+ String standardFilename = backedupFile.getStandardFile().getName();
+ // Does not matter if we use dataDir or logDir since we make the paths of these two directories
+ // same in restoreTempSnapLog object for restoration
+ File localTempDest = new File(restoreTempSnapLog.getDataLogDir(), standardFilename);
+
+ if (!localTempDest.exists()) {
+ LOG.info("Copying " + backedupFile.getBackedUpFile() + " from backup storage to temp dir "
+ + localTempDest.getPath() + ".");
+ storage.copyToLocalStorage(backedupFile.getBackedUpFile(), localTempDest);
+ } else {
+ throw new BackupException("Cannot copy " + backedupFile.getBackedUpFile()
+ + " to the local temp directory because it already exists as " + localTempDest.getPath()
+ + ".");
+ }
+ }
+ }
+
+ /**
+ * Process the copied backup files stored in local restore temporary directory to get them ready to be copied to final destination
+ * The processing currently includes truncating txn logs to zxidToRestore.
+ * @param restoreTempSnapLog A FileTxnSnapLog instance created on the specified local temporary directory path
+ * @param zxidToRestore The zxid to restore to
+ * @throws IOException
+ */
+ private void processCopiedBackupFiles(FileTxnSnapLog restoreTempSnapLog, long zxidToRestore) {
+ if (zxidToRestore != Long.MAX_VALUE) {
+ restoreTempSnapLog.truncateLog(zxidToRestore);
+ LOG.info(
+ "Successfully truncate the logs inside restoreTempDir " + restoreTempDir + " to zxid "
+ + zxidToRestore);
+ }
+ }
+
+ /**
+ * Copy the processed files from local restore temp directory to final destination:
+ * snapshot to snapDir, txn logs to logDir.
+ * @param restoreTempSnapLog A FileTxnSnapLog instance created on the specified local temporary directory path
+ * @throws IOException
+ */
+ private void copyProcessedRestoredFilesToDestination(FileTxnSnapLog restoreTempSnapLog)
+ throws IOException {
+ // Does not matter if we use dataDir or logDir since we make the paths of these two directories
+ // same in restoreTempSnapLog object for restoration
+ File[] processedFiles = restoreTempSnapLog.getDataLogDir().listFiles();
+ if (processedFiles == null) {
+ throw new BackupException(
+ "Failed to get a list of processed files from the local temp directory.");
+ }
+ for (File processedFile : processedFiles) {
+ String fileName = processedFile.getName();
+ if (!Util.isSnapshotFileName(fileName) && !Util.isLogFileName(fileName)) {
+ // Skip files that aren't snapshot nor transaction logs. Should only happen in tests.
+ LOG.info("Skipping copying " + processedFile.getPath()
+ + " from temp dir to final destination directory.");
+ continue;
+ }
+ File finalDestinationBase =
+ Util.isSnapshotFileName(fileName) ? snapLog.getSnapDir() : snapLog.getDataLogDir();
+ LOG.info(
+ "Copying " + processedFile.getPath() + " from temp dir to final destination directory "
+ + finalDestinationBase.getPath() + ".");
+ Files.copy(processedFile.toPath(), new File(finalDestinationBase, fileName).toPath());
+ }
+ LOG.info(
+ "All files were successfully copied to destination directory. Offline restoration was completed.");
+ }
+
+ /**
+ * If the CLI command has specified a znode path to perform spot restoration,
+ * run the spot restoration tool on that path
+ * @throws IOException
+ */
+ @VisibleForTesting
+ protected void performSpotRestoration(File restoreTempDir)
+ throws IOException, InterruptedException {
+ LOG.info("Starting spot restoration for zk path " + znodePathToRestore);
+ zk = new ZooKeeper(zkServerConnectionStr, CONNECTION_TIMEOUT, (event) -> {
+ LOG.info("WATCHER:: client-server connection event received for spot restoration: " + event
+ .toString());
+ });
+ spotRestorationTool =
+ new SpotRestorationTool(restoreTempDir, zk, znodePathToRestore, restoreRecursively);
+ spotRestorationTool.run();
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/SpotRestorationTool.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/SpotRestorationTool.java
new file mode 100644
index 00000000000..6da05d36b13
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/SpotRestorationTool.java
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Scanner;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.data.ACL;
+import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.server.DataNode;
+import org.apache.zookeeper.server.DataTree;
+import org.apache.zookeeper.server.ExitCode;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.util.ServiceUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This is a tool for automatic zk path-based restoration of ZK data based on a zk node path using a collection of
+ * snapshot and transaction logs.
+ */
+public class SpotRestorationTool {
+ private static final Logger LOG = LoggerFactory.getLogger(SpotRestorationTool.class);
+
+ private ZooKeeper zk;
+ private FileTxnSnapLog snapLog;
+ private boolean restoreRecursively;
+ private String targetZNodePath;
+ // A list storing messages about skipped nodes, which will be shown to the user at the end of spot restoration
+ private List messages;
+
+ /**
+ * Constructor
+ * @param dataDir The directory contains fully-restored snapshot and transaction log files to be used for spot restoration
+ * @param zk A client connection to the zk server to be restored
+ * @param targetZNodePath The znode path to restore
+ * @param restoreRecursively If true then restore the whole sub-data tree of the target znode;
+ * if false then restore the target znode only
+ * @throws IOException
+ */
+ public SpotRestorationTool(File dataDir, ZooKeeper zk, String targetZNodePath,
+ boolean restoreRecursively) throws IOException {
+ if (dataDir == null || !dataDir.exists()) {
+ throw new IllegalArgumentException(
+ "The provided dataDir is null or does not exist, please check the input.");
+ }
+ this.zk = zk;
+ this.snapLog = new FileTxnSnapLog(dataDir, dataDir);
+ this.targetZNodePath = targetZNodePath;
+ this.restoreRecursively = restoreRecursively;
+ this.messages = Lists.newArrayList();
+ }
+
+ /**
+ * Run the spot restoration.
+ * 1. If a node exists in restored data tree but not in the zk server, create the node in the server
+ * 2. If a node exists in zk server but not the restored data tree, show messages that inform user
+ * to manually delete the node after this spot restoration run
+ * 3. If a node exists in both zk server and restored data tree, show message that inform user to
+ * manually delete the node after this spot restoration run and run spot restoration on the node path again
+ * @throws IOException
+ */
+ public void run() throws IOException, InterruptedException {
+ LOG.info(
+ "Starting spot restoration for znode path " + targetZNodePath + ", using data provided in "
+ + snapLog.getDataLogDir().getPath());
+ DataTree dataTree = new DataTree();
+ long zxidRestored = snapLog.restore(dataTree, new ConcurrentHashMap<>(), (hdr, rec, digest) -> {
+ // Do nothing since we are trying to build a data tree in memory, not in actual zk server
+ });
+
+ DataNode restoredTargetNode = dataTree.getNode(targetZNodePath);
+ if (restoredTargetNode == null) {
+ LOG.info(
+ "The target znode path does not exist in the restored zk data tree. Exit spot restoration.");
+ return;
+ }
+ Stat restoredTargetNodeStat = new Stat();
+ restoredTargetNode.copyStat(restoredTargetNodeStat);
+
+ LOG.info(
+ "The restored zk data tree is constructed. The highest zxid restored is: " + zxidRestored);
+ LOG.info("Restored target node data: " + Arrays.toString(restoredTargetNode.getData()));
+ LOG.info("Restored target node children: " + Arrays
+ .toString(restoredTargetNode.getChildren().toArray()));
+ LOG.info("Restored target node stat: " + restoredTargetNodeStat.toString());
+ String requestMsg = "Do you want to restore to this point? Enter \"yes\" or \"no\".";
+ String yesMsg = "Performing spot restoration of the ZNode path: " + targetZNodePath;
+ String noMsg =
+ "Spot restoration aborted. No change was made to the ZNode path: ." + targetZNodePath;
+ if (getUserConfirmation(requestMsg, yesMsg, noMsg)) {
+ recursiveRestore(zk, dataTree, targetZNodePath, true);
+ zk.close();
+ LOG.info("Spot restoration for " + targetZNodePath + " was successfully done.");
+ printExitMessages();
+ }
+ }
+
+ /**
+ * 1. Restore the node value in zk server;
+ * 2. check if there are nodes that exist in zk server but not in restored data tree in its child nodes;
+ * 3. Do the above operations for all of its child nodes in the restored data tree
+ * @param zk A client connection to zk server
+ * @param dataTree The restored zk data tree
+ * @param path The znode path to restore
+ * @param shouldOverwrite If the node exist: true if the node will be overwritten;
+ * false if the node will be skipped
+ */
+ private void recursiveRestore(ZooKeeper zk, DataTree dataTree, String path,
+ boolean shouldOverwrite) throws InterruptedException {
+ if (!singleNodeRestore(zk, dataTree, path, shouldOverwrite)) {
+ // This node is skipped, there's no need to traverse its child nodes
+ return;
+ }
+ if (!restoreRecursively) {
+ // Non-recursive spot restoration, so no need to proceed further
+ return;
+ }
+
+ // Find child nodes in restored data tree
+ DataNode node = dataTree.getNode(path);
+ Set childrenSet = node.getChildren();
+ String[] children = childrenSet.toArray(new String[0]);
+
+ // Find child nodes that's in zk server but not in restored data tree
+ try {
+ List destChildren = zk.getChildren(path, false);
+ for (String destChild : destChildren) {
+ if (!childrenSet.contains(destChild)) {
+ String nodePath = path + "/" + destChild;
+ messages.add(nodePath + ": This node does not exist in the restored data tree.");
+ }
+ }
+ } catch (Exception e) {
+ skipNodeOrStopRestoration(path, e);
+ }
+
+ // Traverse the child nodes of this node
+ for (String child : children) {
+ recursiveRestore(zk, dataTree, path + "/" + child, false);
+ }
+ }
+
+ /**
+ * Restore the znode in the zk server, currently only doing creation of a single previously non-existent node,
+ * and only supports persistent nodes
+ * @param zk A client connection to zk server
+ * @param dataTree The restored zk data tree
+ * @param path The znode path to restore
+ * @param shouldOverwrite If the node exist: true if the node will be overwritten;
+ * false if the node will be skipped
+ * @return True if the node is successfully restored, false if the node is skipped
+ */
+ private boolean singleNodeRestore(ZooKeeper zk, DataTree dataTree, String path,
+ boolean shouldOverwrite) throws InterruptedException {
+ DataNode node = dataTree.getNode(path);
+ try {
+ if (zk.exists(path, false) == null) {
+ Stat stat = new Stat();
+ node.copyStat(stat);
+ if (stat.getEphemeralOwner() != 0) {
+ messages.add(path
+ + ": The node is an ephemeral node, which is not supported in spot restoration.");
+ } else {
+ return createNode(path, dataTree);
+ }
+ } else if (shouldOverwrite) {
+ // If it is the originally target node path that the user wants to restore,
+ //we don't skip it just because it already exists in the server,
+ //because we already get user's confirmation to restore this node
+ //and we need to get to its child nodes
+ zk.setData(path, node.getData(), -1);
+ return true;
+ } else {
+ messages.add(path + ": The node already exists in zk server.");
+ }
+ } catch (Exception e) {
+ skipNodeOrStopRestoration(path, e);
+ }
+ return false;
+ }
+
+ @VisibleForTesting
+ protected boolean getUserConfirmation(String requestMsg, String yesMsg, String noMsg)
+ throws InterruptedException {
+ Scanner scanner = new Scanner(System.in);
+ int cnt = 3;
+ while (cnt > 0) {
+ System.out.println(requestMsg);
+ String input = scanner.nextLine().toLowerCase();
+ switch (input) {
+ case "yes":
+ System.out.println(yesMsg);
+ return true;
+ case "no":
+ System.out.println(noMsg);
+ return false;
+ default:
+ System.err.println("Could not recognize the input: " + input + ". Please try again.");
+ cnt--;
+ break;
+ }
+ }
+ System.err.println("Could not recognize user's input for the request: " + requestMsg
+ + ". Exiting spot restoration...");
+ printExitMessages();
+ zk.close();
+ return false;
+ }
+
+ private void skipNodeOrStopRestoration(String errorNodePath, Exception exception)
+ throws InterruptedException {
+ String errorMsg = exception.toString() + "\n";
+ String requestMsg =
+ errorMsg + "Do you want to continue the spot restoration? Enter \"yes\" to skip this node "
+ + errorNodePath
+ + ", and continue the spot restoration for the other nodes; enter \"no\" to stop the spot restoration.";
+ String yesMsg =
+ "Skipping node " + errorNodePath + ". Continuing spot restoration for other nodes.";
+ String noMsg = "Spot restoration is stopped. Reason: " + errorMsg;
+ if (!getUserConfirmation(requestMsg, yesMsg, noMsg)) {
+ printExitMessages();
+ zk.close();
+ ServiceUtils.requestSystemExit(ExitCode.EXECUTION_FINISHED.getValue());
+ } else {
+ messages.add(errorNodePath + ": " + errorMsg);
+ }
+ }
+
+ /**
+ * Print out all the messages about skipped nodes during restoration
+ */
+ private void printExitMessages() {
+ if (!messages.isEmpty()) {
+ LOG.warn("During the spot restoration, the following nodes were skipped.");
+ messages.forEach(System.err::println);
+ LOG.warn("Please examine the above nodes and take appropriate actions.");
+ }
+ }
+
+ /**
+ * Create the nodes which do not exist in the zk server
+ * @param path The node path
+ * @param dataTree The restored zk data tree
+ * @return True if node is successfully created, otherwise false
+ * @throws KeeperException
+ * @throws InterruptedException
+ */
+ private boolean createNode(String path, DataTree dataTree)
+ throws KeeperException, InterruptedException {
+ DataNode node = dataTree.getNode(path);
+ List acls = dataTree.getACL(node);
+ if (acls == null || acls.isEmpty()) {
+ acls = ZooDefs.Ids.OPEN_ACL_UNSAFE;
+ }
+ boolean retry = false;
+ do {
+ try {
+ zk.create(path, node.getData(), acls, CreateMode.PERSISTENT);
+ return true;
+ } catch (KeeperException e) {
+ if (e.code().equals(KeeperException.Code.NONODE)) { // Parent node does not exist
+ String requestMsg = "The parent node for node " + path
+ + " does not exist, do you want to create its parent node(s)? Enter \"yes\" to create,"
+ + " enter \"no\" to skip this node or exit the spot restoration.";
+ String yesMsg = "Creating parent node(s) for " + path;
+ String noMsg = "Skip node " + path
+ + " or exit the spot restoration due to non-existent parent node.";
+ if (getUserConfirmation(requestMsg, yesMsg, noMsg)) {
+ String parentPath = path.substring(0, path.lastIndexOf('/'));
+ retry = createNode(parentPath, dataTree);
+ } else {
+ skipNodeOrStopRestoration(path, e);
+ }
+ } else if (e.code().equals(KeeperException.Code.NODEEXISTS)) {
+ messages.add(path + ": The node already exists in zk server.");
+ } else {
+ throw e;
+ }
+ }
+ } while (retry);
+ return false;
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/exception/BackupException.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/exception/BackupException.java
new file mode 100644
index 00000000000..402841dc13e
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/exception/BackupException.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.zookeeper.server.backup.exception;
+
+/**
+ * Signals a logical error has occurred during the ZooKeeper backup/restore process.
+ * Note this error does not mean an error in I/O, but means the object for the operation is not in appropriate state.
+ * For example: failure to copy a file which maybe due to invalid path or source file does not exist.
+ */
+public class BackupException extends RuntimeException {
+ public BackupException(String message) {
+ super(message);
+ }
+
+ public BackupException(String message, Exception e) {
+ super(message, e);
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupBean.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupBean.java
new file mode 100644
index 00000000000..f0a9dd06a36
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupBean.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.monitoring;
+
+import org.apache.zookeeper.jmx.ZKMBeanInfo;
+
+/**
+ * This class implements ZK backup MBean
+ */
+public class BackupBean implements ZKMBeanInfo, BackupMXBean {
+ private final BackupStats backupStats;
+ private final String name;
+
+ public BackupBean(BackupStats backupStats, long serverId) {
+ this.backupStats = backupStats;
+ this.name = "Backup_id" + serverId;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public boolean isHidden() {
+ return false;
+ }
+
+ // Snapshot backup metrics
+ @Override
+ public int getNumConsecutiveFailedSnapshotIterations() {
+ return backupStats.getNumConsecutiveFailedSnapshotIterations();
+ }
+
+ @Override
+ public long getMinutesSinceLastSuccessfulSnapshotIteration() {
+ return backupStats.getMinutesSinceLastSuccessfulSnapshotIteration();
+ }
+
+ @Override
+ public boolean getSnapshotBackupActiveStatus() {
+ return backupStats.getSnapshotBackupActiveStatus();
+ }
+
+ @Override
+ public long getLastSnapshotIterationDuration() {
+ return backupStats.getSnapshotIterationDuration();
+ }
+
+ @Override
+ public int getNumberOfSnapshotFilesBackedUpLastIteration() {
+ return backupStats.getNumberOfSnapshotFilesBackedUpLastIteration();
+ }
+
+ // Transaction log backup metrics
+ @Override
+ public int getNumConsecutiveFailedTxnLogIterations() {
+ return backupStats.getNumConsecutiveFailedTxnLogIterations();
+ }
+
+ @Override
+ public long getMinutesSinceLastSuccessfulTxnLogIteration() {
+ return backupStats.getMinutesSinceLastSuccessfulTxnLogIteration();
+ }
+
+ @Override
+ public boolean getTxnLogBackupActiveStatus() {
+ return backupStats.getTxnLogBackupActiveStatus();
+ }
+
+ @Override
+ public long getLastTxnLogIterationDuration() {
+ return backupStats.getTxnLogIterationDuration();
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupMXBean.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupMXBean.java
new file mode 100644
index 00000000000..28144ea77c0
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupMXBean.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.monitoring;
+
+/**
+ * ZK backup MBean
+ */
+public interface BackupMXBean {
+ // Snapshot backup metrics
+
+ /**
+ * Counter, reset when a successful backup iteration is completed
+ * For example: if backup iteration A fails, the number is 1; if next backup iteration B succeeds, the number is reset to 0.
+ * If A fails, the number is 1; if then B fails too, the number is incremented to 2.
+ * This metric can be used for alerts.
+ * @return Number of consecutive snapshot backup errors since last successful snapshot backup iteration
+ */
+ int getNumConsecutiveFailedSnapshotIterations();
+
+ /**
+ * Counter, reset when a successful backup iteration is completed
+ * This metric can be used for alerts.
+ * @return Time passed (minutes) since last successful snapshot backup iteration
+ */
+ long getMinutesSinceLastSuccessfulSnapshotIteration();
+
+ /**
+ * Gauge
+ * @return If snapshot backup is currently actively ongoing
+ */
+ boolean getSnapshotBackupActiveStatus();
+
+ /**
+ * Gauge
+ * @return How long it took to complete the last snapshot backup iteration
+ */
+ long getLastSnapshotIterationDuration();
+
+ /**
+ * Gauge
+ * @return Number of snapshot files that were backed up to backup storage in last snapshot backup iteration
+ */
+ int getNumberOfSnapshotFilesBackedUpLastIteration();
+
+ // Transaction log backup metrics
+
+ /**
+ * Counter
+ * For example: if backup iteration A fails, the number is 1; if next backup iteration B succeeds, the number is reset to 0.
+ * If A fails, the number is 1; if then B fails too, the number is incremented to 2.
+ * @return Number of consecutive txn log backup errors since last successful txn log backup iteration
+ */
+ int getNumConsecutiveFailedTxnLogIterations();
+
+ /**
+ * Counter
+ * @return Time passed (minutes) since last successful txn log backup iteration
+ */
+ long getMinutesSinceLastSuccessfulTxnLogIteration();
+
+ /**
+ * Gauge
+ * @return If txn log backup is currently actively ongoing
+ */
+ boolean getTxnLogBackupActiveStatus();
+
+ /**
+ * Gauge
+ * @return How long it took to complete the last txn log backup iteration
+ */
+ long getLastTxnLogIterationDuration();
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupStats.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupStats.java
new file mode 100644
index 00000000000..583d56b747b
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/BackupStats.java
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.monitoring;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class contains ZK backup related statistics
+ */
+public class BackupStats {
+ private static final Logger LOG = LoggerFactory.getLogger(BackupStats.class);
+
+ /*
+ Snapshot backup metric declarations
+ */
+ private int failedSnapshotIterationCount = 0;
+ private long lastSuccessfulSnapshotBackupIterationFinishTime = System.currentTimeMillis();
+ private boolean snapshotBackupActive = false;
+ private long snapshotIterationDuration = 0L;
+ private int numberOfSnapshotFilesBackedUpLastIteration = 0;
+ private int numberOfSnapshotFilesBackedUpThisIteration = 0;
+ private long lastSnapshotBackupIterationStartTime = System.currentTimeMillis();
+
+ /*
+ TxLog backup metric declarations
+ */
+ private int failedTxnLogIterationCount = 0;
+ private long lastSuccessfulTxnLogBackupIterationFinishTime = System.currentTimeMillis();
+ private boolean txnLogBackupActive = false;
+ private long txnLogIterationDuration = 0L;
+ private long lastTxnLogBackupIterationStartTime = System.currentTimeMillis();
+
+ // Snapshot backup metrics
+
+ /**
+ * Counter
+ * For example: if backup iteration A fails, the number is 1; if next backup iteration B succeeds, the number is reset to 0.
+ * If A fails, the number is 1; if then B fails too, the number is incremented to 2.
+ * @return Number of consecutive snapshot backup errors since last successful snapshot backup iteration
+ */
+ public int getNumConsecutiveFailedSnapshotIterations() {
+ return failedSnapshotIterationCount;
+ }
+
+ /**
+ * Counter
+ * @return Time passed (minutes) since last successful snapshot backup iteration
+ */
+ public long getMinutesSinceLastSuccessfulSnapshotIteration() {
+ return (System.currentTimeMillis() - lastSuccessfulSnapshotBackupIterationFinishTime) / (60
+ * 1000);
+ }
+
+ /**
+ * Gauge
+ * @return If snapshot backup is currently actively ongoing
+ */
+ public boolean getSnapshotBackupActiveStatus() {
+ return snapshotBackupActive;
+ }
+
+ /**
+ * Gauge
+ * @return How long it took to complete the last snapshot backup iteration
+ */
+ public long getSnapshotIterationDuration() {
+ return snapshotIterationDuration;
+ }
+
+ /**
+ * Gauge
+ * @return Number of snapshot files that were backed up to backup storage in last snapshot backup iteration
+ */
+ public int getNumberOfSnapshotFilesBackedUpLastIteration() {
+ return numberOfSnapshotFilesBackedUpLastIteration;
+ }
+
+ /**
+ * Record the status and timestamp when a snapshot backup iteration starts
+ */
+ public void setSnapshotBackupIterationStart() {
+ lastSnapshotBackupIterationStartTime = System.currentTimeMillis();
+ snapshotBackupActive = true;
+ numberOfSnapshotFilesBackedUpThisIteration = 0;
+ }
+
+ /**
+ * Record the status and timestamp when a snapshot backup iteration finishes
+ * @param errorFree If this iteration finishes without error
+ */
+ public void setSnapshotBackupIterationDone(boolean errorFree) {
+ long finishTime = System.currentTimeMillis();
+ snapshotIterationDuration = finishTime - lastSnapshotBackupIterationStartTime;
+ snapshotBackupActive = false;
+ numberOfSnapshotFilesBackedUpLastIteration = numberOfSnapshotFilesBackedUpThisIteration;
+ numberOfSnapshotFilesBackedUpThisIteration = 0;
+ if (errorFree) {
+ lastSuccessfulSnapshotBackupIterationFinishTime = finishTime;
+ failedSnapshotIterationCount = 0;
+ } else {
+ failedSnapshotIterationCount++;
+ }
+ }
+
+ /**
+ * To be called during snapshot backup iteration every time one more snapshot file is backed up
+ * A helper to keep track value for "numberOfSnapshotFilesBackedUpLastIteration" metric
+ */
+ public void incrementNumberOfSnapshotFilesBackedUpThisIteration() {
+ numberOfSnapshotFilesBackedUpThisIteration++;
+ }
+
+ // Transaction log backup metrics
+
+ /**
+ * Counter
+ * For example: if backup iteration A fails, the number is 1; if next backup iteration B succeeds, the number is reset to 0.
+ * If A fails, the number is 1; if then B fails too, the number is incremented to 2.
+ * @return Number of consecutive txn log backup errors since last successful txn log backup iteration
+ */
+ public int getNumConsecutiveFailedTxnLogIterations() {
+ return failedTxnLogIterationCount;
+ }
+
+ /**
+ * Counter
+ * @return Time passed (minutes) since last successful txn log backup iteration
+ */
+ public long getMinutesSinceLastSuccessfulTxnLogIteration() {
+ return (System.currentTimeMillis() - lastSuccessfulTxnLogBackupIterationFinishTime) / (60
+ * 1000);
+ }
+
+ /**
+ * Gauge
+ * @return If txn log backup is currently actively ongoing
+ */
+ public boolean getTxnLogBackupActiveStatus() {
+ return txnLogBackupActive;
+ }
+
+ /**
+ * Gauge
+ * @return How long it took to complete the last txn log backup iteration
+ */
+ public long getTxnLogIterationDuration() {
+ return txnLogIterationDuration;
+ }
+
+ /**
+ * Record the status and timestamp when a txn log backup iteration starts
+ */
+ public void setTxnLogBackupIterationStart() {
+ lastTxnLogBackupIterationStartTime = System.currentTimeMillis();
+ txnLogBackupActive = true;
+ }
+
+ /**
+ * Record the status and timestamp when a txn log backup iteration finishes
+ * @param errorFree If this iteration finishes without error
+ */
+ public void setTxnLogBackupIterationDone(boolean errorFree) {
+ long finishTime = System.currentTimeMillis();
+ txnLogBackupActive = false;
+ txnLogIterationDuration = finishTime - lastTxnLogBackupIterationStartTime;
+ if (errorFree) {
+ lastSuccessfulTxnLogBackupIterationFinishTime = finishTime;
+ failedTxnLogIterationCount = 0;
+ } else {
+ failedTxnLogIterationCount++;
+ }
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupBean.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupBean.java
new file mode 100644
index 00000000000..df242d09ed4
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupBean.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.monitoring;
+
+import org.apache.zookeeper.jmx.ZKMBeanInfo;
+
+public class TimetableBackupBean implements ZKMBeanInfo, TimetableBackupMXBean {
+ public static final String TIMETABLE_BACKUP_MBEAN_NAME = "TimetableBackup";
+ private final TimetableBackupStats backupStats;
+
+ public TimetableBackupBean(TimetableBackupStats backupStats) {
+ this.backupStats = backupStats;
+ }
+
+ @Override
+ public String getName() {
+ return TIMETABLE_BACKUP_MBEAN_NAME;
+ }
+
+ @Override
+ public boolean isHidden() {
+ return false;
+ }
+
+ // Timetable backup metrics
+ @Override
+ public int getNumConsecutiveFailedTimetableIterations() {
+ return backupStats.getNumConsecutiveFailedTimetableIterations();
+ }
+
+ @Override
+ public long getMinutesSinceLastSuccessfulTimetableIteration() {
+ return backupStats.getMinutesSinceLastSuccessfulTimetableIteration();
+ }
+
+ @Override
+ public boolean getTimetableBackupActiveStatus() {
+ return backupStats.getTimetableBackupActiveStatus();
+ }
+
+ @Override
+ public long getLastTimetableIterationDuration() {
+ return backupStats.getTimetableIterationDuration();
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupMXBean.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupMXBean.java
new file mode 100644
index 00000000000..e4ed8fc0b0f
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupMXBean.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.monitoring;
+
+public interface TimetableBackupMXBean {
+
+ // Timetable backup metrics
+
+ /**
+ * Counter
+ * For example: if backup iteration A fails, the number is 1; if next backup iteration B succeeds,
+ * the number is reset to 0.
+ * If A fails, the number is 1; if then the next iteration B fails again, the number is
+ * incremented to 2.
+ * @return
+ */
+ int getNumConsecutiveFailedTimetableIterations();
+
+ /**
+ * Counter
+ * @return Time passed (minutes) since last successful timetable backup iteration
+ */
+ long getMinutesSinceLastSuccessfulTimetableIteration();
+
+ /**
+ * Gauge
+ * @return If timetable backup is currently in progress
+ */
+ boolean getTimetableBackupActiveStatus();
+
+ /**
+ * Gauge
+ * @return How long it took to complete the last timetable backup iteration
+ */
+ long getLastTimetableIterationDuration();
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupStats.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupStats.java
new file mode 100644
index 00000000000..767e95f8e92
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/monitoring/TimetableBackupStats.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.monitoring;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * TimetableBackupStats contains fields that represent metrics for timetable backup.
+ */
+public class TimetableBackupStats {
+ /*
+ Timetable backup metric declarations
+ */
+ private int failedTimetableIterationCount = 0;
+ private boolean timetableBackupActive = false;
+ private long lastSuccessfulTimetableBackupIterationFinishTime = System.currentTimeMillis();
+ private long timetableIterationDuration = 0L;
+ private long lastTimetableBackupIterationStartTime = System.currentTimeMillis();
+
+ // Timetable backup metrics
+
+ /**
+ * Counter
+ * For example: if backup iteration A fails, the number is 1; if next backup iteration B succeeds,
+ * the number is reset to 0.
+ * If A fails, the number is 1; if then the next iteration B fails again, the number is
+ * incremented to 2.
+ * @return Number of consecutive timetable backup errors since last successful timetable backup
+ * iteration
+ */
+ public int getNumConsecutiveFailedTimetableIterations() {
+ return failedTimetableIterationCount;
+ }
+
+ /**
+ * Counter
+ * @return Time passed (minutes) since last successful timetable backup iteration
+ */
+ public long getMinutesSinceLastSuccessfulTimetableIteration() {
+ return TimeUnit.MILLISECONDS
+ .toMinutes(System.currentTimeMillis() - lastSuccessfulTimetableBackupIterationFinishTime);
+ }
+
+ /**
+ * Gauge
+ * @return true if timetable backup is currently in progress
+ */
+ public boolean getTimetableBackupActiveStatus() {
+ return timetableBackupActive;
+ }
+
+ /**
+ * Gauge
+ * @return How long it took to complete the last timetable backup iteration
+ */
+ public long getTimetableIterationDuration() {
+ return timetableIterationDuration;
+ }
+
+ /**
+ * Record the status and timestamp when a timetable backup iteration starts
+ */
+ public void setTimetableBackupIterationStart() {
+ lastTimetableBackupIterationStartTime = System.currentTimeMillis();
+ timetableBackupActive = true;
+ }
+
+ /**
+ * Record the status and timestamp when a timetable backup iteration finishes.
+ * @param errorFree If this iteration finishes without error
+ */
+ public void setTimetableBackupIterationDone(boolean errorFree) {
+ long finishTime = System.currentTimeMillis();
+ timetableBackupActive = false;
+ timetableIterationDuration = finishTime - lastTimetableBackupIterationStartTime;
+ if (errorFree) {
+ lastSuccessfulTimetableBackupIterationFinishTime = finishTime;
+ failedTimetableIterationCount = 0;
+ } else {
+ failedTimetableIterationCount++;
+ }
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/BackupStorageProvider.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/BackupStorageProvider.java
new file mode 100644
index 00000000000..c5e4cd35829
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/BackupStorageProvider.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.storage;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import org.apache.zookeeper.server.backup.BackupFileInfo;
+
+/**
+ * Interface for a backup storage provider
+ */
+public interface BackupStorageProvider {
+
+ /**
+ * Get the metadata for a backed-up file with the given name.
+ * @param file the file name relative to the root of the backup storage provider
+ * @return the metadata for the backed-up file
+ * @throws IOException
+ */
+ BackupFileInfo getBackupFileInfo(File file) throws IOException;
+
+ /**
+ * Get the metadata for backedup files with the given prefix.
+ * @param path path relative to the root of the backup storage provider
+ * @param prefix The file prefix
+ * @return the list of files matching the prefix
+ * @throws IOException
+ */
+ List getBackupFileInfos(File path, String prefix) throws IOException;
+
+ /**
+ * Get the list of directories under the given path
+ * @param path the location from where to get the list of directories
+ * @return list of the full child directory names relative to the root of the storage provider
+ * @throws IOException
+ */
+ List getDirectories(File path) throws IOException;
+
+ /**
+ * Open a file
+ * @param path the path of the file to open
+ * @return stream of the file
+ * @throws IOException
+ */
+ InputStream open(File path) throws IOException;
+
+ /**
+ * Copy a local file to backup storage.
+ * This method must guarantee a valid and transactional operation, or implement the operation
+ * in such a way that the {@link #cleanupInvalidFiles(File path) cleanup} method can cleanup
+ * after any interrupted operations.
+ * @param srcFile the local file
+ * @param destName the name to use in backup storage
+ * @throws IOException
+ */
+ void copyToBackupStorage(File srcFile, File destName) throws IOException;
+
+ /**
+ * Copy a file from backup storage to local storage
+ * @param srcName the name of the backup file to copy
+ * @param destFile the local file to which to copy the file
+ * @throws IOException
+ */
+ void copyToLocalStorage(File srcName, File destFile) throws IOException;
+
+ /**
+ * Delete a file from backup storage
+ * @param fileToDelete the name of the backup file to delete
+ * @throws IOException
+ */
+ void delete(File fileToDelete) throws IOException;
+
+ /**
+ * Cleanup any invalid files that may have been left behind by failed operations on the
+ * storage provider
+ * @throws IOException
+ */
+ void cleanupInvalidFiles(File path) throws IOException;
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/BackupStorageUtil.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/BackupStorageUtil.java
new file mode 100644
index 00000000000..e1e994fa340
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/BackupStorageUtil.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.zookeeper.server.backup.storage;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Comparator;
+import java.util.stream.Stream;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+import org.apache.zookeeper.server.persistence.Util;
+
+/**
+ * Util methods for backup storage
+ */
+public class BackupStorageUtil {
+ public static final String TMP_FILE_PREFIX = "TMP_";
+ private static final File[] NO_FILE = new File[0];
+
+ /**
+ * Parse the prefix from a file name, also works for temporary file names in backup storage
+ * @param fileName The file name to be parsed
+ * @return "log" for ZK transaction log files or "snapshot" for ZK snapshots
+ */
+ public static String getFileTypePrefix(String fileName) {
+ String backupFileName = fileName;
+
+ //Remove the temporary file name prefix in order to determine file type
+ if (fileName.startsWith(TMP_FILE_PREFIX)) {
+ backupFileName = fileName.substring(TMP_FILE_PREFIX.length());
+ }
+
+ String fileTypePrefix;
+ if (backupFileName.startsWith(Util.SNAP_PREFIX)) {
+ fileTypePrefix = Util.SNAP_PREFIX;
+ } else if (backupFileName.startsWith(Util.TXLOG_PREFIX)) {
+ fileTypePrefix = Util.TXLOG_PREFIX;
+ } else {
+ throw new BackupException("No matching base file type found for file " + fileName);
+ }
+
+ return fileTypePrefix;
+ }
+
+ /**
+ * Construct the path of a backup file in the backup storage
+ * @param fileName The name of the file
+ * @param parentDir The path to the parent directory of the backup file.
+ * @return The path of the backup file in the format of:
+ * 1. parentDir path is not supplied: {fileName} or {fileName}
+ * 2. parentDir path is provided: {parentDir}/{fileName} or {parentDir}/{fileName}
+ */
+ public static String constructBackupFilePath(String fileName, String parentDir) {
+ //TODO: store snapshots and Txlogs in different subfolders for better organization
+ if (parentDir != null) {
+ return String.valueOf(Paths.get(parentDir, fileName));
+ }
+ return fileName;
+ }
+
+ /**
+ * Construct temporary file name using backup file name
+ * @param fileName A backup file name: log.lowzxid-highzxid, snapshot.lowzxid-highzxid
+ * @return A temporary backup file name: TMP_log.lowzxid-highzxid, TMP_snapshot.lowzxid-highzxid
+ */
+ public static String constructTempFileName(String fileName) {
+ return TMP_FILE_PREFIX + fileName;
+ }
+
+ /**
+ * A basic method for streaming data from an input stream to an output stream
+ * @param inputStream The stream to read from
+ * @param outputStream The stream to write to
+ * @throws IOException
+ */
+ public static void streamData(InputStream inputStream, OutputStream outputStream)
+ throws IOException {
+ byte[] buffer = new byte[1024];
+ int lengthRead;
+ while ((lengthRead = inputStream.read(buffer)) > 0) {
+ outputStream.write(buffer, 0, lengthRead);
+ outputStream.flush();
+ }
+ }
+
+ /**
+ * Create a new file in a specified path, create the parent directories if they do not exist.
+ * @param file The path to create the file.
+ * @param overwriteIfExist If a file already exists in the location,
+ * 1. true: delete the existing file and retry the creation of the new file,
+ * or 2. false: keep the existing file.
+ * @throws IOException
+ */
+ public static void createFile(File file, boolean overwriteIfExist) throws IOException {
+ if (!file.getParentFile().mkdirs()) {
+ System.err.println("Failed to create dirs");
+ }
+ if (!file.getParentFile().exists()) {
+ throw new BackupException("Failed to create parent directories for file " + file.getName());
+ }
+
+ boolean retry = true;
+ while (retry) {
+ retry = overwriteIfExist;
+ if (!file.createNewFile()) {
+ if (file.exists()) {
+ if (retry && !file.delete()) {
+ throw new BackupException("A file with the file path " + file.getPath()
+ + " already exists, and failed to be overwritten.");
+ }
+ } else {
+ throw new BackupException("Failed to create a file at path: " + file.getPath());
+ }
+ }
+ retry = false;
+ }
+ }
+
+ /**
+ * Get a list of all files whose file name starts with a certain prefix under a directory
+ * @param directory The directory to search for the files
+ * @param prefix The prefix of file name
+ * @return
+ */
+ public static File[] getFilesWithPrefix(File directory, String prefix) {
+ if (directory == null) {
+ return NO_FILE;
+ }
+ FilenameFilter fileFilter = (dir, name) -> name.startsWith(prefix);
+ File[] files = directory.listFiles(fileFilter);
+ return files == null ? NO_FILE : files;
+ }
+
+ /**
+ * Delete all the files whose file names starts with temporary file name prefix
+ * @param directory The directory to search for temporary files
+ * @throws IOException
+ */
+ public static void cleanUpTempFiles(File directory) throws IOException {
+ File[] tempFiles = getFilesWithPrefix(directory, TMP_FILE_PREFIX);
+ for (File tempFile : tempFiles) {
+ Files.delete(Paths.get(tempFile.getPath()));
+ }
+ }
+
+ /**
+ * Delete a directory and all files inside it
+ * @param directory The path to the directory
+ * @throws IOException
+ */
+ public static void deleteDirectoryRecursively(File directory) throws IOException {
+ Stream files = Files.walk(Paths.get(directory.getPath()));
+ files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
+ files.close();
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/impl/FileSystemBackupStorage.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/impl/FileSystemBackupStorage.java
new file mode 100644
index 00000000000..89a4baf7084
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/storage/impl/FileSystemBackupStorage.java
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.storage.impl;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import org.apache.zookeeper.server.backup.BackupConfig;
+import org.apache.zookeeper.server.backup.BackupFileInfo;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.storage.BackupStorageUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implementation for backup storage provider for file systems that store files in a tree (hierarchical) structure
+ * To use this class for different file systems, use appropriate address for backupStoragePath in BackupConfig
+ * For example:
+ * 1. hard disk drive & solid-state drive: /mountPoint/relativePathToMountPoint
+ * 2. NFS: /nfsClientMountPoint/relativePathToMountPoint
+ * 3. local disk: an absolute path to a directory
+ */
+public class FileSystemBackupStorage implements BackupStorageProvider {
+ private static final Logger LOG = LoggerFactory.getLogger(FileSystemBackupStorage.class);
+ private final String fileRootPath;
+ private final ReadWriteLock rwLock;
+ private final Lock sharedLock;
+ private final Lock exclusiveLock;
+
+ /**
+ * Constructor using BackupConfig to get backup storage info
+ * @param backupConfig The information and settings about backup storage, to be set as a part of ZooKeeper server config
+ */
+ public FileSystemBackupStorage(BackupConfig backupConfig) {
+ if (!new File(backupConfig.getBackupStoragePath()).exists()) {
+ throw new BackupException(
+ "The backup storage is not ready, please check the path: " + backupConfig
+ .getBackupStoragePath());
+ }
+ fileRootPath = String
+ .join(File.separator, backupConfig.getBackupStoragePath(), backupConfig.getNamespace());
+ rwLock = new ReentrantReadWriteLock();
+ sharedLock = rwLock.readLock();
+ exclusiveLock = rwLock.writeLock();
+ }
+
+ @Override
+ public BackupFileInfo getBackupFileInfo(File file) throws IOException {
+ String backupFilePath = BackupStorageUtil.constructBackupFilePath(file.getName(), fileRootPath);
+ File backupFile = new File(backupFilePath);
+
+ if (!backupFile.exists()) {
+ return new BackupFileInfo(backupFile, BackupFileInfo.NOT_SET, BackupFileInfo.NOT_SET);
+ }
+
+ BasicFileAttributes fileAttributes =
+ Files.readAttributes(Paths.get(backupFilePath), BasicFileAttributes.class);
+ return new BackupFileInfo(backupFile, fileAttributes.lastModifiedTime().toMillis(),
+ fileAttributes.size());
+ }
+
+ @Override
+ public List getBackupFileInfos(File path, String prefix) throws IOException {
+ String filePath = path == null ? "" : path.getPath();
+ String backupDirPath = Paths.get(fileRootPath, filePath).toString();
+ File backupDir = new File(backupDirPath);
+
+ if (!backupDir.exists()) {
+ return new ArrayList<>();
+ }
+
+ File[] files = BackupStorageUtil.getFilesWithPrefix(backupDir, prefix);
+
+ // Read the file info and add to the list. If an exception is thrown, the entire operation will fail
+ List backupFileInfos = new ArrayList<>();
+ for (File file : files) {
+ backupFileInfos.add(getBackupFileInfo(file));
+ }
+ return backupFileInfos;
+ }
+
+ @Override
+ public List getDirectories(File path) {
+ String filePath = path == null ? "" : path.getPath();
+ String backupDirPath = BackupStorageUtil.constructBackupFilePath(filePath, fileRootPath);
+ File backupDir = new File(backupDirPath);
+
+ if (!backupDir.exists()) {
+ throw new BackupException(
+ "Backup directory " + filePath + " does not exist, could not get directory list.");
+ }
+
+ // Filter out all the files which are directories
+ FilenameFilter fileFilter = (dir, name) -> new File(dir, name).isDirectory();
+ File[] dirs = backupDir.listFiles(fileFilter);
+
+ if (dirs == null) {
+ return new ArrayList<>();
+ }
+ return Arrays.asList(dirs);
+ }
+
+ @Override
+ public InputStream open(File path) throws IOException {
+ if (!path.exists() || path.isDirectory()) {
+ throw new BackupException("The file with the file path " + path
+ + " does not exist or is a directory, could not open the file.");
+ }
+ return new FileInputStream(path);
+ }
+
+ @Override
+ public void copyToBackupStorage(File srcFile, File destName) throws IOException {
+ InputStream inputStream = null;
+ OutputStream outputStream = null;
+ String backupTempFilePath;
+ File backupTempFile;
+
+ sharedLock.lock();
+ try {
+ inputStream = open(srcFile);
+
+ backupTempFilePath = BackupStorageUtil
+ .constructBackupFilePath(BackupStorageUtil.constructTempFileName(destName.getName()),
+ fileRootPath);
+ backupTempFile = new File(backupTempFilePath);
+
+ BackupStorageUtil.createFile(backupTempFile, true);
+ outputStream = new FileOutputStream(backupTempFile);
+
+ BackupStorageUtil.streamData(inputStream, outputStream);
+
+ Files.move(Paths.get(backupTempFilePath),
+ Paths.get(BackupStorageUtil.constructBackupFilePath(destName.getName(), fileRootPath)),
+ StandardCopyOption.REPLACE_EXISTING);
+ } finally {
+ try {
+ if (inputStream != null) {
+ inputStream.close();
+ }
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ } catch (Exception e) {
+ // empty catch block. This is added incase exception occurs before releasing sharedLock.
+ } finally {
+ sharedLock.unlock();
+ }
+ }
+ }
+
+ @Override
+ public void copyToLocalStorage(File srcName, File destFile) throws IOException {
+ InputStream inputStream = null;
+ OutputStream outputStream = null;
+
+ // Create input stream from the source file in backup storage
+ String backupFilePath =
+ BackupStorageUtil.constructBackupFilePath(srcName.getName(), fileRootPath);
+ File backupFile = new File(backupFilePath);
+
+ try {
+ inputStream = open(backupFile);
+
+ BackupStorageUtil.createFile(destFile, true);
+ outputStream = new FileOutputStream(destFile);
+
+ BackupStorageUtil.streamData(inputStream, outputStream);
+ } finally {
+ if (inputStream != null) {
+ inputStream.close();
+ }
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ }
+ }
+
+ @Override
+ public void delete(File fileToDelete) throws IOException {
+ String fileName = fileToDelete == null ? "" : fileToDelete.getName();
+ String backupFilePath = BackupStorageUtil.constructBackupFilePath(fileName, fileRootPath);
+ Files.deleteIfExists(Paths.get(backupFilePath));
+ }
+
+ @Override
+ public void cleanupInvalidFiles(File path) throws IOException {
+ if (path == null) {
+ path = new File(fileRootPath);
+ }
+ exclusiveLock.lock();
+ try {
+ BackupStorageUtil.cleanUpTempFiles(path);
+ } finally {
+ exclusiveLock.unlock();
+ }
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/timetable/TimetableBackup.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/timetable/TimetableBackup.java
new file mode 100644
index 00000000000..9e02c8080be
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/timetable/TimetableBackup.java
@@ -0,0 +1,286 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.timetable;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.util.Comparator;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import org.apache.zookeeper.server.backup.BackupFileInfo;
+import org.apache.zookeeper.server.backup.BackupManager;
+import org.apache.zookeeper.server.backup.BackupPoint;
+import org.apache.zookeeper.server.backup.BackupProcess;
+import org.apache.zookeeper.server.backup.BackupStatus;
+import org.apache.zookeeper.server.backup.BackupUtil;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+import org.apache.zookeeper.server.backup.monitoring.TimetableBackupStats;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.txn.TxnHeader;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implements Timetable-specific logic for BackupProcess.
+ *
+ * Backup timetable encodes data of the format :. This is used to locate the
+ * closest zxid backup point given the timestamp. The use case is for users who wish to restore
+ * from backup at a specific time recorded in the backup timetable.
+ */
+public class TimetableBackup extends BackupProcess {
+ public static final String TIMETABLE_PREFIX = "timetable";
+ // Use an ordered map of :
+ private final TreeMap timetableRecordMap = new TreeMap<>();
+ private final File tmpDir;
+ // Lock is used to keep access to timetableRecordMap exclusive
+ private final Lock lock = new ReentrantLock(true);
+
+ // Candidate files to be backed up each iteration sorted by name (using SortedSet)
+ private final SortedSet candidateTimetableBackupFiles =
+ new TreeSet<>(Comparator.comparing(o -> o.getFile().getName()));
+ // BackupStatus is used here to keep track of timetable backup status in case of a crash/restart
+ // BackupStatus is written to a file. After a crash (e.g. JVM crash) or a restart, the
+ // locally-stored zkBackupStatus file will be read back to restore a BackupPoint
+ private final BackupStatus backupStatus;
+ private final BackupPoint backupPoint;
+ private final long timetableBackupIntervalInMs;
+ private final FileTxnSnapLog snapLog;
+ private final TimetableBackupStats backupStats; // Metrics
+
+ /**
+ * Create an instance of TimetableBackup.
+ * @param snapLog
+ * @param tmpDir
+ * @param backupStorageProvider
+ * @param backupIntervalInMilliseconds
+ * @param timetableBackupIntervalInMs
+ * @param backupStatus
+ */
+ public TimetableBackup(FileTxnSnapLog snapLog, File tmpDir,
+ BackupStorageProvider backupStorageProvider, long backupIntervalInMilliseconds,
+ long timetableBackupIntervalInMs, BackupStatus backupStatus, BackupPoint backupPoint,
+ TimetableBackupStats backupStats) {
+ super(LoggerFactory.getLogger(TimetableBackup.class), backupStorageProvider,
+ backupIntervalInMilliseconds);
+ this.tmpDir = tmpDir;
+ this.backupStatus = backupStatus;
+ this.backupPoint = backupPoint;
+ this.backupStats = backupStats;
+ this.snapLog = snapLog;
+ this.timetableBackupIntervalInMs = timetableBackupIntervalInMs;
+ logger.info("TimetableBackup::Starting TimetableBackup Process with backup interval: "
+ + backupIntervalInMilliseconds + " ms and timetable backup interval: "
+ + timetableBackupIntervalInMs + " ms.");
+ }
+
+ @Override
+ protected void initialize() throws IOException {
+ // Start creating records
+ // Note : A thread should always be started in init function instead of class constructor.
+ (new Thread(new TimetableRecorder(snapLog, timetableBackupIntervalInMs))).start();
+
+ // Get the latest timetable backup file from backup storage
+ BackupFileInfo latest = BackupUtil.getLatest(backupStorage, BackupUtil.BackupFileType.TIMETABLE,
+ BackupUtil.IntervalEndpoint.END);
+
+ long latestTimestampBackedUp = latest == null ? BackupUtil.INVALID_TIMESTAMP
+ : latest.getIntervalEndpoint(BackupUtil.IntervalEndpoint.END);
+
+ logger.info(
+ "TimetableBackup::initialize(): latest timestamp from storage: {}, from BackupStatus: {}",
+ latestTimestampBackedUp, backupPoint.getTimestamp());
+
+ if (latestTimestampBackedUp != backupPoint.getTimestamp()) {
+ synchronized (backupStatus) {
+ backupPoint.setTimestamp(latestTimestampBackedUp);
+ backupStatus.update(backupPoint);
+ }
+ }
+ }
+
+ @Override
+ protected void startIteration() throws IOException {
+ backupStats.setTimetableBackupIterationStart();
+
+ // It's possible that the last iteration failed and left some tmp backup files behind - add
+ // them back to candidate backup files so the I/O write will happen again
+ getAllTmpBackupFiles();
+
+ // Create a timetable backup file from the cached records (timetableRecordMap)
+ lock.lock();
+ try {
+ if (!timetableRecordMap.isEmpty()) {
+ // Create a temp timetable backup file
+ // Make the backup file temporary so that it will be deleted after the iteration provided
+ // the I/O write to the backup storage succeeds. Otherwise, this temporary backup file will
+ // continue to exist in tmpDir locally until it's successfully written to the backup storage
+ BackupManager.BackupFile timetableBackupFromThisIteration =
+ new BackupManager.BackupFile(createTimetableBackupFile(), true, 0, 0);
+ candidateTimetableBackupFiles.add(timetableBackupFromThisIteration);
+ timetableRecordMap.clear(); // Clear the map
+ }
+ } catch (Exception e) {
+ logger.error("TimetableBackup::startIteration(): failed to create timetable file to back up!",
+ e);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ protected void endIteration(boolean errorFree) {
+ // timetableRecordMap is cleared in startIteration() already, so we do not clear it here
+ backupStats.setTimetableBackupIterationDone(errorFree);
+ }
+
+ @Override
+ protected BackupManager.BackupFile getNextFileToBackup() throws IOException {
+ BackupManager.BackupFile nextFile = null;
+ if (!candidateTimetableBackupFiles.isEmpty()) {
+ nextFile = candidateTimetableBackupFiles.first();
+ }
+ return nextFile;
+ }
+
+ @Override
+ protected void backupComplete(BackupManager.BackupFile file) throws IOException {
+ // Remove from the candidate set because it has been copied to the backup storage successfully
+ candidateTimetableBackupFiles.remove(file);
+ synchronized (backupStatus) {
+ // Update the latest timestamp to which the timetable backup was successful
+ backupPoint.setTimestamp(Long.parseLong(file.getFile().getName().split("-")[1]));
+ backupStatus.update(backupPoint);
+ }
+ logger.info(
+ "TimetableBackup::backupComplete(): backup complete for file: {}. Updated backed up "
+ + "timestamp to {}", file.getFile().getName(), backupPoint.getTimestamp());
+ }
+
+ /**
+ * Create a file name for timetable backup.
+ * E.g.) timetable.-
+ * @return
+ */
+ private String makeTimetableBackupFileName() {
+ return String.format("%s.%d-%d", TIMETABLE_PREFIX, timetableRecordMap.firstKey(),
+ timetableRecordMap.lastKey());
+ }
+
+ /**
+ * Write the content of timetableRecordMap to a file using a tmpDir.
+ * @return
+ * @throws IOException
+ */
+ private File createTimetableBackupFile() throws IOException {
+ File tempTimetableBackupFile = new File(tmpDir, makeTimetableBackupFileName());
+ logger.info(
+ "TimetableBackup::createTimetableBackupFile(): created temporary timetable backup file with"
+ + " name: " + tempTimetableBackupFile.getName());
+ FileOutputStream fos = new FileOutputStream(tempTimetableBackupFile);
+ ObjectOutputStream oos = new ObjectOutputStream(fos);
+ oos.writeObject(timetableRecordMap);
+ oos.flush();
+ oos.close();
+ fos.close();
+ logger.info(
+ "TimetableBackup::createTimetableBackupFile(): successfully wrote cached timetable data to "
+ + "temporary timetable backup file with name: " + tempTimetableBackupFile.getName());
+ return tempTimetableBackupFile;
+ }
+
+ /**
+ * Get all temporary timetable backup files in tmpDir.
+ */
+ private void getAllTmpBackupFiles() {
+ File[] tmpBackupFiles = tmpDir.listFiles(f -> f.getName().startsWith(TIMETABLE_PREFIX));
+ if (tmpBackupFiles != null && tmpBackupFiles.length != 0) {
+ for (File file : tmpBackupFiles) {
+ // Note that zxid are not needed for timetable backup files, so we just put 0 here
+ candidateTimetableBackupFiles.add(new BackupManager.BackupFile(file, true, 0, 0));
+ }
+ }
+ }
+
+ /**
+ * Child thread that records timetable records (:) at the given interval.
+ *
+ * TimetableBackup: parent thread responsible for creating timetable backup files from
+ * cached record (map) and writing to backup storage
+ * TimetableRecorder: child thread responsible for adding timetable-zxid mappings to the cached
+ * map at every timetable backup interval.
+ */
+ class TimetableRecorder implements Runnable {
+ private final FileTxnSnapLog snapLog;
+ private final long timetableBackupIntervalInMs;
+ private long lastLoggedZxidFromLastRun;
+
+ public TimetableRecorder(FileTxnSnapLog snapLog, long timetableBackupIntervalInMs) {
+ this.snapLog = snapLog;
+ this.timetableBackupIntervalInMs = timetableBackupIntervalInMs;
+ logger.info("TimetableRecorder created with timetable backup interval at "
+ + timetableBackupIntervalInMs + " ms.");
+ }
+
+ @Override
+ public void run() {
+ // The lifecycle of this child thread should be tied to that of TimetableBackup
+ while (isRunning) {
+ try {
+ lock.lock();
+ try {
+ TxnHeader lastLoggedTxnHeader = snapLog.getLastLoggedTxnHeader();
+ if (lastLoggedTxnHeader != null) {
+ // Ignore if the last logged zxid is not valid (-1) because -1 (int) will cause a
+ // NumberFormatException during conversion to Hex String
+ // Also do not create repeat records
+ long zxid = lastLoggedTxnHeader.getZxid();
+ long timestamp = lastLoggedTxnHeader.getTime();
+ if (zxid >= 0 && zxid != lastLoggedZxidFromLastRun) {
+ timetableRecordMap.put(timestamp, Long.toHexString(zxid));
+ lastLoggedZxidFromLastRun = zxid;
+ }
+ }
+ } catch (Exception e) {
+ // Bad state, this shouldn't happen. Throw an exception
+ throw new BackupException(
+ "TimetableRecorder::run(): failed to record a timestamp-zxid mapping!", e);
+ } finally {
+ lock.unlock();
+ }
+ synchronized (TimetableBackup.this) {
+ // synchronized to get notification of termination in case of shutdown
+ // must synchronize on the outer class's reference (TimetableBackup.this) because
+ // the notifyAll() call wakes up all BackupProcess instances
+ TimetableBackup.this.wait(timetableBackupIntervalInMs);
+ }
+ } catch (InterruptedException e) {
+ logger.warn("TimetableRecorder::run(): Interrupted exception while waiting for "
+ + "timetable backup interval.", e.fillInStackTrace());
+ } catch (Exception e) {
+ logger.error("TimetableRecorder::run(): Hit unexpected exception", e.fillInStackTrace());
+ }
+ }
+ }
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/timetable/TimetableUtil.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/timetable/TimetableUtil.java
new file mode 100644
index 00000000000..478ef4ccdd1
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/backup/timetable/TimetableUtil.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.timetable;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.ObjectInputStream;
+import java.util.Map;
+import java.util.TreeMap;
+import org.apache.zookeeper.server.backup.BackupUtil;
+import org.apache.zookeeper.server.backup.exception.BackupException;
+
+/**
+ * Util methods used to operate on timetable backup.
+ */
+public final class TimetableUtil {
+ private static final String TIMETABLE_PREFIX = "timetable.";
+
+ private TimetableUtil() {
+ // Util class
+ }
+
+ /**
+ * Returns the last zxid corresponding to the timestamp preceding the timestamp given as argument.
+ * Note: the given timestamp must be in the comprehensive range created from the timetable
+ * backup files unless it is "latest". This is to prevent any human mistakes of accidentally
+ * entering an arbitrarily high timestamp value and the tool restoring to the latest backup point.
+ * @param timetableBackupFiles
+ * @param timestamp timestamp string (long), or "latest"
+ * @return A map entry consists of timestamp in Long and Hex String representation of the zxid found
+ */
+ public static Map.Entry findLastZxidFromTimestamp(File[] timetableBackupFiles,
+ String timestamp) {
+ // Verify argument: backup files
+ if (timetableBackupFiles == null || timetableBackupFiles.length == 0) {
+ throw new IllegalArgumentException(
+ "TimetableUtil::findLastZxidFromTimestamp(): timetableBackupFiles argument is either null"
+ + " or empty!");
+ }
+
+ // Verify argument: timestamp
+ boolean isLatest = timestamp.equalsIgnoreCase(BackupUtil.LATEST);
+ long timestampLong;
+ if (isLatest) {
+ timestampLong = Long.MAX_VALUE;
+ } else {
+ try {
+ timestampLong = Long.decode(timestamp);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(
+ "TimetableUtil::findLastZxidFromTimestamp(): cannot convert the given timestamp to a"
+ + " valid long! timestamp: " + timestamp, e);
+ }
+ }
+
+ // Traverse the files and find the lower bound, upper bound, and the file that contains the
+ // timestamp
+ long lowerBound = Long.MAX_VALUE, upperBound = Long.MIN_VALUE, lowestDelta = Long.MAX_VALUE;
+ File fileToRead = null;
+ for (File file : timetableBackupFiles) {
+ String[] range = file.getName().replaceAll(TIMETABLE_PREFIX, "").split("-");
+ long low = Long.parseLong(range[0]), high = Long.parseLong(range[1]);
+ lowerBound = Math.min(low, lowerBound);
+ upperBound = Math.max(high, upperBound);
+ if (isLatest) {
+ if (upperBound == high) {
+ fileToRead = file;
+ }
+ } else {
+ // Calculate the delta to find the closest available file either containing the timestamp
+ // in its range or before the timestamp
+ long delta = timestampLong - low;
+ if (delta >= 0 && delta < lowestDelta) {
+ lowestDelta = delta;
+ fileToRead = file;
+ }
+ }
+ }
+
+ // Check if the given timestamp is in range
+ if (!isLatest && (timestampLong < lowerBound || timestampLong > upperBound)) {
+ throw new IllegalArgumentException(
+ "TimetableUtil::findLastZxidFromTimestamp(): timestamp given " + timestampLong
+ + " is not in the timestamp range [" + lowerBound + " , " + upperBound
+ + "] given in the backup files!");
+ }
+
+ // Check if a file is found (this shouldn't happen if timestamp is in range)
+ if (fileToRead == null) {
+ throw new IllegalArgumentException(
+ "TimetableUtil::findLastZxidFromTimestamp(): unable to find the backup file to use!");
+ }
+
+ // Convert timetable backup files to an ordered Map, timestamp:zxid pairs
+ TreeMap timestampZxidPairs = new TreeMap<>();
+ try {
+ FileInputStream fis = new FileInputStream(fileToRead);
+ ObjectInputStream ois = new ObjectInputStream(fis);
+ @SuppressWarnings("unchecked")
+ Map map = (TreeMap) ois.readObject();
+ timestampZxidPairs.putAll(map);
+ ois.close();
+ } catch (Exception e) {
+ throw new BackupException(
+ "TimetableUtil::findLastZxidFromTimestamp(): failed to read timetable backup files!", e);
+ }
+
+ // Find the last zxid corresponding to the timestamp given
+ Map.Entry floorEntry = timestampZxidPairs.floorEntry(timestampLong);
+ if (floorEntry == null) {
+ throw new BackupException("TimetableUtil::findLastZxidFromTimestamp(): floorEntry is null!");
+ }
+ return floorEntry;
+ }
+}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileSnap.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileSnap.java
index df8a59c1a9f..86381f607c8 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileSnap.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileSnap.java
@@ -204,6 +204,29 @@ public List findNRecentSnapshots(int n) throws IOException {
return list;
}
+ /**
+ * returns all valid snapshots excluding the zxid interval given
+ * for example, if the interval given is [A, B], then snapshot.B will not be included in the
+ * returned list
+ * @param startZxid starting zxid of the interval
+ * @param endZxid ending zxid of the interval
+ * @return all valid snapshots excluding the snapshots whose last processed zxid does not fall
+ * into the interval (startZxid, endZxid) given
+ * @throws IOException
+ */
+ public List findValidSnapshots(long startZxid, long endZxid) throws IOException {
+ List files = Util.sortDataDir(snapDir.listFiles(), SNAPSHOT_FILE_PREFIX, false);
+ List list = new ArrayList<>();
+ for (File f : files) {
+ long zxidFromName = Util.getZxidFromName(f.getName(), SNAPSHOT_FILE_PREFIX);
+ if (SnapStream.isValidSnapshot(f) && (zxidFromName < startZxid
+ || zxidFromName > endZxid)) {
+ list.add(f);
+ }
+ }
+ return list;
+ }
+
/**
* serialize the datatree and sessions
* @param dt the datatree to be serialized
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnLog.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnLog.java
index 7d4366065df..d85961b32d8 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnLog.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnLog.java
@@ -202,6 +202,14 @@ public static void setTxnLogSizeLimit(long size) {
txnLogSizeLimit = size;
}
+ /**
+ * Returns the reference to the current log file.
+ * @return
+ */
+ public synchronized File getCurrentFile() {
+ return logFileWrite;
+ }
+
/**
* Return the current on-disk size of log size. This will be accurate only
* after commit() is called. Otherwise, unflushed txns may not be included.
@@ -369,6 +377,41 @@ public long getLastLoggedZxid() {
return zxid;
}
+ /**
+ * get the last TxnHeader that was logged in the transaction logs
+ * @return the last TxnHeader containing txn metadata
+ */
+ public TxnHeader getLastLoggedTxnHeader() {
+ File[] files = getLogFiles(logDir.listFiles(), 0);
+ long maxLog = files.length > 0 ? Util
+ .getZxidFromName(files[files.length - 1].getName(), LOG_FILE_PREFIX) : -1;
+
+ TxnIterator itr = null;
+ TxnHeader hdr = null;
+ try {
+ FileTxnLog txn = new FileTxnLog(logDir);
+ itr = txn.read(maxLog);
+ do {
+ hdr = itr.getHeader();
+ } while (itr.next());
+ } catch (IOException e) {
+ LOG.warn("getLastLoggedZxidTimestampPair():: Unexpected exception", e);
+ } finally {
+ close(itr);
+ }
+ return hdr;
+ }
+
+ private void close(TxnIterator itr) {
+ if (itr != null) {
+ try {
+ itr.close();
+ } catch (IOException ioe) {
+ LOG.warn("Error closing file iterator", ioe);
+ }
+ }
+ }
+
/**
* commit the logs. make sure that everything hits the
* disk
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnSnapLog.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnSnapLog.java
index 9cf8af1fd65..3d6df26420f 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnSnapLog.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/FileTxnSnapLog.java
@@ -462,6 +462,15 @@ public long getLastLoggedZxid() {
return txnLog.getLastLoggedZxid();
}
+ /**
+ * the last logged TxnHeader from the transaction log
+ * @return last logged TxnHeader
+ */
+ public TxnHeader getLastLoggedTxnHeader() {
+ FileTxnLog txnLog = new FileTxnLog(dataDir);
+ return txnLog.getLastLoggedTxnHeader();
+ }
+
/**
* save the datatree and the sessions into a snapshot
* @param dataTree the datatree to be serialized onto disk
@@ -567,6 +576,20 @@ public List findNValidSnapshots(int n) {
return snaplog.findNValidSnapshots(n);
}
+ /**
+ * returns all valid snapshots excluding the zxid interval given
+ * for example, if the interval given is [A, B], then snapshot.B will not be included in the
+ * returned list
+ * @param startZxid start of the zxid interval
+ * @param endZxid end of the zxid interval
+ * @return the list of snapshots in the most recent in front
+ * @throws IOException
+ */
+ public List findValidSnapshots(long startZxid, long endZxid) throws IOException {
+ FileSnap snaplog = new FileSnap(snapDir);
+ return snaplog.findValidSnapshots(startZxid, endZxid);
+ }
+
/**
* get the snapshot logs which may contain transactions newer than the given zxid.
* This includes logs with starting zxid greater than given zxid, as well as the
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/Util.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/Util.java
index 6949c43697b..758e2943417 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/Util.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/Util.java
@@ -45,6 +45,28 @@
*/
public class Util {
+ /**
+ * Constants and enums added for backup and restore.
+ */
+ public static final String SNAP_PREFIX = FileSnap.SNAPSHOT_FILE_PREFIX;
+ public static final String TXLOG_PREFIX = FileTxnLog.LOG_FILE_PREFIX;
+
+ public enum FileType {
+ SNAPSHOT,
+ TXNLOG;
+
+ public static FileType fromPrefix(String prefix) {
+ switch (prefix) {
+ case SNAP_PREFIX:
+ return SNAPSHOT;
+ case TXLOG_PREFIX:
+ return TXNLOG;
+ default:
+ throw new IllegalArgumentException("Unknown FileType prefix: " + prefix);
+ }
+ }
+ }
+
private static final Logger LOG = LoggerFactory.getLogger(Util.class);
private static final String SNAP_DIR = "snapDir";
private static final String LOG_DIR = "logDir";
@@ -147,6 +169,32 @@ public static long getZxidFromName(String name, String prefix) {
return zxid;
}
+ /**
+ * Returns a ZxidRange whose high Zxid could be absent.
+ * @param name
+ * @param prefix
+ * @return
+ */
+ public static ZxidRange getZxidRangeFromName(String name, String prefix) {
+ if (SNAP_PREFIX.equals(prefix)) {
+ String extension = SnapStream.getStreamMode(name).getFileExtension();
+ if (!extension.isEmpty()) {
+ name = name.substring(0, name.length() - extension.length());
+ }
+ }
+ ZxidRange zxidRange = ZxidRange.INVALID;
+ String nameParts[] = name.split("[\\.-]");
+ try {
+ if (nameParts.length == 2 && nameParts[0].equals(prefix)) {
+ zxidRange = new ZxidRange(Long.parseLong(nameParts[1], 16));
+ } else if (nameParts.length == 3 && nameParts[0].equals(prefix)) {
+ zxidRange = new ZxidRange(Long.parseLong(nameParts[1], 16),
+ Long.parseLong(nameParts[2], 16));
+ }
+ } catch (NumberFormatException e) {}
+ return zxidRange;
+ }
+
/**
* Reads a transaction entry from the input archive.
* @param ia archive to read from
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/ZxidRange.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/ZxidRange.java
new file mode 100644
index 00000000000..13e5dfe9eb5
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/persistence/ZxidRange.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.persistence;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Preconditions.checkState;
+import com.google.common.base.Optional;
+import com.google.common.collect.Range;
+
+/**
+ * A range of Zxids with an optional high zxid.
+ */
+public class ZxidRange {
+ public static final ZxidRange INVALID = new ZxidRange(-1L, Optional.of(-1L), true);
+
+ private long low;
+ private Optional high;
+
+ private ZxidRange(long low, Optional high, boolean allowNeg) {
+ checkNotNull(high);
+ checkArgument(allowNeg || low >= 0, "Zxid must be 0 or greater");
+ checkArgument(allowNeg || !high.isPresent() || high.get() >= 0,
+ "Zxid must be 0 or greater");
+ checkArgument(!high.isPresent() || low <= high.get(),
+ "Invalid zxid range, low must not be greater than high");
+
+ this.low = low;
+ this.high = high;
+ }
+
+ public ZxidRange(long low, long high) {
+ this(low, Optional.of(high), false);
+ }
+
+ public ZxidRange(long low) {
+ this(low, Optional.absent(), false);
+ }
+
+ public ZxidRange(Range range) {
+ this(range.lowerEndpoint(), range.upperEndpoint());
+ }
+
+ public static ZxidRange parse(String value) {
+ String[] zxidParts = value.split("-");
+
+ if (zxidParts.length == 1 && !value.endsWith("-")) {
+ try {
+ return new ZxidRange(Long.parseLong(zxidParts[0], 16));
+ } catch (NumberFormatException e) { }
+ } else if (zxidParts.length == 2) {
+ try {
+ return new ZxidRange(Long.parseLong(zxidParts[0], 16), Long.parseLong(zxidParts[1], 16));
+ } catch (NumberFormatException e) { }
+ }
+
+ return ZxidRange.INVALID;
+ }
+
+ public Range toRange() {
+ return Range.closed(low, high.isPresent() ? high.get() : Long.MAX_VALUE);
+ }
+
+ public long getLow() {
+ return low;
+ }
+
+ public long getHigh() {
+ checkState(high.isPresent());
+ return high.get();
+ }
+
+ public boolean isHighPresent() {
+ return high.isPresent();
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java
index 1b37f291f51..e2ef8a7e261 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java
@@ -47,6 +47,8 @@
import org.apache.zookeeper.metrics.impl.DefaultMetricsProvider;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.auth.ProviderRegistry;
+import org.apache.zookeeper.server.backup.BackupConfig;
+import org.apache.zookeeper.server.backup.BackupSystemProperty;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.auth.QuorumAuth;
@@ -107,6 +109,11 @@ public class QuorumPeerConfig {
protected int purgeInterval = 0;
protected boolean syncEnabled = true;
+ // ZooKeeper server-side backup config
+ protected boolean backupEnabled = false;
+ protected BackupConfig backupConfig;
+ protected BackupConfig.Builder backupConfigBuilder = new BackupConfig.Builder();
+
protected String initialConfig;
protected LearnerType peerType = LearnerType.PARTICIPANT;
@@ -337,6 +344,33 @@ public void parseProperties(Properties zkProp) throws IOException, ConfigExcepti
snapRetainCount = Integer.parseInt(value);
} else if (key.equals("autopurge.purgeInterval")) {
purgeInterval = Integer.parseInt(value);
+ } else if (key.equals(BackupSystemProperty.BACKUP_ENABLED)) {
+ backupEnabled = Boolean.parseBoolean(value);
+ backupConfigBuilder.setEnabled(backupEnabled);
+ } else if (key.equals(BackupSystemProperty.BACKUP_STATUS_DIR)) {
+ backupConfigBuilder.setStatusDir(vff.create(value));
+ } else if (key.equals(BackupSystemProperty.BACKUP_TMP_DIR)) {
+ backupConfigBuilder.setTmpDir(vff.create(value));
+ } else if (key.equals(BackupSystemProperty.BACKUP_INTERVAL_MINUTES)) {
+ backupConfigBuilder.setBackupIntervalInMinutes(Integer.parseInt(value));
+ } else if (key.equals(BackupSystemProperty.BACKUP_STORAGE_CONFIG)) {
+ backupConfigBuilder.setStorageConfig(vff.create(value));
+ } else if (key.equals(BackupSystemProperty.BACKUP_STORAGE_PATH)) {
+ backupConfigBuilder.setBackupStoragePath(value);
+ } else if (key.equals(BackupSystemProperty.BACKUP_RETENTION_DAYS)) {
+ backupConfigBuilder.setRetentionPeriodInDays(Integer.parseInt(value));
+ } else if (key.equals(BackupSystemProperty.BACKUP_RETENTION_MAINTENANCE_INTERVAL_HOURS)) {
+ backupConfigBuilder.setRetentionMaintenanceIntervalInHours(Integer.parseInt(value));
+ } else if (key.equals(BackupSystemProperty.BACKUP_STORAGE_PROVIDER_CLASS_NAME)) {
+ backupConfigBuilder.setStorageProviderClassName(value);
+ } else if (key.equals(BackupSystemProperty.BACKUP_NAMESPACE)) {
+ backupConfigBuilder.setNamespace(value);
+ } else if (key.equals(BackupSystemProperty.BACKUP_TIMETABLE_ENABLED)) {
+ backupConfigBuilder.setTimetableEnabled(Boolean.parseBoolean(value));
+ } else if (key.equals(BackupSystemProperty.BACKUP_TIMETABLE_STORAGE_PATH)) {
+ backupConfigBuilder.setTimetableStoragePath(value);
+ } else if (key.equals(BackupSystemProperty.BACKUP_TIMETABLE_BACKUP_INTERVAL_MS)) {
+ backupConfigBuilder.setTimetableBackupIntervalInMs(Long.parseLong(value));
} else if (key.equals("standaloneEnabled")) {
setStandaloneEnabled(parseBoolean(key, value));
} else if (key.equals("reconfigEnabled")) {
@@ -491,6 +525,16 @@ public void parseProperties(Properties zkProp) throws IOException, ConfigExcepti
backupOldConfig();
}
}
+
+ // Create a BackupConfig object for backup
+ if (backupEnabled) {
+ try {
+ backupConfigBuilder.build().ifPresent(b -> backupConfig = b);
+ } catch (org.apache.zookeeper.common.ConfigException e) {
+ // TODO: Merge QuorumPeerConfig.ConfigException and org.apache.zookeeper.common.ConfigException
+ throw new ConfigException(e.getMessage(), e);
+ }
+ }
}
/**
@@ -964,4 +1008,7 @@ private boolean parseBoolean(String key, String value) throws ConfigException {
+ ". Choose 'true' or 'false.'");
}
}
+ public BackupConfig getBackupConfig() {
+ return backupConfig;
+ }
}
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerMain.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerMain.java
index 5ed2d42863a..00cacb94121 100644
--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerMain.java
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerMain.java
@@ -35,6 +35,7 @@
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.admin.AdminServer.AdminServerException;
import org.apache.zookeeper.server.auth.ProviderRegistry;
+import org.apache.zookeeper.server.backup.BackupManager;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog.DatadirException;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
@@ -133,6 +134,13 @@ protected void initializeAndRun(String[] args) throws ConfigException, IOExcepti
config.getPurgeInterval());
purgeMgr.start();
+ if (config.backupEnabled && config.getBackupConfig() != null) {
+ // Backup is enabled and the backup config is not null
+ BackupManager backupManager = new BackupManager(config.dataDir, config.dataLogDir,
+ config.getServerId(), config.getBackupConfig());
+ backupManager.start();
+ }
+
if (args.length == 1 && config.isDistributed()) {
runFromConfig(config);
} else {
diff --git a/zookeeper-server/src/main/resources/lib/animal-sniffer-annotations-1.17.LICENSE.txt b/zookeeper-server/src/main/resources/lib/animal-sniffer-annotations-1.17.LICENSE.txt
new file mode 100644
index 00000000000..016a46a9abf
--- /dev/null
+++ b/zookeeper-server/src/main/resources/lib/animal-sniffer-annotations-1.17.LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2008 Kohsuke Kawaguchi and codehaus.org.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/zookeeper-server/src/main/resources/lib/checker-qual-2.5.2.LICENSE.txt b/zookeeper-server/src/main/resources/lib/checker-qual-2.5.2.LICENSE.txt
new file mode 100644
index 00000000000..ba4eeff936a
--- /dev/null
+++ b/zookeeper-server/src/main/resources/lib/checker-qual-2.5.2.LICENSE.txt
@@ -0,0 +1,25 @@
+Checker Framework qualifiers (checker-qual) 2.5.2
+
+The annotations and utility classes in checker-qual.jar are licensed under
+the MIT License, as specified by the Checker Framework license:
+https://github.com/typetools/checker-framework/blob/checker-framework-2.5.2/LICENSE.txt
+
+MIT License:
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/cli/CommandFactoryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/cli/CommandFactoryTest.java
index 2173514d368..975f121de97 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/cli/CommandFactoryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/cli/CommandFactoryTest.java
@@ -18,6 +18,8 @@
package org.apache.zookeeper.cli;
+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 org.junit.jupiter.api.Test;
@@ -35,4 +37,20 @@ public void testCommandCreation() {
CommandFactory.getInstance(CommandFactory.Command.CREATE);
assertTrue(cliCommand instanceof CreateCommand);
}
+
+ @Test
+ public void testRestoreCommandRegistrationAndMissingArguments() {
+ CliCommand command = CommandFactory.getInstance(CommandFactory.Command.RESTORE);
+ assertTrue(command instanceof RestoreCommand);
+ assertThrows(CliParseException.class, () -> command.parse(new String[]{"restore"}));
+ assertThrows(CliParseException.class,
+ () -> command.parse(new String[]{"restore", "--unknown-option"}));
+ }
+
+ @Test
+ public void testRestoreInvalidStorageReturnsFailure() throws CliException {
+ CliCommand command = CommandFactory.getInstance(CommandFactory.Command.RESTORE);
+ command.parse(new String[]{"restore", "-z", "latest", "-b", "invalid"});
+ assertFalse(command.exec());
+ }
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/BackupBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/BackupBeanTest.java
new file mode 100644
index 00000000000..e4dc28cca73
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/BackupBeanTest.java
@@ -0,0 +1,315 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.DummyWatcher;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.jmx.MBeanRegistry;
+import org.apache.zookeeper.jmx.ZKMBeanInfo;
+import org.apache.zookeeper.server.ServerCnxn;
+import org.apache.zookeeper.server.ServerCnxnFactory;
+import org.apache.zookeeper.server.SyncRequestProcessor;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.server.backup.monitoring.BackupBean;
+import org.apache.zookeeper.server.backup.monitoring.TimetableBackupBean;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.storage.impl.FileSystemBackupStorage;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.Assert;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests ZooKeeper backup-related metrics: BackupBean and TimetableBackupBean.
+ */
+@TestMethodOrder(MethodOrderer.Alphanumeric.class)
+public class BackupBeanTest extends ZKTestCase {
+ private static final Logger LOG = LoggerFactory.getLogger(BackupBeanTest.class);
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
+ private static final int CONNECTION_TIMEOUT = 300000;
+ private static final String TEST_NAMESPACE = "TEST_NAMESPACE";
+
+ private ZooKeeper connection;
+ private File dataDir;
+ private File backupStatusDir;
+ private File backupTmpDir;
+ private File backupDir;
+ private ZooKeeperServer zks;
+ private ServerCnxnFactory serverCnxnFactory;
+ private BackupStorageProvider backupStorage;
+ private BackupStatus backupStatus;
+ private FileTxnSnapLog snapLog;
+ private BackupConfig backupConfig;
+
+ @BeforeEach
+ public void setup() throws Exception {
+ dataDir = ClientBase.createTmpDir();
+ backupStatusDir = ClientBase.createTmpDir();
+ backupTmpDir = ClientBase.createTmpDir();
+ backupDir = ClientBase.createTmpDir();
+
+ backupConfig = new BackupConfig.Builder().
+ setEnabled(true).
+ setStatusDir(testBaseDir).
+ setTmpDir(testBaseDir).
+ setBackupStoragePath(backupDir.getAbsolutePath()).
+ setNamespace(TEST_NAMESPACE).
+ setStorageProviderClassName(FileSystemBackupStorage.class.getName()).
+ setTimetableEnabled(true).
+ setTimetableBackupIntervalInMs(100L).// 0.1s to ensure in-memory records are created
+ setTimetableStoragePath(backupDir.getAbsolutePath()).
+ build().get();
+ backupStorage = new FileSystemBackupStorage(backupConfig);
+
+ ClientBase.setupTestEnv();
+
+ LOG.info("Starting Zk");
+
+ zks = new ZooKeeperServer(dataDir, dataDir, 3000);
+ SyncRequestProcessor.setSnapCount(100);
+ final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
+ serverCnxnFactory = ServerCnxnFactory.createFactory(PORT, -1);
+ serverCnxnFactory.startup(zks);
+
+ LOG.info("Waiting for server startup");
+
+ Assert.assertTrue("waiting for server being up ",
+ ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+
+ backupStatus = new BackupStatus(backupStatusDir);
+
+ snapLog = new FileTxnSnapLog(dataDir, dataDir);
+
+ connection = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE);
+ }
+
+ @AfterEach
+ public void teardown() throws Exception {
+ if (connection != null) {
+ connection.close();
+ }
+ connection = null;
+
+ LOG.info("Closing and cleaning up Zk");
+
+ LOG.info("Closing Zk");
+
+ if (serverCnxnFactory != null) {
+ serverCnxnFactory.closeAll(ServerCnxn.DisconnectReason.SERVER_SHUTDOWN);
+ serverCnxnFactory.shutdown();
+ serverCnxnFactory = null;
+ }
+
+ if (zks != null) {
+ zks.getZKDatabase().close();
+ zks.shutdown();
+ zks = null;
+ }
+
+ Assert.assertTrue("waiting for server to shutdown",
+ ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+
+ backupStatus = null;
+ serverCnxnFactory = null;
+ zks = null;
+ snapLog = null;
+ backupStorage = null;
+ }
+
+ @Test
+ public void test1_MBeanRegistration() throws IOException {
+ // Register MBean when initializing backup manager
+ long serverId = 0L;
+ BackupManager bm = new BackupManager(dataDir, dataDir, serverId, backupConfig);
+ String expectedMBeanName = "Backup_id" + serverId;
+ String expectedTimetableMBeanName =
+ TimetableBackupBean.TIMETABLE_BACKUP_MBEAN_NAME;
+ Set mbeans = MBeanRegistry.getInstance().getRegisteredBeans();
+ Assert.assertTrue(containsMBean(mbeans, expectedMBeanName, false));
+ Assert.assertTrue(containsMBean(mbeans, expectedTimetableMBeanName, false));
+
+ // Unregister MBean when stopping backup manager
+ bm.stop();
+ mbeans = MBeanRegistry.getInstance().getRegisteredBeans();
+ Assert.assertFalse(containsMBean(mbeans, expectedMBeanName, false));
+ Assert.assertFalse(containsMBean(mbeans, expectedTimetableMBeanName, false));
+ }
+
+ private boolean containsMBean(Set mbeanSet, String mbeanName, boolean isHidden) {
+ Optional foundMBean = mbeanSet.stream()
+ .filter(mbean -> mbean.getName().equals(mbeanName) && mbean.isHidden() == isHidden)
+ .findAny();
+ return foundMBean.isPresent();
+ }
+
+ @Test
+ public void test2_MBeanUpdate() throws Exception {
+ MockBackupManager backupManager = new MockBackupManager(dataDir, dataDir, 0, backupConfig);
+ BackupBean backupBean = backupManager.getBackupBean();
+
+ Assert.assertEquals(0, backupBean.getMinutesSinceLastSuccessfulSnapshotIteration());
+ Assert.assertEquals(0, backupBean.getMinutesSinceLastSuccessfulTxnLogIteration());
+
+ String[] nodeNames = {"/firstNode", "/secondNode", "/thirdNode", "/fourthNode", "/fifthNode"};
+
+ createNode(connection, nodeNames[0]);
+ backupManager.getSnapBackup(snapLog, true).run(1);
+ backupManager.getLogBackup(snapLog, true).run(1);
+ Assert.assertTrue(backupBean.getLastSnapshotIterationDuration() > 0L);
+ Assert.assertTrue(backupBean.getLastTxnLogIterationDuration() > 0L);
+ Assert.assertEquals(1, backupBean.getNumberOfSnapshotFilesBackedUpLastIteration());
+ Assert.assertEquals(0, backupBean.getNumConsecutiveFailedSnapshotIterations());
+ Assert.assertEquals(0, backupBean.getNumConsecutiveFailedTxnLogIterations());
+ Assert.assertFalse(backupBean.getSnapshotBackupActiveStatus());
+ Assert.assertFalse(backupBean.getTxnLogBackupActiveStatus());
+
+ createNode(connection, nodeNames[1]);
+ backupManager.getSnapBackup(snapLog, false).run(1);
+ backupManager.getLogBackup(snapLog, true).run(1);
+ Assert.assertEquals(1, backupBean.getNumConsecutiveFailedSnapshotIterations());
+ Assert.assertEquals(0, backupBean.getNumConsecutiveFailedTxnLogIterations());
+
+ createNode(connection, nodeNames[2]);
+ backupManager.getSnapBackup(snapLog, true).run(1);
+ backupManager.getLogBackup(snapLog, false).run(1);
+ Assert.assertEquals(0, backupBean.getNumConsecutiveFailedSnapshotIterations());
+ Assert.assertEquals(1, backupBean.getNumConsecutiveFailedTxnLogIterations());
+
+ createNode(connection, nodeNames[3]);
+ backupManager.getSnapBackup(snapLog, false).run(1);
+ backupManager.getLogBackup(snapLog, false).run(1);
+ Assert.assertEquals(1, backupBean.getNumConsecutiveFailedSnapshotIterations());
+ Assert.assertEquals(2, backupBean.getNumConsecutiveFailedTxnLogIterations());
+
+ createNode(connection, nodeNames[4]);
+ backupManager.getSnapBackup(snapLog, true).run(1);
+ backupManager.getLogBackup(snapLog, true).run(1);
+ Assert.assertEquals(0, backupBean.getNumConsecutiveFailedSnapshotIterations());
+ Assert.assertEquals(0, backupBean.getNumConsecutiveFailedTxnLogIterations());
+
+ // Wait one minute for metrics with minute granularity
+ Thread.sleep(60 * 1000L);
+ Assert.assertTrue(backupBean.getMinutesSinceLastSuccessfulSnapshotIteration() > 0L);
+ Assert.assertTrue(backupBean.getMinutesSinceLastSuccessfulTxnLogIteration() > 0L);
+
+ backupManager.stop();
+ }
+
+ @Test
+ public void test3_TimetableBackupMBean() throws IOException, InterruptedException {
+ MockBackupManager bm = new MockBackupManager(dataDir, dataDir, 0, backupConfig);
+ bm.initialize();
+ TimetableBackupBean timetableBackupBean = bm.getTimetableBackupBean();
+
+ bm.getTimetableBackup().run(1);
+
+ // Wait one minute for metrics with minute granularity
+ Thread.sleep(60 * 1000L);
+ long lastTimetableIterationDuration = timetableBackupBean.getLastTimetableIterationDuration();
+ long minutesSinceLastSuccessfulTimetableIteration =
+ timetableBackupBean.getMinutesSinceLastSuccessfulTimetableIteration();
+ int numConsecutiveFailedTimetableIterations =
+ timetableBackupBean.getNumConsecutiveFailedTimetableIterations();
+
+ // Verify the metric values
+ Assert.assertTrue(lastTimetableIterationDuration > 0L);
+ Assert.assertTrue(minutesSinceLastSuccessfulTimetableIteration > 0L);
+ Assert.assertEquals(0, numConsecutiveFailedTimetableIterations);
+
+ bm.stop();
+ }
+
+ private void createNode(ZooKeeper zk, String path) throws Exception {
+ zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ }
+
+ private static class MockBackupManager extends BackupManager {
+
+ public MockBackupManager(File snapDir, File dataLogDir, long serverId,
+ BackupConfig backupConfig) throws IOException {
+ super(snapDir, dataLogDir, serverId, backupConfig);
+ }
+
+ public BackupBean getBackupBean() {
+ return this.backupBean;
+ }
+
+ public TimetableBackupBean getTimetableBackupBean() {
+ return this.timetableBackupBean;
+ }
+
+ public MockSnapshotBackupProcess getSnapBackup(FileTxnSnapLog snapLog, boolean errorFree) {
+ return new MockSnapshotBackupProcess(snapLog, errorFree, backupBean);
+ }
+
+ public MockTxnLogBackupProcess getLogBackup(FileTxnSnapLog snapLog, boolean errorFree) {
+ return new MockTxnLogBackupProcess(snapLog, errorFree, backupBean);
+ }
+
+ private class MockSnapshotBackupProcess extends BackupManager.SnapBackup {
+ private final boolean expectedErrorFree;
+ private final BackupBean backupBean;
+
+ public MockSnapshotBackupProcess(FileTxnSnapLog snapLog, boolean expectedErrorFree,
+ BackupBean backupBean) {
+ super(snapLog);
+ this.expectedErrorFree = expectedErrorFree;
+ this.backupBean = backupBean;
+ }
+
+ @Override
+ protected void endIteration(boolean errorFree) {
+ Assert.assertTrue(backupBean.getSnapshotBackupActiveStatus());
+ super.endIteration(expectedErrorFree);
+ }
+ }
+
+ private class MockTxnLogBackupProcess extends BackupManager.TxnLogBackup {
+ private final boolean expectedErrorFree;
+ private final BackupBean backupBean;
+
+ public MockTxnLogBackupProcess(FileTxnSnapLog snapLog, boolean expectedErrorFree,
+ BackupBean backupBean) {
+ super(snapLog);
+ this.expectedErrorFree = expectedErrorFree;
+ this.backupBean = backupBean;
+ }
+
+ @Override
+ protected void endIteration(boolean errorFree) {
+ Assert.assertTrue(backupBean.getTxnLogBackupActiveStatus());
+ super.endIteration(expectedErrorFree);
+ }
+ }
+ }
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/BackupConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/BackupConfigTest.java
new file mode 100644
index 00000000000..b5e8140097a
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/BackupConfigTest.java
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.zookeeper.server.backup;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import java.io.File;
+import java.util.Properties;
+import org.apache.zookeeper.common.ConfigException;
+import org.apache.zookeeper.server.backup.storage.impl.FileSystemBackupStorage;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+public class BackupConfigTest {
+ private static final File DEFAULT_STATUS_DIR = new File("/backup/status");
+ private static final File DEFAULT_TMP_DIR = new File("/tmp/backup");
+ private static final File DEFAULT_STORAGE_CONFIG = new File("/storage/config");
+ private static final String DEFAULT_STORAGE_MOUNT_PATH = "/storage/path";
+ // Use FileSystemBackupStorage for testing
+ private static final String DEFAULT_STORAGE_PROVIDER_CLASS_NAME =
+ "org.apache.zookeeper.server.backup.storage.impl.FileSystemBackupStorage";
+
+ @Test
+ public void testQuorumConfigurationLoadsBackup(@TempDir File directory) throws Exception {
+ Properties properties = new Properties();
+ properties.setProperty("dataDir", directory.getAbsolutePath());
+ properties.setProperty("clientPort", "2181");
+ properties.setProperty(BackupSystemProperty.BACKUP_ENABLED, "true");
+ properties.setProperty(BackupSystemProperty.BACKUP_STATUS_DIR, directory.getAbsolutePath());
+ properties.setProperty(BackupSystemProperty.BACKUP_TMP_DIR, directory.getAbsolutePath());
+ properties.setProperty(BackupSystemProperty.BACKUP_STORAGE_PATH, directory.getAbsolutePath());
+ properties.setProperty(BackupSystemProperty.BACKUP_STORAGE_PROVIDER_CLASS_NAME,
+ FileSystemBackupStorage.class.getName());
+ properties.setProperty(BackupSystemProperty.BACKUP_NAMESPACE, "configuration-test");
+ properties.setProperty(BackupSystemProperty.BACKUP_INTERVAL_MINUTES, "2");
+ properties.setProperty(BackupSystemProperty.BACKUP_TIMETABLE_ENABLED, "true");
+ properties.setProperty(BackupSystemProperty.BACKUP_TIMETABLE_STORAGE_PATH, directory.getAbsolutePath());
+ properties.setProperty(BackupSystemProperty.BACKUP_TIMETABLE_BACKUP_INTERVAL_MS, "250");
+ QuorumPeerConfig config = new QuorumPeerConfig();
+ config.parseProperties(properties);
+ BackupConfig backup = config.getBackupConfig();
+ assertEquals("configuration-test", backup.getNamespace());
+ assertEquals(2, backup.getBackupIntervalInMinutes());
+ assertTrue(backup.isTimetableEnabled());
+ assertEquals(250L, backup.getTimetableBackupIntervalInMs());
+ }
+
+ @Test
+ public void testQuorumConfigurationDoesNotEnableBackupByDefault(@TempDir File directory) throws Exception {
+ Properties properties = new Properties();
+ properties.setProperty("dataDir", directory.getAbsolutePath());
+ properties.setProperty("clientPort", "2181");
+ QuorumPeerConfig config = new QuorumPeerConfig();
+ config.parseProperties(properties);
+ assertNull(config.getBackupConfig());
+ }
+
+ @Test
+ public void testQuorumConfigurationRejectsIncompleteBackup(@TempDir File directory) {
+ Properties properties = new Properties();
+ properties.setProperty("dataDir", directory.getAbsolutePath());
+ properties.setProperty("clientPort", "2181");
+ properties.setProperty(BackupSystemProperty.BACKUP_ENABLED, "true");
+ assertThrows(QuorumPeerConfig.ConfigException.class,
+ () -> new QuorumPeerConfig().parseProperties(properties));
+ }
+
+ @Test
+ public void testEnabled() throws Exception {
+ assertFalse(new BackupConfig.Builder().build().isPresent());
+ assertTrue(builder().build().isPresent());
+ assertFalse(
+ builder().withProperty(BackupSystemProperty.BACKUP_ENABLED, "false").build().isPresent());
+ assertTrue(
+ builder().withProperty(BackupSystemProperty.BACKUP_ENABLED, "true").build().isPresent());
+ }
+
+ @Test
+ public void testStatusDir() throws Exception {
+ try {
+ new BackupConfig.Builder().setEnabled(true).setTmpDir(DEFAULT_TMP_DIR)
+ .setStorageConfig(DEFAULT_STORAGE_CONFIG).setBackupStoragePath(DEFAULT_STORAGE_MOUNT_PATH)
+ .build();
+ assertTrue(false);
+ } catch (ConfigException exc) {
+ assertTrue(true);
+ }
+
+ assertEquals(DEFAULT_STATUS_DIR, builder().build().get().getStatusDir());
+ File expected = new File("/expected");
+ assertEquals(expected, builder().setStatusDir(expected).build().get().getStatusDir());
+ assertEquals(expected,
+ builder().withProperty(BackupSystemProperty.BACKUP_STATUS_DIR, expected.getAbsolutePath())
+ .build().get().getStatusDir());
+ }
+
+ @Test
+ public void testTmpDir() throws Exception {
+ try {
+ new BackupConfig.Builder().setEnabled(true).setStatusDir(DEFAULT_STATUS_DIR)
+ .setStorageConfig(DEFAULT_STORAGE_CONFIG).setBackupStoragePath(DEFAULT_STORAGE_MOUNT_PATH)
+ .build();
+ assertTrue(false);
+ } catch (ConfigException exc) {
+ assertTrue(true);
+ }
+
+ assertEquals(DEFAULT_TMP_DIR, builder().build().get().getTmpDir());
+ File expected = new File("/expected");
+ assertEquals(expected, builder().setTmpDir(expected).build().get().getTmpDir());
+ assertEquals(expected,
+ builder().withProperty(BackupSystemProperty.BACKUP_TMP_DIR, expected.getAbsolutePath())
+ .build().get().getTmpDir());
+ }
+
+ @Test
+ public void testInterval() throws Exception {
+ assertEquals(BackupConfig.DEFAULT_BACKUP_INTERVAL_MINUTES,
+ builder().build().get().getBackupIntervalInMinutes());
+ int expectedInterval = 3; // 3 minutes
+ assertEquals(expectedInterval,
+ builder().setBackupIntervalInMinutes(expectedInterval).build().get().getBackupIntervalInMinutes());
+ assertEquals(expectedInterval, builder()
+ .withProperty(BackupSystemProperty.BACKUP_INTERVAL_MINUTES, "3")
+ .build().get().getBackupIntervalInMinutes());
+ }
+
+ @Test
+ public void testStorageConfig() throws Exception {
+ try {
+ new BackupConfig.Builder().setEnabled(true).setStatusDir(DEFAULT_STATUS_DIR)
+ .setTmpDir(DEFAULT_TMP_DIR).setBackupStoragePath(DEFAULT_STORAGE_MOUNT_PATH).build();
+ assertTrue(false);
+ } catch (ConfigException exc) {
+ assertTrue(true);
+ }
+
+ assertEquals(DEFAULT_STORAGE_CONFIG, builder().build().get().getStorageConfig());
+ File expected = new File("/expected");
+ assertEquals(expected, builder().setStorageConfig(expected).build().get().getStorageConfig());
+ assertEquals(expected, builder()
+ .withProperty(BackupSystemProperty.BACKUP_STORAGE_CONFIG, expected.getAbsolutePath())
+ .build().get().getStorageConfig());
+ }
+
+ @Test
+ public void testMountPath() throws Exception {
+ try {
+ new BackupConfig.Builder().setEnabled(true).setStatusDir(DEFAULT_STATUS_DIR)
+ .setTmpDir(DEFAULT_TMP_DIR).setStorageConfig(DEFAULT_STORAGE_CONFIG).build();
+ assertTrue(false);
+ } catch (ConfigException exc) {
+ assertTrue(true);
+ }
+
+ assertEquals(DEFAULT_STORAGE_MOUNT_PATH, builder().build().get().getBackupStoragePath());
+ String expected = "/expected";
+ assertEquals(expected, builder().setBackupStoragePath(expected).build().get().getBackupStoragePath());
+ assertEquals(expected,
+ builder().withProperty(BackupSystemProperty.BACKUP_STORAGE_PATH, expected).build().get()
+ .getBackupStoragePath());
+ }
+
+ @Test
+ public void testRetentionPeriod() throws Exception {
+ assertEquals(BackupConfig.DEFAULT_RETENTION_DAYS, builder().build().get().getRetentionPeriod());
+ int expected = BackupConfig.DEFAULT_RETENTION_DAYS;
+ assertEquals(expected,
+ builder().setRetentionPeriodInDays(expected).build().get().getRetentionPeriod());
+ assertEquals(expected,
+ builder().withProperty(BackupSystemProperty.BACKUP_RETENTION_DAYS, "20").build().get()
+ .getRetentionPeriod());
+ }
+
+ @Test
+ public void testRetentionMaintenanceInterval() throws Exception {
+ assertEquals(BackupConfig.DEFAULT_RETENTION_MAINTENANCE_INTERVAL_HOURS,
+ builder().build().get().getRetentionMaintenanceIntervalInHours());
+ int expected = 3; // 3 hours
+ assertEquals(expected, builder().setRetentionMaintenanceIntervalInHours(expected).build().get()
+ .getRetentionMaintenanceIntervalInHours());
+ assertEquals(expected, builder()
+ .withProperty(BackupSystemProperty.BACKUP_RETENTION_MAINTENANCE_INTERVAL_HOURS, "3")
+ .build().get().getRetentionMaintenanceIntervalInHours());
+ }
+
+ private BackupConfig.Builder builder() {
+ return new BackupConfig.Builder().setEnabled(true).setStatusDir(DEFAULT_STATUS_DIR)
+ .setTmpDir(DEFAULT_TMP_DIR).setStorageConfig(DEFAULT_STORAGE_CONFIG)
+ .setBackupStoragePath(DEFAULT_STORAGE_MOUNT_PATH)
+ .setStorageProviderClassName(DEFAULT_STORAGE_PROVIDER_CLASS_NAME);
+ }
+}
\ No newline at end of file
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/RestorationToolTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/RestorationToolTest.java
new file mode 100644
index 00000000000..a8134cf9b72
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/RestorationToolTest.java
@@ -0,0 +1,620 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.when;
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Objects;
+import java.util.Random;
+import java.util.stream.Collectors;
+import org.apache.commons.cli.CommandLine;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.DummyWatcher;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.cli.RestoreCommand;
+import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.server.ServerCnxn;
+import org.apache.zookeeper.server.ServerCnxnFactory;
+import org.apache.zookeeper.server.SyncRequestProcessor;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.storage.BackupStorageUtil;
+import org.apache.zookeeper.server.backup.storage.impl.FileSystemBackupStorage;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.server.persistence.Util;
+import org.apache.zookeeper.server.persistence.ZxidRange;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.Assert;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class RestorationToolTest extends ZKTestCase {
+ private static final Logger LOG = LoggerFactory.getLogger(RestorationToolTest.class);
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
+ private static final int CONNECTION_TIMEOUT = 300000;
+ private static final String TEST_NAMESPACE = "TEST_NAMESPACE";
+
+ private ZooKeeper connection;
+ private File dataDir;
+ private File backupTmpDir;
+ private File backupDir;
+ private File backupStatusDir;
+ private ZooKeeperServer zks;
+ private ServerCnxnFactory serverCnxnFactory;
+ private BackupStorageProvider backupStorage;
+ private BackupConfig backupConfig;
+ private Random random = new Random();
+ private final int txnCnt = 1000;
+ private File restoreDir;
+ private FileTxnSnapLog restoreSnapLog;
+ private File backupFileRootDir;
+ private File restoreTempDir;
+ private File timetableDir;
+ private BackupManager backupManager;
+ private long timestampInMiddle;
+
+ @BeforeEach
+ public void setup() throws Exception {
+ backupStatusDir = ClientBase.createTmpDir();
+ backupTmpDir = ClientBase.createTmpDir();
+ dataDir = ClientBase.createTmpDir();
+ backupDir = ClientBase.createTmpDir();
+ restoreDir = ClientBase.createTmpDir();
+ restoreTempDir = ClientBase.createTmpDir();
+ timetableDir = ClientBase.createTmpDir();
+
+ backupConfig = new BackupConfig.Builder().
+ setEnabled(true).
+ setStatusDir(backupStatusDir).
+ setTmpDir(backupTmpDir).
+ setBackupStoragePath(backupDir.getAbsolutePath()).
+ setNamespace(TEST_NAMESPACE).
+ setStorageProviderClassName(FileSystemBackupStorage.class.getName()).
+ setTimetableEnabled(true).
+ setTimetableBackupIntervalInMs(100L).
+ setTimetableStoragePath(timetableDir.getPath()).
+ build().get();
+ backupStorage = new FileSystemBackupStorage(backupConfig);
+ backupFileRootDir = new File(backupDir, TEST_NAMESPACE);
+
+ ClientBase.setupTestEnv();
+
+ LOG.info("Starting Zk");
+ zks = new ZooKeeperServer(dataDir, dataDir, 3000);
+ SyncRequestProcessor.setSnapCount(100);
+ final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
+ serverCnxnFactory = ServerCnxnFactory.createFactory(PORT, -1);
+ serverCnxnFactory.startup(zks);
+
+ LOG.info("Waiting for server startup");
+ Assert.assertTrue("waiting for server being up ",
+ ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+
+ connection = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE);
+ restoreSnapLog = new FileTxnSnapLog(restoreDir, restoreDir);
+
+ backupManager = new BackupManager(dataDir, dataDir, -1, backupConfig);
+ backupManager.initialize();
+
+ for (int i = 1; i < txnCnt; i++) {
+ connection
+ .create("/node" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ if (getRandomBoolean(0.4f)) {
+ zks.getTxnLogFactory().rollLog();
+ backupManager.getLogBackup().run(1);
+ }
+ if (i == 1 || getRandomBoolean(0.2f)) {
+ zks.takeSnapshot();
+ }
+ // Record a timestamp that's in the valid backup timestamp range, used to test restoration to timestamp
+ if (i == txnCnt / 2) {
+ timestampInMiddle = System.currentTimeMillis();
+ }
+ }
+
+ backupManager.getLogBackup().run(1);
+ backupManager.getSnapBackup().run(1);
+ }
+
+ @AfterEach
+ public void teardown() throws Exception {
+ if (connection != null) {
+ connection.close();
+ }
+ connection = null;
+
+ LOG.info("Closing and cleaning up Zk");
+
+ LOG.info("Closing Zk");
+
+ if (serverCnxnFactory != null) {
+ serverCnxnFactory.closeAll(ServerCnxn.DisconnectReason.SERVER_SHUTDOWN);
+ serverCnxnFactory.shutdown();
+ serverCnxnFactory = null;
+ }
+
+ if (zks != null) {
+ zks.getZKDatabase().close();
+ zks.shutdown();
+ zks = null;
+ }
+
+ Assert.assertTrue("waiting for server to shutdown",
+ ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+
+ serverCnxnFactory = null;
+ zks = null;
+ backupStorage = null;
+ }
+
+ @Test
+ public void testSuccessfulRestorationToZxid() throws IOException, InterruptedException {
+ for (int i = 0; i < 5; i++) {
+ int restoreZxid = i == 0 ? 1 : 1 + random.nextInt(txnCnt);
+ File restoreTempDir = ClientBase.createTmpDir();
+ RestoreFromBackupTool restoreTool =
+ new RestoreFromBackupTool(backupStorage, restoreSnapLog, restoreZxid, false,
+ restoreTempDir);
+ restoreTool.run();
+ validateRestoreCoverage(restoreZxid);
+
+ // Clean up restoreDir for next test
+ List filePaths =
+ Files.walk(Paths.get(restoreDir.getPath())).filter(Files::isRegularFile)
+ .collect(Collectors.toList());
+ filePaths.forEach(filePath -> {
+ try {
+ Files.delete(filePath);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ });
+ }
+ }
+
+ @Test
+ public void testInitialSnapshotRejectsMissingFirstTransaction() throws IOException {
+ BackupStorageProvider storage = Mockito.mock(BackupStorageProvider.class);
+ when(storage.getBackupFileInfos(null, Util.SNAP_PREFIX))
+ .thenReturn(Collections.singletonList(new BackupFileInfo(new File("snapshot.0-1"), 0, 0)));
+ when(storage.getBackupFileInfos(null, Util.TXLOG_PREFIX))
+ .thenReturn(Collections.singletonList(new BackupFileInfo(new File("log.2-3"), 0, 0)));
+ when(storage.getBackupFileInfos(null, BackupUtil.LOST_LOG_PREFIX))
+ .thenReturn(Collections.emptyList());
+ RestoreFromBackupTool tool =
+ new RestoreFromBackupTool(storage, restoreSnapLog, 3, true, restoreTempDir);
+ assertThrows(IllegalArgumentException.class, tool::run);
+ }
+
+ @Test
+ public void testSuccessfulRestorationToLatest() throws IOException, InterruptedException {
+ RestoreFromBackupTool restoreTool =
+ new RestoreFromBackupTool(backupStorage, restoreSnapLog, Long.MAX_VALUE, false,
+ restoreTempDir);
+ restoreTool.run();
+ validateRestoreCoverage(txnCnt);
+ }
+
+ @Test
+ public void testFailedRestorationWithOutOfRangeZxid() throws IOException {
+ try {
+ RestoreFromBackupTool restoreTool =
+ new RestoreFromBackupTool(backupStorage, restoreSnapLog, txnCnt + 1, false,
+ restoreTempDir);
+ restoreTool.run();
+ Assert.fail(
+ "The restoration should fail because the zxid restoration point specified is out of range.");
+ } catch (IllegalArgumentException e) {
+ e.printStackTrace();
+ } catch (Exception e1) {
+ Assert.fail("RestoreException should be thrown.");
+ }
+ }
+
+ @Test
+ public void testFailedRestorationWithLostLog() {
+ FilenameFilter filter = (dir, name) -> name.startsWith(Util.TXLOG_PREFIX);
+ File[] backupLogs = backupFileRootDir.listFiles(filter);
+ Assert.assertNotNull(backupLogs);
+ for (File backupLog : backupLogs) {
+ backupLog.renameTo(
+ new File(backupLog.getPath().replaceAll(Util.TXLOG_PREFIX, BackupUtil.LOST_LOG_PREFIX)));
+ }
+ try {
+ RestoreFromBackupTool restoreTool =
+ new RestoreFromBackupTool(backupStorage, restoreSnapLog, txnCnt, false, restoreTempDir);
+ restoreTool.run();
+ Assert.fail("The restoration should fail because the transaction logs are lost logs.");
+ } catch (IllegalArgumentException e) {
+ e.printStackTrace();
+ } catch (Exception e1) {
+ Assert.fail("RestoreException should be thrown.");
+ }
+ }
+
+ private void validateRestoreCoverage(int restoreZxid) throws IOException {
+ // Test restored snapshots
+ File restoredSnapshot = restoreSnapLog.findMostRecentSnapshot();
+ Assert.assertNotNull(restoredSnapshot);
+ // File name is changed when file is restored to local, so go to backup storage to find the whole zxid range
+ File[] matchedSnapshotInBackupStorage =
+ BackupStorageUtil.getFilesWithPrefix(backupFileRootDir, restoredSnapshot.getName() + "-");
+ Assert.assertEquals(1, matchedSnapshotInBackupStorage.length);
+ ZxidRange snapZxidRange =
+ Util.getZxidRangeFromName(matchedSnapshotInBackupStorage[0].getName(), Util.SNAP_PREFIX);
+ System.out.println(Arrays.toString(matchedSnapshotInBackupStorage));
+ Assert.assertTrue("High zxid of restored snapshot " + Long.toHexString(snapZxidRange.getHigh())
+ + " is larger than the restoreZxid " + Long.toHexString(restoreZxid) + ".",
+ snapZxidRange.getHigh() <= restoreZxid);
+
+ // Test restored txn logs
+ List restoredLogs =
+ Arrays.asList(Objects.requireNonNull(restoreSnapLog.getDataLogDir().listFiles()));
+ restoredLogs.sort(new Comparator() {
+ @Override
+ public int compare(File o1, File o2) {
+ long o1Zxid = Util.getZxidFromName(o1.getName(), Util.TXLOG_PREFIX);
+ long o2Zxid = Util.getZxidFromName(o2.getName(), Util.TXLOG_PREFIX);
+ return Long.compare(o1Zxid, o2Zxid);
+ }
+ });
+ Assert.assertTrue(
+ "The oldest restored txn log has a higher zxid than the low zxid of restored snapshot.",
+ Util.getZxidFromName(restoredLogs.get(0).getName(), Util.TXLOG_PREFIX) <= snapZxidRange
+ .getLow());
+ Assert.assertTrue("The restored files does not cover to the restoreZxid.",
+ restoreSnapLog.getLastLoggedZxid() >= restoreZxid);
+
+ // Validate all the zxids are covered
+ boolean[] coveredZxid = new boolean[txnCnt + 1];
+ for (File restoredLog : restoredLogs) {
+ if (!restoredLog.getName().startsWith(Util.TXLOG_PREFIX)) {
+ continue;
+ }
+ File[] matchedLogInBackupStorage =
+ BackupStorageUtil.getFilesWithPrefix(backupFileRootDir, restoredLog.getName() + "-");
+ Assert.assertEquals(
+ "Number of matched transaction log file for file " + restoredLog.getName() + " is not 1.",
+ 1, matchedLogInBackupStorage.length);
+ ZxidRange logZxidRange =
+ Util.getZxidRangeFromName(matchedLogInBackupStorage[0].getName(), Util.TXLOG_PREFIX);
+ int lowZxid = (int) logZxidRange.getLow();
+ int highZxid = (int) logZxidRange.getHigh();
+ for (int i = lowZxid; i <= highZxid; i++) {
+ coveredZxid[i] = true;
+ }
+ }
+
+ for (int i = Math.max(1, (int) snapZxidRange.getLow()); i <= restoreZxid; i++) {
+ Assert.assertTrue("Zxid " + Long.toHexString(i) + " is not covered in the restoration.",
+ coveredZxid[i]);
+ }
+ }
+
+ private boolean getRandomBoolean(float p) {
+ return random.nextFloat() < p;
+ }
+
+ @Test
+ public void testRestoreToZxidByCommandLine() throws IOException {
+ //Restore to a random zxid
+ int restoreZxid = 1 + random.nextInt(txnCnt);
+ RestoreFromBackupTool restoreTool = new RestoreFromBackupTool();
+ CommandLine cl = Mockito.mock(CommandLine.class);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_ZXID)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.BACKUP_STORE)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.SNAP_DESTINATION)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.LOG_DESTINATION)).thenReturn(true);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_ZXID))
+ .thenReturn(String.valueOf(restoreZxid));
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.BACKUP_STORE))
+ .thenReturn("gpfs::" + backupDir.getPath() + ":" + TEST_NAMESPACE);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.SNAP_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.LOG_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ Assert.assertTrue(restoreTool.runWithRetries(cl));
+ validateRestoreCoverage(restoreZxid);
+
+ //Restore to latest
+ //Use an empty directory as restoration destination; otherwise, the restoration will fail
+ restoreDir = ClientBase.createTmpDir();
+ restoreSnapLog = new FileTxnSnapLog(restoreDir, restoreDir);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.SNAP_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.LOG_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_ZXID))
+ .thenReturn(BackupUtil.LATEST);
+ Assert.assertTrue(restoreTool.runWithRetries(cl));
+ validateRestoreCoverage(txnCnt);
+ }
+
+ @Test
+ public void testRestoreToTimestampByCommandLine() throws IOException {
+ //Test restoration CLI using a timestamp recorded in the midpoint of the test ZNode creation
+ backupManager.getTimetableBackup().run(1);
+ RestoreFromBackupTool restoreTool = new RestoreFromBackupTool();
+ CommandLine cl = Mockito.mock(CommandLine.class);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_ZXID)).thenReturn(false);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_TIMESTAMP)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.BACKUP_STORE)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.SNAP_DESTINATION)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.LOG_DESTINATION)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.TIMETABLE_STORAGE_PATH)).thenReturn(true);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_TIMESTAMP))
+ .thenReturn(String.valueOf(timestampInMiddle));
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.BACKUP_STORE))
+ .thenReturn("gpfs::" + backupDir.getPath() + ":" + TEST_NAMESPACE);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.SNAP_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.LOG_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.TIMETABLE_STORAGE_PATH))
+ .thenReturn(timetableDir.getPath() + "/" + TEST_NAMESPACE);
+ Assert.assertTrue(restoreTool.runWithRetries(cl));
+
+ //Restore to latest using timestamp
+ //Use an empty directory as restoration destination; otherwise, the restoration will fail
+ restoreDir = ClientBase.createTmpDir();
+ restoreSnapLog = new FileTxnSnapLog(restoreDir, restoreDir);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.SNAP_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.LOG_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_TIMESTAMP))
+ .thenReturn(BackupUtil.LATEST);
+ Assert.assertTrue(restoreTool.runWithRetries(cl));
+ validateRestoreCoverage(txnCnt);
+ }
+
+ @Test
+ public void testSpotRestorationTool() throws IOException, InterruptedException, KeeperException {
+ //TEST 1.
+ //Target node: /testsr
+ // This test is going to test three scenarios:
+ // 1. Nodes exist in backup files but not in the running zk server
+ // Path => value:
+ // /testsr/restore => restore
+ // /testsr/restore/node0 => restore0
+ // Expected: nodes are created in the running zk server
+ // 2. Nodes not exist in backup files but in the running zk server
+ // Path => value:
+ // /testsr/new => new
+ // /testsr/new/node0 => new0
+ // Expected: messages printed at the end indicate the node is skipped
+ // 3. Nodes exist in both backup files and in the running zk server, but with different values
+ // Path => value in backup files; value in running server
+ // /testsr/existing => restoredVal; existingVal
+ // Expected: messages printed at the end indicate the node is skipped
+
+ // Create several znodes in original zk server whose data will be backed up for testing
+ connection.create("/testsr", "restoredTarget".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+ connection.create("/testsr/restore", "restore".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+ connection.create("/testsr/restore/node0", "restore0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+ connection.create("/testsr/existing", "restoredVal".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+ backupManager.getLogBackup().run(1);
+ backupManager.getSnapBackup().run(1);
+
+ // Close the original zk server and zk client;
+ //start a new server as the server to be restored, and a new client connection
+ connection.close();
+ zks.shutdown();
+ LOG.info("ZK server is shut down.");
+
+ dataDir = ClientBase.createTmpDir();
+ LOG.info("Starting a new zk server.");
+ zks = new ZooKeeperServer(dataDir, dataDir, 3000);
+ SyncRequestProcessor.setSnapCount(100);
+ serverCnxnFactory.startup(zks);
+
+ LOG.info("Waiting for server startup");
+ Assert.assertTrue("waiting for server being up",
+ ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ connection = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE);
+
+ // Create several znodes in the running zk server
+ connection
+ .create("/testsr", "target".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ connection.create("/testsr/new", "new".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+ connection.create("/testsr/new/node0", "new0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+ connection.create("/testsr/existing", "existingVal".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+
+ // Copy backup files to restoreDir
+ RestoreFromBackupTool restoreTool = new RestoreFromBackupTool();
+ CommandLine cl = Mockito.mock(CommandLine.class);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_ZXID)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.BACKUP_STORE)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.SNAP_DESTINATION)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.LOG_DESTINATION)).thenReturn(true);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_ZXID))
+ .thenReturn((BackupUtil.LATEST));
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.BACKUP_STORE))
+ .thenReturn("gpfs::" + backupDir.getPath() + ":" + TEST_NAMESPACE);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.SNAP_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.LOG_DESTINATION))
+ .thenReturn(restoreDir.getPath());
+ Assert.assertTrue(restoreTool.runWithRetries(cl));
+
+ // Do spot restoration using the backup files
+ String targetZnodePath = "/testsr";
+ MockSpotRestorationTool tool =
+ new MockSpotRestorationTool(restoreDir, connection, targetZnodePath, true);
+ tool.run();
+
+ connection = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE);
+
+ // The target node's value should be updated
+ Assert.assertArrayEquals("restoredTarget".getBytes(),
+ connection.getData("/testsr", false, new Stat()));
+
+ // These nodes should be created in the zk server
+ Assert.assertArrayEquals("restore".getBytes(),
+ connection.getData("/testsr/restore", false, new Stat()));
+ Assert.assertArrayEquals("restore0".getBytes(),
+ connection.getData("/testsr/restore/node0", false, new Stat()));
+
+ // We do not delete new nodes, only log them in the messages
+ Assert.assertNotNull(connection.exists("/testsr/new", false));
+ Assert.assertNotNull(connection.exists("/testsr/new/node0", false));
+
+ // We do not update existing nodes' values, only log them in the messages
+ Assert.assertArrayEquals("existingVal".getBytes(),
+ connection.getData("/testsr/existing", false, new Stat()));
+
+ LOG.info("Please examine the messages printed out. "
+ + "There should be messages for skipping nodes: \"/testsr/new\" and \"/testsr/existing\".");
+
+ //TEST 2.
+ // Test target node's parent nodes do not exist
+ connection.close();
+ zks.shutdown();
+ LOG.info("ZK server is shut down.");
+
+ dataDir = ClientBase.createTmpDir();
+ LOG.info("Starting a new zk server.");
+ zks = new ZooKeeperServer(dataDir, dataDir, 3000);
+ SyncRequestProcessor.setSnapCount(100);
+ serverCnxnFactory.startup(zks);
+
+ LOG.info("Waiting for server startup");
+ Assert.assertTrue("waiting for server being up",
+ ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ connection = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE);
+
+ targetZnodePath = "/testsr/restore/node0";
+ tool = new MockSpotRestorationTool(restoreDir, connection, targetZnodePath, true);
+ tool.run();
+
+ connection = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE);
+
+ Assert.assertArrayEquals("restoredTarget".getBytes(),
+ connection.getData("/testsr", false, new Stat()));
+ Assert.assertArrayEquals("restore".getBytes(),
+ connection.getData("/testsr/restore", false, new Stat()));
+ Assert.assertArrayEquals("restore0".getBytes(),
+ connection.getData("/testsr/restore/node0", false, new Stat()));
+ }
+
+ @Test
+ public void testSpotRestorationByCommandLine() throws IOException, InterruptedException {
+ //Test restoration CLI using a timestamp recorded in the midpoint of the test ZNode creation
+ backupManager.getTimetableBackup().run(1);
+
+ // Close the original zk server and zk client;
+ //start a new server as the server to be restored
+ connection.close();
+ zks.shutdown();
+ LOG.info("ZK server is shut down.");
+
+ dataDir = ClientBase.createTmpDir();
+ LOG.info("Starting a new zk server.");
+ zks = new ZooKeeperServer(dataDir, dataDir, 3000);
+ SyncRequestProcessor.setSnapCount(100);
+ serverCnxnFactory.startup(zks);
+
+ LOG.info("Waiting for server startup");
+ Assert.assertTrue("waiting for server being up",
+ ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+
+ // Mock CLI command
+ CommandLine cl = Mockito.mock(CommandLine.class);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_ZXID)).thenReturn(false);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.RESTORE_TIMESTAMP)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.BACKUP_STORE)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.SNAP_DESTINATION)).thenReturn(false);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.LOG_DESTINATION)).thenReturn(false);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.LOCAL_RESTORE_TEMP_DIR_PATH)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.TIMETABLE_STORAGE_PATH)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.ZNODE_PATH_TO_RESTORE)).thenReturn(true);
+ when(cl.hasOption(RestoreCommand.OptionShortForm.ZK_SERVER_CONNECTION_STRING)).thenReturn(true);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.RESTORE_TIMESTAMP))
+ .thenReturn(String.valueOf(timestampInMiddle));
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.BACKUP_STORE))
+ .thenReturn("gpfs::" + backupDir.getPath() + ":" + TEST_NAMESPACE);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.LOCAL_RESTORE_TEMP_DIR_PATH))
+ .thenReturn(restoreTempDir.getPath());
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.TIMETABLE_STORAGE_PATH))
+ .thenReturn(timetableDir.getPath() + "/" + TEST_NAMESPACE);
+ // Restore the first node created, so we are sure this node exists at the moment of timestamp provided
+ String nodePath = "/node1";
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.ZNODE_PATH_TO_RESTORE))
+ .thenReturn(nodePath);
+ when(cl.getOptionValue(RestoreCommand.OptionShortForm.ZK_SERVER_CONNECTION_STRING))
+ .thenReturn(HOSTPORT);
+
+ // Run restoration
+ RestoreFromBackupTool restoreTool = new MockRestoreFromBackupTool();
+ Assert.assertTrue(restoreTool.runWithRetries(cl));
+ Assert.assertNotNull(zks.getZKDatabase().getNode(nodePath));
+ }
+
+ class MockSpotRestorationTool extends SpotRestorationTool {
+ public MockSpotRestorationTool(File dataDir, ZooKeeper zk, String targetZNodePath,
+ boolean restoreRecursively) throws IOException {
+ super(dataDir, zk, targetZNodePath, restoreRecursively);
+ }
+
+ @Override
+ protected boolean getUserConfirmation(String requestMsg, String yesMsg, String noMsg) {
+ return true;
+ }
+ }
+
+ class MockRestoreFromBackupTool extends RestoreFromBackupTool {
+ @Override
+ protected void performSpotRestoration(File restoreTempDir)
+ throws IOException, InterruptedException {
+ LOG.info("Starting spot restoration for zk path " + znodePathToRestore);
+ zk = new ZooKeeper(zkServerConnectionStr, CONNECTION_TIMEOUT, (event) -> {
+ LOG.info("WATCHER:: client-server connection event received for spot restoration: " + event
+ .toString());
+ });
+ spotRestorationTool =
+ new MockSpotRestorationTool(restoreTempDir, zk, znodePathToRestore, restoreRecursively);
+ spotRestorationTool.run();
+ }
+ }
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/storage/impl/FileSystemBackupStorageTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/storage/impl/FileSystemBackupStorageTest.java
new file mode 100644
index 00000000000..1f3f7be597f
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/storage/impl/FileSystemBackupStorageTest.java
@@ -0,0 +1,149 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.storage.impl;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.commons.io.FileUtils;
+import org.apache.zookeeper.common.ConfigException;
+import org.apache.zookeeper.server.backup.BackupConfig;
+import org.apache.zookeeper.server.backup.BackupFileInfo;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.storage.BackupStorageUtil;
+import org.junit.Assert;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+@TestMethodOrder(MethodOrderer.Alphanumeric.class)
+public class FileSystemBackupStorageTest {
+ private static String testFolderPath;
+ private static String testFileDirPath;
+ private static String backupFileDirPath;
+ private static List testFileNames =
+ new ArrayList<>(Arrays.asList("log.testFile_0", "snapshot.testFile_1", "log.testFile_2"));
+ private static BackupStorageProvider backupStorage;
+ private static List testFiles;
+ private static List backupFiles;
+ private static final String NAMESPACE = "test";
+ private static final String BACKUP_STORAGE_PATH = "./localBackupStorageTest";
+
+ @BeforeAll
+ public static void beforeClass() throws ConfigException, IOException {
+ // Build backup config that point the backup storage to a local directory
+ new File(BACKUP_STORAGE_PATH).mkdir();
+ BackupConfig backupConfig = new BackupConfig.Builder().setEnabled(true)
+ .setStatusDir(new File("./localBackupStorageTest/backup/status")).
+ setTmpDir(new File("./localBackupStorageTest/tmp/backup"))
+ .setStorageProviderClassName(FileSystemBackupStorage.class.getName())
+ .setBackupStoragePath(BACKUP_STORAGE_PATH).setNamespace(NAMESPACE).build().get();
+
+ backupStorage = new FileSystemBackupStorage(backupConfig);
+ // The path to the directory that contains all directories and files created for this test
+ testFolderPath =
+ Paths.get(Paths.get("").toAbsolutePath().toString(), backupConfig.getBackupStoragePath())
+ .toString();
+ // The path to the directory that backup files will be stored
+ backupFileDirPath = String.join(File.separator, testFolderPath, NAMESPACE);
+ // The path to the directory that contains the test files representing logs/snapshots in ZK dataDir
+ testFileDirPath = String.join(File.separator, testFolderPath, "testFiles");
+ testFiles = new ArrayList<>();
+ backupFiles = new ArrayList<>();
+
+ // Create the test files in the testFileDir, and add reference to testFiles list for easy reference
+ for (String testFileName : testFileNames) {
+ String testFilePath = String.join(File.separator, testFileDirPath, testFileName);
+ File testFile = new File(testFilePath);
+ testFiles.add(testFile);
+ BackupStorageUtil.createFile(testFile, false);
+ FileWriter fileWriter = new FileWriter(testFile);
+ for (int i = 0; i < 1000; i++) {
+ fileWriter.write(testFileName);
+ fileWriter.write('\n');
+ }
+ fileWriter.close();
+ Assert.assertTrue(testFile.exists());
+ Assert.assertTrue(sizeOf(testFile) > 0);
+ }
+ }
+
+ @AfterAll
+ public static void afterClass() throws IOException {
+ FileUtils.deleteDirectory(new File(testFolderPath));
+ }
+
+ @Test
+ public void test0_CopyToBackupStorage() throws IOException {
+ for (File testFile : testFiles) {
+ backupStorage.copyToBackupStorage(testFile, testFile);
+ String backupFilePath =
+ BackupStorageUtil.constructBackupFilePath(testFile.getName(), backupFileDirPath);
+ File backupFile = new File(backupFilePath);
+ backupFiles.add(backupFile);
+ Assert.assertEquals(sizeOf(testFile), sizeOf(backupFile));
+ }
+ }
+
+ @Test
+ public void test1_GetBackupFileInfo() throws IOException {
+ BackupFileInfo validFileInfo = backupStorage.getBackupFileInfo(testFiles.get(0));
+ BackupFileInfo invalidFileInfo =
+ backupStorage.getBackupFileInfo(new File("log.invalidBackupFile"));
+ Assert.assertEquals(validFileInfo.getSize(), sizeOf(testFiles.get(0)));
+ Assert.assertEquals(invalidFileInfo.getSize(), BackupFileInfo.NOT_SET);
+ }
+
+ @Test
+ public void test2_GetBackupFileInfos() throws IOException {
+ List fileInfos = backupStorage.getBackupFileInfos(new File(""), "log");
+ Assert.assertEquals(2, fileInfos.size());
+ }
+
+ @Test
+ public void test3_CopyToLocalStorage() throws IOException {
+ for (File testFile : testFiles) {
+ Files.delete(Paths.get(testFile.getPath()));
+ Assert.assertFalse(testFile.exists());
+ backupStorage.copyToLocalStorage(testFile,
+ new File(String.join(File.separator, testFileDirPath, testFile.getName())));
+ Assert.assertTrue(testFile.exists());
+ }
+ }
+
+ @Test
+ public void test4_Delete() throws IOException {
+ for (int i = 0; i < testFiles.size(); i++) {
+ backupStorage.delete(testFiles.get(i));
+ Assert.assertFalse(backupFiles.get(i).exists());
+ }
+ }
+
+ private static long sizeOf(File file) throws IOException {
+ return Files.readAttributes(Paths.get(file.getPath()), BasicFileAttributes.class).size();
+ }
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/timetable/TimetableUtilTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/timetable/TimetableUtilTest.java
new file mode 100644
index 00000000000..550ddaf87d1
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/backup/timetable/TimetableUtilTest.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zookeeper.server.backup.timetable;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.util.Map;
+import java.util.TreeMap;
+import org.junit.Assert;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TimetableUtilTest {
+ private static final int NUM_BACKUP_FILES = 5;
+ private static final File[] TIMETABLE_BACKUP_FILES = new File[NUM_BACKUP_FILES];
+
+ /**
+ * Creates a timetable sequence: (10, 10), (20, 20), ..., (50, 50) for testing
+ * @throws IOException
+ */
+ @BeforeAll
+ public static void setupTestData() throws IOException {
+ for (int i = 1; i <= NUM_BACKUP_FILES; i++) {
+ // Multiple by 10 to give it space in between
+ createTimetableBackupFile(i * 10, i * 10, i - 1);
+ }
+ }
+
+ @AfterAll
+ public static void removeTestData() {
+ for (File file : TIMETABLE_BACKUP_FILES) {
+ file.delete();
+ }
+ }
+
+ @Test
+ public void testFindLastZxidFromTimestamp() {
+ String result =
+ TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, Long.toString(25L)).getValue();
+ Assert.assertEquals(Long.toHexString(20), result);
+
+ result = TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, Long.toString(35L)).getValue();
+ Assert.assertEquals(Long.toHexString(30), result);
+
+ result = TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, Long.toString(50L)).getValue();
+ Assert.assertEquals(Long.toHexString(50), result);
+
+ result = TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, Long.toString(10L)).getValue();
+ Assert.assertEquals(Long.toHexString(10), result);
+
+ result = TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, Long.toString(41L)).getValue();
+ Assert.assertEquals(Long.toHexString(40), result);
+ }
+
+ @Test
+ public void testFindLatestZxidFromTimestamp() {
+ String result = TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, "latest").getValue();
+ Assert.assertEquals(Long.toHexString(50), result);
+ }
+
+ @Test
+ public void testTimestampOutsideWindowLow() {
+ assertThrows(IllegalArgumentException.class,
+ () -> TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, Long.toString(5)));
+ }
+
+ @Test
+ public void testTimestampOutsideWindowHigh() {
+ assertThrows(IllegalArgumentException.class,
+ () -> TimetableUtil.findLastZxidFromTimestamp(TIMETABLE_BACKUP_FILES, Long.toString(55)));
+ }
+
+ @Test
+ public void testEmptyFiles() {
+ assertThrows(IllegalArgumentException.class,
+ () -> TimetableUtil.findLastZxidFromTimestamp(null, Long.toString(25)));
+ }
+
+ private static void createTimetableBackupFile(long timestamp, long zxid, int fileNum)
+ throws IOException {
+ Map timetableRecords = new TreeMap<>();
+ timetableRecords.put(timestamp, Long.toHexString(zxid));
+
+ File file = new File("timetable." + timestamp + "-" + timestamp);
+ FileOutputStream f = new FileOutputStream(file);
+ ObjectOutputStream s = new ObjectOutputStream(f);
+ s.writeObject(timetableRecords);
+ s.close();
+
+ TIMETABLE_BACKUP_FILES[fileNum] = file;
+ }
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/BackupManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/BackupManagerTest.java
new file mode 100644
index 00000000000..dc8ca8998d8
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/BackupManagerTest.java
@@ -0,0 +1,759 @@
+/*
+ * 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 com.google.common.collect.Range;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.TreeMap;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.server.ServerCnxn;
+import org.apache.zookeeper.server.ServerCnxnFactory;
+import org.apache.zookeeper.server.SyncRequestProcessor;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.server.backup.BackupConfig;
+import org.apache.zookeeper.server.backup.BackupFileInfo;
+import org.apache.zookeeper.server.backup.BackupManager;
+import org.apache.zookeeper.server.backup.BackupPoint;
+import org.apache.zookeeper.server.backup.BackupStatus;
+import org.apache.zookeeper.server.backup.BackupUtil;
+import org.apache.zookeeper.server.backup.BackupUtil.BackupFileType;
+import org.apache.zookeeper.server.backup.storage.BackupStorageProvider;
+import org.apache.zookeeper.server.backup.storage.impl.FileSystemBackupStorage;
+import org.apache.zookeeper.server.backup.timetable.TimetableBackup;
+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.persistence.ZxidRange;
+import org.junit.Assert;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests BackupManager. This class is intended to be in the package "org.apache.zookeeper.test" to
+ * leverage other ZK testing components such as ClientBase.
+ */
+public class BackupManagerTest extends ZKTestCase implements Watcher {
+
+ private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
+ private static final int CONNECTION_TIMEOUT = 300000;
+ private static final Logger LOG = LoggerFactory.getLogger(BackupManagerTest.class);
+ private static final String TEST_EMPTY_NAMESPACE = "";
+
+ private ZooKeeper connection;
+ private File dataDir;
+ private File backupStatusDir;
+ private File backupTmpDir;
+ private File backupDir;
+ private ZooKeeperServer zks;
+ private ServerCnxnFactory serverCnxnFactory;
+ private BackupStorageProvider backupStorage;
+ private BackupManager backupManager;
+ private BackupStatus backupStatus;
+ private FileTxnSnapLog snapLog;
+ private int createdNodeCount = 0;
+ private BackupConfig backupConfig;
+ /*
+ * For timetable backup testing
+ */
+ private static final long TIMETABLE_BACKUP_INTERVAL_IN_MS = 100L;
+ private File timetableBackupDir;
+ private BackupConfig.Builder backupConfigBuilder;
+
+ @BeforeEach
+ public void setup() throws Exception {
+ LOG.info("Setting up directories");
+
+ dataDir = ClientBase.createTmpDir();
+ backupStatusDir = ClientBase.createTmpDir();
+ backupTmpDir = ClientBase.createTmpDir();
+ backupDir = ClientBase.createTmpDir();
+ timetableBackupDir = ClientBase.createTmpDir();
+
+ // Create a dummy config
+ backupConfigBuilder = new BackupConfig.Builder();
+ backupConfig = backupConfigBuilder.
+ setEnabled(true).
+ setStatusDir(backupStatusDir).
+ setTmpDir(backupTmpDir).
+ setBackupStoragePath(backupDir.getAbsolutePath()).
+ setNamespace(TEST_EMPTY_NAMESPACE).
+ // Use FileSystemBackupStorage with a local path for testing
+ setStorageProviderClassName(FileSystemBackupStorage.class.getName()).
+ setTimetableEnabled(true).
+ setTimetableStoragePath(timetableBackupDir.getAbsolutePath()).
+ setTimetableBackupIntervalInMs(TIMETABLE_BACKUP_INTERVAL_IN_MS).
+ build().get();
+ // Create BackupStorage
+ backupStorage = new FileSystemBackupStorage(backupConfig);
+
+ setupZk();
+ connection = createConnection();
+ }
+
+ @AfterEach
+ public void teardown() throws Exception {
+ closeConnection(connection);
+ connection = null;
+ cleanupZk();
+ }
+
+ @Test
+ public void testEmptyDirectory() throws Exception {
+ File dataDir = ClientBase.createTmpDir();
+ File backupTmpDir = ClientBase.createTmpDir();
+ File backupDir = ClientBase.createTmpDir();
+
+ BackupConfig backupConfig = new BackupConfig.Builder().
+ setEnabled(true).
+ setStatusDir(dataDir).
+ setTmpDir(backupTmpDir).
+ setBackupIntervalInMinutes(15).
+ setStorageProviderClassName(FileSystemBackupStorage.class.getName()).
+ setBackupStoragePath(backupDir.getAbsolutePath()).
+ build().get();
+
+ BackupManager bm = new BackupManager(dataDir, dataDir, -1, backupConfig);
+ bm.initialize();
+
+ bm.getLogBackup().run(1);
+ bm.getSnapBackup().run(1);
+
+ Assert.assertFalse("No files should have been backed up.", backupDir.list() == null);
+ Assert.assertFalse("No temporary files should have been created.",
+ backupTmpDir.list() == null);
+ BackupStatus bs = new BackupStatus(dataDir);
+ BackupPoint bp = bs.read();
+ Assert.assertEquals("backupStatus should be set to min for log",
+ bp.getLogZxid(), BackupUtil.INVALID_LOG_ZXID);
+ Assert.assertEquals("backupStatus should be set to min for snap",
+ bp.getSnapZxid(), BackupUtil.INVALID_SNAP_ZXID);
+ }
+
+ @Test
+ public void testSwitchToNewBackupNode() throws Exception {
+ createNodes(connection, 1000);
+ backupManager.getLogBackup().run(1);
+ backupManager.getSnapBackup().run(1);
+
+ BackupPoint bp = backupStatus.read();
+ String[] filesOrig = getBackupFiles(backupDir);
+ Assert.assertEquals("backup status and backupmanager must match log",
+ bp.getLogZxid(), backupManager.getBackedupLogZxid());
+ Assert.assertEquals("backup status and backupmanager must match snap",
+ bp.getSnapZxid(), backupManager.getBackedupSnapZxid());
+
+ File backupStatusFile = new File(backupStatusDir, BackupStatus.STATUS_FILENAME);
+ backupStatusFile.delete();
+
+ backupManager.initialize();
+ BackupPoint bp2 = backupStatus.read();
+ Assert.assertEquals(
+ "backup status and backupmanager must match log after switch to new backup node",
+ bp2.getLogZxid(),
+ backupManager.getBackedupLogZxid());
+ Assert.assertEquals(
+ "backup status and backupmanager must match snap after switch to new backup node",
+ bp2.getSnapZxid(),
+ backupManager.getBackedupSnapZxid());
+ Assert.assertEquals("backup point must match prior backup point -- snap",
+ bp.getLogZxid(), bp2.getLogZxid());
+ Assert.assertEquals("backup point must match prior backup point -- snap",
+ bp.getSnapZxid(), bp2.getSnapZxid());
+
+ backupManager.getLogBackup().run(1);
+ backupManager.getSnapBackup().run(1);
+
+ String[] filesPost = getBackupFiles(backupDir);
+ Assert.assertArrayEquals("files before and after switch to new backup node",
+ filesOrig, filesPost);
+
+ createNodes(connection, 1000);
+ backupManager.getLogBackup().run(1);
+ backupManager.getSnapBackup().run(1);
+
+ String[] filesPostCreates = getBackupFiles(backupDir);
+ List> zxids = BackupUtil.getRanges(backupStorage, BackupFileType.TXNLOG);
+
+ Assert.assertTrue("must have more backups", filesPostCreates.length > filesPost.length);
+
+ for (int i = 0; i < zxids.size(); i++) {
+ LOG.info("zxids[{}]: {}", i, zxids.get(i));
+ }
+
+ for (int i = 0; i < zxids.size() - 1; i++) {
+ Assert.assertEquals("max of previous must be one less than next min",
+ (zxids.get(i).upperEndpoint() + 1), zxids.get(i + 1).lowerEndpoint().longValue());
+ }
+ }
+
+ @Test
+ public void testBackupManager() throws Exception {
+ backupManager.initialize();
+
+ backupManager.getSnapBackup().run(1);
+
+ String[] files = getBackupFiles(backupDir);
+ Assert.assertTrue("Must have some snapshots", files != null);
+
+ Assert.assertEquals("Must have just a single snapshot", 1, files.length);
+ Assert.assertTrue("File must be called snapshot.0-*",
+ files[0].startsWith(Util.SNAP_PREFIX + ".0-"));
+
+ BackupPoint bp;
+
+ createNodes(connection, 1);
+ backupManager.getLogBackup().run(1);
+ bp = backupStatus.read();
+
+ Assert.assertEquals("Must have copied last txn",
+ bp.getLogZxid(), zks.getTxnLogFactory().getLastLoggedZxid());
+ List> zxids = BackupUtil.getRanges(backupStorage, BackupFileType.TXNLOG);
+ Range lastZxid = zxids.get(zxids.size() - 1);
+
+ Assert.assertEquals("last log must be 1-2", lastZxid, Range.closed(1L, 2L));
+
+ createNodes(connection, 1);
+ backupManager.getLogBackup().run(1);
+ zxids = BackupUtil.getRanges(backupStorage, BackupFileType.TXNLOG);
+ int count = zxids.size();
+ lastZxid = zxids.get(zxids.size() - 1);
+
+ Assert.assertEquals("last log must be 3-3", lastZxid, Range.closed(3L, 3L));
+
+ backupManager.getLogBackup().run(1);
+ zxids = BackupUtil.getRanges(backupStorage, BackupFileType.TXNLOG);
+ lastZxid = zxids.get(zxids.size() - 1);
+ int count2 = zxids.size();
+
+ Assert.assertEquals("last log must be 3-3", lastZxid, Range.closed(3L, 3L));
+ Assert.assertEquals("no new files", count, count2);
+
+ createNodes(connection, 1);
+ backupManager.getLogBackup().run(1);
+ zxids = BackupUtil.getRanges(backupStorage, BackupFileType.TXNLOG);
+ lastZxid = zxids.get(zxids.size() - 1);
+
+ Assert.assertEquals("last log must be 4-4", lastZxid, Range.closed(4L, 4L));
+
+ createNodes(connection, 100);
+ backupManager.getLogBackup().run(1);
+ backupManager.getSnapBackup().run(1);
+
+ FileTxnSnapLog snapLog = new FileTxnSnapLog(dataDir, dataDir);
+ List snaps = snapLog.findNRecentSnapshots(100);
+ Collections.reverse(snaps);
+ List backupFiles = BackupUtil.getBackupFiles(
+ backupStorage,
+ BackupFileType.SNAPSHOT,
+ BackupUtil.IntervalEndpoint.START,
+ BackupUtil.SortOrder.ASCENDING);
+
+ Assert.assertEquals("must have only two snapshots", 2, backupFiles.size());
+ long firstSnapZxid = Util.getZxidFromName(snaps.get(0).getName(), Util.SNAP_PREFIX);
+ long firstBackupZxid = backupFiles.get(0).getRange().lowerEndpoint();
+ long lastSnapZxid = Util.getZxidFromName(
+ snaps.get(snaps.size() - 1).getName(), Util.SNAP_PREFIX);
+ long lastBackupZxid = backupFiles.get(1).getRange().lowerEndpoint();
+
+ Assert.assertEquals("first snapshot starting zxid must match",
+ firstSnapZxid, firstBackupZxid);
+ Assert.assertEquals("last snapshot starting zxid must match",
+ lastSnapZxid, lastBackupZxid);
+ }
+
+ @Test
+ public void restorabilityTest() throws Exception {
+ String[] nodeNames = {"/firstNode", "/secondNode", "/thirdNode", "/fourthNode"};
+
+ createNode(connection, nodeNames[0]);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+
+ createNode(connection, nodeNames[1]);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+
+ deleteNode(connection, nodeNames[1]);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+
+ createNode(connection, nodeNames[2]);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+
+ createNode(connection, nodeNames[3]);
+
+ closeConnection(connection);
+
+ boolean[][] expectedByLog = new boolean[][]{
+ {true, false, false, false},
+ {true, true, false, false},
+ {true, false, false, false},
+ {true, false, true, false}
+ };
+
+ for (int log = 0; log < 4; log++) {
+ restoreAndValidate(0, log, nodeNames, expectedByLog[log]);
+ }
+ }
+
+ @Test
+ public void testBackupFileMerge() throws Exception {
+ createNode(connection, "/fooBar");
+ backupManager.getLogBackup().run(1);
+
+ String[] backupFiles = getBackupFiles(backupDir);
+ Assert.assertEquals("Should have one backed up file", 1, backupFiles.length);
+
+ zks.getTxnLogFactory().rollLog();
+ createNode(connection, "/foo1");
+ long zxid1 = zks.getTxnLogFactory().getLastLoggedZxid();
+ createNode(connection, "/foo2");
+
+ zks.getTxnLogFactory().rollLog();
+ createNode(connection, "/foo3");
+ createNode(connection, "/foo4");
+ zks.getTxnLogFactory().rollLog();
+ createNode(connection, "/foo5");
+ createNode(connection, "/foo6");
+
+ File[] logs = snapLog.getSnapshotLogs(0);
+ Assert.assertEquals("Should have four log files.", 4, logs.length);
+ Assert.assertEquals("Should have zero additional txn in first file beyond backup point",
+ backupManager.getBackedupLogZxid() + 1, zxid1);
+ Assert.assertEquals("Zxid of second file must be backup point plus 1",
+ backupManager.getBackedupLogZxid() + 1,
+ Util.getZxidFromName(logs[1].getName(), Util.TXLOG_PREFIX));
+
+ backupManager.getLogBackup().run(1);
+ backupFiles = getBackupFiles(backupDir);
+
+ Assert.assertEquals("Should have two backed up files even with multiple log files",
+ 2, backupFiles.length);
+ }
+
+ @Test
+ public void testBackupWithNoNewRecords() throws Exception {
+ createNode(connection, "/foo");
+ backupManager.getLogBackup().run(1);
+ long backedUpLog1 = backupManager.getBackedupLogZxid();
+ backupManager.getLogBackup().run(1);
+ Assert.assertEquals("Backup point cannot have moved #1",
+ backedUpLog1, backupManager.getBackedupLogZxid());
+ backupManager.getLogBackup().run(1);
+ Assert.assertEquals("Backup point cannot have moved #2",
+ backedUpLog1, backupManager.getBackedupLogZxid());
+ }
+
+ @Test
+ public void testLostLogs() throws Exception {
+ createNode(connection, "/foo");
+ backupManager.getLogBackup().run(1);
+ createNode(connection, "/foobar");
+ createNode(connection, "/foobar2");
+ zks.getTxnLogFactory().rollLog();
+ createNode(connection, "/foobar3");
+ createNode(connection, "/foobar4");
+ zks.getTxnLogFactory().rollLog();
+ createNode(connection, "/foobar5");
+
+ File[] logs = snapLog.getSnapshotLogs(0);
+
+ for (int f = 0; f < logs.length; f++) {
+ LOG.info("File {}: {}", f, logs[f].getPath());
+ }
+
+ Assert.assertEquals("Should have three log files", 3, logs.length);
+ logs[0].delete();
+ logs[1].delete();
+ backupManager.getLogBackup().run(1);
+ backupManager.getLogBackup().run(1);
+ backupManager.getLogBackup().run(1);
+
+ String[] backupFiles = getBackupFiles(backupDir);
+ Assert.assertEquals("Should have three files in backup dir", 3, backupFiles.length);
+
+ boolean lostLogsFileFound = false;
+ for (String s : backupFiles) {
+ LOG.info("backupFile: {}", s);
+ if (s.equals("lostLogs.3-6")) {
+ lostLogsFileFound = true;
+ break;
+ }
+ }
+
+ Assert.assertTrue("Must have a lostLogs.3-6 file", lostLogsFileFound);
+ }
+
+ @Test
+ public void testCleanupOfInvalidFilesOnStartUp() throws Exception {
+ createNodes(connection, 110);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+ createNodes(connection, 110);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+ createNodes(connection, 110);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+ createNodes(connection, 110);
+ backupManager.getSnapBackup().run(1);
+ backupManager.getLogBackup().run(1);
+
+ String[] expectedBackupFiles = getBackupFiles(backupDir);
+
+ backupManager.initialize();
+
+ String[] actualBackupFiles = getBackupFiles(backupDir);
+
+ Assert.assertArrayEquals("no files should have been deleted",
+ expectedBackupFiles, actualBackupFiles);
+
+ // Add some invalid files
+ File badFile = new File(
+ backupDir,
+ makeTmpName(BackupUtil.makeBackupName(Util.makeSnapshotName(1000), 1010)));
+ badFile.createNewFile();
+
+ badFile = new File(
+ backupDir,
+ makeTmpName(BackupUtil.makeBackupName(Util.makeSnapshotName(1100), 1110)));
+ badFile.createNewFile();
+
+ badFile = new File(
+ backupDir,
+ makeTmpName(BackupUtil.makeBackupName(Util.makeLogName(1000), 1200)));
+ badFile.createNewFile();
+
+ backupManager.initialize();
+
+ actualBackupFiles = getBackupFiles(backupDir);
+
+ Assert.assertArrayEquals("bad files were should have been deleted",
+ expectedBackupFiles, actualBackupFiles);
+ }
+
+ @Test
+ public void testTimetableBackup() throws Exception {
+ String[] files = timetableBackupDir.list((dir, name) -> !name.equals("initialize"));
+ // Contains "initialize" file only, no timetable backup files expected
+ Assert.assertTrue(files != null && files.length == 0);
+
+ // This sleep is necessary to make sure the lastLoggedZxid has been updated in the timetable's
+ // child thread
+ Thread.sleep(1000L);
+
+ // Backup timetable and extract the last zxid from the timetable
+ backupManager.getTimetableBackup().run(1);
+ // Must contain a timetable backup file
+ File[] fileObjs =
+ timetableBackupDir.listFiles(f -> f.getName().startsWith(TimetableBackup.TIMETABLE_PREFIX));
+ Assert.assertNotNull(fileObjs);
+ Assert.assertEquals(1, fileObjs.length);
+ File firstBackupFile = fileObjs[0];
+ TreeMap timetableRecords = convertTimetableBackupFileToMap(firstBackupFile);
+ Assert.assertNotNull(timetableRecords);
+ Assert.assertFalse(timetableRecords.isEmpty());
+ String lastZxid = timetableRecords.lastEntry().getValue();
+ long lastZxidLong = Long.valueOf(lastZxid, 16);
+
+ // Increment zxid by creating znodes
+ int increment = 5;
+ createNodes(connection, increment);
+
+ long lastZxidLongAfterIncrement = lastZxidLong + increment;
+ String lastZxidAfterIncrement = Long.toHexString(lastZxidLongAfterIncrement);
+
+ // This sleep is necessary to make sure the lastLoggedZxid has been updated in-memory
+ Thread.sleep(1000L);
+
+ // Check that the next timetable backup file created has the matching incremented zxid
+ backupManager.getTimetableBackup().run(1);
+ fileObjs = timetableBackupDir.listFiles(
+ f -> f.getName().startsWith(TimetableBackup.TIMETABLE_PREFIX) && !f.getName()
+ .equals(firstBackupFile.getName()));
+ Assert.assertNotNull(fileObjs);
+ Assert.assertEquals(1, fileObjs.length);
+ File secondBackupFile = fileObjs[0];
+ timetableRecords = convertTimetableBackupFileToMap(secondBackupFile);
+ Assert.assertNotNull(timetableRecords);
+ Assert.assertFalse(timetableRecords.isEmpty());
+ lastZxid = timetableRecords.lastEntry().getValue();
+ Assert.assertEquals(lastZxidAfterIncrement, lastZxid);
+
+ // Now try to create another instance of BackupManager to simulate a local JVM (server) restart
+ // This is to test whether BackupManager can correctly restore a backup point from BackupStatus
+ // And from the backup storage
+ BackupManager newBackupManager = new BackupManager(dataDir, dataDir, 0, backupConfig);
+ newBackupManager.initialize();
+ BackupStatus newBackupStatus = new BackupStatus(backupStatusDir);
+ BackupPoint newBackupPoint = newBackupStatus.read();
+ long timestampFromBackupPoint = newBackupPoint.getTimestamp();
+ long timestampFromBackupFile = timetableRecords.lastEntry().getKey();
+ // Latest timestamps backed up in BackupStatus and from backup storage must match
+ Assert.assertEquals(timestampFromBackupFile, timestampFromBackupPoint);
+ newBackupManager.stop();
+ }
+
+ @Test
+ public void testSnapshotZxidRangesWithCompressionSuffixes() {
+ for (String extension : new String[]{"", ".gz", ".snappy"}) {
+ ZxidRange startOnly = Util.getZxidRangeFromName("snapshot.10000005f" + extension, Util.SNAP_PREFIX);
+ Assert.assertEquals(0x10000005fL, startOnly.getLow());
+ Assert.assertFalse(startOnly.isHighPresent());
+ ZxidRange bounded = Util.getZxidRangeFromName("snapshot.10000005f-200000002" + extension, Util.SNAP_PREFIX);
+ Assert.assertEquals(0x10000005fL, bounded.getLow());
+ Assert.assertEquals(0x200000002L, bounded.getHigh());
+ Assert.assertEquals(Range.closed(0x10000005fL, 0x200000002L),
+ BackupUtil.getRangeFromName("snapshot.10000005f-200000002" + extension, Util.SNAP_PREFIX));
+ }
+ Assert.assertSame(ZxidRange.INVALID, Util.getZxidRangeFromName("snapshot.10000005f.zip", Util.SNAP_PREFIX));
+ Assert.assertSame(ZxidRange.INVALID, Util.getZxidRangeFromName("log.10000005f.gz", Util.TXLOG_PREFIX));
+ }
+
+ @Test
+ public void testBackupFileNamingOnStreamMode() throws Exception {
+ // Test using a non-default StreamMode to see if the backup file naming is compatible with
+ // different StreamModes used in snapshot compression
+ SnapStream.StreamMode origStreamMode = SnapStream.getStreamMode();
+ SnapStream.setStreamMode(SnapStream.StreamMode.GZIP);
+
+ // Test case 1: make sure backup files are generated correctly with StreamMode extension
+ backupManager.initialize();
+ createNodes(connection, 110);
+ backupManager.getSnapBackup().run(1);
+ String[] expectedBackupFiles = getBackupFiles(backupDir);
+
+ // Sort the snapshot backup file name array because the first snapshot may not have
+ // the stream mode set. We want to look at the latest snapshot file and check if it contains
+ // the stream mode extension
+ Arrays.sort(expectedBackupFiles);
+ String newestSnapshotBackupFileName = expectedBackupFiles[expectedBackupFiles.length - 1];
+ Assert.assertTrue(
+ newestSnapshotBackupFileName.endsWith(SnapStream.StreamMode.GZIP.getFileExtension()));
+
+ // Test case 2: when the backup file is read into a BackupFileInfo object (for restoration),
+ // make sure the standard file name is created correctly in the following format:
+ // snapshot..
+ File[] snapshotBackups = backupDir.listFiles(
+ f -> f.getName().startsWith(Util.SNAP_PREFIX) && f.getName()
+ .endsWith(SnapStream.StreamMode.GZIP.getFileExtension()));
+ Assert.assertNotNull(snapshotBackups);
+
+ BackupFileInfo compressedSnapshotBackupFileInfo =
+ new BackupFileInfo(snapshotBackups[0], BackupFileInfo.NOT_SET, BackupFileInfo.NOT_SET);
+ Assert.assertTrue(compressedSnapshotBackupFileInfo.getRange().lowerEndpoint() >= 0);
+ Assert.assertTrue(compressedSnapshotBackupFileInfo.getRange().upperEndpoint()
+ >= compressedSnapshotBackupFileInfo.getRange().lowerEndpoint());
+ String standardFileName = compressedSnapshotBackupFileInfo.getStandardFile().getName();
+ Assert.assertTrue(standardFileName.endsWith(SnapStream.StreamMode.GZIP.getFileExtension()));
+
+ // Restore the original StreamMode
+ SnapStream.setStreamMode(origStreamMode);
+ }
+
+ private TreeMap convertTimetableBackupFileToMap(File timetableBackupFile)
+ throws IOException, ClassNotFoundException {
+ FileInputStream f = new FileInputStream(timetableBackupFile);
+ ObjectInputStream s = new ObjectInputStream(f);
+ @SuppressWarnings("unchecked")
+ TreeMap timetableRecords = (TreeMap) s.readObject();
+ s.close();
+ return timetableRecords;
+ }
+
+ private String makeTmpName(String filename) {
+ return "TMP_" + filename;
+ }
+
+ private void restoreAndValidate(int startingSnap, int endIndex, String[] nodeNames, boolean[] expectedExistence) throws Exception {
+ ZooKeeper c = null;
+
+ try {
+ c = closeRestoreRestartGetConnection(startingSnap, endIndex);
+
+ for (int n = 0; n < nodeNames.length && n < expectedExistence.length; n++) {
+ String msg = "Node " + nodeNames[n] + " existence after restore from snap "
+ + startingSnap + " and ending with log " + endIndex + ".";
+ Assert.assertEquals(msg, expectedExistence[n], exists(c, nodeNames[n]));
+ LOG.info("PASSED: " + msg);
+ }
+ } finally {
+ closeConnection(c);
+ }
+ }
+
+ private ZooKeeper closeRestoreRestartGetConnection(int startingSnap, int endIndex) throws Exception {
+ closeZk();
+ deleteDataFiles();
+ restoreFromBackup(startingSnap, endIndex);
+ startZk();
+ return createConnection();
+ }
+
+ private void deleteDataFiles() {
+ for (File f : snapLog.getSnapDir().listFiles()) {
+ LOG.info("Deleting file {}", f.getPath());
+ f.delete();
+ }
+ for (File f : snapLog.getDataLogDir().listFiles()) {
+ LOG.info("Deleting file {}", f.getPath());
+ f.delete();
+ }
+ }
+
+ private void restoreFromBackup(int startingSnap, int endPoint) throws Exception {
+ LOG.info("Restoring from backup: Snap {} Log {}", startingSnap, endPoint);
+
+ List snaps = BackupUtil.getBackupFilesByMin(backupStorage, BackupFileType.SNAPSHOT);
+ List logs = BackupUtil.getBackupFilesByMin(backupStorage, BackupFileType.TXNLOG);
+
+ copyToLocal(snaps.get(startingSnap), snapLog.getSnapDir());
+
+ for (int i = startingSnap; i <= endPoint; i++) {
+ copyToLocal(logs.get(i), snapLog.getDataLogDir());
+ }
+ }
+
+ private void copyToLocal(BackupFileInfo src, File destDir) throws IOException {
+ String name = src.getStandardFile().getName();
+ File dest = new File(destDir, name);
+
+ LOG.info("Copying from {} to {}", src.getBackedUpFile(), dest);
+ backupStorage.copyToLocalStorage(src.getBackedUpFile(), dest);
+ }
+
+ private void setupZk() throws Exception {
+ ClientBase.setupTestEnv();
+ startZk();
+ snapLog = new FileTxnSnapLog(dataDir, dataDir);
+ }
+
+ private void startZk() throws Exception {
+ LOG.info("Starting Zk");
+
+ zks = new ZooKeeperServer(dataDir, dataDir, 3000);
+ SyncRequestProcessor.setSnapCount(100);
+ final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
+ serverCnxnFactory = ServerCnxnFactory.createFactory(PORT, -1);
+ serverCnxnFactory.startup(zks);
+
+ LOG.info("Waiting for server startup");
+
+ Assert.assertTrue("waiting for server being up ",
+ ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+
+ backupManager = new BackupManager(dataDir, dataDir, 0, backupConfig);
+ backupManager.initialize();
+ backupStatus = new BackupStatus(backupStatusDir);
+ }
+
+ private void closeZk() throws Exception {
+ LOG.info("Closing Zk");
+
+ if (serverCnxnFactory != null) {
+ serverCnxnFactory.closeAll(ServerCnxn.DisconnectReason.SERVER_SHUTDOWN);
+ serverCnxnFactory.shutdown();
+ serverCnxnFactory = null;
+ }
+
+ if (zks != null) {
+ zks.getZKDatabase().close();
+ zks.shutdown();
+ zks = null;
+ }
+
+ Assert.assertTrue("waiting for server to shutdown",
+ ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ }
+
+ private void cleanupZk() throws Exception {
+ LOG.info("Closing and cleaning up Zk");
+
+ closeZk();
+ backupManager.stop();
+ backupManager = null;
+ backupStatus = null;
+ serverCnxnFactory = null;
+ zks = null;
+ snapLog = null;
+ }
+
+ private ZooKeeper createConnection() throws IOException {
+ return new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this);
+ }
+
+ private void closeConnection(ZooKeeper zk) throws InterruptedException {
+ if (zk != null) {
+ zk.close();
+ }
+ }
+
+ private void createNodes(ZooKeeper zk, int count) throws Exception {
+ int last = createdNodeCount + count;
+ for (; createdNodeCount < last; createdNodeCount++) {
+ zk.create("/invalidsnap-" + createdNodeCount, new byte[0], Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT);
+ }
+ }
+
+ private void createNode(ZooKeeper zk, String path) throws Exception {
+ zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ }
+
+ private void deleteNode(ZooKeeper zk, String path) throws Exception {
+ zk.delete(path, -1);
+ }
+
+ private boolean exists(ZooKeeper zk, String path) throws Exception {
+ return zk.exists(path, false) != null;
+ }
+
+ private String[] getBackupFiles(File path) {
+ FilenameFilter filter = new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.startsWith(Util.SNAP_PREFIX)
+ || name.startsWith(Util.TXLOG_PREFIX)
+ || name.startsWith(BackupUtil.LOST_LOG_PREFIX);
+ }
+ };
+
+ return path.list(filter);
+ }
+
+ public void process(WatchedEvent event) {
+ // do nothing
+ }
+}
\ No newline at end of file