This is an automated email from the ASF dual-hosted git repository.

keith-turner pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/accumulo.git


The following commit(s) were added to refs/heads/main by this push:
     new 5306f8ef53 enables in place bulk imports (#6681)
5306f8ef53 is described below

commit 5306f8ef537a1bd778db3760af170b6593225322
Author: Keith Turner <[email protected]>
AuthorDate: Mon Nov 30 11:23:59 2026 -0500

    enables in place bulk imports (#6681)
    
    Bulk import operations usually move files to a new name and directory.
    These changes allow optionally leaving bulk imported files in place.
---
 .../java/org/apache/accumulo/core/Constants.java   |   1 +
 .../core/client/admin/TableOperations.java         |  59 +++++++-
 .../core/clientImpl/TableOperationsImpl.java       |   7 +
 .../accumulo/core/clientImpl/bulk/BulkImport.java  |  11 +-
 .../core/clientImpl/bulk/BulkSerialize.java        |   8 +-
 .../core/metadata/schema/MetadataSchema.java       |  24 +++
 .../org/apache/accumulo/core/util/ColumnFQ.java    |   9 ++
 .../core/clientImpl/bulk/BulkSerializeTest.java    |   2 +-
 .../main/java/org/apache/accumulo/gc/GCRun.java    |  22 +++
 .../java/org/apache/accumulo/gc/GcCandidates.java  |  30 ++--
 .../accumulo/manager/FateServiceHandler.java       |  17 ++-
 .../manager/tableOps/bulkVer2/BulkInfo.java        |   5 +-
 .../tableOps/bulkVer2/ComputeBulkRange.java        |   6 +-
 .../manager/tableOps/bulkVer2/LoadFiles.java       |   4 +-
 .../manager/tableOps/bulkVer2/PrepBulkImport.java  |  58 +++----
 .../tableOps/bulkVer2/ReserveExternalDir.java      | 133 ++++++++++++++++
 .../shell/commands/ImportDirectoryCommand.java     |  12 +-
 .../shell/commands/ImportDirectoryCommandTest.java |   4 +
 .../apache/accumulo/test/functional/BulkNewIT.java | 167 +++++++++++++++++++++
 19 files changed, 526 insertions(+), 53 deletions(-)

diff --git a/core/src/main/java/org/apache/accumulo/core/Constants.java 
b/core/src/main/java/org/apache/accumulo/core/Constants.java
index 727ed903ea..5c31233180 100644
--- a/core/src/main/java/org/apache/accumulo/core/Constants.java
+++ b/core/src/main/java/org/apache/accumulo/core/Constants.java
@@ -101,6 +101,7 @@ public class Constants {
   public static final String ZTEST_LOCK = "/test/lock";
 
   public static final String BULK_PREFIX = "b-";
+  public static final String BULK_EXT_PREFIX = "be-";
   public static final String BULK_RENAME_FILE = "renames.json";
   public static final String BULK_LOAD_MAPPING = "loadmap.json";
   public static final String BULK_WORKING_PREFIX = "accumulo-bulk-";
diff --git 
a/core/src/main/java/org/apache/accumulo/core/client/admin/TableOperations.java 
b/core/src/main/java/org/apache/accumulo/core/client/admin/TableOperations.java
index 3b77a03f61..0d331ceac4 100644
--- 
a/core/src/main/java/org/apache/accumulo/core/client/admin/TableOperations.java
+++ 
b/core/src/main/java/org/apache/accumulo/core/client/admin/TableOperations.java
@@ -32,6 +32,7 @@ import java.util.function.Consumer;
 import java.util.function.Predicate;
 import java.util.stream.Stream;
 
+import org.apache.accumulo.core.client.AccumuloClient;
 import org.apache.accumulo.core.client.AccumuloException;
 import org.apache.accumulo.core.client.AccumuloSecurityException;
 import org.apache.accumulo.core.client.IteratorSetting;
@@ -646,14 +647,57 @@ public interface TableOperations {
      * @param value override the time values in the input files, and use the 
current time for all
      *        mutations
      */
-    ImportMappingOptions tableTime(boolean value);
+    ImportOptions tableTime(boolean value);
 
     /**
      * Ignores empty bulk import source directory, rather than throwing an 
IllegalArgumentException.
      *
      * @since 2.1.0
      */
-    ImportMappingOptions ignoreEmptyDir(boolean ignore);
+    ImportOptions ignoreEmptyDir(boolean ignore);
+
+    /**
+     * Avoids moving and renaming the files from the source directory where 
they are bulk imported
+     * from. The files will be used by Accumulo directly from their current 
location and Accumulo
+     * will assume ownership of the files and manage them. Users should not 
delete, rename, or
+     * modify the files after the bulk import operation. Accumulo will delete 
the files when it no
+     * longer references them. When the directory is empty, Accumulo will 
delete it. If the
+     * directory was populated by a map reduce job it may put informational 
files there like
+     * {@code _SUCCESS}, these files should be removed prior to bulk import as 
they will eventually
+     * prevent deletion of the directory. The directory should only have 
imported rfiles in it,
+     * otherwise it can not be deleted after all imported rfiles are deleted.
+     *
+     * <p>
+     * This option defaults to false and will move files by default unless set 
to true.
+     *
+     * <p>
+     * When using this, the directory containing the files must be named by 
calling
+     * {@link #allocateBulkDirectory()}. An allocated bulk directory name can 
only be used for one
+     * bulk import operation, attempting to reuse it will fail.
+     *
+     * <pre>
+     * {@code
+     * // Example of how to properly use this API
+     * void bulkImport(AccumuloClient client, String tableName) {
+     *
+     *   String bulkDir = client.tableOperations().allocateBulkDirectory();
+     *
+     *   // The path must end with bulkDir
+     *   String bulkPath = "hdfs://nn1/whatever/you/want/" + bulkDir;
+     *
+     *   // TODO create some rfiles and place them in bulkPath
+     *   // TODO remove any extraneous files from bulkPath
+     *
+     *   
client.tableOperations().importDirectory(bulkPath).to(tableName).useFilesInPlace(true)
+     *       .load();
+     * }
+     *
+     * }
+     * </pre>
+     *
+     * @since 4.0.0
+     */
+    ImportOptions useFilesInPlace(boolean inPlace);
 
     /**
      * Loads the files into the table.
@@ -739,6 +783,17 @@ public interface TableOperations {
     throw new UnsupportedOperationException();
   }
 
+  /**
+   * When bulk importing files and leaving them in place (not moving them), 
the files must be in a
+   * directory named by calling this method.
+   *
+   * @return a directory name to be used for bulk imports
+   * @see ImportOptions#useFilesInPlace(boolean)
+   */
+  default String allocateBulkDirectory() {
+    throw new UnsupportedOperationException();
+  }
+
   /**
    * Initiates taking a table offline, but does not wait for action to complete
    *
diff --git 
a/core/src/main/java/org/apache/accumulo/core/clientImpl/TableOperationsImpl.java
 
b/core/src/main/java/org/apache/accumulo/core/clientImpl/TableOperationsImpl.java
index 67ff4e8d94..5029029010 100644
--- 
a/core/src/main/java/org/apache/accumulo/core/clientImpl/TableOperationsImpl.java
+++ 
b/core/src/main/java/org/apache/accumulo/core/clientImpl/TableOperationsImpl.java
@@ -176,6 +176,7 @@ import org.slf4j.LoggerFactory;
 
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
 
 public class TableOperationsImpl extends TableOperationsHelper {
 
@@ -2177,6 +2178,12 @@ public class TableOperationsImpl extends 
TableOperationsHelper {
     return new BulkImport(directory, context);
   }
 
+  @Override
+  public String allocateBulkDirectory() {
+    return Constants.BULK_EXT_PREFIX
+        + 
Strings.padStart(Long.toString(RANDOM.get().nextLong(Long.MAX_VALUE), 36), 13, 
'0');
+  }
+
   @Override
   public TimeType getTimeType(final String tableName) throws 
TableNotFoundException {
     TableId tableId = context.getTableId(tableName);
diff --git 
a/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkImport.java 
b/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkImport.java
index 75d1020a74..049b4ff3e1 100644
--- 
a/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkImport.java
+++ 
b/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkImport.java
@@ -55,6 +55,7 @@ import org.apache.accumulo.core.Constants;
 import org.apache.accumulo.core.client.AccumuloException;
 import org.apache.accumulo.core.client.AccumuloSecurityException;
 import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.client.admin.TableOperations;
 import 
org.apache.accumulo.core.client.admin.TableOperations.ImportDestinationArguments;
 import 
org.apache.accumulo.core.client.admin.TableOperations.ImportMappingOptions;
 import org.apache.accumulo.core.clientImpl.AccumuloBulkMergeException;
@@ -102,6 +103,7 @@ public class BulkImport implements 
ImportDestinationArguments, ImportMappingOpti
   private Executor executor = null;
   private final String dir;
   private int numThreads = -1;
+  private boolean useFilesInPlace = false;
 
   private final ClientContext context;
   private String tableName;
@@ -125,6 +127,12 @@ public class BulkImport implements 
ImportDestinationArguments, ImportMappingOpti
     return this;
   }
 
+  @Override
+  public TableOperations.ImportOptions useFilesInPlace(boolean inPlace) {
+    this.useFilesInPlace = inPlace;
+    return this;
+  }
+
   @Override
   public void load()
       throws TableNotFoundException, IOException, AccumuloException, 
AccumuloSecurityException {
@@ -171,7 +179,8 @@ public class BulkImport implements 
ImportDestinationArguments, ImportMappingOpti
 
       List<ByteBuffer> args = 
Arrays.asList(ByteBuffer.wrap(tableId.canonical().getBytes(UTF_8)),
           ByteBuffer.wrap(srcPath.toString().getBytes(UTF_8)),
-          ByteBuffer.wrap((setTime + "").getBytes(UTF_8)));
+          ByteBuffer.wrap((setTime + "").getBytes(UTF_8)),
+          ByteBuffer.wrap((useFilesInPlace + "").getBytes(UTF_8)));
       try {
         tableOps.doBulkFateOperation(args, tableName);
         shouldRetry = false;
diff --git 
a/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerialize.java
 
b/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerialize.java
index 533a43c237..a5f045d33d 100644
--- 
a/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerialize.java
+++ 
b/core/src/main/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerialize.java
@@ -122,10 +122,12 @@ public class BulkSerialize {
    * by BulkImportMove
    */
   public static LoadMappingIterator getUpdatedLoadMapping(String bulkDir, 
TableId tableId,
-      Input input) throws IOException {
-    Map<String,String> renames = readRenameMap(bulkDir, input);
+      Input input, boolean useFilesInPlace) throws IOException {
     LoadMappingIterator lmi = readLoadMapping(bulkDir, tableId, input);
-    lmi.setRenameMap(renames);
+    if (!useFilesInPlace) {
+      Map<String,String> renames = readRenameMap(bulkDir, input);
+      lmi.setRenameMap(renames);
+    }
     return lmi;
   }
 }
diff --git 
a/core/src/main/java/org/apache/accumulo/core/metadata/schema/MetadataSchema.java
 
b/core/src/main/java/org/apache/accumulo/core/metadata/schema/MetadataSchema.java
index e3f2863249..349e769898 100644
--- 
a/core/src/main/java/org/apache/accumulo/core/metadata/schema/MetadataSchema.java
+++ 
b/core/src/main/java/org/apache/accumulo/core/metadata/schema/MetadataSchema.java
@@ -624,6 +624,30 @@ public class MetadataSchema {
 
   }
 
+  /**
+   * Holds names of bulk external directories that are reserved
+   */
+  public static class BulkExtDirSection {
+    private static final Section section =
+        new Section(RESERVED_PREFIX + "bedr", true, RESERVED_PREFIX + "beds", 
false);
+
+    public static Range getRange() {
+      return section.getRange();
+    }
+
+    public static String getRowPrefix() {
+      return section.getRowPrefix();
+    }
+
+    public static String prefix(String dirName) {
+      Preconditions.checkArgument(!dirName.contains("/"));
+      return getRowPrefix() + dirName;
+    }
+
+    public static final ColumnFQ ID_COL = new ColumnFQ(new Text("fate"), new 
Text("id"));
+
+  }
+
   /**
    * Holds information about compactions that were deleted from tablets 
metadata by split or merge
    * operations. These may still be running and may have tmp files that need 
to be cleaned up.
diff --git a/core/src/main/java/org/apache/accumulo/core/util/ColumnFQ.java 
b/core/src/main/java/org/apache/accumulo/core/util/ColumnFQ.java
index 6a938f4570..d95f32ba20 100644
--- a/core/src/main/java/org/apache/accumulo/core/util/ColumnFQ.java
+++ b/core/src/main/java/org/apache/accumulo/core/util/ColumnFQ.java
@@ -20,6 +20,7 @@ package org.apache.accumulo.core.util;
 
 import org.apache.accumulo.core.client.ScannerBase;
 import org.apache.accumulo.core.data.Column;
+import org.apache.accumulo.core.data.Condition;
 import org.apache.accumulo.core.data.Key;
 import org.apache.accumulo.core.data.Mutation;
 import org.apache.accumulo.core.data.Value;
@@ -66,10 +67,18 @@ public class ColumnFQ implements Comparable<ColumnFQ> {
     m.put(colf, colq, v);
   }
 
+  public void put(Mutation m, String s) {
+    put(m, new Value(s));
+  }
+
   public void putDelete(Mutation m) {
     m.putDelete(colf, colq);
   }
 
+  public Condition newCondition() {
+    return new Condition(colf, colq);
+  }
+
   @Override
   public boolean equals(Object o) {
     if (!(o instanceof ColumnFQ ocfq)) {
diff --git 
a/core/src/test/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerializeTest.java
 
b/core/src/test/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerializeTest.java
index f5eb76b914..328648de48 100644
--- 
a/core/src/test/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerializeTest.java
+++ 
b/core/src/test/java/org/apache/accumulo/core/clientImpl/bulk/BulkSerializeTest.java
@@ -112,7 +112,7 @@ public class BulkSerializeTest {
     };
 
     try (LoadMappingIterator lmi =
-        BulkSerialize.getUpdatedLoadMapping("/some/dir", tableId, input)) {
+        BulkSerialize.getUpdatedLoadMapping("/some/dir", tableId, input, 
false)) {
       SortedMap<KeyExtent,Bulk.Files> actual = new TreeMap<>();
       lmi.forEachRemaining(e -> actual.put(e.getKey(), e.getValue()));
       assertEquals(newNameMapping, actual);
diff --git a/server/gc/src/main/java/org/apache/accumulo/gc/GCRun.java 
b/server/gc/src/main/java/org/apache/accumulo/gc/GCRun.java
index 8ae528ddfd..dbab5ad3da 100644
--- a/server/gc/src/main/java/org/apache/accumulo/gc/GCRun.java
+++ b/server/gc/src/main/java/org/apache/accumulo/gc/GCRun.java
@@ -47,9 +47,11 @@ import java.util.stream.Stream;
 
 import org.apache.accumulo.core.Constants;
 import org.apache.accumulo.core.client.IsolatedScanner;
+import org.apache.accumulo.core.client.MutationsRejectedException;
 import org.apache.accumulo.core.client.TableNotFoundException;
 import org.apache.accumulo.core.conf.AccumuloConfiguration;
 import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.data.Mutation;
 import org.apache.accumulo.core.data.TableId;
 import org.apache.accumulo.core.fate.zookeeper.ZooReader;
 import org.apache.accumulo.core.fate.zookeeper.ZooUtil;
@@ -132,6 +134,26 @@ public class GCRun implements GarbageCollectionEnvironment 
{
 
     log.info("Batch {} attempting to delete {} gcCandidates of type {} from 
metadata",
         batchCount.get(), gcCandidates.size(), type);
+
+    // Delete bulk ext dir name reservations before deleting candidates so 
that in failure case they
+    // will still be deleted.
+    if (level == DataLevel.USER && type == GcCandidateType.VALID) {
+      try (var writer = 
context.createBatchWriter(SystemTables.METADATA.tableName())) {
+        for (var candidate : gcCandidates) {
+          if (candidate.getType() == GcCandidate.Type.BULK_DIR) {
+            var dirName = new Path(candidate.getPath()).getName();
+            if (dirName.startsWith(Constants.BULK_EXT_PREFIX)) {
+              Mutation m = new 
Mutation(MetadataSchema.BulkExtDirSection.prefix(dirName));
+              MetadataSchema.BulkExtDirSection.ID_COL.putDelete(m);
+              writer.addMutation(m);
+            }
+          }
+        }
+      } catch (TableNotFoundException | MutationsRejectedException e) {
+        throw new IllegalStateException(e);
+      }
+    }
+
     context.getAmple().deleteGcCandidates(level, gcCandidates, type);
   }
 
diff --git a/server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java 
b/server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java
index d57280a468..d77b6102e7 100644
--- a/server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java
+++ b/server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java
@@ -18,6 +18,7 @@
  */
 package org.apache.accumulo.gc;
 
+import static org.apache.accumulo.core.Constants.BULK_EXT_PREFIX;
 import static org.apache.accumulo.core.Constants.BULK_PREFIX;
 import static org.apache.accumulo.core.Constants.CLONE_PREFIX;
 import static 
org.apache.accumulo.core.Constants.GENERATED_TABLET_DIRECTORY_PREFIX;
@@ -66,8 +67,8 @@ import com.google.common.collect.Iterators;
  * <li>All file paths generated by Accumulo will include a table id. If users 
are allowed to
  * generate file names for bulk import, then those paths would not include a 
table id.</li>
  * <li>Tablet directories either have a {@code t-} prefix or are named {@code 
default_tablet}</li>
- * <li>Bulk directories will have a {@code b-} prefix. If users are allowed to 
generate file names
- * for bulk import, it would be best for this code enforce another prefix like 
{@code be-}</li>
+ * <li>Bulk directories will have a {@code b-} prefix. Users generated file 
names for bulk import
+ * will be in a globally unique directory name with the prefix {@code be-}</li>
  * </ul>
  *
  * <p>
@@ -91,10 +92,7 @@ import com.google.common.collect.Iterators;
  *
  * <p>
  * When matching table deletion candidates, bulk and tablet directories are 
considered. User
- * generated bulk paths are not expected to have a table id, but if they did 
this could cause a
- * match that prevents deleting an empty table directory. As simple solution 
to this would be to
- * give user generated bulk directories a different prefix like {@code be-}, 
then those need not be
- * considered for matching.
+ * generated bulk paths are not expected to have a table id and are not 
considered.
  */
 public class GcCandidates extends AbstractCollection<GcCandidate> {
 
@@ -166,8 +164,8 @@ public class GcCandidates extends 
AbstractCollection<GcCandidate> {
           }
           case BULK_DIR -> {
             var lastThree = lastThree(candidate.getPath(), 1);
-            Preconditions.checkArgument(isBulkDir(lastThree.name), "Not a bulk 
dir %s",
-                lastThree.name);
+            Preconditions.checkArgument(isBulkDir(lastThree.name) || 
isBulkExtDir(lastThree.name),
+                "Not a bulk dir %s", lastThree.name);
             bulkDirCandidates.put(lastThree.name, candidate);
           }
           case TABLE_DIR -> {
@@ -213,6 +211,10 @@ public class GcCandidates extends 
AbstractCollection<GcCandidate> {
     return dirName.startsWith(BULK_PREFIX);
   }
 
+  private static boolean isBulkExtDir(String dirName) {
+    return dirName.startsWith(BULK_EXT_PREFIX);
+  }
+
   private static boolean isTabletDir(String dirName) {
     return dirName.startsWith(GENERATED_TABLET_DIRECTORY_PREFIX) || 
dirName.startsWith(CLONE_PREFIX)
         || dirName.equals(DEFAULT_TABLET_DIR_NAME) || 
dirName.equals(ROOT_TABLET_DIR_NAME)
@@ -234,18 +236,24 @@ public class GcCandidates extends 
AbstractCollection<GcCandidate> {
       
nonNullConsumer.accept(tableDirCandidates.remove(reference.getTableId().toString()));
     } else {
       var lastThree = lastThree(reference.getMetadataPath(), 2);
-      if (isTabletDir(lastThree.dir)) {
+      final boolean isTabletDir = isTabletDir(lastThree.dir);
+      final boolean isBulkDir = isBulkDir(lastThree.dir);
+      final boolean isBulkExtDir = isBulkExtDir(lastThree.dir);
+
+      if (isTabletDir) {
         Preconditions.checkArgument(lastThree.maybeATableId != null,
             "Path with tablet dir had no table id : %s", 
reference.getMetadataPath());
         nonNullConsumer.accept(
             tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + 
lastThree.dir));
-      } else if (isBulkDir(lastThree.dir)) {
+      } else if (isBulkDir || isBulkExtDir) {
         nonNullConsumer.accept(bulkDirCandidates.remove(lastThree.dir));
       } else {
         throw new IllegalArgumentException(
             "Unknown directory type in path: " + reference.getMetadataPath());
       }
-      if (lastThree.maybeATableId != null) {
+
+      if (isTabletDir || isBulkDir) {
+        Preconditions.checkArgument(lastThree.maybeATableId != null);
         
nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
       }
       nonNullConsumer.accept(fileCandidates.remove("/" + lastThree.dir + "/" + 
lastThree.name));
diff --git 
a/server/manager/src/main/java/org/apache/accumulo/manager/FateServiceHandler.java
 
b/server/manager/src/main/java/org/apache/accumulo/manager/FateServiceHandler.java
index e6db2aebb5..4bbfed6da7 100644
--- 
a/server/manager/src/main/java/org/apache/accumulo/manager/FateServiceHandler.java
+++ 
b/server/manager/src/main/java/org/apache/accumulo/manager/FateServiceHandler.java
@@ -73,6 +73,7 @@ import org.apache.accumulo.core.fate.Fate;
 import org.apache.accumulo.core.fate.FateId;
 import org.apache.accumulo.core.fate.FateInstanceType;
 import org.apache.accumulo.core.fate.ReadOnlyFateStore.TStatus;
+import org.apache.accumulo.core.fate.Repo;
 import org.apache.accumulo.core.fate.TraceRepo;
 import org.apache.accumulo.core.iteratorsImpl.IteratorConfigUtil;
 import org.apache.accumulo.core.manager.state.tables.TableState;
@@ -87,8 +88,10 @@ import org.apache.accumulo.core.util.Validator;
 import org.apache.accumulo.core.util.tables.TableNameUtil;
 import org.apache.accumulo.core.volume.Volume;
 import org.apache.accumulo.manager.tableOps.ChangeTableState;
+import org.apache.accumulo.manager.tableOps.FateEnv;
 import org.apache.accumulo.manager.tableOps.availability.LockTable;
 import org.apache.accumulo.manager.tableOps.bulkVer2.ComputeBulkRange;
+import org.apache.accumulo.manager.tableOps.bulkVer2.ReserveExternalDir;
 import org.apache.accumulo.manager.tableOps.clone.CloneTable;
 import org.apache.accumulo.manager.tableOps.compact.CompactRange;
 import org.apache.accumulo.manager.tableOps.compact.cancel.CancelCompactions;
@@ -649,13 +652,15 @@ class FateServiceHandler implements FateService.Iface {
       }
       case TABLE_BULK_IMPORT2: {
         TableOperation tableOp = TableOperation.BULK_IMPORT;
-        validateArgumentCount(arguments, tableOp, 3);
+        validateArgumentCount(arguments, tableOp, 4);
         final var tableId =
             validateTableIdArgument(arguments.get(0), tableOp, 
NOT_BUILTIN_TABLE_ID);
         String dir = ByteBufferUtil.toString(arguments.get(1));
 
         boolean setTime = 
Boolean.parseBoolean(ByteBufferUtil.toString(arguments.get(2)));
 
+        boolean useFilesInPlace = 
Boolean.parseBoolean(ByteBufferUtil.toString(arguments.get(3)));
+
         NamespaceId namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
 
         final boolean canBulkImport;
@@ -677,8 +682,14 @@ class FateServiceHandler implements FateService.Iface {
         }
 
         goalMessage += "Bulk import (v2)  " + dir + " to " + tableName + "(" + 
tableId + ")";
-        manager.fateClient(type).seedTransaction(op, fateId,
-            new TraceRepo<>(new ComputeBulkRange(tableId, dir, setTime)), 
autoCleanup, goalMessage);
+        Repo<FateEnv> seed;
+        if (useFilesInPlace) {
+          seed = new ReserveExternalDir(tableId, dir, setTime);
+        } else {
+          seed = new ComputeBulkRange(tableId, dir, setTime);
+        }
+        manager.fateClient(type).seedTransaction(op, fateId, new 
TraceRepo<>(seed), autoCleanup,
+            goalMessage);
         break;
       }
       case TABLE_TABLET_AVAILABILITY: {
diff --git 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/BulkInfo.java
 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/BulkInfo.java
index e96198850c..eeb4dab0fe 100644
--- 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/BulkInfo.java
+++ 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/BulkInfo.java
@@ -63,16 +63,19 @@ class BulkInfo implements Serializable {
   String sourceDir;
   String bulkDir;
   boolean setTime;
+  boolean useFilesInPlace;
   // firstSplit and lastSplit describe the min and max splits in the table 
that overlap the bulk
   // imported data
   byte[] firstSplit;
   byte[] lastSplit;
 
-  static BulkInfo create(TableId tableId, String sourceDir, boolean setTime) {
+  static BulkInfo create(TableId tableId, String sourceDir, boolean setTime,
+      boolean useFilesInPlace) {
     BulkInfo info = new BulkInfo();
     info.tableId = tableId;
     info.sourceDir = sourceDir;
     info.setTime = setTime;
+    info.useFilesInPlace = useFilesInPlace;
     return info;
   }
 }
diff --git 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/ComputeBulkRange.java
 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/ComputeBulkRange.java
index afdc169764..54464800d3 100644
--- 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/ComputeBulkRange.java
+++ 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/ComputeBulkRange.java
@@ -40,7 +40,11 @@ public class ComputeBulkRange extends 
AbstractBulkFateOperation {
   private static final Logger log = 
LoggerFactory.getLogger(ComputeBulkRange.class);
 
   public ComputeBulkRange(TableId tableId, String sourceDir, boolean setTime) {
-    super(BulkInfo.create(tableId, sourceDir, setTime));
+    super(BulkInfo.create(tableId, sourceDir, setTime, false));
+  }
+
+  ComputeBulkRange(BulkInfo bulkInfo) {
+    super(bulkInfo);
   }
 
   @Override
diff --git 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/LoadFiles.java
 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/LoadFiles.java
index 09f07b7393..3dec797bd2 100644
--- 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/LoadFiles.java
+++ 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/LoadFiles.java
@@ -104,8 +104,8 @@ class LoadFiles extends AbstractBulkFateOperation {
     log.trace("Starting for {} (tid = {})", bulkInfo.sourceDir, fateId);
     VolumeManager fs = env.getVolumeManager();
     final Path bulkDir = new Path(bulkInfo.bulkDir);
-    try (LoadMappingIterator lmi =
-        BulkSerialize.getUpdatedLoadMapping(bulkDir.toString(), 
bulkInfo.tableId, fs::open)) {
+    try (LoadMappingIterator lmi = 
BulkSerialize.getUpdatedLoadMapping(bulkDir.toString(),
+        bulkInfo.tableId, fs::open, bulkInfo.useFilesInPlace)) {
 
       Loader loader = new Loader(env, bulkInfo.tableId);
 
diff --git 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/PrepBulkImport.java
 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/PrepBulkImport.java
index d5e61d0942..573a906b61 100644
--- 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/PrepBulkImport.java
+++ 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/PrepBulkImport.java
@@ -262,37 +262,43 @@ public class PrepBulkImport extends 
AbstractBulkFateOperation {
     // now that table lock is acquired check that all splits in load mapping 
exists in table
     checkForMerge(env.getContext(), fateId);
 
-    VolumeManager fs = env.getVolumeManager();
-    final UniqueNameAllocator namer = 
env.getContext().getUniqueNameAllocator();
-    Path sourceDir = new Path(bulkInfo.sourceDir);
-    List<FileStatus> files = 
BulkImport.filterInvalid(fs.listStatus(sourceDir));
-
-    Path bulkDir = createNewBulkDir(env.getContext(), fs, bulkInfo.tableId);
-    Path mappingFile = new Path(sourceDir, Constants.BULK_LOAD_MAPPING);
-
-    Map<String,String> oldToNewNameMap = new HashMap<>();
-
-    Iterator<String> names = namer.getNextNames(files.size());
-
-    for (FileStatus file : files) {
-      // since these are only valid files we know it has an extension
-      String newName = FilePrefix.BULK_IMPORT.createFileName(
-          names.next() + "." + 
FilenameUtils.getExtension(file.getPath().getName()));
-      oldToNewNameMap.put(file.getPath().getName(), new Path(bulkDir, 
newName).getName());
-    }
+    if (bulkInfo.useFilesInPlace) {
+      bulkInfo.bulkDir = bulkInfo.sourceDir;
+      return new LoadFiles(bulkInfo);
+    } else {
+      VolumeManager fs = env.getVolumeManager();
+      final UniqueNameAllocator namer = 
env.getContext().getUniqueNameAllocator();
+      Path sourceDir = new Path(bulkInfo.sourceDir);
+      List<FileStatus> files = 
BulkImport.filterInvalid(fs.listStatus(sourceDir));
+
+      Path bulkDir = createNewBulkDir(env.getContext(), fs, bulkInfo.tableId);
+      Path mappingFile = new Path(sourceDir, Constants.BULK_LOAD_MAPPING);
+
+      Map<String,String> oldToNewNameMap = new HashMap<>();
+
+      Iterator<String> names = namer.getNextNames(files.size());
+
+      for (FileStatus file : files) {
+        // since these are only valid files we know it has an extension
+        String newName = FilePrefix.BULK_IMPORT.createFileName(
+            names.next() + "." + 
FilenameUtils.getExtension(file.getPath().getName()));
+        oldToNewNameMap.put(file.getPath().getName(), new Path(bulkDir, 
newName).getName());
+      }
 
-    // also have to move mapping file
-    oldToNewNameMap.put(mappingFile.getName(), new Path(bulkDir, 
mappingFile.getName()).getName());
+      // also have to move mapping file
+      oldToNewNameMap.put(mappingFile.getName(),
+          new Path(bulkDir, mappingFile.getName()).getName());
 
-    BulkSerialize.writeRenameMap(oldToNewNameMap, bulkDir.toString(), 
fs::create);
+      BulkSerialize.writeRenameMap(oldToNewNameMap, bulkDir.toString(), 
fs::create);
 
-    bulkInfo.bulkDir = bulkDir.toString();
+      bulkInfo.bulkDir = bulkDir.toString();
 
-    BulkLogger.initiating(fateId, bulkInfo.tableId, bulkInfo.setTime, 
bulkInfo.sourceDir,
-        bulkInfo.bulkDir);
+      BulkLogger.initiating(fateId, bulkInfo.tableId, bulkInfo.setTime, 
bulkInfo.sourceDir,
+          bulkInfo.bulkDir);
 
-    // return the next step, which will move files
-    return new BulkImportMove(bulkInfo);
+      // return the next step, which will move files
+      return new BulkImportMove(bulkInfo);
+    }
   }
 
   private Path createNewBulkDir(ServerContext context, VolumeManager fs, 
TableId tableId)
diff --git 
a/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/ReserveExternalDir.java
 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/ReserveExternalDir.java
new file mode 100644
index 0000000000..da42670c8a
--- /dev/null
+++ 
b/server/manager/src/main/java/org/apache/accumulo/manager/tableOps/bulkVer2/ReserveExternalDir.java
@@ -0,0 +1,133 @@
+/*
+ * 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
+ *
+ *   https://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.accumulo.manager.tableOps.bulkVer2;
+
+import static 
org.apache.accumulo.core.client.ConditionalWriter.Status.ACCEPTED;
+import static 
org.apache.accumulo.core.client.ConditionalWriter.Status.REJECTED;
+import static 
org.apache.accumulo.core.metadata.schema.MetadataSchema.BulkExtDirSection.ID_COL;
+
+import java.util.regex.Pattern;
+
+import org.apache.accumulo.core.Constants;
+import 
org.apache.accumulo.core.clientImpl.AcceptableThriftTableOperationException;
+import org.apache.accumulo.core.clientImpl.thrift.TableOperation;
+import org.apache.accumulo.core.clientImpl.thrift.TableOperationExceptionType;
+import 
org.apache.accumulo.core.clientImpl.thrift.ThriftTableOperationException;
+import org.apache.accumulo.core.data.ConditionalMutation;
+import org.apache.accumulo.core.data.Range;
+import org.apache.accumulo.core.data.TableId;
+import org.apache.accumulo.core.fate.FateId;
+import org.apache.accumulo.core.fate.Repo;
+import org.apache.accumulo.core.metadata.SystemTables;
+import org.apache.accumulo.core.metadata.schema.MetadataSchema;
+import org.apache.accumulo.core.security.Authorizations;
+import org.apache.accumulo.manager.tableOps.FateEnv;
+import org.apache.accumulo.server.util.bulkCommand.ListBulk;
+import org.apache.hadoop.fs.Path;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+
+public class ReserveExternalDir extends AbstractBulkFateOperation {
+  private static final long serialVersionUID = 1L;
+
+  private static final Logger log = 
LoggerFactory.getLogger(ReserveExternalDir.class);
+
+  private static final Pattern BULK_EXTERNAL_PATTERN =
+      Pattern.compile(Constants.BULK_EXT_PREFIX + "[0-9a-z]{13}");
+
+  public ReserveExternalDir(TableId tableId, String sourceDir, boolean setTime)
+      throws ThriftTableOperationException {
+    super(BulkInfo.create(tableId, sourceDir, setTime, true));
+    Preconditions.checkArgument(!SystemTables.containsTableId(tableId));
+    if (!BULK_EXTERNAL_PATTERN.matcher(new 
Path(sourceDir).getName()).matches()) {
+      throw new ThriftTableOperationException(tableId.canonical(), null, 
TableOperation.IMPORT,
+          TableOperationExceptionType.OTHER,
+          "Unacceptable bulk directory name. Ensure directory names are 
allocated using the Accumulo API.");
+    }
+
+  }
+
+  private boolean reserveDirectoryName(FateId fateId, FateEnv environment) 
throws Exception {
+
+    var bulkDirName = new Path(bulkInfo.sourceDir).getName();
+    var row = MetadataSchema.BulkExtDirSection.prefix(bulkDirName);
+
+    ConditionalMutation cm = new ConditionalMutation(row);
+    // add a condition requiring the column does not exist
+    cm.addCondition(ID_COL.newCondition());
+    ID_COL.put(cm, fateId.canonical());
+    var result = 
environment.getContext().getSharedUserWriter().get().write(cm);
+    if (result.getStatus() == ACCEPTED) {
+      return true;
+    }
+
+    try (var scanner = 
environment.getContext().createScanner(SystemTables.METADATA.tableName(),
+        Authorizations.EMPTY)) {
+      scanner.setRange(Range.exact(row));
+      ID_COL.fetch(scanner);
+      var iterator = scanner.iterator();
+      if (iterator.hasNext()) {
+        var entry = iterator.next();
+        // When this code runs a second time, in the case of failure, the 
column will exist. If our
+        // fate id is set on the column, then we reserved it.
+        return entry.getValue().toString().equals(fateId.canonical());
+      } else {
+        return reserveDirectoryName(fateId, environment);
+      }
+    }
+  }
+
+  @Override
+  public Repo<FateEnv> call(FateId fateId, FateEnv environment) throws 
Exception {
+    if (reserveDirectoryName(fateId, environment)) {
+      return new ComputeBulkRange(bulkInfo);
+    } else {
+      throw new 
AcceptableThriftTableOperationException(bulkInfo.tableId.canonical(), null,
+          TableOperation.IMPORT, TableOperationExceptionType.OTHER,
+          "Bulk directory name was used by a previous bulk import operation.");
+    }
+  }
+
+  @Override
+  public void undo(FateId fateId, FateEnv environment) throws Exception {
+    var bulkDirName = new Path(bulkInfo.sourceDir).getName();
+    var row = MetadataSchema.BulkExtDirSection.prefix(bulkDirName);
+
+    ConditionalMutation cm = new ConditionalMutation(row);
+    // only delete the reservation if our fate id is set for the value
+    cm.addCondition(ID_COL.newCondition().setValue(fateId.canonical()));
+    ID_COL.putDelete(cm);
+    var result = 
environment.getContext().getSharedUserWriter().get().write(cm);
+
+    // The rejected case can occur for two reason, first when this code runs a 
second time for the
+    // same fate id, second when another fate id held the reservation.
+    if (result.getStatus() != ACCEPTED && result.getStatus() != REJECTED) {
+      log.warn("Failed to delete bulk dir reservation: {} {} {}", fateId, 
bulkDirName,
+          result.getStatus());
+    }
+  }
+
+  @Override
+  public ListBulk.BulkState getState() {
+    return ListBulk.BulkState.PREPARING;
+  }
+
+}
diff --git 
a/shell/src/main/java/org/apache/accumulo/shell/commands/ImportDirectoryCommand.java
 
b/shell/src/main/java/org/apache/accumulo/shell/commands/ImportDirectoryCommand.java
index 07015e68b2..e22d372dd2 100644
--- 
a/shell/src/main/java/org/apache/accumulo/shell/commands/ImportDirectoryCommand.java
+++ 
b/shell/src/main/java/org/apache/accumulo/shell/commands/ImportDirectoryCommand.java
@@ -29,10 +29,13 @@ import org.apache.accumulo.shell.Shell;
 import org.apache.accumulo.shell.Shell.Command;
 import org.apache.accumulo.shell.Token;
 import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
 import org.apache.commons.cli.Options;
 
 public class ImportDirectoryCommand extends Command {
 
+  private static final char IN_PLACE_OPT = 'p';
+
   @Override
   public String description() {
     return "bulk imports an entire directory of data files into an existing 
table."
@@ -56,7 +59,8 @@ public class ImportDirectoryCommand extends Command {
     boolean setTime = Boolean.parseBoolean(cl.getArgs()[1]);
     int status = 0;
     
shellState.getAccumuloClient().tableOperations().importDirectory(dir).to(tableName)
-        .tableTime(setTime).ignoreEmptyDir(ignore).load();
+        
.tableTime(setTime).ignoreEmptyDir(ignore).useFilesInPlace(cl.hasOption(IN_PLACE_OPT))
+        .load();
     return status;
   }
 
@@ -75,6 +79,11 @@ public class ImportDirectoryCommand extends Command {
     final Options opts = super.getOptions();
     opts.addOption(OptUtil.tableOpt("name of the table to import files into"));
     opts.addOption(OptUtil.ignoreEmptyDirOpt("ignore empty bulk import source 
directory"));
+
+    final Option inPlaceOpt =
+        new Option(IN_PLACE_OPT + "", "in-place", false, "import files in 
place avoiding move");
+    inPlaceOpt.setRequired(false);
+    opts.addOption(inPlaceOpt);
     return opts;
   }
 
@@ -83,5 +92,4 @@ public class ImportDirectoryCommand extends Command {
       final Map<CompletionSet,Set<String>> completionSet) {
     registerCompletionForTables(root, completionSet);
   }
-
 }
diff --git 
a/shell/src/test/java/org/apache/accumulo/shell/commands/ImportDirectoryCommandTest.java
 
b/shell/src/test/java/org/apache/accumulo/shell/commands/ImportDirectoryCommandTest.java
index 9826878bb5..273ecf8aaa 100644
--- 
a/shell/src/test/java/org/apache/accumulo/shell/commands/ImportDirectoryCommandTest.java
+++ 
b/shell/src/test/java/org/apache/accumulo/shell/commands/ImportDirectoryCommandTest.java
@@ -76,6 +76,7 @@ public class ImportDirectoryCommandTest {
     expect(cli.hasOption("t")).andReturn(false).once();
     // no -i option supplied
     expect(cli.hasOption("i")).andReturn(false).once();
+    expect(cli.hasOption('p')).andReturn(false).once();
     expect(shellState.getTableName()).andReturn("tablename").once();
 
     expect(cli.getArgs()).andReturn(cliArgs).atLeastOnce();
@@ -89,6 +90,7 @@ public class ImportDirectoryCommandTest {
     expect(bulkImport.to("tablename")).andReturn(bulkImport).once();
     expect(bulkImport.tableTime(false)).andReturn(bulkImport).once();
     expect(bulkImport.ignoreEmptyDir(false)).andReturn(bulkImport).once();
+    expect(bulkImport.useFilesInPlace(false)).andReturn(bulkImport).once();
     bulkImport.load();
     expectLastCall().once();
 
@@ -109,6 +111,7 @@ public class ImportDirectoryCommandTest {
     expect(cli.hasOption("i")).andReturn(true).once();
     // -t option specified, table is from option
     expect(cli.hasOption("t")).andReturn(true).once();
+    expect(cli.hasOption('p')).andReturn(false).once();
     expect(cli.getOptionValue("t")).andReturn("passedName").once();
     expect(tableOperations.exists("passedName")).andReturn(true).once();
 
@@ -122,6 +125,7 @@ public class ImportDirectoryCommandTest {
     expect(bulkImport.to("passedName")).andReturn(bulkImport).once();
     expect(bulkImport.tableTime(false)).andReturn(bulkImport).once();
     expect(bulkImport.ignoreEmptyDir(true)).andReturn(bulkImport).once();
+    expect(bulkImport.useFilesInPlace(false)).andReturn(bulkImport).once();
     bulkImport.load();
     expectLastCall().once();
 
diff --git 
a/test/src/main/java/org/apache/accumulo/test/functional/BulkNewIT.java 
b/test/src/main/java/org/apache/accumulo/test/functional/BulkNewIT.java
index 474b8edc11..7e22e5b825 100644
--- a/test/src/main/java/org/apache/accumulo/test/functional/BulkNewIT.java
+++ b/test/src/main/java/org/apache/accumulo/test/functional/BulkNewIT.java
@@ -19,6 +19,7 @@
 package org.apache.accumulo.test.functional;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
+import static 
org.apache.accumulo.core.metadata.schema.MetadataSchema.BulkExtDirSection.ID_COL;
 import static 
org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType.FILES;
 import static 
org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType.LOADED;
 import static 
org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType.PREV_ROW;
@@ -28,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.math.BigInteger;
@@ -45,6 +47,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.Optional;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
@@ -60,6 +63,7 @@ import java.util.function.Predicate;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
+import org.apache.accumulo.core.Constants;
 import org.apache.accumulo.core.client.Accumulo;
 import org.apache.accumulo.core.client.AccumuloClient;
 import org.apache.accumulo.core.client.AccumuloException;
@@ -68,6 +72,7 @@ import 
org.apache.accumulo.core.client.MutationsRejectedException;
 import org.apache.accumulo.core.client.Scanner;
 import org.apache.accumulo.core.client.ScannerBase;
 import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.client.admin.CloneConfiguration;
 import org.apache.accumulo.core.client.admin.CompactionConfig;
 import org.apache.accumulo.core.client.admin.NewTableConfiguration;
 import org.apache.accumulo.core.client.admin.TabletAvailability;
@@ -1331,6 +1336,168 @@ public class BulkNewIT extends SharedMiniClusterBase {
 
   }
 
+  private Set<String> listReservedBulkExtDirs(ClientContext ctx) throws 
TableNotFoundException {
+    try (var scanner = ctx.createScanner(SystemTables.METADATA.tableName(), 
Authorizations.EMPTY)) {
+      ID_COL.fetch(scanner);
+      final int prefixLen = 
MetadataSchema.BulkExtDirSection.getRowPrefix().length();
+      return scanner.stream().map(entry -> 
entry.getKey().getRowData().toString())
+          .map(row -> 
row.substring(prefixLen)).collect(Collectors.toUnmodifiableSet());
+    }
+  }
+
+  @Test
+  public void testInPlaceFilesCustomDirName() throws Exception {
+    try (AccumuloClient c = 
Accumulo.newClient().from(getClientProps()).build()) {
+      var ctx = (ClientContext) c;
+
+      String dir1 = rootPath + "/import003";
+      String dir2 = rootPath + "/" + Constants.BULK_EXT_PREFIX + "5";
+      Path path1 = new Path(dir1);
+      Path path2 = new Path(dir2);
+      FileSystem fs = getCluster().getFileSystem();
+      fs.mkdirs(path1);
+      fs.mkdirs(path2);
+
+      addSplits(c, tableName, "0199 0399 0599 0799");
+
+      for (int i = 0; i < 5; i++) {
+        writeData(fs, dir1 + "/f" + i + ".", aconf, i * 100, (i + 1) * 100 - 
1);
+      }
+
+      for (int i = 5; i < 10; i++) {
+        writeData(fs, dir2 + "/f" + i + ".", aconf, i * 100, (i + 1) * 100 - 
1);
+      }
+
+      var e1 = assertThrows(AccumuloException.class, () -> 
c.tableOperations().importDirectory(dir1)
+          .to(tableName).useFilesInPlace(true).load());
+      var e2 = assertThrows(AccumuloException.class, () -> 
c.tableOperations().importDirectory(dir2)
+          .to(tableName).useFilesInPlace(true).load());
+      assertEquals(
+          "Unacceptable bulk directory name. Ensure directory names are 
allocated using the Accumulo API.",
+          e1.getMessage());
+      assertEquals(e1.getMessage(), e2.getMessage());
+
+      // check that nothing happened
+      assertEquals(Set.of(), listReservedBulkExtDirs(ctx));
+      assertEquals(6, fs.listStatus(path1).length);
+      assertEquals(6, fs.listStatus(path2).length);
+      try (var scanner = c.createScanner(tableName)) {
+        assertEquals(0, scanner.stream().count());
+      }
+    }
+  }
+
+  @Test
+  public void testInPlaceFiles() throws Exception {
+    try (AccumuloClient c = 
Accumulo.newClient().from(getClientProps()).build()) {
+      var ctx = (ClientContext) c;
+
+      String dir1 = rootPath + "/" + 
c.tableOperations().allocateBulkDirectory();
+      String dir2 = rootPath + "/" + 
c.tableOperations().allocateBulkDirectory();
+      Path path1 = new Path(dir1);
+      Path path2 = new Path(dir2);
+      FileSystem fs = getCluster().getFileSystem();
+      fs.mkdirs(path1);
+      fs.mkdirs(path2);
+
+      addSplits(c, tableName, "0199 0399 0599 0799");
+
+      for (int i = 0; i < 5; i++) {
+        writeData(fs, dir1 + "/f" + i + ".", aconf, i * 100, (i + 1) * 100 - 
1);
+      }
+
+      for (int i = 5; i < 10; i++) {
+        writeData(fs, dir2 + "/f" + i + ".", aconf, i * 100, (i + 1) * 100 - 
1);
+      }
+
+      assertEquals(Set.of(), listReservedBulkExtDirs(ctx));
+      
c.tableOperations().importDirectory(dir1).to(tableName).useFilesInPlace(true).load();
+      assertEquals(Set.of(new Path(dir1).getName()), 
listReservedBulkExtDirs(ctx));
+
+      // attempt to reuse bulk dir
+      var exception = assertThrows(AccumuloException.class, () -> 
c.tableOperations()
+          .importDirectory(dir1).to(tableName).useFilesInPlace(true).load());
+      assertEquals("Bulk directory name was used by a previous bulk import 
operation.",
+          exception.getMessage());
+      // failed operation will leave a loadmap.json file behind, delete it
+      fs.delete(new Path(dir1, Constants.BULK_LOAD_MAPPING), false);
+
+      // ensure the failed operation did not delete the reservation
+      assertEquals(Set.of(new Path(dir1).getName()), 
listReservedBulkExtDirs(ctx));
+
+      
c.tableOperations().importDirectory(dir2).to(tableName).useFilesInPlace(true).load();
+
+      // ensure the files are still there
+      assertEquals(5, fs.listStatus(path1).length);
+      assertEquals(5, fs.listStatus(path2).length);
+
+      verifyData(c, tableName, 0, 100 * 10 - 1, false);
+
+      // ensure the metadata table references the files in the original 
directory
+      try (var tablets = 
ctx.getAmple().readTablets().forTable(ctx.getTableId(tableName)).build()) {
+        tablets.forEach(tm -> {
+          // each tablet should have two files
+          assertEquals(2, tm.getFiles().size());
+          for (var ref : tm.getFiles()) {
+            var parent = ref.getPath().getParent();
+            assertTrue(parent.equals(path1) || parent.equals(path2),
+                () -> "parent: " + parent + " path1: " + path1 + " path2: " + 
path2 + " ");
+          }
+        });
+      }
+
+      // ensure clone works with external files
+      c.tableOperations().clone(tableName, tableName + "_clone",
+          CloneConfiguration.builder().build());
+      verifyData(c, tableName + "_clone", 0, 100 * 10 - 1, false);
+      c.tableOperations().delete(tableName + "_clone");
+
+      // ensure splits work with external files
+      addSplits(c, tableName, "0499");
+      verifyData(c, tableName, 0, 100 * 10 - 1, false);
+
+      // ensure merge works with external files
+      c.tableOperations().merge(tableName, null, new Text("0399"));
+      verifyData(c, tableName, 0, 100 * 10 - 1, false);
+
+      // both bulk dirs should still be reserved
+      assertEquals(Set.of(new Path(dir1).getName(), new Path(dir2).getName()),
+          listReservedBulkExtDirs(ctx));
+
+      // ensure compact works with external files, only compact files from 
first bulk import
+      c.tableOperations().compact(tableName,
+          new CompactionConfig().setWait(true).setEndRow(new Text("0499")));
+      verifyData(c, tableName, 0, 100 * 10 - 1, false);
+
+      // RawLocalFilesystem does not seem to delete the .crc files when a file 
is deleted. Remove
+      // the crc files so the GC can delete the bulk dir.
+      for (var path : List.of(path1, path2)) {
+        for (var file : Optional
+            
.ofNullable(java.nio.file.Path.of(path.toUri()).toFile().listFiles())
+            .orElse(new File[0])) {
+          if (file.getName().endsWith(".crc")) {
+            assertTrue(file.delete());
+          }
+        }
+      }
+      // ensure GC works with external files, should delete the files and 
directory for the first
+      // bulk import after the compaction
+      Wait.waitFor(() -> !fs.exists(path1));
+
+      // The bulk dir reservation for the first bulk import should eventually 
go away
+      Wait.waitFor(() -> listReservedBulkExtDirs(ctx).equals(Set.of(new 
Path(dir2).getName())));
+
+      // delete the table, should cause files from 2nd bulk import to be 
deleted
+      assertTrue(fs.exists(path2));
+      assertEquals(Set.of(new Path(dir2).getName()), 
listReservedBulkExtDirs(ctx));
+
+      c.tableOperations().delete(tableName);
+
+      Wait.waitFor(() -> !fs.exists(path2));
+      Wait.waitFor(() -> listReservedBulkExtDirs(ctx).isEmpty());
+    }
+  }
+
   private void addSplits(AccumuloClient client, String tableName, String 
splitString)
       throws Exception {
     SortedSet<Text> splits = new TreeSet<>();

Reply via email to