mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Load pack modules from temporary copies so the original jars stay unlocked
PackModules copies the pack's jars into a fresh iris-pack-modules-* directory and reads, checks and defines classes from the copies only, so a load sees one consistent snapshot and the pack class loader never holds the originals open (on Windows that locked them against rebuilding). Copies are deleted when the pack closes (after its loader) and on any load failure. Messages and origins keep naming modules/<jar>, including an entry class found in another jar of the pack. Each copy directory holds an owner file with the creating process id. A later load removes directories whose owner process has exited and that hold only that file and jars; everything else is left alone.
This commit is contained in:
1 parent
fe51496ab0
commit
333e2f6459
6 files changed
+415
-26
No files matched your search
@@ -0,0 +1,121 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Copies of one pack load's module jars in a fresh temporary directory. The load reads, checks and
|
||||
* defines classes from the copies only, so it sees one consistent snapshot even if a jar is rebuilt
|
||||
* meanwhile, and the pack's class loader never holds the originals open: on Windows an open jar
|
||||
* cannot be replaced, which would stop a module author from rebuilding while studio has the pack
|
||||
* loaded.
|
||||
*
|
||||
* <p>The directory is named {@code iris-pack-modules-*} and holds the copies plus an owner file
|
||||
* naming the process that made it. {@link #delete()} removes it when the pack closes or its load
|
||||
* fails; {@link StaleJarSnapshots} removes those a crashed process left behind.
|
||||
*/
|
||||
final class JarSnapshot {
|
||||
static final String DIRECTORY_PREFIX = "iris-pack-modules-";
|
||||
static final String OWNER_FILE = "owner.txt";
|
||||
static final String OWNER_HEADER = "Iris pack module jar copies";
|
||||
|
||||
/** A module jar: its path relative to the pack, which every message names, and its copy. */
|
||||
record CopiedJar(String origin, Path copy) {
|
||||
CopiedJar {
|
||||
Objects.requireNonNull(origin, "origin");
|
||||
Objects.requireNonNull(copy, "copy");
|
||||
}
|
||||
}
|
||||
|
||||
private final Path directory;
|
||||
private final List<CopiedJar> jars;
|
||||
|
||||
private JarSnapshot(Path directory, List<CopiedJar> jars) {
|
||||
this.directory = directory;
|
||||
this.jars = List.copyOf(jars);
|
||||
}
|
||||
|
||||
/** Copies {@code jars}, which lie under {@code packRoot}, into a new directory below
|
||||
* {@code temporaryRoot}. Leaves nothing behind if a copy fails.
|
||||
*/
|
||||
static JarSnapshot take(Path packRoot, List<Path> jars, Path temporaryRoot) {
|
||||
var directory = createOwnedDirectory(temporaryRoot);
|
||||
var copies = new ArrayList<CopiedJar>(jars.size());
|
||||
try {
|
||||
for (var jar : jars) {
|
||||
copies.add(copy(packRoot, jar, directory));
|
||||
}
|
||||
return new JarSnapshot(directory, copies);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
new JarSnapshot(directory, copies).deleteAfterFailure(failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
List<CopiedJar> jars() {
|
||||
return jars;
|
||||
}
|
||||
|
||||
/** The pack-relative origin of a copy, or {@code null} if {@code location} is not one of them. */
|
||||
String originOf(Path location) {
|
||||
return jars.stream()
|
||||
.filter(jar -> jar.copy().equals(location))
|
||||
.map(CopiedJar::origin)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/** Deletes the copies, the owner file and the directory. Call only once the pack's class loader
|
||||
* is closed; on Windows an open copy cannot be deleted.
|
||||
*/
|
||||
void delete() {
|
||||
try {
|
||||
for (var jar : jars) {
|
||||
Files.deleteIfExists(jar.copy());
|
||||
}
|
||||
Files.deleteIfExists(directory.resolve(OWNER_FILE));
|
||||
Files.deleteIfExists(directory);
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("Cannot delete the module jar copies in " + directory, exception);
|
||||
}
|
||||
}
|
||||
|
||||
void deleteAfterFailure(Throwable failure) {
|
||||
try {
|
||||
delete();
|
||||
} catch (UncheckedIOException exception) {
|
||||
failure.addSuppressed(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path createOwnedDirectory(Path temporaryRoot) {
|
||||
try {
|
||||
var directory = Files.createTempDirectory(temporaryRoot, DIRECTORY_PREFIX);
|
||||
Files.writeString(directory.resolve(OWNER_FILE), ownerRecord(ProcessHandle.current().pid()), StandardCharsets.UTF_8);
|
||||
return directory;
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("Cannot create a directory for module jar copies in " + temporaryRoot, exception);
|
||||
}
|
||||
}
|
||||
|
||||
/** What the owner file holds: a fixed header, then the id of the process that made the directory. */
|
||||
static String ownerRecord(long pid) {
|
||||
return OWNER_HEADER + "\n" + pid + "\n";
|
||||
}
|
||||
|
||||
private static CopiedJar copy(Path packRoot, Path jar, Path directory) {
|
||||
var origin = packRoot.relativize(jar).toString();
|
||||
var copy = directory.resolve(jar.getFileName().toString());
|
||||
try {
|
||||
Files.copy(jar, copy);
|
||||
return new CopiedJar(origin, copy);
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("Cannot copy module jar " + origin, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@ import java.util.Objects;
|
||||
*
|
||||
* A load either returns a complete pack or throws with nothing left open. Close the pack when it
|
||||
* unloads, after the host has stopped using its graphs, catalog and runners: closing releases the
|
||||
* pack's class loader.
|
||||
* pack's class loader and deletes its copies of the module jars. The original jars are never held
|
||||
* open, so a module author can rebuild them while the pack is loaded.
|
||||
*/
|
||||
public final class LoadedPack implements AutoCloseable {
|
||||
private final PackModules packModules;
|
||||
|
||||
@@ -8,6 +8,7 @@ import java.io.InputStreamReader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
@@ -22,7 +23,9 @@ import java.util.jar.JarFile;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/** One jar in a pack's modules directory, the entry class it names and the classes it holds,
|
||||
* each with the classes it links against.
|
||||
* each with the classes it links against. {@code path} is the load's copy of the jar
|
||||
* ({@link JarSnapshot}); {@code origin} is the original's path relative to the pack, which every
|
||||
* message names.
|
||||
*
|
||||
* <p>The entry point is the jar's own {@code META-INF/services/com.volmit.IrisModule} file, in
|
||||
* the format {@link java.util.ServiceLoader} reads. The host reads that file from this jar only:
|
||||
@@ -51,11 +54,12 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads the single entry class a jar names and the classes it holds. The origin is the jar
|
||||
* path relative to its pack. Fails if a class file cannot be parsed.
|
||||
/** Reads the single entry class a jar names and the classes it holds. Fails if a class file
|
||||
* cannot be parsed.
|
||||
*/
|
||||
static ModuleJar read(Path packRoot, Path jar) {
|
||||
var origin = packRoot.relativize(jar).toString();
|
||||
static ModuleJar read(JarSnapshot.CopiedJar copied) {
|
||||
var origin = copied.origin();
|
||||
var jar = copied.copy();
|
||||
try (var file = openAsClassLoaderSeesIt(jar)) {
|
||||
var entryClass = requireSingleEntryClass(origin, readEntryClasses(file));
|
||||
var classEntries = findClassEntries(file);
|
||||
@@ -80,9 +84,9 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
|
||||
/** Loads and instantiates the entry class through the pack's class loader. The class must come
|
||||
* from this jar, so a copy on the host classpath cannot silently replace the jar's module.
|
||||
*/
|
||||
DiscoveredModule createModule(ClassLoader packLoader) {
|
||||
DiscoveredModule createModule(ClassLoader packLoader, JarSnapshot snapshot) {
|
||||
var type = loadEntryClass(packLoader);
|
||||
requireDefinedHere(type);
|
||||
requireDefinedHere(type, snapshot);
|
||||
var module = instantiate(type);
|
||||
return DiscoveredModule.fromJar(module, readIdentity(module), origin);
|
||||
}
|
||||
@@ -177,11 +181,21 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
|
||||
return type.asSubclass(IrisModule.class);
|
||||
}
|
||||
|
||||
private void requireDefinedHere(Class<?> type) {
|
||||
private void requireDefinedHere(Class<?> type, JarSnapshot snapshot) {
|
||||
var source = type.getProtectionDomain().getCodeSource();
|
||||
var location = source == null ? null : source.getLocation();
|
||||
if (location == null || !location.toExternalForm().equals(url().toExternalForm())) {
|
||||
throw brokenEntryPoint("class is loaded from " + location + ", not from this jar", null);
|
||||
if (location != null && location.toExternalForm().equals(url().toExternalForm())) return;
|
||||
throw brokenEntryPoint("class is loaded from " + describeLocation(location, snapshot) + ", not from this jar", null);
|
||||
}
|
||||
|
||||
/** Another jar of the pack by its origin, never by the path of its copy. */
|
||||
private static String describeLocation(URL location, JarSnapshot snapshot) {
|
||||
if (location == null) return "an unknown location";
|
||||
try {
|
||||
var origin = snapshot.originOf(Path.of(location.toURI()));
|
||||
return origin == null ? location.toString() : origin;
|
||||
} catch (URISyntaxException | IllegalArgumentException | java.nio.file.FileSystemNotFoundException exception) {
|
||||
return location.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,14 @@ import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** The module jars of one pack: every {@code <pack>/modules/*.jar}, one module per jar, ordered
|
||||
* by file name so the result never depends on directory listing order.
|
||||
* by file name so the result never depends on directory listing order. Hosts normally load packs
|
||||
* through {@link LoadedPack}, which uses this.
|
||||
*
|
||||
* <p>The load first copies the jars into a fresh temporary directory ({@link JarSnapshot}) and works
|
||||
* only on the copies, so the originals stay free to be replaced, even on Windows, and the load sees one
|
||||
* consistent set of jars. Messages and origins name the originals ({@code modules/moss.jar}). Copies
|
||||
* are deleted when the pack closes or its load fails; copies a crashed process left behind are removed
|
||||
* by a later load ({@link StaleJarSnapshots}).
|
||||
*
|
||||
* <p>All jars of a pack share one class loader. A pack jar can therefore name another pack jar's
|
||||
* stage constants in {@code requires(...)}. Besides the pack's own classes, that loader sees only
|
||||
@@ -38,16 +45,20 @@ import java.util.stream.Collectors;
|
||||
public final class PackModules implements AutoCloseable {
|
||||
public static final String MODULES_DIRECTORY = "modules";
|
||||
static final String JAR_EXTENSION = ".jar";
|
||||
private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir";
|
||||
private static final System.Logger LOGGER = System.getLogger(PackModules.class.getName());
|
||||
|
||||
private final List<DiscoveredModule> modules;
|
||||
private final List<MissingClasses> missingClasses;
|
||||
private final URLClassLoader loader;
|
||||
private final JarSnapshot snapshot;
|
||||
|
||||
private PackModules(List<DiscoveredModule> modules, List<MissingClasses> missingClasses, URLClassLoader loader) {
|
||||
private PackModules(
|
||||
List<DiscoveredModule> modules, List<MissingClasses> missingClasses, URLClassLoader loader, JarSnapshot snapshot) {
|
||||
this.modules = List.copyOf(modules);
|
||||
this.missingClasses = List.copyOf(missingClasses);
|
||||
this.loader = loader;
|
||||
this.snapshot = snapshot;
|
||||
}
|
||||
|
||||
/** Loads the modules of the pack at {@code packRoot}, exposing only the Iris API. */
|
||||
@@ -64,15 +75,23 @@ public final class PackModules implements AutoCloseable {
|
||||
* trailing dot is accepted; blank names and wildcards are rejected.
|
||||
*/
|
||||
public static PackModules load(Path packRoot, Collection<String> exposedHostPackages) {
|
||||
return load(packRoot, exposedHostPackages, systemTemporaryDirectory());
|
||||
}
|
||||
|
||||
/** Like {@link #load(Path, Collection)}, copying the jars below {@code temporaryRoot}. */
|
||||
static PackModules load(Path packRoot, Collection<String> exposedHostPackages, Path temporaryRoot) {
|
||||
Objects.requireNonNull(packRoot, "packRoot");
|
||||
var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages));
|
||||
var jars = findModuleJars(packRoot).stream()
|
||||
.map(jar -> ModuleJar.read(packRoot, jar))
|
||||
.toList();
|
||||
var missingClasses = PackClassCheck.requireLinkable(jars, host);
|
||||
var packModules = defineModules(packRoot, jars, missingClasses, host);
|
||||
logLoad(packName(packRoot), packModules);
|
||||
return packModules;
|
||||
StaleJarSnapshots.remove(temporaryRoot);
|
||||
var snapshot = JarSnapshot.take(packRoot, findModuleJars(packRoot), temporaryRoot);
|
||||
try {
|
||||
var packModules = loadSnapshot(packRoot, snapshot, host);
|
||||
logLoad(packName(packRoot), packModules);
|
||||
return packModules;
|
||||
} catch (RuntimeException | Error failure) {
|
||||
snapshot.deleteAfterFailure(failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
/** One module per jar, in jar file name order. */
|
||||
@@ -88,13 +107,27 @@ public final class PackModules implements AutoCloseable {
|
||||
return missingClasses;
|
||||
}
|
||||
|
||||
/** Closes the class loader, then deletes the jar copies, which an open loader would keep locked on Windows. */
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
loader.close();
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("Cannot close module class loader " + loader.getName(), exception);
|
||||
var failure = new UncheckedIOException("Cannot close module class loader " + loader.getName(), exception);
|
||||
snapshot.deleteAfterFailure(failure);
|
||||
throw failure;
|
||||
}
|
||||
snapshot.delete();
|
||||
}
|
||||
|
||||
private static Path systemTemporaryDirectory() {
|
||||
return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY));
|
||||
}
|
||||
|
||||
private static PackModules loadSnapshot(Path packRoot, JarSnapshot snapshot, ExposedHostClassLoader host) {
|
||||
var jars = snapshot.jars().stream().map(ModuleJar::read).toList();
|
||||
var missingClasses = PackClassCheck.requireLinkable(jars, host);
|
||||
return defineModules(packRoot, jars, missingClasses, host, snapshot);
|
||||
}
|
||||
|
||||
private static List<Path> findModuleJars(Path packRoot) {
|
||||
@@ -115,11 +148,11 @@ public final class PackModules implements AutoCloseable {
|
||||
}
|
||||
|
||||
private static PackModules defineModules(
|
||||
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader host) {
|
||||
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader host, JarSnapshot snapshot) {
|
||||
var loader = newPackClassLoader(packRoot, jars, host);
|
||||
try {
|
||||
var modules = createModules(jars, loader);
|
||||
return new PackModules(modules, withoutDeclaredOptional(missingClasses, modules), loader);
|
||||
var modules = createModules(jars, loader, snapshot);
|
||||
return new PackModules(modules, withoutDeclaredOptional(missingClasses, modules), loader, snapshot);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
closeAfterFailure(loader, failure);
|
||||
throw failure;
|
||||
@@ -142,8 +175,8 @@ public final class PackModules implements AutoCloseable {
|
||||
return name == null ? packRoot.toString() : name.toString();
|
||||
}
|
||||
|
||||
private static List<DiscoveredModule> createModules(List<ModuleJar> jars, ClassLoader loader) {
|
||||
return jars.stream().map(jar -> jar.createModule(loader)).toList();
|
||||
private static List<DiscoveredModule> createModules(List<ModuleJar> jars, ClassLoader loader, JarSnapshot snapshot) {
|
||||
return jars.stream().map(jar -> jar.createModule(loader, snapshot)).toList();
|
||||
}
|
||||
|
||||
/** A module's optional packages excuse only its own jar's missing classes. They are read from
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.volmit.host;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.System.Logger.Level;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.DirectoryIteratorException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Removes module jar copies that a process left behind when it crashed before closing its packs.
|
||||
*
|
||||
* <p>Only directories this code provably created are touched: a directory named
|
||||
* {@code iris-pack-modules-*}, holding an owner file with the expected header, whose owner process
|
||||
* no longer runs, and holding nothing but that owner file and {@code .jar} files. Anything else is
|
||||
* left alone, including copies of a process that still runs (another server, or this one) and
|
||||
* directories whose owner file is missing because the crash came before it was written.
|
||||
*/
|
||||
final class StaleJarSnapshots {
|
||||
private static final System.Logger LOGGER = System.getLogger(PackModules.class.getName());
|
||||
|
||||
private StaleJarSnapshots() {}
|
||||
|
||||
static void remove(Path temporaryRoot) {
|
||||
for (var candidate : candidates(temporaryRoot)) {
|
||||
ownerOf(candidate)
|
||||
.filter(StaleJarSnapshots::hasExited)
|
||||
.ifPresent(owner -> removeIfOnlyCopies(candidate, owner));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Path> candidates(Path temporaryRoot) {
|
||||
var candidates = new ArrayList<Path>();
|
||||
try (var entries = Files.newDirectoryStream(temporaryRoot, JarSnapshot.DIRECTORY_PREFIX + "*")) {
|
||||
entries.forEach(candidates::add);
|
||||
} catch (IOException | DirectoryIteratorException exception) {
|
||||
LOGGER.log(Level.DEBUG, "Cannot look for stale module jar copies in " + temporaryRoot, exception);
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
/** The owner process id, if {@code directory} is a real directory with a valid owner file. */
|
||||
private static Optional<Long> ownerOf(Path directory) {
|
||||
var ownerFile = directory.resolve(JarSnapshot.OWNER_FILE);
|
||||
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
|
||||
if (!Files.isRegularFile(ownerFile, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
|
||||
try {
|
||||
var lines = Files.readAllLines(ownerFile, StandardCharsets.UTF_8);
|
||||
if (lines.size() != 2 || !lines.getFirst().equals(JarSnapshot.OWNER_HEADER)) return Optional.empty();
|
||||
return parsePid(lines.get(1));
|
||||
} catch (IOException exception) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<Long> parsePid(String text) {
|
||||
try {
|
||||
return Optional.of(Long.parseLong(text));
|
||||
} catch (NumberFormatException exception) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasExited(long pid) {
|
||||
return ProcessHandle.of(pid).map(process -> !process.isAlive()).orElse(true);
|
||||
}
|
||||
|
||||
private static void removeIfOnlyCopies(Path directory, long owner) {
|
||||
try {
|
||||
var entries = listEntries(directory);
|
||||
if (!entries.stream().allMatch(StaleJarSnapshots::isSnapshotFile)) return;
|
||||
for (var entry : entries) {
|
||||
Files.delete(entry);
|
||||
}
|
||||
Files.delete(directory);
|
||||
LOGGER.log(Level.INFO, () -> "Removed module jar copies left by exited process " + owner + " in " + directory);
|
||||
} catch (IOException exception) {
|
||||
LOGGER.log(Level.DEBUG, "Cannot remove stale module jar copies in " + directory, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Path> listEntries(Path directory) throws IOException {
|
||||
try (var entries = Files.list(directory)) {
|
||||
return entries.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isSnapshotFile(Path entry) {
|
||||
var name = entry.getFileName().toString();
|
||||
return Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)
|
||||
&& (name.equals(JarSnapshot.OWNER_FILE) || name.endsWith(PackModules.JAR_EXTENSION));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user