You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@accumulo.apache.org by "dlmarion (via GitHub)" <gi...@apache.org> on 2026/10/23 15:06:03 UTC

[PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

dlmarion opened a new pull request, #6611:
URL: https://github.com/apache/accumulo/pull/6611

   Removed the logic that enforced RFiles were located in paths that contained '/tables/<tableId>/<tabletDir>'. Removed getVolume(), getTableId(), and getTabletDir() from ReferencedTabletFile and the parsing of the parts into the FileParts object.
   
   Modified the GarbageCollector such that file candidates were matched by full URI and modified the logic that removed directories as an optimization to also remove RFiles not located in the directory.
   
   Made related changes to volume replacment, table disk usage and scan server references.
   
   Modified existing tests and created a new ExternalTabletFileIT that has coverage for scanning, major compaction and garbage collection.
   
   Assisted-By: OpenAI GPT-6 Luna


-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4392612871


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -119,18 +123,72 @@ private String makeRelative(String path, int expectedLen) {
     return relPath;
   }
 
-  private SortedMap<String,GcCandidate> makeRelative(Collection<GcCandidate> candidates) {
+  private String makeCandidateKey(String path) {
+    try {
+      String relative = makeRelative(path, 0);
+      if (SimpleGarbageCollector.isDir(relative)) {
+        return DIRECTORY_CANDIDATE_KEY_PREFIX + relative;
+      }
+    } catch (IllegalArgumentException e) {
+      // Paths for external files do not have the Accumulo tables/<table>/<tablet> structure.
+      // Their full URI is their identity, so don't discard them or compare by path suffix.
+    }
+
+    return fileCandidateKey(path);
+  }
+
+  private String fileCandidateKey(String path) {
+    if (path.endsWith("/")) {
+      throw new IllegalArgumentException("GC file candidate is a directory: " + path);
+    }
+    Path candidatePath = new Path(path);
+    if (candidatePath.toUri().getScheme() != null) {
+      if (candidatePath.getName().isEmpty()) {
+        throw new IllegalArgumentException("GC file candidate does not identify a file: " + path);
+      }
+      return FILE_CANDIDATE_KEY_PREFIX + candidatePath;
+    }
+
+    // Relative paths are retained for compatibility with older metadata entries. Once paths are
+    // absolute, full URI identity is required so files at distinct locations cannot alias.
+    String relative = tryMakeRelative(path, 3);
+    if (relative == null) {
+      throw new IllegalArgumentException("Invalid relative GC file candidate: " + path);
+    }
+    return FILE_CANDIDATE_KEY_PREFIX + "RELATIVE|" + relative;
+  }
+
+  private String directoryCandidateKey(String relativePath) {
+    return DIRECTORY_CANDIDATE_KEY_PREFIX + relativePath;
+  }
+
+  private String tabletDirectoryKey(String filePath) {
+    String relativeFile = tryMakeRelative(filePath, 3);
+    if (relativeFile == null) {
+      // External files are not in an Accumulo tablet directory and have no directory candidate to
+      // suppress.
+      return null;
+    }
+    return directoryCandidateKey(relativeFile.substring(0, relativeFile.lastIndexOf('/')));
+  }
+
+  private String tryMakeRelative(String path, int expectedLen) {
+    try {
+      return makeRelative(path, expectedLen);
+    } catch (IllegalArgumentException e) {
+      return null;
+    }
+  }
+
+  private SortedMap<String,GcCandidate> makeCandidateMap(Collection<GcCandidate> candidates) {
     SortedMap<String,GcCandidate> ret = new TreeMap<>();
 
     for (GcCandidate candidate : candidates) {
-      String relPath;
       try {
-        relPath = makeRelative(candidate.getPath(), 0);
-      } catch (IllegalArgumentException iae) {
+        ret.put(makeCandidateKey(candidate.getPath()), candidate);

Review Comment:
   Prefixing keys with `FILE|` and `DIR|` in this map prevents some of the efficient operations that used to be possible.  The old code leveraged the sorted to map to efficiently find all files that started with a given directory.  This was done using range operations on the keys.  I think we could restore this efficient behavior if we did the following two things.
   
     * Normalize the paths in the map (like change hdfs://foo////a//b/ to hdfs://foo/a/b/
     * Adopt the convention that all directory keys end with `/` and no file entries end with slash.  Drop the `FILE` and `DIR` prefixes.  With this convention we could have  a static function `isDir()` that looks at the last char of the string.
   
   With those changes, hopefully we can continue to do things similar to the way the existing code does and efficiently find all files with a given dir.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4615252817


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   So, there is an issue with external files. The accounting for seen tableIds fails because the table id is not part of the file path with external files.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4635662759


##########
server/base/src/main/java/org/apache/accumulo/server/util/adminCommand/ListVolumesUsed.java:
##########
@@ -72,11 +72,18 @@ public void execute(JCommander cl, ServerOpts options) throws Exception {
   }
 
   private String getTableURI(String rootTabletDir) {
-    Path ret = FileType.TABLE.getVolume(new Path(rootTabletDir));
-    if (ret == null) {
+    Path path = new Path(rootTabletDir);
+    try {
+      Path ret = FileType.TABLE.getVolume(path);
+      if (ret != null) {
+        return ret.toString();
+      }
       return "RELATIVE";
+    } catch (IllegalArgumentException e) {
+      // External file references need not contain the Accumulo tables directory. Include their
+      // full URI so this command remains useful without inventing a volume root.
+      return "EXTERNAL: " + path;

Review Comment:
   Could probably make this a bit more useful, these external paths will not be completely arbitrary.  They will eventually look something like `<some external path>/<bulk dir>/<file name>`.  We could at the very least return `<some external path>` for this case to avoid printing alot of stuff for this command.  It seems ok to make some assumptions about these paths.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -134,9 +134,10 @@ public int removeBlip(String blip) {
     bulkDirCandidates.remove(lastThree.name);
 
     var tailIter = fileCandidates.tailMap(blipPrefix).keySet().iterator();
+    String blipDir = blipPrefix + "/";

Review Comment:
   A few lines up when blipPrefix is created could add the trailing slash then.



##########
server/base/src/main/java/org/apache/accumulo/server/fs/VolumeUtil.java:
##########
@@ -62,23 +62,39 @@ public static Path removeTrailingSlash(Path path) {
   }
 
   public static Path switchVolume(Path path, FileType ft, Map<Path,Path> replacements) {
-    Path replacement = null;
-    if (!replacements.isEmpty()) {
-      // removing trailing slash for exact match comparison on the volume itself
-      Path volume = removeTrailingSlash(ft.getVolume(requireNonNull(path)));
-      replacement = replacements.entrySet().stream()
-          .filter(entry -> removeTrailingSlash(entry.getKey()).equals(volume))
-          .map(entry -> new Path(entry.getValue(), requireNonNull(ft.removeVolume(path))))
-          .findFirst().orElse(null);
-    }
-    if (replacement != null) {
-      log.trace("Replacing {} with {} for {}", path, replacement, ft);
-      return replacement;
+    requireNonNull(path);
+    for (Entry<Path,Path> entry : replacements.entrySet()) {
+      Path source = removeTrailingSlash(entry.getKey());
+      Path relative = getRelativePath(source, path);
+      if (relative != null) {
+        Path replacement = relative.toString().equals(".") ? entry.getValue()

Review Comment:
   The case of `"."` seems to be when a path exactly matches a volume.  This does not seems like an expected case, seems like we will always have some stuff after the volume like a wal file, tablet file, tablet dir, etc.  Wondering if an exception should be thrown instead of just continuing like its ok.
   
   This code used to find an exact volume in the path and look for a match to that.  Now it looks for the first volume that shares a prefix.  Wondering if we need to find the longest prefix that matches. Like if I had the following replacements and had the path `hdfs://nn1/accumulo/v1/tables/1/t-2/f1.rf`, it seems like the new code could translate this to `hdfs://nn2/accumulo/v1/tables/1/t-2/f1.rf` or `hdfs://nn3/accumulo/v1/tables/1/t-2/f1.rf`.  Seems like the old code would have always translated to  `hdfs://nn2/accumulo/v1/tables/1/t-2/f1.rf`.  Its an oddball case and not sure it would ever actually happen, but does seems like a difference in behavior.
   
   ```
     hdfs://nn1/accumulo   => hdfs://nn3/accumulo
     hdfs://nn1/accumulo/v1   => hdfs://nn2/accumulo/v1
   ```



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4486265267


##########
core/src/main/java/org/apache/accumulo/core/metadata/ScanServerRefTabletFile.java:
##########
@@ -19,37 +19,43 @@
 package org.apache.accumulo.core.metadata;
 
 import java.net.URI;
+import java.util.Collection;
+import java.util.HashSet;
 import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
 import java.util.UUID;
 
 import org.apache.accumulo.core.data.Key;
 import org.apache.accumulo.core.data.Mutation;
+import org.apache.accumulo.core.data.TableId;
 import org.apache.accumulo.core.data.Value;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.Text;
 
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+
+@SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW",
+    justification = "Constructor validation is required for proper initialization")
 public class ScanServerRefTabletFile extends ReferencedTabletFile {
 
-  private final Value NULL_VALUE = new Value(new byte[0]);
   private final Text serverAddress;
   private final Text uuid;
+  private final Set<TableId> tableIds;

Review Comment:
   I'm not sure that I can remove the tableIds from ScanServerRefTabletFile. It appears they are needed in GCRun.getReferences when computing the stream of ReferenceFile's (which require a TableId).



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4619038194


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   Tried removing the table id from the ref, but that was not workable.  So instead attempted to make the code less confusing (sometimes the table id came from the path and sometimes it came from the extent) and opened #6659



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4645059916


##########
server/base/src/main/java/org/apache/accumulo/server/fs/VolumeUtil.java:
##########
@@ -62,23 +62,39 @@ public static Path removeTrailingSlash(Path path) {
   }
 
   public static Path switchVolume(Path path, FileType ft, Map<Path,Path> replacements) {
-    Path replacement = null;
-    if (!replacements.isEmpty()) {
-      // removing trailing slash for exact match comparison on the volume itself
-      Path volume = removeTrailingSlash(ft.getVolume(requireNonNull(path)));
-      replacement = replacements.entrySet().stream()
-          .filter(entry -> removeTrailingSlash(entry.getKey()).equals(volume))
-          .map(entry -> new Path(entry.getValue(), requireNonNull(ft.removeVolume(path))))
-          .findFirst().orElse(null);
-    }
-    if (replacement != null) {
-      log.trace("Replacing {} with {} for {}", path, replacement, ft);
-      return replacement;
+    requireNonNull(path);
+    for (Entry<Path,Path> entry : replacements.entrySet()) {
+      Path source = removeTrailingSlash(entry.getKey());
+      Path relative = getRelativePath(source, path);
+      if (relative != null) {
+        Path replacement = relative.toString().equals(".") ? entry.getValue()

Review Comment:
   in fc9c3df I reverted the code to it's original state, then added code in an exception handler to deal with external files. The IllegalArgumentException is thrown when the expected file type (e.g. `tables`) is not found in the path. The code in the exception handler replaces the volume with the longest matching replacement.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4645025590


##########
server/base/src/main/java/org/apache/accumulo/server/util/adminCommand/ListVolumesUsed.java:
##########
@@ -72,11 +72,18 @@ public void execute(JCommander cl, ServerOpts options) throws Exception {
   }
 
   private String getTableURI(String rootTabletDir) {
-    Path ret = FileType.TABLE.getVolume(new Path(rootTabletDir));
-    if (ret == null) {
+    Path path = new Path(rootTabletDir);
+    try {
+      Path ret = FileType.TABLE.getVolume(path);
+      if (ret != null) {
+        return ret.toString();
+      }
       return "RELATIVE";
+    } catch (IllegalArgumentException e) {
+      // External file references need not contain the Accumulo tables directory. Include their
+      // full URI so this command remains useful without inventing a volume root.
+      return "EXTERNAL: " + path;

Review Comment:
   addressed in fc9c3df, made assumptions about the path and used `.getParent().getParent()`.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4645016393


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -134,9 +134,10 @@ public int removeBlip(String blip) {
     bulkDirCandidates.remove(lastThree.name);
 
     var tailIter = fileCandidates.tailMap(blipPrefix).keySet().iterator();
+    String blipDir = blipPrefix + "/";

Review Comment:
   Good catch, fixed in fc9c3df



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion merged PR #6611:
URL: https://github.com/apache/accumulo/pull/6611


-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4381732387


##########
core/src/main/java/org/apache/accumulo/core/metadata/ScanServerRefTabletFile.java:
##########
@@ -19,37 +19,43 @@
 package org.apache.accumulo.core.metadata;
 
 import java.net.URI;
+import java.util.Collection;
+import java.util.HashSet;
 import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
 import java.util.UUID;
 
 import org.apache.accumulo.core.data.Key;
 import org.apache.accumulo.core.data.Mutation;
+import org.apache.accumulo.core.data.TableId;
 import org.apache.accumulo.core.data.Value;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.Text;
 
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+
+@SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW",
+    justification = "Constructor validation is required for proper initialization")
 public class ScanServerRefTabletFile extends ReferencedTabletFile {
 
-  private final Value NULL_VALUE = new Value(new byte[0]);
   private final Text serverAddress;
   private final Text uuid;
+  private final Set<TableId> tableIds;

Review Comment:
   ```suggestion
   ```
   Traced how table ids are used in the code and found we may be able to remove tracking of table ids  for scan server refs if we make the following change.  That would simplify this class and avoid persisting data this is not really needed.
   
   ```diff
   diff --git a/server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java b/server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java
   index 6b9a4ed23c..b9301d1e25 100644
   --- a/server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java
   +++ b/server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java
   @@ -202,7 +202,11 @@ public class GarbageCollectionAlgorithm {
        Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
        try (Stream<Reference> references = gce.getReferences()) {
          references.forEach(ref -> {
   -        tableIdsSeen.add(ref.getTableId());
   +        if (ref.isDirectory()) {
   +          // Every tablet must have a directory, but not every tablet has files. Only need to look
   +          // for directories to ensure a tables tablets were seen.
   +          tableIdsSeen.add(ref.getTableId());
   +        }
    
            if (ref.isDirectory()) {
              ServerColumnFamily.validateDirCol(ref.getMetadataPath());
   ```
   
   The above will avoid getting the table id when its not really needed for what the code is trying to accomplish.  The other place that gets the table id is [here](https://github.com/apache/accumulo/blob/537042c61c1e43c2c78f9588550f1146b065b996/server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java#L167) and that case should never happen for scan refs.  That case is for handling a super old relative reference in the metadata table from really old versions of Accumulo, scan server refs have always been absolute.  Maybe we can change ReferenceFile to throw an UnsupportedOperationException if trying to get the table id for a scan server reference as its not expected to be called for that case.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -216,18 +300,31 @@ private long removeBlipCandidates(GarbageCollectionEnvironment gce,
         while (blipiter.hasNext()) {
           blipCount++;
           String blipPath = blipiter.next();
-          blipPath = makeRelative(blipPath, 2);
-
-          Iterator<String> tailIter = candidateMap.tailMap(blipPath).keySet().iterator();
+          Path blip = new Path(blipPath);
+          boolean absoluteBlip = blip.toUri().getScheme() != null;
+          String relativeBlip = null;
+          try {
+            relativeBlip = makeRelative(blipPath, 2);
+          } catch (IllegalArgumentException e) {
+            // External bulk-load paths are matched using their full URI below.
+          }
 
+          Iterator<Entry<String,GcCandidate>> candidateIter = candidateMap.entrySet().iterator();
           int count = 0;
-
-          while (tailIter.hasNext()) {
-            if (tailIter.next().startsWith(blipPath)) {
+          while (candidateIter.hasNext()) {

Review Comment:
   There is a big change in complexity here.  The old code was `O(N*log2(M))` where this new code seems to be `O(N*M)`. Not sure if this can be avoided, but if it can it would be nice to avoid the big jump in computation.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4498729426


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -69,6 +71,15 @@ public class GarbageCollectionAlgorithm {
    * hdfs://foo.com:6000/accumulo/tables/4//t0//F001.rf returning 4/t0/F001.rf.
    */
   private String makeRelative(String path, int expectedLen) {
+    String relative = tryMakeRelative(path, expectedLen);
+    if (relative == null) {
+      throw new IllegalArgumentException("Failed to make path relative. Bad reference: " + path);
+    }
+    return relative;
+  }
+
+  // Returns null when the path does not match the expected Accumulo table path layout.
+  private String tryMakeRelative(String path, int expectedLen) {

Review Comment:
   Looking at how this currently works, using the `tables` dirs to determine if a path is a directory of file is problematic.  Opened #6638 that is a WIP, its the beginning of work to remove the need to use `tables` in the path to determine if a something is a dir or file.  That plus other outstanding changes to remove support for relative paths could dramatically simplify this code.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4629685503


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -127,17 +127,19 @@ public Iterator<GcCandidate> iterator() {
   }
 
   public int removeBlip(String blip) {
-    var lastThree = lastThree(blip, false, 2, 2);
-
-    String blipPrefix = "/" + lastThree.name;
-
-    bulkDirCandidates.remove(lastThree.name);
+    log.trace("Removing candidates for bulk load in-progress marker: {}", blip);
+    var removed = bulkDirCandidates.remove(blip);
+    if (removed != null) {
+      log.trace("Removed {} from bulkDirCandidates", removed.getPath());
+    }
 
-    var tailIter = fileCandidates.tailMap(blipPrefix).keySet().iterator();
+    var tailIter = fileCandidates.tailMap(blip).keySet().iterator();
     int removeCount = 0;
     while (tailIter.hasNext()) {
-      if (tailIter.next().startsWith(blipPrefix)) {
+      String fileCandidate = tailIter.next();
+      if (fileCandidate.startsWith(blip + "/")) {

Review Comment:
   Fixed in 4444d87



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4659955209


##########
server/base/src/main/java/org/apache/accumulo/server/fs/VolumeUtil.java:
##########
@@ -62,23 +62,39 @@ public static Path removeTrailingSlash(Path path) {
   }
 
   public static Path switchVolume(Path path, FileType ft, Map<Path,Path> replacements) {
-    Path replacement = null;
-    if (!replacements.isEmpty()) {
-      // removing trailing slash for exact match comparison on the volume itself
-      Path volume = removeTrailingSlash(ft.getVolume(requireNonNull(path)));
-      replacement = replacements.entrySet().stream()
-          .filter(entry -> removeTrailingSlash(entry.getKey()).equals(volume))
-          .map(entry -> new Path(entry.getValue(), requireNonNull(ft.removeVolume(path))))
-          .findFirst().orElse(null);
-    }
-    if (replacement != null) {
-      log.trace("Replacing {} with {} for {}", path, replacement, ft);
-      return replacement;
+    requireNonNull(path);
+    for (Entry<Path,Path> entry : replacements.entrySet()) {
+      Path source = removeTrailingSlash(entry.getKey());
+      Path relative = getRelativePath(source, path);
+      if (relative != null) {
+        Path replacement = relative.toString().equals(".") ? entry.getValue()

Review Comment:
   Using exceptions for expected cases is not good because the exception could be caused by something other than what is expected.  Also if the code is executed frequently creating exceptions is expensive relative to some sort of if stmt that does an explicit check.  Creating an exception requires filling in the stack trace which used to be slow, probably still is.
   
   The external paths are being added for a single use case, bulk imports.  If we assumed this new use case always had paths of the form `<a fully qualifies uri and path>/be-<unique id>/<file>` it could potentially simplify things here and in the GC code.  If we look at the parent dir and it has the prefix `be-` then we know its an external file. The bulk import operation could enforce this minimal naming convention.  If we assumed that convention, then this code could have simple if stmt to check for it.
   



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4605405314


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -18,163 +18,357 @@
  */
 package org.apache.accumulo.gc;
 
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.file.Path;
 import java.util.AbstractCollection;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
 import java.util.function.Consumer;
 
 import org.apache.accumulo.core.gc.GcCandidate;
 import org.apache.accumulo.core.gc.Reference;
+import org.apache.hadoop.fs.Path;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Iterators;
-
 /**
  * Code that supports efficient removal of references from a set of gc candidates.
  */
 public class GcCandidates extends AbstractCollection<GcCandidate> {
 
   private static final Logger log = LoggerFactory.getLogger(GcCandidates.class);
 
-  private final SortedMap<String,GcCandidate> fileCandidates = new TreeMap<>();
-  private final HashMap<String,GcCandidate> tabletDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> bulkDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> tableDirCandidates = new HashMap<>();
+  // Absolute file paths must retain their complete URI identity. Relative paths are legacy
+  // candidates and are tracked separately so they can be conservatively matched to managed files.
+  private final SortedMap<String,GcCandidate> absoluteFileCandidates = new TreeMap<>();
+  private final SortedMap<String,GcCandidate> relativeFileCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> absoluteFilesByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tabletDirCandidates = new HashMap<>();
+  private final SortedMap<String,GcCandidate> bulkDirCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> bulkDirsByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tableDirCandidates = new HashMap<>();
 
-  private record LastThree(String maybeATableId, String dir, String name) {
+  public GcCandidates(Iterable<GcCandidate> candidates) {
+    for (GcCandidate candidate : candidates) {
+      try {
+        switch (candidate.getType()) {
+          case TABLET_FILE -> addFileCandidate(candidate);
+          case TABLET_DIR ->
+            tabletDirCandidates.put(relativePath(candidate.getPath(), 2), candidate);
+          case BULK_DIR -> addBulkDirCandidate(candidate);
+          case TABLE_DIR -> tableDirCandidates.put(relativePath(candidate.getPath(), 1), candidate);
+        }
+      } catch (IllegalArgumentException e) {
+        log.warn("Ignoring invalid deletion candidate {}", candidate);
+      }
+    }
   }
 
-  private LastThree lastThree(String strPath, int minPathLength) {
-    return lastThree(strPath, true, minPathLength, Integer.MAX_VALUE);
+  private void addFileCandidate(GcCandidate candidate) {
+    Path path = new Path(candidate.getPath());
+    if (path.toUri().getScheme() != null) {
+      String normalized = path.toString();
+      absoluteFileCandidates.put(normalized, candidate);
+      String managedPath = managedPath(path, 3);
+      if (managedPath != null) {
+        addIndex(absoluteFilesByManagedPath, managedPath, normalized);
+      }
+    } else {

Review Comment:
   File candidates should always have a scheme, so should not never execute this branch.
   
   I don't think any changes to this class are needed to support external files.  If the changes are needed then what problem are they solving?
   
   I see lots problems with the changes that were made.  Also the changes to this class add huge amounts of complexity that seems completely unnecessary and incorrect.



##########
core/src/main/java/org/apache/accumulo/core/metadata/ScanServerRefTabletFile.java:
##########
@@ -76,6 +72,11 @@ public Value getValue() {
     return NULL_VALUE;
   }
 
+  public Set<TableId> getTableIds() {

Review Comment:
   Seems like this is never called and could be removed.



##########
server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java:
##########
@@ -110,38 +111,38 @@ public static void deleteTable(TableId tableId, boolean insertDeletes, ServerCon
       Ample ample = context.getAmple();
       ms.setRange(new KeyExtent(tableId, null, null).toMetaRange());
 
-      // Insert tmp delete markers before deleting data from metadata... this makes the code
-      // idempotent. TmpDeletes avoids race conditions with GC deleting in use candidates. The
-      // actual deletes markers must be inserted after the tables metadata is deleted. If the actual
-      // delete markers are inserted before deleting the tablet metadata, then the GC may see them
-      // as in use and delete them. Buffering delete markers in memory may not fit and would not be
-      // idempotent, so write them to a temp area.
+      // Temporary candidates avoid a race with GC while tablet metadata is being deleted. Also
+      // retain candidates for external files when directory deletion is optimized.
+      ms.fetchColumnFamily(DataFileColumnFamily.NAME);
       if (insertDeletes) {
-
-        ms.fetchColumnFamily(DataFileColumnFamily.NAME);
         ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms);
+      }
 
-        for (Entry<Key,Value> cell : ms) {
-          Key key = cell.getKey();
+      for (Entry<Key,Value> cell : ms) {
+        Key key = cell.getKey();
 
-          if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) {
-            StoredTabletFile stf = new StoredTabletFile(key.getColumnQualifierData().toString());
+        if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) {
+          StoredTabletFile stf = new StoredTabletFile(key.getColumnQualifierData().toString());
+          if (insertDeletes || !isInTableDirectories(context, tableId, stf.getPath())) {

Review Comment:
   If the caller of the function does not want to insert delete candidates, then why do it for external files?  Looking at the code that calls this with false, its doing some sort of cleanup of a failed table creation usually so it does not seem necessary to add this logic.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -18,163 +18,357 @@
  */
 package org.apache.accumulo.gc;
 
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.file.Path;
 import java.util.AbstractCollection;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
 import java.util.function.Consumer;
 
 import org.apache.accumulo.core.gc.GcCandidate;
 import org.apache.accumulo.core.gc.Reference;
+import org.apache.hadoop.fs.Path;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Iterators;
-
 /**
  * Code that supports efficient removal of references from a set of gc candidates.
  */
 public class GcCandidates extends AbstractCollection<GcCandidate> {
 
   private static final Logger log = LoggerFactory.getLogger(GcCandidates.class);
 
-  private final SortedMap<String,GcCandidate> fileCandidates = new TreeMap<>();
-  private final HashMap<String,GcCandidate> tabletDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> bulkDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> tableDirCandidates = new HashMap<>();
+  // Absolute file paths must retain their complete URI identity. Relative paths are legacy
+  // candidates and are tracked separately so they can be conservatively matched to managed files.
+  private final SortedMap<String,GcCandidate> absoluteFileCandidates = new TreeMap<>();
+  private final SortedMap<String,GcCandidate> relativeFileCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> absoluteFilesByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tabletDirCandidates = new HashMap<>();
+  private final SortedMap<String,GcCandidate> bulkDirCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> bulkDirsByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tableDirCandidates = new HashMap<>();
 
-  private record LastThree(String maybeATableId, String dir, String name) {
+  public GcCandidates(Iterable<GcCandidate> candidates) {
+    for (GcCandidate candidate : candidates) {
+      try {
+        switch (candidate.getType()) {
+          case TABLET_FILE -> addFileCandidate(candidate);
+          case TABLET_DIR ->
+            tabletDirCandidates.put(relativePath(candidate.getPath(), 2), candidate);
+          case BULK_DIR -> addBulkDirCandidate(candidate);
+          case TABLE_DIR -> tableDirCandidates.put(relativePath(candidate.getPath(), 1), candidate);
+        }
+      } catch (IllegalArgumentException e) {
+        log.warn("Ignoring invalid deletion candidate {}", candidate);
+      }
+    }
   }
 
-  private LastThree lastThree(String strPath, int minPathLength) {
-    return lastThree(strPath, true, minPathLength, Integer.MAX_VALUE);
+  private void addFileCandidate(GcCandidate candidate) {
+    Path path = new Path(candidate.getPath());
+    if (path.toUri().getScheme() != null) {
+      String normalized = path.toString();
+      absoluteFileCandidates.put(normalized, candidate);
+      String managedPath = managedPath(path, 3);
+      if (managedPath != null) {
+        addIndex(absoluteFilesByManagedPath, managedPath, normalized);
+      }
+    } else {
+      String normalized = relativePath(candidate.getPath(), 3);
+      relativeFileCandidates.put(normalized, candidate);
+    }
   }
 
-  private LastThree lastThree(String strPath, boolean expectScheme, int minPathLength,
-      int maxPathLength) {
-    URI uri = null;
-    try {
-      uri = new URI(strPath);
-    } catch (URISyntaxException e) {
-      throw new IllegalArgumentException(e);
+  private void addBulkDirCandidate(GcCandidate candidate) {
+    Path path = new Path(candidate.getPath());
+    if (path.toUri().getScheme() == null) {
+      throw new IllegalArgumentException("Bulk directory candidate must be an absolute URI");
     }
-
-    if (expectScheme && uri.getScheme() == null) {
-      throw new IllegalArgumentException("Missing scheme in URI " + strPath);
+    String normalized = path.toString();
+    bulkDirCandidates.put(normalized, candidate);
+    String managedPath = managedPath(path, 2);
+    if (managedPath != null) {
+      addIndex(bulkDirsByManagedPath, managedPath, normalized);
     }
+  }
 
-    // TODO what about other parts of the URI?
-    var path = Path.of(uri.getPath());
+  private static void addIndex(SortedMap<String,Set<String>> index, String key, String path) {
+    index.computeIfAbsent(key, ignored -> new HashSet<>()).add(path);
+  }
 
-    int count = path.getNameCount();
-    if (count < minPathLength) {
-      throw new IllegalArgumentException("Path too short " + strPath);
+  private static String relativePath(String path, int expectedComponents) {
+    String candidatePath = path.startsWith("../") ? path.substring(3) : path;
+    Path parsed = new Path(candidatePath);
+    if (parsed.toUri().getScheme() != null) {
+      throw new IllegalArgumentException("Expected a relative candidate path: " + path);
+    }
+    String normalized = parsed.toString();
+    while (normalized.startsWith("/")) {
+      normalized = normalized.substring(1);
+    }
+    if (normalized.isEmpty()) {
+      throw new IllegalArgumentException("Empty candidate path");
     }
+    if (componentCount(normalized) != expectedComponents) {
+      throw new IllegalArgumentException("Unexpected candidate path depth: " + path);
+    }
+    return "/" + normalized;
+  }
 
-    if (count > maxPathLength) {
-      throw new IllegalArgumentException("Path too long " + strPath);
+  private static int componentCount(String path) {
+    int count = 0;
+    boolean inComponent = false;
+    for (int i = 0; i < path.length(); i++) {
+      char c = path.charAt(i);
+      if (c == '/') {
+        inComponent = false;
+      } else if (!inComponent) {
+        count++;
+        inComponent = true;
+      }
     }
+    return count;
+  }
 
-    if (count == 1) {
-      return new LastThree(null, null, path.getName(count - 1).toString());
-    } else if (count == 2) {
-      return new LastThree(null, path.getName(count - 2).toString(),
-          path.getName(count - 1).toString());
-    } else if (count >= 3) {
-      return new LastThree(path.getName(count - 3).toString(), path.getName(count - 2).toString(),
-          path.getName(count - 1).toString());
-    } else {
-      throw new IllegalArgumentException("Bad path " + path);
+  /**
+   * Extracts the table-relative tablet file or directory path if the URI follows the normal
+   * {@code .../tables/<tableId>/<tabletDir>/...} layout.
+   */
+  private static String managedPath(Path path, int componentsAfterTables) {
+    Path current = path;
+    String[] suffix = new String[componentsAfterTables];
+    for (int i = componentsAfterTables - 1; i >= 0; i--) {
+      if (current == null || current.getName().isEmpty()) {
+        return null;
+      }
+      suffix[i] = current.getName();
+      current = current.getParent();
+    }
+    if (current == null || !"tables".equals(current.getName())) {
+      return null;
+    }
+    StringBuilder result = new StringBuilder();
+    for (String component : suffix) {
+      result.append('/').append(component);
     }
+    return result.toString();
   }
 
-  public GcCandidates(Iterable<GcCandidate> candidates) {
-    candidates.forEach(candidate -> {
-      try {
-        switch (candidate.getType()) {
-          case TABLET_FILE -> {
-            var lastThree = lastThree(candidate.getPath(), 2);
-            fileCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
-          }
-          case TABLET_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 2, 2);
-            tabletDirCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
-          }
-          case BULK_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), 1);
-            bulkDirCandidates.put(lastThree.name, candidate);
-          }
-          case TABLE_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 1, 1);
-            tableDirCandidates.put(lastThree.name, candidate);
+  @Override
+  public Iterator<GcCandidate> iterator() {
+    return new Iterator<>() {

Review Comment:
   Why replace the guava method for concatenating iterators with all of this custom code?  That guava code is much more succinct and is probably well tested.



##########
server/tserver/src/main/java/org/apache/accumulo/tserver/ScanServer.java:
##########
@@ -593,6 +592,7 @@ private Map<KeyExtent,TabletMetadata> getTabletMetadata(Collection<KeyExtent> ex
 
   static class ReservedFile {
     final Set<Long> activeReservations = new ConcurrentSkipListSet<>();
+    final Set<TableId> tableIds = ConcurrentHashMap.newKeySet();

Review Comment:
   Not sure any of the changes to this class are needed, the changes do not make sense to me. The code is trying to reserve files, not files and table ids.  If the changes are needed, then what are they trying to accomplish? Seems like they are left over from trying to get table ids for each scan server ref.



##########
core/src/main/java/org/apache/accumulo/core/metadata/ReferencedTabletFile.java:
##########
@@ -171,34 +59,27 @@ public ReferencedTabletFile(Path metaPath) {
    * qualify an absolute path or create a new file.
    */
   public ReferencedTabletFile(Path metaPath, Range range) {
-    super(Objects.requireNonNull(metaPath), range);
-    log.trace("Parsing TabletFile from {}", metaPath);
-    parts = parsePath(metaPath);
-  }
-
-  public String getVolume() {
-    return parts.getVolume();
-  }
-
-  public TableId getTableId() {
-    return parts.getTableId();
+    super(validatePath(metaPath), range);
+    log.trace("Creating tablet file reference from {}", metaPath);
   }
 
-  public String getTabletDir() {
-    return parts.getTabletDir();
+  private static Path validatePath(Path metaPath) {
+    Path path = ValidationUtil.validate(Objects.requireNonNull(metaPath));
+    Preconditions.checkArgument(!path.getName().isEmpty(), "Path must identify a file: %s", path);

Review Comment:
   We could also check that it has a parent, we expect each tablet file to at least have a dir and file name.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -18,163 +18,357 @@
  */
 package org.apache.accumulo.gc;
 
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.file.Path;
 import java.util.AbstractCollection;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
 import java.util.function.Consumer;
 
 import org.apache.accumulo.core.gc.GcCandidate;
 import org.apache.accumulo.core.gc.Reference;
+import org.apache.hadoop.fs.Path;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Iterators;
-
 /**
  * Code that supports efficient removal of references from a set of gc candidates.
  */
 public class GcCandidates extends AbstractCollection<GcCandidate> {
 
   private static final Logger log = LoggerFactory.getLogger(GcCandidates.class);
 
-  private final SortedMap<String,GcCandidate> fileCandidates = new TreeMap<>();
-  private final HashMap<String,GcCandidate> tabletDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> bulkDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> tableDirCandidates = new HashMap<>();
+  // Absolute file paths must retain their complete URI identity. Relative paths are legacy
+  // candidates and are tracked separately so they can be conservatively matched to managed files.
+  private final SortedMap<String,GcCandidate> absoluteFileCandidates = new TreeMap<>();
+  private final SortedMap<String,GcCandidate> relativeFileCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> absoluteFilesByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tabletDirCandidates = new HashMap<>();
+  private final SortedMap<String,GcCandidate> bulkDirCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> bulkDirsByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tableDirCandidates = new HashMap<>();
 
-  private record LastThree(String maybeATableId, String dir, String name) {
+  public GcCandidates(Iterable<GcCandidate> candidates) {
+    for (GcCandidate candidate : candidates) {
+      try {
+        switch (candidate.getType()) {
+          case TABLET_FILE -> addFileCandidate(candidate);
+          case TABLET_DIR ->
+            tabletDirCandidates.put(relativePath(candidate.getPath(), 2), candidate);
+          case BULK_DIR -> addBulkDirCandidate(candidate);
+          case TABLE_DIR -> tableDirCandidates.put(relativePath(candidate.getPath(), 1), candidate);
+        }
+      } catch (IllegalArgumentException e) {
+        log.warn("Ignoring invalid deletion candidate {}", candidate);
+      }
+    }
   }
 
-  private LastThree lastThree(String strPath, int minPathLength) {
-    return lastThree(strPath, true, minPathLength, Integer.MAX_VALUE);
+  private void addFileCandidate(GcCandidate candidate) {
+    Path path = new Path(candidate.getPath());
+    if (path.toUri().getScheme() != null) {
+      String normalized = path.toString();
+      absoluteFileCandidates.put(normalized, candidate);
+      String managedPath = managedPath(path, 3);
+      if (managedPath != null) {
+        addIndex(absoluteFilesByManagedPath, managedPath, normalized);
+      }
+    } else {
+      String normalized = relativePath(candidate.getPath(), 3);
+      relativeFileCandidates.put(normalized, candidate);
+    }
   }
 
-  private LastThree lastThree(String strPath, boolean expectScheme, int minPathLength,
-      int maxPathLength) {
-    URI uri = null;
-    try {
-      uri = new URI(strPath);
-    } catch (URISyntaxException e) {
-      throw new IllegalArgumentException(e);
+  private void addBulkDirCandidate(GcCandidate candidate) {
+    Path path = new Path(candidate.getPath());
+    if (path.toUri().getScheme() == null) {
+      throw new IllegalArgumentException("Bulk directory candidate must be an absolute URI");
     }
-
-    if (expectScheme && uri.getScheme() == null) {
-      throw new IllegalArgumentException("Missing scheme in URI " + strPath);
+    String normalized = path.toString();
+    bulkDirCandidates.put(normalized, candidate);
+    String managedPath = managedPath(path, 2);
+    if (managedPath != null) {
+      addIndex(bulkDirsByManagedPath, managedPath, normalized);
     }
+  }
 
-    // TODO what about other parts of the URI?
-    var path = Path.of(uri.getPath());
+  private static void addIndex(SortedMap<String,Set<String>> index, String key, String path) {
+    index.computeIfAbsent(key, ignored -> new HashSet<>()).add(path);
+  }
 
-    int count = path.getNameCount();
-    if (count < minPathLength) {
-      throw new IllegalArgumentException("Path too short " + strPath);
+  private static String relativePath(String path, int expectedComponents) {
+    String candidatePath = path.startsWith("../") ? path.substring(3) : path;
+    Path parsed = new Path(candidatePath);
+    if (parsed.toUri().getScheme() != null) {
+      throw new IllegalArgumentException("Expected a relative candidate path: " + path);
+    }
+    String normalized = parsed.toString();
+    while (normalized.startsWith("/")) {
+      normalized = normalized.substring(1);
+    }
+    if (normalized.isEmpty()) {
+      throw new IllegalArgumentException("Empty candidate path");
     }
+    if (componentCount(normalized) != expectedComponents) {
+      throw new IllegalArgumentException("Unexpected candidate path depth: " + path);
+    }
+    return "/" + normalized;
+  }
 
-    if (count > maxPathLength) {
-      throw new IllegalArgumentException("Path too long " + strPath);
+  private static int componentCount(String path) {
+    int count = 0;
+    boolean inComponent = false;
+    for (int i = 0; i < path.length(); i++) {
+      char c = path.charAt(i);
+      if (c == '/') {
+        inComponent = false;
+      } else if (!inComponent) {
+        count++;
+        inComponent = true;
+      }
     }
+    return count;
+  }
 
-    if (count == 1) {
-      return new LastThree(null, null, path.getName(count - 1).toString());
-    } else if (count == 2) {
-      return new LastThree(null, path.getName(count - 2).toString(),
-          path.getName(count - 1).toString());
-    } else if (count >= 3) {
-      return new LastThree(path.getName(count - 3).toString(), path.getName(count - 2).toString(),
-          path.getName(count - 1).toString());
-    } else {
-      throw new IllegalArgumentException("Bad path " + path);
+  /**
+   * Extracts the table-relative tablet file or directory path if the URI follows the normal
+   * {@code .../tables/<tableId>/<tabletDir>/...} layout.
+   */
+  private static String managedPath(Path path, int componentsAfterTables) {
+    Path current = path;
+    String[] suffix = new String[componentsAfterTables];
+    for (int i = componentsAfterTables - 1; i >= 0; i--) {
+      if (current == null || current.getName().isEmpty()) {
+        return null;
+      }
+      suffix[i] = current.getName();
+      current = current.getParent();
+    }
+    if (current == null || !"tables".equals(current.getName())) {
+      return null;
+    }
+    StringBuilder result = new StringBuilder();
+    for (String component : suffix) {
+      result.append('/').append(component);
     }
+    return result.toString();
   }
 
-  public GcCandidates(Iterable<GcCandidate> candidates) {
-    candidates.forEach(candidate -> {
-      try {
-        switch (candidate.getType()) {
-          case TABLET_FILE -> {
-            var lastThree = lastThree(candidate.getPath(), 2);
-            fileCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
-          }
-          case TABLET_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 2, 2);
-            tabletDirCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
-          }
-          case BULK_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), 1);
-            bulkDirCandidates.put(lastThree.name, candidate);
-          }
-          case TABLE_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 1, 1);
-            tableDirCandidates.put(lastThree.name, candidate);
+  @Override
+  public Iterator<GcCandidate> iterator() {
+    return new Iterator<>() {
+      private final Iterator<GcCandidate> files = concat(absoluteFileCandidates.values().iterator(),
+          relativeFileCandidates.values().iterator());
+      private final Iterator<GcCandidate> tabletDirs = tabletDirCandidates.values().iterator();
+      private final Iterator<GcCandidate> bulkDirs = bulkDirCandidates.values().iterator();
+      private final Iterator<GcCandidate> tableDirs = tableDirCandidates.values().iterator();
+      private Iterator<GcCandidate> current = files;
+
+      private boolean advance() {
+        while (!current.hasNext()) {
+          if (current == files) {
+            current = tabletDirs;
+          } else if (current == tabletDirs) {
+            current = bulkDirs;
+          } else if (current == bulkDirs) {
+            current = tableDirs;
+          } else {
+            return false;
           }
         }
-      } catch (IllegalArgumentException e) {
-        log.warn("Ignoring invalid deletion candidate {}", candidate);
+        return true;
       }
-    });
+
+      @Override
+      public boolean hasNext() {
+        return advance();
+      }
+
+      @Override
+      public GcCandidate next() {
+        if (!advance()) {
+          throw new java.util.NoSuchElementException();
+        }
+        return current.next();
+      }
+    };
   }
 
-  @Override
-  public Iterator<GcCandidate> iterator() {
-    return Iterators.unmodifiableIterator(Iterators.concat(fileCandidates.values().iterator(),
-        tabletDirCandidates.values().iterator(), bulkDirCandidates.values().iterator(),
-        tableDirCandidates.values().iterator()));
+  private static Iterator<GcCandidate> concat(Iterator<GcCandidate> first,

Review Comment:
   Why replace the guava code with this? 



##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   ` getTableId()` never throws this exception.  IMO it would be best to stick with the `if(ref.isDirectory())` code because every tablet has a directory, directories only come from tablets, and we are not interested in refs (like scan server refs) that do not come from tablets.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -18,163 +18,357 @@
  */
 package org.apache.accumulo.gc;
 
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.file.Path;
 import java.util.AbstractCollection;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
 import java.util.function.Consumer;
 
 import org.apache.accumulo.core.gc.GcCandidate;
 import org.apache.accumulo.core.gc.Reference;
+import org.apache.hadoop.fs.Path;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Iterators;
-
 /**
  * Code that supports efficient removal of references from a set of gc candidates.
  */
 public class GcCandidates extends AbstractCollection<GcCandidate> {
 
   private static final Logger log = LoggerFactory.getLogger(GcCandidates.class);
 
-  private final SortedMap<String,GcCandidate> fileCandidates = new TreeMap<>();
-  private final HashMap<String,GcCandidate> tabletDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> bulkDirCandidates = new HashMap<>();
-  private final HashMap<String,GcCandidate> tableDirCandidates = new HashMap<>();
+  // Absolute file paths must retain their complete URI identity. Relative paths are legacy
+  // candidates and are tracked separately so they can be conservatively matched to managed files.
+  private final SortedMap<String,GcCandidate> absoluteFileCandidates = new TreeMap<>();
+  private final SortedMap<String,GcCandidate> relativeFileCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> absoluteFilesByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tabletDirCandidates = new HashMap<>();
+  private final SortedMap<String,GcCandidate> bulkDirCandidates = new TreeMap<>();
+  private final SortedMap<String,Set<String>> bulkDirsByManagedPath = new TreeMap<>();
+  private final Map<String,GcCandidate> tableDirCandidates = new HashMap<>();
 
-  private record LastThree(String maybeATableId, String dir, String name) {
+  public GcCandidates(Iterable<GcCandidate> candidates) {
+    for (GcCandidate candidate : candidates) {
+      try {
+        switch (candidate.getType()) {
+          case TABLET_FILE -> addFileCandidate(candidate);
+          case TABLET_DIR ->
+            tabletDirCandidates.put(relativePath(candidate.getPath(), 2), candidate);
+          case BULK_DIR -> addBulkDirCandidate(candidate);
+          case TABLE_DIR -> tableDirCandidates.put(relativePath(candidate.getPath(), 1), candidate);
+        }
+      } catch (IllegalArgumentException e) {
+        log.warn("Ignoring invalid deletion candidate {}", candidate);
+      }
+    }
   }
 
-  private LastThree lastThree(String strPath, int minPathLength) {
-    return lastThree(strPath, true, minPathLength, Integer.MAX_VALUE);
+  private void addFileCandidate(GcCandidate candidate) {
+    Path path = new Path(candidate.getPath());
+    if (path.toUri().getScheme() != null) {
+      String normalized = path.toString();
+      absoluteFileCandidates.put(normalized, candidate);
+      String managedPath = managedPath(path, 3);
+      if (managedPath != null) {
+        addIndex(absoluteFilesByManagedPath, managedPath, normalized);
+      }
+    } else {
+      String normalized = relativePath(candidate.getPath(), 3);
+      relativeFileCandidates.put(normalized, candidate);
+    }
   }
 
-  private LastThree lastThree(String strPath, boolean expectScheme, int minPathLength,
-      int maxPathLength) {
-    URI uri = null;
-    try {
-      uri = new URI(strPath);
-    } catch (URISyntaxException e) {
-      throw new IllegalArgumentException(e);
+  private void addBulkDirCandidate(GcCandidate candidate) {
+    Path path = new Path(candidate.getPath());
+    if (path.toUri().getScheme() == null) {
+      throw new IllegalArgumentException("Bulk directory candidate must be an absolute URI");
     }
-
-    if (expectScheme && uri.getScheme() == null) {
-      throw new IllegalArgumentException("Missing scheme in URI " + strPath);
+    String normalized = path.toString();
+    bulkDirCandidates.put(normalized, candidate);
+    String managedPath = managedPath(path, 2);
+    if (managedPath != null) {
+      addIndex(bulkDirsByManagedPath, managedPath, normalized);
     }
+  }
 
-    // TODO what about other parts of the URI?
-    var path = Path.of(uri.getPath());
+  private static void addIndex(SortedMap<String,Set<String>> index, String key, String path) {
+    index.computeIfAbsent(key, ignored -> new HashSet<>()).add(path);
+  }
 
-    int count = path.getNameCount();
-    if (count < minPathLength) {
-      throw new IllegalArgumentException("Path too short " + strPath);
+  private static String relativePath(String path, int expectedComponents) {
+    String candidatePath = path.startsWith("../") ? path.substring(3) : path;
+    Path parsed = new Path(candidatePath);
+    if (parsed.toUri().getScheme() != null) {
+      throw new IllegalArgumentException("Expected a relative candidate path: " + path);
+    }
+    String normalized = parsed.toString();
+    while (normalized.startsWith("/")) {
+      normalized = normalized.substring(1);
+    }
+    if (normalized.isEmpty()) {
+      throw new IllegalArgumentException("Empty candidate path");
     }
+    if (componentCount(normalized) != expectedComponents) {
+      throw new IllegalArgumentException("Unexpected candidate path depth: " + path);
+    }
+    return "/" + normalized;
+  }
 
-    if (count > maxPathLength) {
-      throw new IllegalArgumentException("Path too long " + strPath);
+  private static int componentCount(String path) {
+    int count = 0;
+    boolean inComponent = false;
+    for (int i = 0; i < path.length(); i++) {
+      char c = path.charAt(i);
+      if (c == '/') {
+        inComponent = false;
+      } else if (!inComponent) {
+        count++;
+        inComponent = true;
+      }
     }
+    return count;
+  }
 
-    if (count == 1) {
-      return new LastThree(null, null, path.getName(count - 1).toString());
-    } else if (count == 2) {
-      return new LastThree(null, path.getName(count - 2).toString(),
-          path.getName(count - 1).toString());
-    } else if (count >= 3) {
-      return new LastThree(path.getName(count - 3).toString(), path.getName(count - 2).toString(),
-          path.getName(count - 1).toString());
-    } else {
-      throw new IllegalArgumentException("Bad path " + path);
+  /**
+   * Extracts the table-relative tablet file or directory path if the URI follows the normal
+   * {@code .../tables/<tableId>/<tabletDir>/...} layout.
+   */
+  private static String managedPath(Path path, int componentsAfterTables) {
+    Path current = path;
+    String[] suffix = new String[componentsAfterTables];
+    for (int i = componentsAfterTables - 1; i >= 0; i--) {
+      if (current == null || current.getName().isEmpty()) {
+        return null;
+      }
+      suffix[i] = current.getName();
+      current = current.getParent();
+    }
+    if (current == null || !"tables".equals(current.getName())) {
+      return null;
+    }
+    StringBuilder result = new StringBuilder();
+    for (String component : suffix) {
+      result.append('/').append(component);
     }
+    return result.toString();
   }
 
-  public GcCandidates(Iterable<GcCandidate> candidates) {
-    candidates.forEach(candidate -> {
-      try {
-        switch (candidate.getType()) {
-          case TABLET_FILE -> {
-            var lastThree = lastThree(candidate.getPath(), 2);
-            fileCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
-          }
-          case TABLET_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 2, 2);
-            tabletDirCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
-          }
-          case BULK_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), 1);
-            bulkDirCandidates.put(lastThree.name, candidate);
-          }
-          case TABLE_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 1, 1);
-            tableDirCandidates.put(lastThree.name, candidate);
+  @Override
+  public Iterator<GcCandidate> iterator() {
+    return new Iterator<>() {
+      private final Iterator<GcCandidate> files = concat(absoluteFileCandidates.values().iterator(),
+          relativeFileCandidates.values().iterator());
+      private final Iterator<GcCandidate> tabletDirs = tabletDirCandidates.values().iterator();
+      private final Iterator<GcCandidate> bulkDirs = bulkDirCandidates.values().iterator();
+      private final Iterator<GcCandidate> tableDirs = tableDirCandidates.values().iterator();
+      private Iterator<GcCandidate> current = files;
+
+      private boolean advance() {
+        while (!current.hasNext()) {
+          if (current == files) {
+            current = tabletDirs;
+          } else if (current == tabletDirs) {
+            current = bulkDirs;
+          } else if (current == bulkDirs) {
+            current = tableDirs;
+          } else {
+            return false;
           }
         }
-      } catch (IllegalArgumentException e) {
-        log.warn("Ignoring invalid deletion candidate {}", candidate);
+        return true;
       }
-    });
+
+      @Override
+      public boolean hasNext() {
+        return advance();
+      }
+
+      @Override
+      public GcCandidate next() {
+        if (!advance()) {
+          throw new java.util.NoSuchElementException();
+        }
+        return current.next();
+      }
+    };
   }
 
-  @Override
-  public Iterator<GcCandidate> iterator() {
-    return Iterators.unmodifiableIterator(Iterators.concat(fileCandidates.values().iterator(),
-        tabletDirCandidates.values().iterator(), bulkDirCandidates.values().iterator(),
-        tableDirCandidates.values().iterator()));
+  private static Iterator<GcCandidate> concat(Iterator<GcCandidate> first,
+      Iterator<GcCandidate> second) {
+    return new Iterator<>() {
+      @Override
+      public boolean hasNext() {
+        return first.hasNext() || second.hasNext();
+      }
+
+      @Override
+      public GcCandidate next() {
+        return first.hasNext() ? first.next() : second.next();
+      }
+    };
   }
 
   public int removeBlip(String blip) {
-    var lastThree = lastThree(blip, false, 2, 2);
+    try {
+      Path blipPath = new Path(blip);
+      String normalized = blipPath.toString();
+      int removed = 0;
 
-    String blipPrefix = "/" + lastThree.name;
+      if (blipPath.toUri().getScheme() == null) {
+        String managed = relativePath(blip, 2);
+        String relativePrefix = withTrailingSlash(managed);
+        removed += removeSortedPrefix(relativeFileCandidates, relativePrefix, null);
+        removed += removeManagedPrefix(absoluteFilesByManagedPath, relativeFileCandidates,
+            absoluteFileCandidates, relativePrefix);
+        removeManagedBulkDirs(managed);
+        tabletDirCandidates.remove(managed);
+      } else {

Review Comment:
   Blips should always be of the form `/tableid/bulkdir`, so this code add a lot of unneeded complexity where the old code would just fail if a blip was not of the expected form. 



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4618003930


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   MAybe you are running into a quirk w/ the unit test.  Need to add a dir reference for each table to simulate what would be seen when scanning the metadata table.  When scanning the metadata table will see a dir ref for each tablet, the GC was looking for this inorder to verify it saw all tables in ZK in th e metadata table.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4618869002


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   I got everything working and pushed the changes. Not sure it's the way you want it, but the unit tests, sunny, GarbageCollectorIT, and the new ExternalTabletFileIT pass.
   
   The big change is using full file paths in the GC code, except for TABLE_DIR and TABLET_DIR types.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4666279912


##########
server/base/src/main/java/org/apache/accumulo/server/fs/VolumeUtil.java:
##########
@@ -62,23 +62,39 @@ public static Path removeTrailingSlash(Path path) {
   }
 
   public static Path switchVolume(Path path, FileType ft, Map<Path,Path> replacements) {
-    Path replacement = null;
-    if (!replacements.isEmpty()) {
-      // removing trailing slash for exact match comparison on the volume itself
-      Path volume = removeTrailingSlash(ft.getVolume(requireNonNull(path)));
-      replacement = replacements.entrySet().stream()
-          .filter(entry -> removeTrailingSlash(entry.getKey()).equals(volume))
-          .map(entry -> new Path(entry.getValue(), requireNonNull(ft.removeVolume(path))))
-          .findFirst().orElse(null);
-    }
-    if (replacement != null) {
-      log.trace("Replacing {} with {} for {}", path, replacement, ft);
-      return replacement;
+    requireNonNull(path);
+    for (Entry<Path,Path> entry : replacements.entrySet()) {
+      Path source = removeTrailingSlash(entry.getKey());
+      Path relative = getRelativePath(source, path);
+      if (relative != null) {
+        Path replacement = relative.toString().equals(".") ? entry.getValue()

Review Comment:
   Fair point, I fixed the logic in ff31412



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4621272974


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -95,21 +96,20 @@ private LastThree lastThree(String strPath, boolean expectScheme, int minPathLen
   public GcCandidates(Iterable<GcCandidate> candidates) {
     candidates.forEach(candidate -> {
       try {
+        String normalized = new org.apache.hadoop.fs.Path(candidate.getPath()).toString();

Review Comment:
   One thing that seems tricky w/ volume replacement is that the GC process could potentially be scanning the metadata table when volume replacement is partially done. If this happens could it cause the GC to delete files it should not if its using absolute paths?



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4392743964


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -216,18 +300,31 @@ private long removeBlipCandidates(GarbageCollectionEnvironment gce,
         while (blipiter.hasNext()) {
           blipCount++;
           String blipPath = blipiter.next();
-          blipPath = makeRelative(blipPath, 2);
-
-          Iterator<String> tailIter = candidateMap.tailMap(blipPath).keySet().iterator();
+          Path blip = new Path(blipPath);
+          boolean absoluteBlip = blip.toUri().getScheme() != null;
+          String relativeBlip = null;
+          try {
+            relativeBlip = makeRelative(blipPath, 2);
+          } catch (IllegalArgumentException e) {
+            // External bulk-load paths are matched using their full URI below.
+          }
 
+          Iterator<Entry<String,GcCandidate>> candidateIter = candidateMap.entrySet().iterator();
           int count = 0;
-
-          while (tailIter.hasNext()) {
-            if (tailIter.next().startsWith(blipPath)) {
+          while (candidateIter.hasNext()) {

Review Comment:
   The comment I made elsewhere about reworking the keys in the map to be able to continue leveraging the sorted order of the map may help avoid this increase in computational complexity.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4495275965


##########
core/src/main/java/org/apache/accumulo/core/metadata/ScanServerRefTabletFile.java:
##########
@@ -19,37 +19,43 @@
 package org.apache.accumulo.core.metadata;
 
 import java.net.URI;
+import java.util.Collection;
+import java.util.HashSet;
 import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
 import java.util.UUID;
 
 import org.apache.accumulo.core.data.Key;
 import org.apache.accumulo.core.data.Mutation;
+import org.apache.accumulo.core.data.TableId;
 import org.apache.accumulo.core.data.Value;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.Text;
 
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+
+@SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW",
+    justification = "Constructor validation is required for proper initialization")
 public class ScanServerRefTabletFile extends ReferencedTabletFile {
 
-  private final Value NULL_VALUE = new Value(new byte[0]);
   private final Text serverAddress;
   private final Text uuid;
+  private final Set<TableId> tableIds;

Review Comment:
   Removed table ids from ScanServerRefTabletFile in dfa43d3.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4618889720


##########
core/src/main/java/org/apache/accumulo/core/metadata/ReferencedTabletFile.java:
##########
@@ -171,34 +59,27 @@ public ReferencedTabletFile(Path metaPath) {
    * qualify an absolute path or create a new file.
    */
   public ReferencedTabletFile(Path metaPath, Range range) {
-    super(Objects.requireNonNull(metaPath), range);
-    log.trace("Parsing TabletFile from {}", metaPath);
-    parts = parsePath(metaPath);
-  }
-
-  public String getVolume() {
-    return parts.getVolume();
-  }
-
-  public TableId getTableId() {
-    return parts.getTableId();
+    super(validatePath(metaPath), range);
+    log.trace("Creating tablet file reference from {}", metaPath);
   }
 
-  public String getTabletDir() {
-    return parts.getTabletDir();
+  private static Path validatePath(Path metaPath) {
+    Path path = ValidationUtil.validate(Objects.requireNonNull(metaPath));
+    Preconditions.checkArgument(!path.getName().isEmpty(), "Path must identify a file: %s", path);

Review Comment:
   Added below.



##########
server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java:
##########
@@ -110,38 +111,38 @@ public static void deleteTable(TableId tableId, boolean insertDeletes, ServerCon
       Ample ample = context.getAmple();
       ms.setRange(new KeyExtent(tableId, null, null).toMetaRange());
 
-      // Insert tmp delete markers before deleting data from metadata... this makes the code
-      // idempotent. TmpDeletes avoids race conditions with GC deleting in use candidates. The
-      // actual deletes markers must be inserted after the tables metadata is deleted. If the actual
-      // delete markers are inserted before deleting the tablet metadata, then the GC may see them
-      // as in use and delete them. Buffering delete markers in memory may not fit and would not be
-      // idempotent, so write them to a temp area.
+      // Temporary candidates avoid a race with GC while tablet metadata is being deleted. Also
+      // retain candidates for external files when directory deletion is optimized.
+      ms.fetchColumnFamily(DataFileColumnFamily.NAME);
       if (insertDeletes) {
-
-        ms.fetchColumnFamily(DataFileColumnFamily.NAME);
         ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms);
+      }
 
-        for (Entry<Key,Value> cell : ms) {
-          Key key = cell.getKey();
+      for (Entry<Key,Value> cell : ms) {
+        Key key = cell.getKey();
 
-          if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) {
-            StoredTabletFile stf = new StoredTabletFile(key.getColumnQualifierData().toString());
+        if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) {
+          StoredTabletFile stf = new StoredTabletFile(key.getColumnQualifierData().toString());
+          if (insertDeletes || !isInTableDirectories(context, tableId, stf.getPath())) {

Review Comment:
   I still need to look at this comment.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4629690506


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -95,21 +96,20 @@ private LastThree lastThree(String strPath, boolean expectScheme, int minPathLen
   public GcCandidates(Iterable<GcCandidate> candidates) {
     candidates.forEach(candidate -> {
       try {
+        String normalized = new org.apache.hadoop.fs.Path(candidate.getPath()).toString();
         switch (candidate.getType()) {
           case TABLET_FILE -> {
-            var lastThree = lastThree(candidate.getPath(), 2);
-            fileCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
+            fileCandidates.put(normalized, candidate);
           }
           case TABLET_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 2, 2);
+            var lastThree = lastThree(normalized, false, 2, 2);
             tabletDirCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
           }
           case BULK_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), 1);
-            bulkDirCandidates.put(lastThree.name, candidate);
+            bulkDirCandidates.put(normalized, candidate);

Review Comment:
   Fixed in 4444d87



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4618095462


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   Going to look into removing the table id from the ref, its very confusing they way it works.  The table id is from the extent not the file path and its only needed for a validation the GC does against table ids in ZK.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4620447798


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -95,21 +96,20 @@ private LastThree lastThree(String strPath, boolean expectScheme, int minPathLen
   public GcCandidates(Iterable<GcCandidate> candidates) {
     candidates.forEach(candidate -> {
       try {
+        String normalized = new org.apache.hadoop.fs.Path(candidate.getPath()).toString();
         switch (candidate.getType()) {
           case TABLET_FILE -> {
-            var lastThree = lastThree(candidate.getPath(), 2);
-            fileCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
+            fileCandidates.put(normalized, candidate);
           }
           case TABLET_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), false, 2, 2);
+            var lastThree = lastThree(normalized, false, 2, 2);
             tabletDirCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
           }
           case BULK_DIR -> {
-            var lastThree = lastThree(candidate.getPath(), 1);
-            bulkDirCandidates.put(lastThree.name, candidate);
+            bulkDirCandidates.put(normalized, candidate);

Review Comment:
   Would be good to ensure there is no trailing slash for the dir as its not expected.
   
   ```suggestion
               Preconditions.checkArgument(!normalized.endsWith("/"));
               bulkDirCandidates.put(normalized, candidate);
   ```
   
   Also, should check that the bulk dir has a scheme.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -127,17 +127,19 @@ public Iterator<GcCandidate> iterator() {
   }
 
   public int removeBlip(String blip) {
-    var lastThree = lastThree(blip, false, 2, 2);
-
-    String blipPrefix = "/" + lastThree.name;
-
-    bulkDirCandidates.remove(lastThree.name);
+    log.trace("Removing candidates for bulk load in-progress marker: {}", blip);
+    var removed = bulkDirCandidates.remove(blip);
+    if (removed != null) {
+      log.trace("Removed {} from bulkDirCandidates", removed.getPath());
+    }
 
-    var tailIter = fileCandidates.tailMap(blipPrefix).keySet().iterator();
+    var tailIter = fileCandidates.tailMap(blip).keySet().iterator();
     int removeCount = 0;
     while (tailIter.hasNext()) {
-      if (tailIter.next().startsWith(blipPrefix)) {
+      String fileCandidate = tailIter.next();
+      if (fileCandidate.startsWith(blip + "/")) {

Review Comment:
   Could construct the string once and use it for the tail map.
   
   ```suggestion
       String blipWithSlash = blip + "/";
       var tailIter = fileCandidates.tailMap(blipWithSlash).keySet().iterator();
   int removeCount = 0;
   while (tailIter.hasNext()) {
         String fileCandidate = tailIter.next();
         if (fileCandidate.startsWith(blipWithSlash)) {
   ```



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -161,14 +163,23 @@ public void remove(Reference reference, Consumer<GcCandidate> removedConsumer) {
           .accept(tabletDirCandidates.remove("/" + reference.getTableId() + "/" + lastThree.name));
       nonNullConsumer.accept(tableDirCandidates.remove(reference.getTableId().toString()));
     } else {
-      var lastThree = lastThree(reference.getMetadataPath(), 2);
-      if (lastThree.maybeATableId != null) {
-        nonNullConsumer.accept(
-            tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
-        nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+      String path = reference.getMetadataPath();
+      try {
+        var lastThree = lastThree(path, 2);
+        if (lastThree.maybeATableId != null) {
+          nonNullConsumer.accept(
+              tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
+          nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+        }
+      } catch (IllegalArgumentException iae) {

Review Comment:
   Why catch and ignore this? 



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -161,14 +163,23 @@ public void remove(Reference reference, Consumer<GcCandidate> removedConsumer) {
           .accept(tabletDirCandidates.remove("/" + reference.getTableId() + "/" + lastThree.name));
       nonNullConsumer.accept(tableDirCandidates.remove(reference.getTableId().toString()));
     } else {
-      var lastThree = lastThree(reference.getMetadataPath(), 2);
-      if (lastThree.maybeATableId != null) {
-        nonNullConsumer.accept(
-            tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
-        nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+      String path = reference.getMetadataPath();

Review Comment:
   Need to normalize this to be safe and avoid deleting referenced files.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -127,17 +127,19 @@ public Iterator<GcCandidate> iterator() {
   }
 
   public int removeBlip(String blip) {
-    var lastThree = lastThree(blip, false, 2, 2);
-
-    String blipPrefix = "/" + lastThree.name;
-
-    bulkDirCandidates.remove(lastThree.name);
+    log.trace("Removing candidates for bulk load in-progress marker: {}", blip);

Review Comment:
   It would be safer to normalize the blip.  Also could ensure it does not end w/ a trailing slash.
   
   ```suggestion
       Preconditions.checkArgument(!blip.endsWith("/"));
   
       log.trace("Removing candidates for bulk load in-progress marker: {}", blip);
       // normalize blip to be safe
       // TODO ensure blip has a scheme
       blip = new org.apache.hadoop.fs.Path(blip).toString();
   ```
   
   
   Also, should probably check that the blip has a scheme.



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -95,21 +96,20 @@ private LastThree lastThree(String strPath, boolean expectScheme, int minPathLen
   public GcCandidates(Iterable<GcCandidate> candidates) {
     candidates.forEach(candidate -> {
       try {
+        String normalized = new org.apache.hadoop.fs.Path(candidate.getPath()).toString();

Review Comment:
   May be good to put this into a private static normalize method.  
   
   How confident are you in using this approach to normalize paths?  Is it documented in the hadoop javadocs, can we rely on it going forward as new versions of hadoop come out?  If the normalization is not reliable it could lead to deleting referenced files.  I looked into using URI to normalize instead, but did not come to a conclusion if it was better or worse than using hadoop path. I did find that URI has a normalize method and played with it in jshell.  I also looked a little bit at the hadoop path internals to see what it does for normalization, to see if it just uses URI and it does not. The hadoop code does its own thing for normalization in the version I looked at.
   
   Overall I like using the full absolute paths instead of the shorter paths taken from the last three when it makes sense to do so, however I am a bit wary about its correctness. One thing I liked about the shorter paths was I could look at the normalization code and feel confident about it.  Also w/ the shorter paths did not have to worry about volume replacement. Now that needs to be considered for correctness, not sure what the status of that is in the GC code.  W/ the short paths did not have to worry about volume replacement. So I like the full paths if we can get them correct, however they seem to have more error cases to worry about.  The advantage of the full paths is it avoids over matching, the shorter paths may overmatch but are less likely to delete referenced files. Using the shorter paths was predicated on the concept that the last two path elements were unique when taken together.
   



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -161,14 +163,23 @@ public void remove(Reference reference, Consumer<GcCandidate> removedConsumer) {
           .accept(tabletDirCandidates.remove("/" + reference.getTableId() + "/" + lastThree.name));
       nonNullConsumer.accept(tableDirCandidates.remove(reference.getTableId().toString()));
     } else {
-      var lastThree = lastThree(reference.getMetadataPath(), 2);
-      if (lastThree.maybeATableId != null) {
-        nonNullConsumer.accept(
-            tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
-        nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+      String path = reference.getMetadataPath();
+      try {
+        var lastThree = lastThree(path, 2);
+        if (lastThree.maybeATableId != null) {
+          nonNullConsumer.accept(
+              tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
+          nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+        }
+      } catch (IllegalArgumentException iae) {
+        log.debug("Unable to determine table and tablet dirs for path {}", path);
+      }
+      log.trace("Removing file candidate that matches: {}", path);
+      nonNullConsumer.accept(fileCandidates.remove(path));
+      if (path.contains(Constants.BULK_PREFIX)) {
+        log.trace("Removing file candidate that matches bulk dir path: {}", path.lastIndexOf("/"));
+        nonNullConsumer.accept(bulkDirCandidates.remove(path.substring(0, path.lastIndexOf("/"))));

Review Comment:
   This logs the int returned by `lastIndexOf()`
   
   ```suggestion
           var dirPath = path.substring(0, path.lastIndexOf("/"));
           log.trace("Removing file candidate that matches bulk dir path: {}", dirPath);
           nonNullConsumer.accept(bulkDirCandidates.remove(dirPath));
   ```



##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -95,21 +96,20 @@ private LastThree lastThree(String strPath, boolean expectScheme, int minPathLen
   public GcCandidates(Iterable<GcCandidate> candidates) {
     candidates.forEach(candidate -> {
       try {
+        String normalized = new org.apache.hadoop.fs.Path(candidate.getPath()).toString();
         switch (candidate.getType()) {
           case TABLET_FILE -> {
-            var lastThree = lastThree(candidate.getPath(), 2);
-            fileCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
+            fileCandidates.put(normalized, candidate);

Review Comment:
   For tablet files used to check if they had a scheme, should probably still do that.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4659955209


##########
server/base/src/main/java/org/apache/accumulo/server/fs/VolumeUtil.java:
##########
@@ -62,23 +62,39 @@ public static Path removeTrailingSlash(Path path) {
   }
 
   public static Path switchVolume(Path path, FileType ft, Map<Path,Path> replacements) {
-    Path replacement = null;
-    if (!replacements.isEmpty()) {
-      // removing trailing slash for exact match comparison on the volume itself
-      Path volume = removeTrailingSlash(ft.getVolume(requireNonNull(path)));
-      replacement = replacements.entrySet().stream()
-          .filter(entry -> removeTrailingSlash(entry.getKey()).equals(volume))
-          .map(entry -> new Path(entry.getValue(), requireNonNull(ft.removeVolume(path))))
-          .findFirst().orElse(null);
-    }
-    if (replacement != null) {
-      log.trace("Replacing {} with {} for {}", path, replacement, ft);
-      return replacement;
+    requireNonNull(path);
+    for (Entry<Path,Path> entry : replacements.entrySet()) {
+      Path source = removeTrailingSlash(entry.getKey());
+      Path relative = getRelativePath(source, path);
+      if (relative != null) {
+        Path replacement = relative.toString().equals(".") ? entry.getValue()

Review Comment:
   Using exceptions for expected cases is not good because the exception could be caused by something other than what is expected.  Also if the code is executed frequently creating exceptions is expensive relative to some sort of if stmt that does an explicit check.  Creating an exception requires filling in the stack trace which used to be slow, probably still is.
   
   The external paths are being added for a single use case, bulk imports.  If we assumed this new use case always had paths of the form `<a fully qualifies uri and path>/be-<unique id>/<file>` it could potentially simplify things here and in the GC code.  If we look at the parent dir and it has the prefix `be-` then we know its an external file. The bulk import operation could enforce this minimal naming convention.
   



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4496054262


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -119,18 +123,72 @@ private String makeRelative(String path, int expectedLen) {
     return relPath;
   }
 
-  private SortedMap<String,GcCandidate> makeRelative(Collection<GcCandidate> candidates) {
+  private String makeCandidateKey(String path) {
+    try {
+      String relative = makeRelative(path, 0);
+      if (SimpleGarbageCollector.isDir(relative)) {
+        return DIRECTORY_CANDIDATE_KEY_PREFIX + relative;
+      }
+    } catch (IllegalArgumentException e) {
+      // Paths for external files do not have the Accumulo tables/<table>/<tablet> structure.
+      // Their full URI is their identity, so don't discard them or compare by path suffix.
+    }
+
+    return fileCandidateKey(path);
+  }
+
+  private String fileCandidateKey(String path) {
+    if (path.endsWith("/")) {
+      throw new IllegalArgumentException("GC file candidate is a directory: " + path);
+    }
+    Path candidatePath = new Path(path);
+    if (candidatePath.toUri().getScheme() != null) {
+      if (candidatePath.getName().isEmpty()) {
+        throw new IllegalArgumentException("GC file candidate does not identify a file: " + path);
+      }
+      return FILE_CANDIDATE_KEY_PREFIX + candidatePath;
+    }
+
+    // Relative paths are retained for compatibility with older metadata entries. Once paths are
+    // absolute, full URI identity is required so files at distinct locations cannot alias.
+    String relative = tryMakeRelative(path, 3);
+    if (relative == null) {
+      throw new IllegalArgumentException("Invalid relative GC file candidate: " + path);
+    }
+    return FILE_CANDIDATE_KEY_PREFIX + "RELATIVE|" + relative;
+  }
+
+  private String directoryCandidateKey(String relativePath) {
+    return DIRECTORY_CANDIDATE_KEY_PREFIX + relativePath;
+  }
+
+  private String tabletDirectoryKey(String filePath) {
+    String relativeFile = tryMakeRelative(filePath, 3);
+    if (relativeFile == null) {
+      // External files are not in an Accumulo tablet directory and have no directory candidate to
+      // suppress.
+      return null;
+    }
+    return directoryCandidateKey(relativeFile.substring(0, relativeFile.lastIndexOf('/')));
+  }
+
+  private String tryMakeRelative(String path, int expectedLen) {
+    try {
+      return makeRelative(path, expectedLen);
+    } catch (IllegalArgumentException e) {
+      return null;
+    }
+  }
+
+  private SortedMap<String,GcCandidate> makeCandidateMap(Collection<GcCandidate> candidates) {
     SortedMap<String,GcCandidate> ret = new TreeMap<>();
 
     for (GcCandidate candidate : candidates) {
-      String relPath;
       try {
-        relPath = makeRelative(candidate.getPath(), 0);
-      } catch (IllegalArgumentException iae) {
+        ret.put(makeCandidateKey(candidate.getPath()), candidate);

Review Comment:
   In 698c481 I removed the `FILE|` and `DIR|` prefixes and implemented your suggestion.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4616761678


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   The tableId comes from the tablet metadata it seems, not from the file.  An external file will never be a dir reference, so should be ok to look for dir refs.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4629663222


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -95,21 +96,20 @@ private LastThree lastThree(String strPath, boolean expectScheme, int minPathLen
   public GcCandidates(Iterable<GcCandidate> candidates) {
     candidates.forEach(candidate -> {
       try {
+        String normalized = new org.apache.hadoop.fs.Path(candidate.getPath()).toString();
         switch (candidate.getType()) {
           case TABLET_FILE -> {
-            var lastThree = lastThree(candidate.getPath(), 2);
-            fileCandidates.put("/" + lastThree.dir + "/" + lastThree.name, candidate);
+            fileCandidates.put(normalized, candidate);

Review Comment:
   Fixed in 4444d87



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4617662290


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   Isn't the problem here that the tableId is not in the directory path at all?



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4616907377


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   I backed out the changes to GcAlgorithm and GcCandidates. My comment above was about the following test failing:
   
   ```
     @Test
     public void externalFilesAreMatchedByFullUri() throws Exception {
       TestGCE gce = new TestGCE();
   
       var sameNameDifferentLocation = gce.addCandidate("hdfs://nn1/external/b/shared.rf");
       var referencedCandidate = gce.addCandidate("hdfs://nn2/external/b/shared.rf");
       gce.addFileReference("4", null, referencedCandidate.getPath());
   
       new GarbageCollectionAlgorithm().collect(gce);
   
       assertFileDeleted(gce, sameNameDifferentLocation);
       assertCandidateRemoved(gce, GcCandidateType.INUSE, referencedCandidate);
     }
   ```
   
   It fails because `referencedCandidate` is added to table `4`, but there is nothing in the file path for a tableId.
   
   I have made modifications so that file and bulk candidates are tracked by full path. That fixes this test, and working through some other failures.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4617025219


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -53,8 +53,10 @@ private void removeCandidatesInUse(GarbageCollectionEnvironment gce, GcCandidate
     Set<TableId> tableIdsSeen = new HashSet<>(tableIdsBefore.size());
     try (Stream<Reference> references = gce.getReferences()) {
       references.forEach(ref -> {
-        if (ref.isDirectory()) {
+        try {
           tableIdsSeen.add(ref.getTableId());
+        } catch (UnsupportedOperationException uoe) {

Review Comment:
   GcCandidates was assuming that `dir/file` at the end of the path is unique.  This would be the case the if the bulk import operation enforced not reusing dir names as was discussed.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4659955209


##########
server/base/src/main/java/org/apache/accumulo/server/fs/VolumeUtil.java:
##########
@@ -62,23 +62,39 @@ public static Path removeTrailingSlash(Path path) {
   }
 
   public static Path switchVolume(Path path, FileType ft, Map<Path,Path> replacements) {
-    Path replacement = null;
-    if (!replacements.isEmpty()) {
-      // removing trailing slash for exact match comparison on the volume itself
-      Path volume = removeTrailingSlash(ft.getVolume(requireNonNull(path)));
-      replacement = replacements.entrySet().stream()
-          .filter(entry -> removeTrailingSlash(entry.getKey()).equals(volume))
-          .map(entry -> new Path(entry.getValue(), requireNonNull(ft.removeVolume(path))))
-          .findFirst().orElse(null);
-    }
-    if (replacement != null) {
-      log.trace("Replacing {} with {} for {}", path, replacement, ft);
-      return replacement;
+    requireNonNull(path);
+    for (Entry<Path,Path> entry : replacements.entrySet()) {
+      Path source = removeTrailingSlash(entry.getKey());
+      Path relative = getRelativePath(source, path);
+      if (relative != null) {
+        Path replacement = relative.toString().equals(".") ? entry.getValue()

Review Comment:
   Using exceptions for expected cases is not good because the exception could be caused by something other than what is expected.  Also if the code is executed frequently creating exceptions is expensive relative to some sort of if stmt that does an explicit check.  Creating an exception requires filling in the stack trace which used to be slow, probably still is.
   
   The external paths are being added for a single use case, bulk imports.  If we assumed this new use case always had paths of the form `<a fully qualifies uri and path>/be-<unique id>/<file>` it could potentially simplify things here and in the GC code.  If we look at the parent dir and it has the prefix `be-` then we know its an external file.
   



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4660009015


##########
server/base/src/test/java/org/apache/accumulo/server/fs/VolumeUtilTest.java:
##########
@@ -52,6 +52,10 @@ public void testSwitchVolume() {
         FileType.TABLE, replacements));
     assertNull(VolumeUtil.switchVolume(new Path("file:/nn1/a/accumulo/tables/t-00000/C000.rf"),
         FileType.TABLE, replacements));
+    assertEquals(new Path("viewfs:/a/accumulo/external/C000.rf"), VolumeUtil.switchVolume(
+        new Path("hdfs://nn1/accumulo/external/C000.rf"), FileType.TABLE, replacements));
+    assertNull(VolumeUtil.switchVolume(new Path("hdfs://nn1/accumulo-sibling/external/C000.rf"),
+        FileType.TABLE, replacements));

Review Comment:
   could add another test for the longest volume case.



##########
test/src/main/java/org/apache/accumulo/test/ExternalTabletFileIT.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.time.Duration;
+
+import org.apache.accumulo.core.client.Accumulo;
+import org.apache.accumulo.core.client.AccumuloClient;
+import org.apache.accumulo.core.client.Scanner;
+import org.apache.accumulo.core.client.admin.CompactionConfig;
+import org.apache.accumulo.core.client.rfile.RFile;
+import org.apache.accumulo.core.client.rfile.RFileWriter;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.data.Key;
+import org.apache.accumulo.core.data.TableId;
+import org.apache.accumulo.core.data.Value;
+import org.apache.accumulo.core.dataImpl.KeyExtent;
+import org.apache.accumulo.core.gc.GcCandidate;
+import org.apache.accumulo.core.metadata.StoredTabletFile;
+import org.apache.accumulo.core.metadata.schema.Ample;
+import org.apache.accumulo.core.metadata.schema.DataFileValue;
+import org.apache.accumulo.core.metadata.schema.TabletMetadata;
+import org.apache.accumulo.core.security.Authorizations;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.functional.ConfigurableMacBase;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.junit.jupiter.api.Test;
+
+/** Exercises tablet files stored outside Accumulo's configured table directories. */
+public class ExternalTabletFileIT extends ConfigurableMacBase {
+
+  private static final Duration GC_WAIT = Duration.ofSeconds(45);
+  private static final long GC_POLL_MS = 100;
+
+  @Override
+  public void configure(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.useMiniDFS(true);
+    cfg.setProperty(Property.GC_CYCLE_START, "1s");
+    cfg.setProperty(Property.GC_CYCLE_DELAY, "1s");
+    super.configure(cfg, hadoopCoreSite);
+  }
+
+  @Override
+  protected Duration defaultTimeout() {
+    return Duration.ofMinutes(3);
+  }
+
+  @Test
+  public void scanAndCompactExternalFile() throws Exception {
+    try (AccumuloClient client = Accumulo.newClient().from(getClientProperties()).build()) {
+      FileSystem fs = getCluster().getMiniDfs().getFileSystem();
+      String table = getUniqueNames(1)[0];
+      client.tableOperations().create(table);
+
+      Path externalFile = writeRFile(fs, "scan-compact");
+      addFileReference(client, table, externalFile, fs.getFileStatus(externalFile).getLen(), 2);
+
+      assertRows(client, table);
+
+      client.tableOperations().compact(table, new CompactionConfig().setWait(true));
+
+      assertRows(client, table);
+      assertTrue(hasConfiguredVolumeFile(client, table));
+      Wait.waitFor(() -> !fs.exists(externalFile), GC_WAIT.toMillis(), GC_POLL_MS,
+          "GC did not remove compacted external RFile " + externalFile);
+    }
+  }
+

Review Comment:
   Could add a test to split and then merge a tablet w/ an external file.  For the data being written by the helper function could add a split at `r1`.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub) via notifications" <no...@accumulo.apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4493986931


##########
core/src/main/java/org/apache/accumulo/core/metadata/ScanServerRefTabletFile.java:
##########
@@ -19,37 +19,43 @@
 package org.apache.accumulo.core.metadata;
 
 import java.net.URI;
+import java.util.Collection;
+import java.util.HashSet;
 import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
 import java.util.UUID;
 
 import org.apache.accumulo.core.data.Key;
 import org.apache.accumulo.core.data.Mutation;
+import org.apache.accumulo.core.data.TableId;
 import org.apache.accumulo.core.data.Value;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.Text;
 
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+
+@SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW",
+    justification = "Constructor validation is required for proper initialization")
 public class ScanServerRefTabletFile extends ReferencedTabletFile {
 
-  private final Value NULL_VALUE = new Value(new byte[0]);
   private final Text serverAddress;
   private final Text uuid;
+  private final Set<TableId> tableIds;

Review Comment:
   Should be able to make ScanServerRefTabletFile.geTableId throw an unsupported operation exception because it should not be used.  The tables ids are used by gc to ensure we saw a tablet for each table id in ZK (its a validation to ensure the GC does not skip data for any reason like a scanner bug).  Scan server refs are not part of the tablet metadata and we should not use them for that validation, if we make the change to only get table id when its a dir.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "keith-turner (via GitHub)" <gi...@apache.org>.
keith-turner commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4392612871


##########
server/gc/src/main/java/org/apache/accumulo/gc/GarbageCollectionAlgorithm.java:
##########
@@ -119,18 +123,72 @@ private String makeRelative(String path, int expectedLen) {
     return relPath;
   }
 
-  private SortedMap<String,GcCandidate> makeRelative(Collection<GcCandidate> candidates) {
+  private String makeCandidateKey(String path) {
+    try {
+      String relative = makeRelative(path, 0);
+      if (SimpleGarbageCollector.isDir(relative)) {
+        return DIRECTORY_CANDIDATE_KEY_PREFIX + relative;
+      }
+    } catch (IllegalArgumentException e) {
+      // Paths for external files do not have the Accumulo tables/<table>/<tablet> structure.
+      // Their full URI is their identity, so don't discard them or compare by path suffix.
+    }
+
+    return fileCandidateKey(path);
+  }
+
+  private String fileCandidateKey(String path) {
+    if (path.endsWith("/")) {
+      throw new IllegalArgumentException("GC file candidate is a directory: " + path);
+    }
+    Path candidatePath = new Path(path);
+    if (candidatePath.toUri().getScheme() != null) {
+      if (candidatePath.getName().isEmpty()) {
+        throw new IllegalArgumentException("GC file candidate does not identify a file: " + path);
+      }
+      return FILE_CANDIDATE_KEY_PREFIX + candidatePath;
+    }
+
+    // Relative paths are retained for compatibility with older metadata entries. Once paths are
+    // absolute, full URI identity is required so files at distinct locations cannot alias.
+    String relative = tryMakeRelative(path, 3);
+    if (relative == null) {
+      throw new IllegalArgumentException("Invalid relative GC file candidate: " + path);
+    }
+    return FILE_CANDIDATE_KEY_PREFIX + "RELATIVE|" + relative;
+  }
+
+  private String directoryCandidateKey(String relativePath) {
+    return DIRECTORY_CANDIDATE_KEY_PREFIX + relativePath;
+  }
+
+  private String tabletDirectoryKey(String filePath) {
+    String relativeFile = tryMakeRelative(filePath, 3);
+    if (relativeFile == null) {
+      // External files are not in an Accumulo tablet directory and have no directory candidate to
+      // suppress.
+      return null;
+    }
+    return directoryCandidateKey(relativeFile.substring(0, relativeFile.lastIndexOf('/')));
+  }
+
+  private String tryMakeRelative(String path, int expectedLen) {
+    try {
+      return makeRelative(path, expectedLen);
+    } catch (IllegalArgumentException e) {
+      return null;
+    }
+  }
+
+  private SortedMap<String,GcCandidate> makeCandidateMap(Collection<GcCandidate> candidates) {
     SortedMap<String,GcCandidate> ret = new TreeMap<>();
 
     for (GcCandidate candidate : candidates) {
-      String relPath;
       try {
-        relPath = makeRelative(candidate.getPath(), 0);
-      } catch (IllegalArgumentException iae) {
+        ret.put(makeCandidateKey(candidate.getPath()), candidate);

Review Comment:
   Prefixing keys with in this map prevents some of the efficient operations that used to be possible.  The old code leveraged the sorted to map to efficiently find all files that started with a given directory.  This was done using range operations on the keys.  I think we could restore this efficient behavior if we did the following two things.
   
     * Normalize the paths in the map (like change hdfs://foo////a//b/ to hdfs://foo/a/b/
     * Adopt the convention that all directory keys end with `/` and no file entries end with slash.  Drop the `FILE` and `DIR` prefixes.  With this convention we could have  a static function `isDir()` that looks at the last char of the string.
   
   With those changes, hopefully we can continue to do things similar to the way the existing code does and efficiently find all files with a given dir.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4629666581


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -161,14 +163,23 @@ public void remove(Reference reference, Consumer<GcCandidate> removedConsumer) {
           .accept(tabletDirCandidates.remove("/" + reference.getTableId() + "/" + lastThree.name));
       nonNullConsumer.accept(tableDirCandidates.remove(reference.getTableId().toString()));
     } else {
-      var lastThree = lastThree(reference.getMetadataPath(), 2);
-      if (lastThree.maybeATableId != null) {
-        nonNullConsumer.accept(
-            tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
-        nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+      String path = reference.getMetadataPath();
+      try {
+        var lastThree = lastThree(path, 2);
+        if (lastThree.maybeATableId != null) {
+          nonNullConsumer.accept(
+              tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
+          nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+        }
+      } catch (IllegalArgumentException iae) {
+        log.debug("Unable to determine table and tablet dirs for path {}", path);
+      }
+      log.trace("Removing file candidate that matches: {}", path);
+      nonNullConsumer.accept(fileCandidates.remove(path));
+      if (path.contains(Constants.BULK_PREFIX)) {
+        log.trace("Removing file candidate that matches bulk dir path: {}", path.lastIndexOf("/"));
+        nonNullConsumer.accept(bulkDirCandidates.remove(path.substring(0, path.lastIndexOf("/"))));

Review Comment:
   Fixed in 4444d87



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4629906092


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -95,21 +96,20 @@ private LastThree lastThree(String strPath, boolean expectScheme, int minPathLen
   public GcCandidates(Iterable<GcCandidate> candidates) {
     candidates.forEach(candidate -> {
       try {
+        String normalized = new org.apache.hadoop.fs.Path(candidate.getPath()).toString();

Review Comment:
   Regarding the questions around Path - I looked into this a little further. Specifically for files, a Hadoop Path object is at the root of AbstractTabletFile. I think AbstractTabletFile objects are going to be both GcCandidate's and Reference's, but we are translating the file path's to a String and then trying to validate and normalize them. I'm wondering if, for files, we should use Path in GcCandidate and ReferenceFile as long as possible, instead of converting them to String early on in the process.



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4629670000


##########
server/gc/src/main/java/org/apache/accumulo/gc/GcCandidates.java:
##########
@@ -161,14 +163,23 @@ public void remove(Reference reference, Consumer<GcCandidate> removedConsumer) {
           .accept(tabletDirCandidates.remove("/" + reference.getTableId() + "/" + lastThree.name));
       nonNullConsumer.accept(tableDirCandidates.remove(reference.getTableId().toString()));
     } else {
-      var lastThree = lastThree(reference.getMetadataPath(), 2);
-      if (lastThree.maybeATableId != null) {
-        nonNullConsumer.accept(
-            tabletDirCandidates.remove("/" + lastThree.maybeATableId + "/" + lastThree.dir));
-        nonNullConsumer.accept(tableDirCandidates.remove(lastThree.maybeATableId));
+      String path = reference.getMetadataPath();

Review Comment:
   Fixed in 4444d87



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fixes and verification for RFiles located outside of tables directory [accumulo]

Posted by "dlmarion (via GitHub) via notifications" <no...@accumulo.apache.org>.
dlmarion commented on code in PR #6611:
URL: https://github.com/apache/accumulo/pull/6611#discussion_r4666274656


##########
test/src/main/java/org/apache/accumulo/test/ExternalTabletFileIT.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.time.Duration;
+
+import org.apache.accumulo.core.client.Accumulo;
+import org.apache.accumulo.core.client.AccumuloClient;
+import org.apache.accumulo.core.client.Scanner;
+import org.apache.accumulo.core.client.admin.CompactionConfig;
+import org.apache.accumulo.core.client.rfile.RFile;
+import org.apache.accumulo.core.client.rfile.RFileWriter;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.core.data.Key;
+import org.apache.accumulo.core.data.TableId;
+import org.apache.accumulo.core.data.Value;
+import org.apache.accumulo.core.dataImpl.KeyExtent;
+import org.apache.accumulo.core.gc.GcCandidate;
+import org.apache.accumulo.core.metadata.StoredTabletFile;
+import org.apache.accumulo.core.metadata.schema.Ample;
+import org.apache.accumulo.core.metadata.schema.DataFileValue;
+import org.apache.accumulo.core.metadata.schema.TabletMetadata;
+import org.apache.accumulo.core.security.Authorizations;
+import org.apache.accumulo.minicluster.ServerType;
+import org.apache.accumulo.miniclusterImpl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.functional.ConfigurableMacBase;
+import org.apache.accumulo.test.util.Wait;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.junit.jupiter.api.Test;
+
+/** Exercises tablet files stored outside Accumulo's configured table directories. */
+public class ExternalTabletFileIT extends ConfigurableMacBase {
+
+  private static final Duration GC_WAIT = Duration.ofSeconds(45);
+  private static final long GC_POLL_MS = 100;
+
+  @Override
+  public void configure(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.useMiniDFS(true);
+    cfg.setProperty(Property.GC_CYCLE_START, "1s");
+    cfg.setProperty(Property.GC_CYCLE_DELAY, "1s");
+    super.configure(cfg, hadoopCoreSite);
+  }
+
+  @Override
+  protected Duration defaultTimeout() {
+    return Duration.ofMinutes(3);
+  }
+
+  @Test
+  public void scanAndCompactExternalFile() throws Exception {
+    try (AccumuloClient client = Accumulo.newClient().from(getClientProperties()).build()) {
+      FileSystem fs = getCluster().getMiniDfs().getFileSystem();
+      String table = getUniqueNames(1)[0];
+      client.tableOperations().create(table);
+
+      Path externalFile = writeRFile(fs, "scan-compact");
+      addFileReference(client, table, externalFile, fs.getFileStatus(externalFile).getLen(), 2);
+
+      assertRows(client, table);
+
+      client.tableOperations().compact(table, new CompactionConfig().setWait(true));
+
+      assertRows(client, table);
+      assertTrue(hasConfiguredVolumeFile(client, table));
+      Wait.waitFor(() -> !fs.exists(externalFile), GC_WAIT.toMillis(), GC_POLL_MS,
+          "GC did not remove compacted external RFile " + externalFile);
+    }
+  }
+

Review Comment:
   Added in ff31412



##########
server/base/src/test/java/org/apache/accumulo/server/fs/VolumeUtilTest.java:
##########
@@ -52,6 +52,10 @@ public void testSwitchVolume() {
         FileType.TABLE, replacements));
     assertNull(VolumeUtil.switchVolume(new Path("file:/nn1/a/accumulo/tables/t-00000/C000.rf"),
         FileType.TABLE, replacements));
+    assertEquals(new Path("viewfs:/a/accumulo/external/C000.rf"), VolumeUtil.switchVolume(
+        new Path("hdfs://nn1/accumulo/external/C000.rf"), FileType.TABLE, replacements));
+    assertNull(VolumeUtil.switchVolume(new Path("hdfs://nn1/accumulo-sibling/external/C000.rf"),
+        FileType.TABLE, replacements));

Review Comment:
   Added in ff31412



-- 
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: notifications-unsubscribe@accumulo.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org