diff --git a/src/main/java/com/volmit/host/JarSnapshot.java b/src/main/java/com/volmit/host/JarSnapshot.java new file mode 100644 index 000000000..e34e022a3 --- /dev/null +++ b/src/main/java/com/volmit/host/JarSnapshot.java @@ -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. + * + *

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 jars; + + private JarSnapshot(Path directory, List 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 jars, Path temporaryRoot) { + var directory = createOwnedDirectory(temporaryRoot); + var copies = new ArrayList(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 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); + } + } +} diff --git a/src/main/java/com/volmit/host/LoadedPack.java b/src/main/java/com/volmit/host/LoadedPack.java index bf12bdd92..1b309c465 100644 --- a/src/main/java/com/volmit/host/LoadedPack.java +++ b/src/main/java/com/volmit/host/LoadedPack.java @@ -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; diff --git a/src/main/java/com/volmit/host/ModuleJar.java b/src/main/java/com/volmit/host/ModuleJar.java index bd8bad707..58e075639 100644 --- a/src/main/java/com/volmit/host/ModuleJar.java +++ b/src/main/java/com/volmit/host/ModuleJar.java @@ -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. * *

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 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 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 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(); } } diff --git a/src/main/java/com/volmit/host/PackModules.java b/src/main/java/com/volmit/host/PackModules.java index f58f04e16..d0aa74c87 100644 --- a/src/main/java/com/volmit/host/PackModules.java +++ b/src/main/java/com/volmit/host/PackModules.java @@ -16,7 +16,14 @@ import java.util.function.Predicate; import java.util.stream.Collectors; /** The module jars of one pack: every {@code /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. + * + *

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}). * *

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 modules; private final List missingClasses; private final URLClassLoader loader; + private final JarSnapshot snapshot; - private PackModules(List modules, List missingClasses, URLClassLoader loader) { + private PackModules( + List modules, List 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 exposedHostPackages) { + return load(packRoot, exposedHostPackages, systemTemporaryDirectory()); + } + + /** Like {@link #load(Path, Collection)}, copying the jars below {@code temporaryRoot}. */ + static PackModules load(Path packRoot, Collection 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 findModuleJars(Path packRoot) { @@ -115,11 +148,11 @@ public final class PackModules implements AutoCloseable { } private static PackModules defineModules( - Path packRoot, List jars, List missingClasses, ClassLoader host) { + Path packRoot, List jars, List 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 createModules(List jars, ClassLoader loader) { - return jars.stream().map(jar -> jar.createModule(loader)).toList(); + private static List createModules(List 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 diff --git a/src/main/java/com/volmit/host/StaleJarSnapshots.java b/src/main/java/com/volmit/host/StaleJarSnapshots.java new file mode 100644 index 000000000..979a3b9b7 --- /dev/null +++ b/src/main/java/com/volmit/host/StaleJarSnapshots.java @@ -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. + * + *

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 candidates(Path temporaryRoot) { + var candidates = new ArrayList(); + 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 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 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 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)); + } +} diff --git a/src/test/java/com/volmit/host/PackJarSnapshotTest.java b/src/test/java/com/volmit/host/PackJarSnapshotTest.java new file mode 100644 index 000000000..960e0c2bd --- /dev/null +++ b/src/test/java/com/volmit/host/PackJarSnapshotTest.java @@ -0,0 +1,124 @@ +package com.volmit.host; + +import com.volmit.support.TestModuleJar; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import static com.volmit.support.TestModuleJar.module; +import static org.junit.jupiter.api.Assertions.*; + +class PackJarSnapshotTest { + private static final String NO_MEMBERS = ""; + private static final String NO_STAGES = ""; + private static final String UNUSED_CLASS = "pack.gamma.Unused"; + private static final long EXITED_PROCESS = Long.MAX_VALUE; + + @TempDir + Path pack; + + @TempDir + Path temporaryRoot; + + private static String origin(String jarName) { + return Path.of(PackModules.MODULES_DIRECTORY, jarName).toString(); + } + + private Path writeGamma() { + return module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES) + .source(UNUSED_CLASS, "package pack.gamma; final class Unused {}") + .writeInto(pack, "gamma.jar"); + } + + private PackModules load() { + return PackModules.load(pack, List.of(), temporaryRoot); + } + + private List snapshotDirectories() throws IOException { + try (var entries = Files.list(temporaryRoot)) { + return entries.filter(entry -> entry.getFileName().toString().startsWith(JarSnapshot.DIRECTORY_PREFIX)).toList(); + } + } + + private Path staleDirectory(String name, String ownerRecord) throws IOException { + var directory = Files.createDirectory(temporaryRoot.resolve(JarSnapshot.DIRECTORY_PREFIX + name)); + Files.writeString(directory.resolve(JarSnapshot.OWNER_FILE), ownerRecord); + Files.write(directory.resolve("moss.jar"), new byte[] {1, 2, 3}); + return directory; + } + + @Test + void loaderReadsFromACopySoTheOriginalCanBeReplacedWhileLoaded() throws Exception { + var original = writeGamma(); + + try (var packModules = load()) { + var module = packModules.modules().getFirst(); + var location = Path.of(module.module().getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); + assertEquals(1, snapshotDirectories().size()); + assertEquals(snapshotDirectories().getFirst().resolve("gamma.jar"), location); + assertEquals(origin("gamma.jar"), module.origin()); + + Files.delete(original); + Files.write(original, new byte[] {0}); + assertNotNull(module.module().getClass().getClassLoader().loadClass(UNUSED_CLASS)); + } + } + + @Test + void copiesAreDeletedWhenThePackCloses() throws Exception { + writeGamma(); + + try (var ignored = load()) { + assertEquals(1, snapshotDirectories().size()); + } + + assertTrue(snapshotDirectories().isEmpty()); + } + + @Test + void copiesAreDeletedWhenTheLoadFails() throws Exception { + writeGamma(); + new TestModuleJar().writeInto(pack, "broken.jar"); + assertThrows(IllegalArgumentException.class, this::load); + assertTrue(snapshotDirectories().isEmpty(), "failure while reading jars"); + + Files.delete(pack.resolve(PackModules.MODULES_DIRECTORY).resolve("broken.jar")); + module("pack.throwing.Throwing", "throwing:core", "public Throwing() { throw new IllegalStateException(\"boom\"); }", NO_STAGES) + .writeInto(pack, "throwing.jar"); + assertThrows(IllegalArgumentException.class, this::load); + assertTrue(snapshotDirectories().isEmpty(), "failure after the class loader exists"); + } + + @Test + void errorsNameTheOriginalJarNeverItsCopy() { + module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "alpha.jar"); + new TestModuleJar().entryPoint("pack.alpha.Alpha").writeInto(pack, "beta.jar"); + + var message = assertThrows(IllegalArgumentException.class, this::load).getMessage(); + + assertEquals("Module jar " + origin("beta.jar") + " has a broken entry point pack.alpha.Alpha: class is loaded from " + + origin("alpha.jar") + ", not from this jar", message); + assertFalse(message.contains(temporaryRoot.toString()), message); + } + + @Test + void loadRemovesCopiesOfExitedProcessesOnly() throws Exception { + var exited = staleDirectory("exited", JarSnapshot.ownerRecord(EXITED_PROCESS)); + var running = staleDirectory("running", JarSnapshot.ownerRecord(ProcessHandle.current().pid())); + var unmarked = Files.createDirectory(temporaryRoot.resolve(JarSnapshot.DIRECTORY_PREFIX + "unmarked")); + var foreignHeader = staleDirectory("foreign", "Something else\n" + EXITED_PROCESS + "\n"); + var unexpectedContent = staleDirectory("unexpected", JarSnapshot.ownerRecord(EXITED_PROCESS)); + Files.writeString(unexpectedContent.resolve("notes.txt"), "not ours"); + var otherName = Files.createDirectory(temporaryRoot.resolve("other-" + JarSnapshot.DIRECTORY_PREFIX)); + Files.writeString(otherName.resolve(JarSnapshot.OWNER_FILE), JarSnapshot.ownerRecord(EXITED_PROCESS)); + + try (var ignored = load()) { + assertFalse(Files.exists(exited)); + for (var kept : List.of(running, unmarked, foreignHeader, unexpectedContent, otherName)) { + assertTrue(Files.exists(kept), kept.toString()); + } + } + } +}