Caideyipi commented on code in PR #18516:
URL: https://github.com/apache/iotdb/pull/18516#discussion_r3852283687


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/tools/ImportWAL.java:
##########
@@ -0,0 +1,1336 @@
+/*
+ * 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.iotdb.db.tools;
+
+import org.apache.iotdb.commons.path.MeasurementPath;
+import org.apache.iotdb.db.i18n.ImportWALMessages;
+import 
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.DeleteDataNode;
+import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertNode;
+import 
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowsNode;
+import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.ObjectNode;
+import 
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.RelationalDeleteDataNode;
+import 
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.RelationalInsertRowNode;
+import 
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.RelationalInsertRowsNode;
+import 
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.RelationalInsertTabletNode;
+import 
org.apache.iotdb.db.storageengine.dataregion.memtable.AlignedWritableMemChunk;
+import org.apache.iotdb.db.storageengine.dataregion.memtable.IMemTable;
+import org.apache.iotdb.db.storageengine.dataregion.memtable.IWritableMemChunk;
+import 
org.apache.iotdb.db.storageengine.dataregion.memtable.IWritableMemChunkGroup;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.WALEntry;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.WALEntryType;
+import org.apache.iotdb.db.storageengine.dataregion.wal.io.WALReader;
+import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALFileUtils;
+import 
org.apache.iotdb.db.subscription.broker.consensus.ConsensusLogToTabletConverter;
+import org.apache.iotdb.db.subscription.columnfilter.ColumnFilterMatcher;
+import org.apache.iotdb.db.utils.datastructure.AlignedTVList;
+import org.apache.iotdb.db.utils.datastructure.TVList;
+import org.apache.iotdb.isession.SessionDataSet;
+import org.apache.iotdb.rpc.IoTDBConnectionException;
+import org.apache.iotdb.rpc.StatementExecutionException;
+import org.apache.iotdb.session.Session;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.enums.ColumnCategory;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.file.metadata.IDeviceID;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BitMap;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.write.record.Tablet;
+import org.apache.tsfile.write.schema.IMeasurementSchema;
+import org.apache.tsfile.write.schema.MeasurementSchema;
+
+import java.io.Console;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class ImportWAL {
+
+  private static final int CODE_OK = 0;
+  private static final int CODE_ERROR = 1;
+  private static final String DEFAULT_HOST = "127.0.0.1";
+  private static final int DEFAULT_PORT = 6667;
+  private static final String DEFAULT_USER = "root";
+  private static final int DEFAULT_THREAD_NUM = 1;
+  private static final int SNAPSHOT_TABLET_ROW_LIMIT = 1024;
+
+  private ImportWAL() {}
+
+  public static void main(final String[] args) {
+    System.exit(run(args, System.out, System.err));
+  }
+
+  static int run(final String[] args, final PrintStream out, final PrintStream 
err) {
+    final Options options = createOptions();
+    if (containsHelpOption(args)) {
+      printHelp(options, out);
+      return CODE_OK;
+    }
+
+    final CommandLine commandLine;
+    try {
+      commandLine = new DefaultParser().parse(options, args);
+    } catch (final ParseException e) {
+      err.printf(ImportWALMessages.MESSAGE_ARGUMENT_ERROR_ARG_A9767F62, 
e.getMessage());
+      err.println();
+      printHelp(options, err);
+      return CODE_ERROR;
+    }
+
+    try {
+      final Path source = Paths.get(commandLine.getOptionValue("file"));
+      final List<Path> walFiles = collectWALFiles(source);
+      final String database = commandLine.getOptionValue("database");
+      final boolean deleteSource =
+          shouldDeleteSource(commandLine.getOptionValue("on_success", "none"));
+      final int threadNum =
+          parseThreadNum(
+              commandLine.getOptionValue("thread_num", 
String.valueOf(DEFAULT_THREAD_NUM)));
+      final String password = getPassword(commandLine);
+      final String host = commandLine.getOptionValue("host", DEFAULT_HOST);
+      final int port = parsePort(commandLine.getOptionValue("port", 
String.valueOf(DEFAULT_PORT)));
+      final String username = commandLine.getOptionValue("username", 
DEFAULT_USER);
+      final WALReplayer.ReplayDecisionController replayDecisionController =
+          new WALReplayer.ReplayDecisionController(System.console());
+      final ReplayStatistics statistics =
+          replayWALDirectories(
+              walFiles,
+              threadNum,
+              () ->
+                  createWALReplayWorker(
+                      host, port, username, password, database, 
replayDecisionController),
+              out,
+              deleteSource);
+      out.printf(
+          ImportWALMessages
+              
.MESSAGE_REPLAYED_ARG_OPERATIONS_FROM_ARG_WAL_FILES_SKIPPED_ARG_ENTRIES_F0D37E3A,
+          statistics.replayedOperationCount,
+          walFiles.size(),
+          statistics.skippedEntryCount);
+      out.println();
+      out.printf(
+          ImportWALMessages
+              
.MESSAGE_IMPORT_DURATION_ARG_SECONDS_TOTAL_SIZE_ARG_BYTES_AVERAGE_RATE_ARG_MB_PER_SECOND_4B4EA58D,
+          statistics.getElapsedSeconds(),
+          statistics.getTotalBytes(),
+          statistics.getAverageRateMbPerSecond());
+      out.println();
+      if (deleteSource) {
+        out.printf(
+            ImportWALMessages.MESSAGE_DELETED_ARG_SOURCE_WAL_FILES_C7A5AA1B, 
walFiles.size());
+        out.println();
+      }
+      return CODE_OK;
+    } catch (final Exception e) {
+      err.printf(ImportWALMessages.MESSAGE_WAL_IMPORT_FAILED_ARG_55C014BA, 
e.getMessage());
+      err.println();
+      return CODE_ERROR;
+    }
+  }
+
+  private static Options createOptions() {
+    final Options options = new Options();
+    options.addOption(
+        Option.builder("f")
+            .longOpt("file")
+            .hasArg()
+            .required()
+            .desc(
+                ImportWALMessages
+                    
.MESSAGE_PATH_OF_A_WAL_FILE_OR_A_DIRECTORY_CONTAINING_WAL_FILES_473D0554)
+            .build());
+    options.addOption(
+        Option.builder("h")
+            .longOpt("host")
+            .hasArg()
+            
.desc(ImportWALMessages.MESSAGE_TARGET_IOTDB_HOST_DEFAULT_127_0_0_1_3729156F)
+            .build());
+    options.addOption(
+        Option.builder("p")
+            .longOpt("port")
+            .hasArg()
+            
.desc(ImportWALMessages.MESSAGE_TARGET_IOTDB_RPC_PORT_DEFAULT_6667_FC0D345D)
+            .build());
+    options.addOption(
+        Option.builder("u")
+            .longOpt("username")
+            .hasArg()
+            
.desc(ImportWALMessages.MESSAGE_TARGET_IOTDB_USERNAME_DEFAULT_ROOT_EB91453B)
+            .build());
+    options.addOption(
+        Option.builder("pw")
+            .longOpt("password")
+            .hasArg()
+            .desc(
+                ImportWALMessages
+                    
.MESSAGE_TARGET_IOTDB_PASSWORD_PROMPTED_INTERACTIVELY_IF_OMITTED_29681961)
+            .build());
+    options.addOption(
+        Option.builder("db")
+            .longOpt("database")
+            .hasArg()
+            
.desc(ImportWALMessages.MESSAGE_TARGET_DATABASE_FOR_TABLE_MODEL_WAL_ENTRIES_27BACD1C)
+            .build());
+    options.addOption(
+        Option.builder("os")
+            .longOpt("on_success")
+            .argName("on_success")
+            .hasArg()
+            .desc(
+                ImportWALMessages
+                    
.MESSAGE_WHEN_ALL_WAL_FILES_ARE_REPLAYED_SUCCESSFULLY_DO_OPERATION_ON_SOURCE_WAL_FILES_OPTIONAL_PARAMETERS_ARE_NONE_DEFAULT_AND_DELETE_41963A66)
+            .build());
+    options.addOption(
+        Option.builder("tn")
+            .longOpt("thread_num")
+            .argName("thread_num")
+            .hasArg()
+            .desc(
+                ImportWALMessages
+                    
.MESSAGE_NUMBER_OF_THREADS_USED_TO_REPLAY_WAL_DIRECTORIES_IN_PARALLEL_DEFAULT_1_6AEF4F50)
+            .build());
+    options.addOption(
+        Option.builder()
+            .longOpt("help")
+            .desc(ImportWALMessages.MESSAGE_PRINT_THIS_HELP_MESSAGE_E800AF7A)
+            .build());
+    return options;
+  }
+
+  private static String getPassword(final CommandLine commandLine) {
+    return getPassword(commandLine, System.console());
+  }
+
+  static String getPassword(final CommandLine commandLine, final Console 
console) {
+    if (commandLine.hasOption("password")) {
+      return commandLine.getOptionValue("password");
+    }
+    if (console == null) {
+      throw new IllegalArgumentException(
+          ImportWALMessages
+              
.EXCEPTION_PASSWORD_WAS_NOT_PROVIDED_AND_INTERACTIVE_INPUT_IS_UNAVAILABLE_40F42BCD);
+    }
+    final char[] password =
+        
console.readPassword(ImportWALMessages.MESSAGE_PASSWORD_PROMPT_F2D0E794);
+    if (password == null) {
+      throw new IllegalArgumentException(
+          ImportWALMessages
+              
.EXCEPTION_PASSWORD_WAS_NOT_PROVIDED_AND_INTERACTIVE_INPUT_IS_UNAVAILABLE_40F42BCD);
+    }
+    return new String(password);
+  }
+
+  static boolean shouldDeleteSource(final String onSuccess) {
+    final String normalizedOnSuccess = onSuccess.trim();
+    if ("none".equalsIgnoreCase(normalizedOnSuccess)) {
+      return false;
+    }
+    if ("delete".equalsIgnoreCase(normalizedOnSuccess)) {
+      return true;
+    }
+    throw new IllegalArgumentException(
+        String.format(
+            ImportWALMessages
+                
.EXCEPTION_UNSUPPORTED_ON_SUCCESS_VALUE_ARG_EXPECTED_NONE_OR_DELETE_F1C8EACE,
+            onSuccess));
+  }
+
+  private static boolean containsHelpOption(final String[] args) {
+    if (args == null) {
+      return false;
+    }
+    for (final String arg : args) {
+      if ("--help".equals(arg) || "-help".equals(arg)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private static void printHelp(final Options options, final PrintStream 
stream) {
+    final HelpFormatter formatter = new HelpFormatter();
+    formatter.setWidth(120);
+    formatter.printHelp(
+        new PrintWriter(stream, true),
+        120,
+        ImportWALMessages.MESSAGE_IMPORT_WAL_5E42804E,
+        null,
+        options,
+        2,
+        2,
+        null,
+        true);
+  }
+
+  private static int parsePort(final String port) {
+    try {
+      final int value = Integer.parseInt(port);
+      if (value <= 0 || value > 65535) {
+        throw new NumberFormatException(port);
+      }
+      return value;
+    } catch (final NumberFormatException e) {
+      throw new IllegalArgumentException(
+          String.format(ImportWALMessages.EXCEPTION_INVALID_PORT_ARG_A7CDD5AC, 
port), e);
+    }
+  }
+
+  static int parseThreadNum(final String threadNum) {
+    try {
+      final int value = Integer.parseInt(threadNum);
+      if (value <= 0) {
+        throw new NumberFormatException(threadNum);
+      }
+      return value;
+    } catch (final NumberFormatException e) {
+      throw new IllegalArgumentException(
+          String.format(
+              ImportWALMessages
+                  
.EXCEPTION_INVALID_THREAD_COUNT_ARG_EXPECTED_A_POSITIVE_INTEGER_F3AE2CFD,
+              threadNum),
+          e);
+    }
+  }
+
+  private static Session createSession(
+      final String host,
+      final int port,
+      final String username,
+      final String password,
+      final String database) {
+    final Session.Builder builder =
+        new 
Session.Builder().host(host).port(port).username(username).password(password);
+    if (database != null) {
+      builder.sqlDialect("table").database(database);
+    }
+    return builder.build();
+  }
+
+  private static WALReplayWorker createWALReplayWorker(
+      final String host,
+      final int port,
+      final String username,
+      final String password,
+      final String database,
+      final WALReplayer.ReplayDecisionController replayDecisionController)
+      throws IOException {
+    final Session treeSession = createSession(host, port, username, password, 
null);
+    final Session tableSession =
+        database == null ? null : createSession(host, port, username, 
password, database);
+    try {
+      treeSession.open(false);
+      if (tableSession != null) {
+        tableSession.open(false);
+      }
+      return new SessionWALReplayer(treeSession, tableSession, database, 
replayDecisionController);
+    } catch (final IoTDBConnectionException e) {
+      closeSession(tableSession);
+      closeSession(treeSession);
+      throw new IOException(e.getMessage(), e);
+    }
+  }
+
+  private static void closeSession(final Session session) {
+    if (session == null) {
+      return;
+    }
+    try {
+      session.close();
+    } catch (final IoTDBConnectionException ignored) {
+      // The import result has already been determined; closing failure must 
not hide it.
+    }
+  }
+
+  static List<Path> collectWALFiles(final Path source) throws IOException {
+    if (!Files.exists(source)) {
+      throw new IOException(
+          String.format(
+              
ImportWALMessages.EXCEPTION_SOURCE_PATH_DOES_NOT_EXIST_ARG_7C806CA2, source));
+    }
+    if (Files.isRegularFile(source)) {
+      if (!isWALFile(source)) {
+        throw new IOException(
+            String.format(
+                
ImportWALMessages.EXCEPTION_SOURCE_FILE_IS_NOT_A_WAL_FILE_ARG_14A43F76, 
source));
+      }
+      return List.of(source.toAbsolutePath().normalize());
+    }
+    if (!Files.isDirectory(source)) {
+      throw new IOException(
+          String.format(
+              
ImportWALMessages.EXCEPTION_SOURCE_PATH_DOES_NOT_EXIST_ARG_7C806CA2, source));
+    }
+
+    final List<Path> walFiles;
+    try (Stream<Path> stream = Files.walk(source)) {
+      walFiles =
+          stream
+              .filter(Files::isRegularFile)
+              .filter(ImportWAL::isWALFile)
+              .map(path -> path.toAbsolutePath().normalize())
+              .sorted(WAL_FILE_COMPARATOR)
+              .collect(Collectors.toList());
+    }
+    if (walFiles.isEmpty()) {
+      throw new IOException(
+          
String.format(ImportWALMessages.EXCEPTION_NO_WAL_FILES_FOUND_UNDER_ARG_45F7FA22,
 source));
+    }
+    return walFiles;
+  }
+
+  private static boolean isWALFile(final Path path) {
+    return 
path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(".wal");
+  }
+
+  private static final Comparator<Path> WAL_FILE_COMPARATOR =
+      Comparator.comparing((Path path) -> Objects.toString(path.getParent(), 
""))
+          .thenComparingLong(ImportWAL::getWALVersion)
+          .thenComparing(path -> path.getFileName().toString());
+
+  private static long getWALVersion(final Path path) {
+    final String filename = path.getFileName().toString();
+    return WALFileUtils.WAL_FILE_NAME_PATTERN.matcher(filename).find()
+        ? WALFileUtils.parseVersionId(filename)
+        : Long.MAX_VALUE;
+  }
+
+  static ReplayStatistics replayWALFiles(final List<Path> walFiles, final 
WALReplayer replayer)
+      throws IOException {
+    return replayWALFiles(walFiles, replayer, null);
+  }
+
+  static ReplayStatistics replayWALFiles(
+      final List<Path> walFiles, final WALReplayer replayer, final PrintStream 
progressStream)
+      throws IOException {
+    return replayWALFiles(walFiles, replayer, progressStream, false);
+  }
+
+  static ReplayStatistics replayWALFiles(
+      final List<Path> walFiles,
+      final WALReplayer replayer,
+      final PrintStream progressStream,
+      final boolean deleteSource)
+      throws IOException {
+    final long startNanos = System.nanoTime();
+    final ReplayStatistics statistics = createReplayStatistics(walFiles);
+    for (final Path walFile : walFiles) {
+      recordCompletedFile(
+          statistics,
+          replayWALFile(walFile, replayer),
+          walFiles.size(),
+          startNanos,
+          progressStream);
+    }
+    if (deleteSource) {

Review Comment:
   [P1] Do not delete source WALs when replay skipped entries
   
   --on_success delete is applied solely based on the absence of a replay 
exception. However, WALReplayer.replay() returns false for SKIP/SKIP_ALL on 
tree-model deletes and unsupported entries (lines 768-781), and replayWALFile() 
only increments skippedEntryCount while still marking the file completed. 
Consequently, choosing s/l with --on_success delete reaches this block (the 
parallel path at line 554 has the same issue) and deletes the WAL containing 
the skipped operation, even though the command reports success. Please retain 
any source file that contains a skipped data entry (while distinguishing 
control entries such as signals), rather than treating no exception as a fully 
successful replay.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to