You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jena.apache.org by an...@apache.org on 2024/03/05 22:57:43 UTC
(jena) branch main updated (e1e9c890f2 -> e54eb5e45f)
This is an automated email from the ASF dual-hosted git repository.
andy pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/jena.git
from e1e9c890f2 GH-2297: Add CORS configuration file as command line parameter to Fuseki Main.
new 5d3f3d78b8 Better code organisation for TDB2 database operations
new f0e8c46955 Constants for log-logging
new e54eb5e45f GH-2254: Atomic compaction
The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../src/main/java/org/apache/jena/atlas/io/IO.java | 4 +-
.../java/org/apache/jena/atlas/logging/LogCtl.java | 18 +-
.../main/java/org/apache/jena/dboe/sys/IO_DB.java | 58 +-----
.../apache/jena/fuseki/system/spot/SpotTDB2.java | 13 +-
.../src/main/java/org/apache/jena/tdb2/TDB2.java | 1 -
.../java/org/apache/jena/tdb2/sys/DatabaseOps.java | 210 +++++++++++++++++----
.../jena/tdb2/setup/TestStoreParamsCreate.java | 2 +-
.../apache/jena/tdb2/sys/TestDatabaseCompact.java | 35 ++++
8 files changed, 228 insertions(+), 113 deletions(-)
(jena) 01/03: Better code organisation for TDB2 database operations
Posted by an...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
andy pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/jena.git
commit 5d3f3d78b8bdc0952135a00279eea8bfa6c5c657
Author: Andy Seaborne <an...@apache.org>
AuthorDate: Sat Mar 2 12:11:13 2024 +0000
Better code organisation for TDB2 database operations
---
.../main/java/org/apache/jena/dboe/sys/IO_DB.java | 56 +--------
.../apache/jena/fuseki/system/spot/SpotTDB2.java | 13 +-
.../src/main/java/org/apache/jena/tdb2/TDB2.java | 1 -
.../java/org/apache/jena/tdb2/sys/DatabaseOps.java | 135 ++++++++++++++++++---
.../jena/tdb2/setup/TestStoreParamsCreate.java | 2 +-
5 files changed, 122 insertions(+), 85 deletions(-)
diff --git a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java
index 52e4ea3dac..970f8e3865 100644
--- a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java
+++ b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java
@@ -19,25 +19,17 @@
package org.apache.jena.dboe.sys;
import java.io.File;
-import java.io.IOException;
-import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.List;
import java.util.Objects;
-import java.util.regex.Pattern;
import org.apache.jena.atlas.RuntimeIOException;
-import org.apache.jena.atlas.logging.FmtLog;
-import org.apache.jena.dboe.DBOpEnvException;
import org.apache.jena.dboe.base.file.Location;
public class IO_DB {
// Location == org.apache.jena.dboe.base.file.Location
-
+
/** Convert a {@link Path} to a {@link Location}. */
public static Location asLocation(Path path) {
Objects.requireNonNull(path, "IOX.asLocation(null)");
@@ -57,50 +49,4 @@ public class IO_DB {
public static File asFile(org.apache.jena.dboe.base.file.Location loc) {
return new File(loc.getDirectoryPath());
}
-
- /** Find the files in this directory that have namebase as a prefix and
- * are then numbered.
- * <p>
- * Returns a sorted list from, low to high index.
- */
- public static List<Path> scanForDirByPattern(Path directory, String namebase, String nameSep) {
- Pattern pattern = Pattern.compile(Pattern.quote(namebase)+
- Pattern.quote(nameSep)+
- "[\\d]+");
- List<Path> paths = new ArrayList<>();
- try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, namebase + "*")) {
- for ( Path entry : stream ) {
- if ( !pattern.matcher(entry.getFileName().toString()).matches() ) {
- throw new DBOpEnvException("Invalid filename for matching: "+entry.getFileName());
- // Alternative: Skip bad trailing parts but more likely there is a naming problem.
- // LOG.warn("Invalid filename for matching: {} skipped", entry.getFileName());
- // continue;
- }
- // Follows symbolic links.
- if ( !Files.isDirectory(entry) )
- throw new DBOpEnvException("Not a directory: "+entry);
- paths.add(entry);
- }
- }
- catch (IOException ex) {
- FmtLog.warn(IO_DB.class, "Can't inspect directory: (%s, %s)", directory, namebase);
- throw new DBOpEnvException(ex);
- }
- Comparator<Path> comp = (f1, f2) -> {
- int num1 = extractIndex(f1.getFileName().toString(), namebase, nameSep);
- int num2 = extractIndex(f2.getFileName().toString(), namebase, nameSep);
- return Integer.compare(num1, num2);
- };
- paths.sort(comp);
- //indexes.sort(Long::compareTo);
- return paths;
- }
-
- /** Given a filename in "base-NNNN" format, return the value of NNNN */
- public static int extractIndex(String name, String namebase, String nameSep) {
- int i = namebase.length()+nameSep.length();
- String numStr = name.substring(i);
- int num = Integer.parseInt(numStr);
- return num;
- }
}
diff --git a/jena-fuseki2/jena-fuseki-core/src/main/java/org/apache/jena/fuseki/system/spot/SpotTDB2.java b/jena-fuseki2/jena-fuseki-core/src/main/java/org/apache/jena/fuseki/system/spot/SpotTDB2.java
index d0c4fca5cd..9e52eb1907 100644
--- a/jena-fuseki2/jena-fuseki-core/src/main/java/org/apache/jena/fuseki/system/spot/SpotTDB2.java
+++ b/jena-fuseki2/jena-fuseki-core/src/main/java/org/apache/jena/fuseki/system/spot/SpotTDB2.java
@@ -33,7 +33,6 @@ import org.apache.jena.tdb2.TDBException;
import org.apache.jena.tdb2.params.StoreParams;
import org.apache.jena.tdb2.params.StoreParamsCodec;
import org.apache.jena.tdb2.sys.DatabaseOps;
-import org.apache.jena.tdb2.sys.Util;
class SpotTDB2 {
@@ -115,21 +114,11 @@ class SpotTDB2 {
/** Return the current active database area within a database directory. */
private static Path storageDir(Location location) {
- // Database directory
- Path path = IO_DB.asPath(location);
// Storage directory in database directory.
- Path db = findLocation(path, DatabaseOps.dbPrefix);
+ Path db = DatabaseOps.findStorageLocation(location);
return db;
}
- private static Path findLocation(Path directory, String namebase) {
- if ( ! Files.exists(directory) )
- return null;
- // In-order, low to high.
- List<Path> maybe = IO_DB.scanForDirByPattern(directory, namebase, DatabaseOps.SEP);
- return Util.getLastOrNull(maybe);
- }
-
// Places for StoreParams: location or default
private static StoreParams getStoreParams(Location location) {
StoreParams params = StoreParamsCodec.read(location);
diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/TDB2.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/TDB2.java
index bc1a10c3a5..522af67d3a 100644
--- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/TDB2.java
+++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/TDB2.java
@@ -126,7 +126,6 @@ public class TDB2 {
SystemTDB.init();
EnvTDB.processGlobalSystemProperties();
-
MappingRegistry.addPrefixMapping(SystemTDB.tdbSymbolPrefix, SystemTDB.symbolNamespace);
AssemblerUtils.init();
VocabTDB2.init();
diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java
index 3b5f5d1c22..2a8caf6c78 100644
--- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java
+++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java
@@ -20,8 +20,10 @@ package org.apache.jena.tdb2.sys;
import java.io.*;
import java.nio.file.*;
+import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
+import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.GZIPOutputStream;
@@ -30,7 +32,9 @@ import org.apache.jena.atlas.io.IOX;
import org.apache.jena.atlas.lib.DateTimeUtils;
import org.apache.jena.atlas.lib.Lib;
import org.apache.jena.atlas.lib.Pair;
+import org.apache.jena.atlas.logging.FmtLog;
import org.apache.jena.atlas.logging.Log;
+import org.apache.jena.dboe.DBOpEnvException;
import org.apache.jena.dboe.base.file.Location;
import org.apache.jena.dboe.sys.IO_DB;
import org.apache.jena.dboe.sys.Names;
@@ -50,7 +54,8 @@ import org.apache.jena.tdb2.store.DatasetGraphTDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/** Operations on and about TDB2 databases.
+/**
+ * Operations related to TDB2 databases.
* <p>
* TDB2 uses a hierarchical structure to manage on disk.
* <p>
@@ -68,9 +73,16 @@ import org.slf4j.LoggerFactory;
*/
public class DatabaseOps {
private static Logger LOG = LoggerFactory.getLogger(DatabaseOps.class);
- public static final String dbPrefix = "Data";
- public static final String SEP = "-";
- public static final String startCount = "0001";
+ // Composition of a database storage area directory name.
+ public static final String dbNameBase = "Data";
+ public static final String SEP = "-";
+ public static final String dbSuffixPattern = "[\\d]+";
+
+ public static final String startCount = "0001";
+
+ // Additional suffix used during compact
+ private static final String dbTmpSuffix = "-tmp";
+ private static final String dbTmpPattern = "[\\d]+"+dbTmpSuffix;
private static final String BACKUPS_DIR = "Backups";
// Basename of the backup file. "backup_{DateTime}.nq.gz
@@ -101,15 +113,20 @@ public class DatabaseOps {
if ( ! containerLocation.exists() )
throw new TDBException("No such location: "+containerLocation);
Path path = IO_DB.asPath(containerLocation);
+
+ // Clean any temporary files and directories that there might be.
+ cleanDatabaseDirectory(path);
+
// Scan for DBs
- Path existingStorage = findLocation(path, dbPrefix);
+ Path existingStorage = findStorageLocation(path);
boolean isNewArea = (existingStorage == null);
Path db = existingStorage;
if ( db == null ) {
- db = path.resolve(dbPrefix+SEP+startCount);
+ db = path.resolve(dbNameBase+SEP+startCount);
IOX.createDirectory(db);
}
+
Location storageLocation = IO_DB.asLocation(db);
// ---- Find the params (if any).
@@ -139,6 +156,11 @@ public class DatabaseOps {
return appDSG;
}
+ /**
+ * Clear out any partial compactions.
+ */
+ private static void cleanDatabaseDirectory(Path directory) {
+ }
private static ReorderTransformation maybeTransform(ReorderTransformation reorderTransform, Location location) {
if ( reorderTransform != null )
@@ -249,10 +271,10 @@ public class DatabaseOps {
public static void compact(DatasetGraphSwitchable container, boolean shouldDeleteOld) {
checkSupportsAdmin(container);
synchronized(compactionLock) {
- Path base = container.getContainerPath();
- Path db1 = findLocation(base, dbPrefix);
+ Path containerPath = container.getContainerPath();
+ Path db1 = findStorageLocation(containerPath);
if ( db1 == null )
- throw new TDBException("No location: ("+base+", "+dbPrefix+")");
+ throw new TDBException("No location: ("+containerPath+", "+dbNameBase+")");
Location loc1 = IO_DB.asLocation(db1);
// -- Checks
@@ -266,15 +288,31 @@ public class DatabaseOps {
throw new TDBException("Inconsistent (not latest?) : "+loc1a+" : "+loc1);
// Check version
- int v = IO_DB.extractIndex(db1.getFileName().toString(), dbPrefix, SEP);
- String next = FilenameUtils.filename(dbPrefix, SEP, v+1);
+ int v = extractIndex(db1.getFileName().toString(), dbNameBase, SEP);
+ String next = FilenameUtils.filename(dbNameBase, SEP, v+1);
Path db2 = db1.getParent().resolve(next);
IOX.createDirectory(db2);
Location loc2 = IO_DB.asLocation(db2);
LOG.debug(String.format("Compact %s -> %s\n", db1.getFileName(), db2.getFileName()));
- compact(container, loc1, loc2);
+ Location loc2tmp = loc2;
+ try {
+ compact(container, loc1, loc2tmp);
+
+ Path path2 = Path.of(loc2.getDirectoryPath());
+ Path path2tmp = Path.of(loc2tmp.getDirectoryPath());
+
+ Files.move(path2tmp, path2);
+
+ // Move loc2tmp to loc2
+ } catch (IOException ex) {
+ // Delete loc2tmp;
+ throw IOX.exception(ex);
+ } catch (Throwable th) {
+ // Delete loc2tmp;
+ throw th;
+ }
if ( shouldDeleteOld ) {
// Compact put each of the databases into exclusive mode to do the switchover.
@@ -337,7 +375,7 @@ public class DatabaseOps {
CopyDSG.copy(dsgBase, dsgCompact);
if ( false ) {
- // DEVELOMENT. FAke a long copy time in state copy.
+ // DEVELOPMENT. Fake a long copy time in state copy.
System.err.println("-- Inside compact 1");
Lib.sleep(3_000);
System.err.println("-- Inside compact 2");
@@ -372,7 +410,6 @@ public class DatabaseOps {
});
-
// This switches off the source database.
// It waits until all transactions (readers) have finished.
// This call is not undone.
@@ -407,11 +444,77 @@ public class DatabaseOps {
}
}
- private static Path findLocation(Path directory, String namebase) {
+ /**
+ * Find the files in this directory that have namebase as a prefix and
+ * are then numbered.
+ * <p>
+ * Returns a sorted list from, low to high index.
+ * @param directory Path to the data base directory
+ * @param namebase Initial common component of the name
+ * @param nameSep Separator
+ * @param trailerPattern Pattern for the part of the name after the namebase.
+ * @return List<Path> List sorted low to high
+ *
+ */
+ private static List<Path> scanForDirByPattern(Path directory, String namebase, String nameSep, String trailerPattern) {
+ Pattern pattern = Pattern.compile(Pattern.quote(namebase)+
+ Pattern.quote(nameSep)+
+ trailerPattern);
+ List<Path> paths = new ArrayList<>();
+ try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, namebase + "*")) {
+ for ( Path entry : stream ) {
+ if ( !pattern.matcher(entry.getFileName().toString()).matches() ) {
+ throw new DBOpEnvException("Invalid filename for matching: "+entry.getFileName());
+ // Alternative: Skip bad trailing parts but more likely there is a naming problem.
+ // LOG.warn("Invalid filename for matching: {} skipped", entry.getFileName());
+ // continue;
+ }
+ // Follows symbolic links.
+ if ( !Files.isDirectory(entry) )
+ throw new DBOpEnvException("Not a directory: "+entry);
+ paths.add(entry);
+ }
+ }
+ catch (IOException ex) {
+ FmtLog.warn(IO_DB.class, "Can't inspect directory: (%s, %s)", directory, namebase);
+ throw new DBOpEnvException(ex);
+ }
+ Comparator<Path> comp = (f1, f2) -> {
+ int num1 = extractIndex(f1.getFileName().toString(), namebase, nameSep);
+ int num2 = extractIndex(f2.getFileName().toString(), namebase, nameSep);
+ return Integer.compare(num1, num2);
+ };
+ paths.sort(comp);
+ //indexes.sort(Long::compareTo);
+ return paths;
+ }
+
+ /** Given a filename in "base-NNNN" format, return the value of NNNN */
+ public static int extractIndex(String name, String namebase, String nameSep) {
+ int i = namebase.length()+nameSep.length();
+ String numStr = name.substring(i);
+ int num = Integer.parseInt(numStr);
+ return num;
+ }
+
+ /**
+ * Find the active working storage area for a TDB2 database.
+ * Return null if none.
+ */
+ public static Path findStorageLocation(Location directory) {
+ Path dirPath = IO_DB.asPath(directory);
+ return findStorageLocation(dirPath);
+ }
+
+ /**
+ * Find the active working storage area for a TDB2 database.
+ * Return null if none.
+ */
+ public static Path findStorageLocation(Path directory) {
if ( ! Files.exists(directory) )
return null;
// In-order, low to high.
- List<Path> maybe = IO_DB.scanForDirByPattern(directory, namebase, SEP);
+ List<Path> maybe = scanForDirByPattern(directory, dbNameBase, SEP, dbSuffixPattern);
return Util.getLastOrNull(maybe);
}
diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/setup/TestStoreParamsCreate.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/setup/TestStoreParamsCreate.java
index 63b292db9a..2aabad3b7f 100644
--- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/setup/TestStoreParamsCreate.java
+++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/setup/TestStoreParamsCreate.java
@@ -44,7 +44,7 @@ public class TestStoreParamsCreate {
// This may be different for each test
private final String DB_DIR = ConfigTest.getCleanDir();
private final Path dbContainer = Path.of(DB_DIR);
- private final Path dbStorage = dbContainer.resolve(DatabaseOps.dbPrefix+DatabaseOps.SEP+DatabaseOps.startCount);
+ private final Path dbStorage = dbContainer.resolve(DatabaseOps.dbNameBase+DatabaseOps.SEP+DatabaseOps.startCount);
private final Path cfgContainer = dbContainer.resolve(Names.TDB_CONFIG_FILE);
private final Path cfgStorage = dbStorage.resolve(Names.TDB_CONFIG_FILE);
(jena) 03/03: GH-2254: Atomic compaction
Posted by an...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
andy pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/jena.git
commit e54eb5e45fbb546342681046049509a76df58cc9
Author: Andy Seaborne <an...@apache.org>
AuthorDate: Sat Mar 2 16:21:23 2024 +0000
GH-2254: Atomic compaction
---
.../main/java/org/apache/jena/dboe/sys/IO_DB.java | 2 +-
.../java/org/apache/jena/tdb2/sys/DatabaseOps.java | 131 +++++++++++++--------
.../apache/jena/tdb2/sys/TestDatabaseCompact.java | 35 ++++++
3 files changed, 116 insertions(+), 52 deletions(-)
diff --git a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java
index 970f8e3865..e3915ac5fb 100644
--- a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java
+++ b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/sys/IO_DB.java
@@ -46,7 +46,7 @@ public class IO_DB {
}
/** Convert a {@link Location} to a {@link File}. */
- public static File asFile(org.apache.jena.dboe.base.file.Location loc) {
+ public static File asFile(Location loc) {
return new File(loc.getDirectoryPath());
}
}
diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java
index 2a8caf6c78..44b278678f 100644
--- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java
+++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/DatabaseOps.java
@@ -23,15 +23,14 @@ import java.nio.file.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
+import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import java.util.stream.Stream;
import java.util.zip.GZIPOutputStream;
import org.apache.jena.atlas.RuntimeIOException;
+import org.apache.jena.atlas.io.IO;
import org.apache.jena.atlas.io.IOX;
-import org.apache.jena.atlas.lib.DateTimeUtils;
-import org.apache.jena.atlas.lib.Lib;
-import org.apache.jena.atlas.lib.Pair;
+import org.apache.jena.atlas.lib.*;
import org.apache.jena.atlas.logging.FmtLog;
import org.apache.jena.atlas.logging.Log;
import org.apache.jena.dboe.DBOpEnvException;
@@ -48,7 +47,10 @@ import org.apache.jena.sparql.engine.optimizer.reorder.ReorderTransformation;
import org.apache.jena.sparql.sse.SSE_ParseException;
import org.apache.jena.system.Txn;
import org.apache.jena.tdb2.TDBException;
-import org.apache.jena.tdb2.params.*;
+import org.apache.jena.tdb2.params.StoreParams;
+import org.apache.jena.tdb2.params.StoreParamsBuilder;
+import org.apache.jena.tdb2.params.StoreParamsCodec;
+import org.apache.jena.tdb2.params.StoreParamsFactory;
import org.apache.jena.tdb2.store.DatasetGraphSwitchable;
import org.apache.jena.tdb2.store.DatasetGraphTDB;
import org.slf4j.Logger;
@@ -82,12 +84,14 @@ public class DatabaseOps {
// Additional suffix used during compact
private static final String dbTmpSuffix = "-tmp";
- private static final String dbTmpPattern = "[\\d]+"+dbTmpSuffix;
+ private static final String dbTmpPattern = "[\\d]+-tmp";
private static final String BACKUPS_DIR = "Backups";
// Basename of the backup file. "backup_{DateTime}.nq.gz
private static final String BACKUPS_FN = "backup";
+ private enum ScanAccept { EXACT, SKIP }
+
/**
* Create a fresh database - called by {@code DatabaseMgr}.
* It is important to go via {@code DatabaseConnection} to avoid
@@ -160,6 +164,11 @@ public class DatabaseOps {
* Clear out any partial compactions.
*/
private static void cleanDatabaseDirectory(Path directory) {
+ List<Path> tmpDirs = scanForDirByPattern(directory, dbNameBase, SEP, dbTmpPattern, ScanAccept.SKIP);
+ for ( Path dir : tmpDirs ) {
+ FmtLog.info(LOG, "Remove incomplete compaction temporary directory: "+dir);
+ IO.deleteAll(dir);
+ }
}
private static ReorderTransformation maybeTransform(ReorderTransformation reorderTransform, Location location) {
@@ -292,25 +301,28 @@ public class DatabaseOps {
String next = FilenameUtils.filename(dbNameBase, SEP, v+1);
Path db2 = db1.getParent().resolve(next);
- IOX.createDirectory(db2);
- Location loc2 = IO_DB.asLocation(db2);
LOG.debug(String.format("Compact %s -> %s\n", db1.getFileName(), db2.getFileName()));
+ if ( Files.exists(db2) )
+ throw new TDBException("Inconsistent : "+db2+" already exists");
- Location loc2tmp = loc2;
- try {
- compact(container, loc1, loc2tmp);
-
- Path path2 = Path.of(loc2.getDirectoryPath());
- Path path2tmp = Path.of(loc2tmp.getDirectoryPath());
+ // Location of the storage area for the compacted database.
+ // This is a temporary direction that is atomically moved into place when complete.
+ Path tmpDir = makeTempDirName(db2);
+ if ( Files.exists(tmpDir) )
+ throw new TDBException("Inconsistent : tmpdir"+tmpDir+" already exists");
+ IOX.createDirectory(tmpDir);
+ Location loc2tmp = Location.create(tmpDir);
- Files.move(path2tmp, path2);
-
- // Move loc2tmp to loc2
- } catch (IOException ex) {
- // Delete loc2tmp;
- throw IOX.exception(ex);
+ try {
+ compact(container, loc1, loc2tmp, db2);
+ // Container now using the new location.
+ } catch (RuntimeIOException ex) {
+ // Clear up - disk problems.
+ try { IO.deleteAll(tmpDir); } catch (Throwable th) { /* Continue with original error. */ }
+ throw ex;
} catch (Throwable th) {
- // Delete loc2tmp;
+ // Jena and Java errors
+ try { IO.deleteAll(tmpDir); } catch (Throwable th2) { /* Continue with original error. */ }
throw th;
}
@@ -319,25 +331,22 @@ public class DatabaseOps {
// There are no previous transactions on the old database at this point.
Path loc1Path = IO_DB.asPath(loc1);
LOG.debug("Deleting old database after successful compaction (old db path='" + loc1Path + "')...");
- deleteDatabase(loc1Path);
+ IO.deleteAll(loc1Path);
}
}
}
- private static void deleteDatabase(Path locationPath) {
- try (Stream<Path> walk = Files.walk(locationPath)){
- walk.sorted(Comparator.reverseOrder())
- .map(Path::toFile)
- .forEach(File::delete);
- } catch (IOException ex) {
- throw IOX.exception(ex);
- }
+ private static Path makeTempDirName(Path path) {
+ String dirname = path.toString();
+ if ( dirname.endsWith("/"))
+ dirname = StrUtils.chop(dirname);
+ return Path.of(dirname+dbTmpSuffix);
}
/** Copy the latest version from one location to another. */
- private static void compact(DatasetGraphSwitchable container, Location loc1, Location loc2) {
- if ( loc1.isMem() || loc2.isMem() )
- throw new TDBException("Compact involves a memory location: "+loc1+" : "+loc2);
+ private static void compact(DatasetGraphSwitchable container, Location loc1, Location loc2tmp, Path path2final) {
+ if ( loc1.isMem() || loc2tmp.isMem() )
+ throw new TDBException("Compact involves a memory location: "+loc1+" : "+loc2tmp);
StoreConnection srcConn = StoreConnection.connectExisting(loc1);
@@ -370,19 +379,27 @@ public class DatabaseOps {
// These are held up on a lock in the switchable container.
// -- Copy the current state to the new area.
- copyConfigFiles(loc1, loc2);
- DatasetGraphTDB dsgCompact = StoreConnection.connectCreate(loc2).getDatasetGraphTDB();
- CopyDSG.copy(dsgBase, dsgCompact);
+ copyConfigFiles(loc1, loc2tmp);
+ DatasetGraphTDB dsgTmpCompact = StoreConnection.connectCreate(loc2tmp).getDatasetGraphTDB();
if ( false ) {
// DEVELOPMENT. Fake a long copy time in state copy.
System.err.println("-- Inside compact 1");
Lib.sleep(3_000);
System.err.println("-- Inside compact 2");
}
+ CopyDSG.copy(dsgBase, dsgTmpCompact);
+ StoreConnection.internalExpel(loc2tmp, true);
+ // Now on-disk in tmp location.
+
+ moveDirectory(loc2tmp, path2final);
+ Location loc2final = Location.create(path2final); // Location must exist.
+
+ // Next generation storage datasetGraph.
+ DatasetGraphTDB dsgCompact = StoreConnection.connectCreate(loc2final).getDatasetGraphTDB();
- TransactionCoordinator txnMgr2 = dsgCompact.getTxnSystem().getTxnMgr();
// Update TransactionCoordinator and switch over.
+ TransactionCoordinator txnMgr2 = dsgCompact.getTxnSystem().getTxnMgr();
txnMgr2.execExclusive(()->{
// No active transactions in either database.
txnMgr2.takeOverFrom(txnMgr1);
@@ -419,6 +436,13 @@ public class DatabaseOps {
StoreConnection.release(dsgBase.getLocation());
}
+ private static void moveDirectory(Location locTmp, Path pathDst) {
+ Path pathSrc = IO_DB.asPath(locTmp);
+ try {
+ Files.move(pathSrc, pathDst);
+ } catch (IOException ex) { throw IOX.exception(ex); }
+ }
+
/** Copy certain configuration files from {@code loc1} to {@code loc2}. */
private static void copyConfigFiles(Location loc1, Location loc2) {
FileFilter copyFiles = (pathname)->{
@@ -454,20 +478,20 @@ public class DatabaseOps {
* @param nameSep Separator
* @param trailerPattern Pattern for the part of the name after the namebase.
* @return List<Path> List sorted low to high
- *
*/
- private static List<Path> scanForDirByPattern(Path directory, String namebase, String nameSep, String trailerPattern) {
+ private static List<Path> scanForDirByPattern(Path directory, String namebase, String nameSep, String trailerPattern, ScanAccept skipOthers) {
Pattern pattern = Pattern.compile(Pattern.quote(namebase)+
Pattern.quote(nameSep)+
trailerPattern);
List<Path> paths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, namebase + "*")) {
for ( Path entry : stream ) {
- if ( !pattern.matcher(entry.getFileName().toString()).matches() ) {
- throw new DBOpEnvException("Invalid filename for matching: "+entry.getFileName());
- // Alternative: Skip bad trailing parts but more likely there is a naming problem.
- // LOG.warn("Invalid filename for matching: {} skipped", entry.getFileName());
- // continue;
+ String filename = entry.getFileName().toString();
+ if ( !pattern.matcher(filename).matches() ) {
+ switch ( skipOthers ) {
+ case EXACT: throw new DBOpEnvException("Invalid filename for matching: "+entry.getFileName());
+ case SKIP: continue;
+ }
}
// Follows symbolic links.
if ( !Files.isDirectory(entry) )
@@ -489,12 +513,17 @@ public class DatabaseOps {
return paths;
}
- /** Given a filename in "base-NNNN" format, return the value of NNNN */
- public static int extractIndex(String name, String namebase, String nameSep) {
- int i = namebase.length()+nameSep.length();
- String numStr = name.substring(i);
- int num = Integer.parseInt(numStr);
- return num;
+ private static Pattern numberPattern = Pattern.compile("[\\d]+");
+ /** Given a filename in "base-NNNN(-text)" format, return the value of NNNN */
+ private static int extractIndex(String name, String namebase, String nameSep) {
+ Matcher matcher = numberPattern.matcher(name);
+ if ( matcher.find() ) {
+ var numStr = matcher.group();
+ int num = Integer.parseInt(numStr);
+ return num;
+ } else {
+ throw new InternalErrorException("Expected to find a number in '"+name+"'");
+ }
}
/**
@@ -514,7 +543,7 @@ public class DatabaseOps {
if ( ! Files.exists(directory) )
return null;
// In-order, low to high.
- List<Path> maybe = scanForDirByPattern(directory, dbNameBase, SEP, dbSuffixPattern);
+ List<Path> maybe = scanForDirByPattern(directory, dbNameBase, SEP, dbSuffixPattern, ScanAccept.EXACT);
return Util.getLastOrNull(maybe);
}
diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/sys/TestDatabaseCompact.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/sys/TestDatabaseCompact.java
index 573d94fab4..354c29fb3a 100644
--- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/sys/TestDatabaseCompact.java
+++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/sys/TestDatabaseCompact.java
@@ -21,6 +21,9 @@ package org.apache.jena.tdb2.sys;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
@@ -298,4 +301,36 @@ public class TestDatabaseCompact
Txn.executeWrite(dsg, ()->{});
assertEquals(2, counter.get());
}
+
+ @Test public void compact_recovery_1() throws IOException {
+ DatasetGraph dsg = DatabaseMgr.connectDatasetGraph(dir);
+ Txn.executeWrite(dsg, ()->dsg.add(quad1));
+
+ DatasetGraphSwitchable dsgs = (DatasetGraphSwitchable)dsg;
+ DatasetGraph dsg1 = dsgs.get();
+ Location loc1 = ((DatasetGraphTDB)dsg1).getLocation();
+
+ // Mock some temporary files.
+ Path pathTmp1 = dsgs.getContainerPath().resolve("Data-9999-tmp");
+ Files.createDirectory(pathTmp1);
+ Path pathTmp2 = dsgs.getContainerPath().resolve("Data-9998-tmp");
+ Files.createDirectory(pathTmp2);
+ Path pathFile2 = pathTmp2.resolve("data");
+ Files.writeString(pathFile2, "Hello world");
+
+ assertTrue(Files.exists(pathTmp1));
+ assertTrue(Files.exists(pathFile2));
+ assertTrue(Files.exists(pathTmp2));
+ // Drop database
+ TDBInternal.expel(dsg);
+
+ // Reconnect
+ DatasetGraph dsg2 = DatabaseMgr.connectDatasetGraph(dir);
+ Txn.executeRead(dsg2, ()->assertTrue(dsg2.contains(quad1)));
+
+ // These should no longer exist.
+ assertFalse(Files.exists(pathTmp1));
+ assertFalse(Files.exists(pathFile2));
+ assertFalse(Files.exists(pathTmp2));
+ }
}
(jena) 02/03: Constants for log-logging
Posted by an...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
andy pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/jena.git
commit f0e8c46955f3dc1dfb652740d0da561be8b062d0
Author: Andy Seaborne <an...@apache.org>
AuthorDate: Sat Mar 2 14:26:06 2024 +0000
Constants for log-logging
---
.../src/main/java/org/apache/jena/atlas/io/IO.java | 4 ++--
.../java/org/apache/jena/atlas/logging/LogCtl.java | 18 ++++++++++++++++--
2 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/jena-base/src/main/java/org/apache/jena/atlas/io/IO.java b/jena-base/src/main/java/org/apache/jena/atlas/io/IO.java
index fac0bf4e11..5dc8211247 100644
--- a/jena-base/src/main/java/org/apache/jena/atlas/io/IO.java
+++ b/jena-base/src/main/java/org/apache/jena/atlas/io/IO.java
@@ -579,7 +579,7 @@ public class IO
* This function does not follow symbolic links.
*/
public static void deleteAll(Path start) {
- // Walks down the tree and delete directories on the way backup.
+ // Walk down the tree deleting files, and delete directories on the way backup.
try {
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
@@ -598,7 +598,7 @@ public class IO
}
});
}
- catch (IOException ex) { IO.exception(ex); return; }
+ catch (IOException ex) { throw IOX.exception(ex); }
}
// Do nothing buffer. Never read from this, it may be corrupt because it is shared.
diff --git a/jena-base/src/main/java/org/apache/jena/atlas/logging/LogCtl.java b/jena-base/src/main/java/org/apache/jena/atlas/logging/LogCtl.java
index e0429ec5aa..b0c67b081a 100644
--- a/jena-base/src/main/java/org/apache/jena/atlas/logging/LogCtl.java
+++ b/jena-base/src/main/java/org/apache/jena/atlas/logging/LogCtl.java
@@ -285,9 +285,23 @@ public class LogCtl {
private static final String[] log4j2files = {"log4j2.properties", "log4j2.xml"};
+ /**
+ * Environment variable for debugging logging initialization.
+ * Set "true" to get trace on stderr.
+ */
+ // Must be final for static LogLogging to work.
+ public static final String envLogLoggingProperty = "JENA_LOGLOGGING";
+
+ /**
+ * Property variable for debugging logging initialization. Set "true" to get
+ * trace on stderr.
+ */
+ // Must be final for static LogLogging to work.
+ public static final String logLoggingProperty = "jena.logLogging";
+
private static final boolean LogLogging =
- System.getenv("JENA_LOGLOGGING") != null ||
- System.getProperty("jena.loglogging") != null;
+ System.getenv(envLogLoggingProperty) != null ||
+ System.getProperty(logLoggingProperty) != null;
private static void logLogging(String fmt, Object ... args) {
if ( LogLogging ) {