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

slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-mvnd.git

commit 61255e1ff076326ae284b2057a3b680049022b3a
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Fri Nov 6 22:23:15 2026 +0100

    Reset a corrupt daemon registry under the file lock and keep a copy
    
    The reset ran after the lock was released and could wipe a registry another 
process had just written.
---
 .../org/mvndaemon/mvnd/common/DaemonRegistry.java  | 182 ++++++++++++---------
 .../mvndaemon/mvnd/common/DaemonRegistryTest.java  |  37 +++++
 2 files changed, 146 insertions(+), 73 deletions(-)

diff --git a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java 
b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java
index 876777a3..0443dcdd 100644
--- a/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java
+++ b/common/src/main/java/org/mvndaemon/mvnd/common/DaemonRegistry.java
@@ -208,84 +208,90 @@ public class DaemonRegistry implements AutoCloseable {
 
         synchronized (lck) {
             try (FileLock l = tryLock()) {
-                channel.position(0);
-                DataInputStream is = new DataInputStream(new 
BufferedInputStream(Channels.newInputStream(channel)));
-                infosMap.clear();
-                int nb = is.available() < 4 ? 0 : is.readInt();
-                for (int i = 0; i < nb; i++) {
-                    String daemonId = is.readUTF();
-                    String javaHome = is.readUTF();
-                    String mavenHome = is.readUTF();
-                    int pid = is.readInt();
-                    String address = is.readUTF();
-
-                    byte[] token = new byte[DaemonInfo.TOKEN_SIZE];
-                    is.read(token);
-
-                    String locale = is.readUTF();
-                    List<String> opts = new ArrayList<>();
-                    int nbOpts = is.readInt();
-                    for (int j = 0; j < nbOpts; j++) {
-                        opts.add(is.readUTF());
+                try {
+                    channel.position(0);
+                    DataInputStream is = new DataInputStream(new 
BufferedInputStream(Channels.newInputStream(channel)));
+                    infosMap.clear();
+                    int nb = is.available() < 4 ? 0 : is.readInt();
+                    for (int i = 0; i < nb; i++) {
+                        String daemonId = is.readUTF();
+                        String javaHome = is.readUTF();
+                        String mavenHome = is.readUTF();
+                        int pid = is.readInt();
+                        String address = is.readUTF();
+
+                        byte[] token = new byte[DaemonInfo.TOKEN_SIZE];
+                        is.read(token);
+
+                        String locale = is.readUTF();
+                        List<String> opts = new ArrayList<>();
+                        int nbOpts = is.readInt();
+                        for (int j = 0; j < nbOpts; j++) {
+                            opts.add(is.readUTF());
+                        }
+                        DaemonState state = 
DaemonState.values()[is.readByte()];
+                        long lastIdle = is.readLong();
+                        long lastBusy = is.readLong();
+                        DaemonInfo di = new DaemonInfo(
+                                daemonId, javaHome, mavenHome, pid, address, 
token, locale, opts, state, lastIdle,
+                                lastBusy);
+                        infosMap.putIfAbsent(di.getId(), di);
+                    }
+                    stopEvents.clear();
+                    nb = is.available() < 4 ? 0 : is.readInt();
+                    for (int i = 0; i < nb; i++) {
+                        String daemonId = is.readUTF();
+                        long date = is.readLong();
+                        int ord = is.readByte();
+                        DaemonExpirationStatus des = ord >= 0 ? 
DaemonExpirationStatus.values()[ord] : null;
+                        String reason = is.readUTF();
+                        DaemonStopEvent se = new DaemonStopEvent(daemonId, 
date, des, reason);
+                        stopEvents.add(se);
                     }
-                    DaemonState state = DaemonState.values()[is.readByte()];
-                    long lastIdle = is.readLong();
-                    long lastBusy = is.readLong();
-                    DaemonInfo di = new DaemonInfo(
-                            daemonId, javaHome, mavenHome, pid, address, 
token, locale, opts, state, lastIdle,
-                            lastBusy);
-                    infosMap.putIfAbsent(di.getId(), di);
-                }
-                stopEvents.clear();
-                nb = is.available() < 4 ? 0 : is.readInt();
-                for (int i = 0; i < nb; i++) {
-                    String daemonId = is.readUTF();
-                    long date = is.readLong();
-                    int ord = is.readByte();
-                    DaemonExpirationStatus des = ord >= 0 ? 
DaemonExpirationStatus.values()[ord] : null;
-                    String reason = is.readUTF();
-                    DaemonStopEvent se = new DaemonStopEvent(daemonId, date, 
des, reason);
-                    stopEvents.add(se);
-                }
 
-                if (updater != null) {
-                    updater.run();
-                    channel.truncate(0);
-                    DataOutputStream os =
-                            new DataOutputStream(new 
BufferedOutputStream(Channels.newOutputStream(channel)));
-                    os.writeInt(infosMap.size());
-                    for (DaemonInfo di : infosMap.values()) {
-                        String id = di.getId();
-                        os.writeUTF(id);
-                        os.writeUTF(di.getJavaHome());
-                        os.writeUTF(di.getMvndHome());
-                        os.writeInt(di.getPid());
-                        os.writeUTF(di.getAddress());
-                        os.write(di.getToken());
-                        os.writeUTF(di.getLocale());
-                        os.writeInt(di.getOptions().size());
-                        for (String opt : di.getOptions()) {
-                            os.writeUTF(opt);
+                    if (updater != null) {
+                        updater.run();
+                        channel.truncate(0);
+                        DataOutputStream os =
+                                new DataOutputStream(new 
BufferedOutputStream(Channels.newOutputStream(channel)));
+                        os.writeInt(infosMap.size());
+                        for (DaemonInfo di : infosMap.values()) {
+                            String id = di.getId();
+                            os.writeUTF(id);
+                            os.writeUTF(di.getJavaHome());
+                            os.writeUTF(di.getMvndHome());
+                            os.writeInt(di.getPid());
+                            os.writeUTF(di.getAddress());
+                            os.write(di.getToken());
+                            os.writeUTF(di.getLocale());
+                            os.writeInt(di.getOptions().size());
+                            for (String opt : di.getOptions()) {
+                                os.writeUTF(opt);
+                            }
+                            os.writeByte((byte) di.getState().ordinal());
+                            os.writeLong(di.getLastIdle());
+                            os.writeLong(di.getLastBusy());
                         }
-                        os.writeByte((byte) di.getState().ordinal());
-                        os.writeLong(di.getLastIdle());
-                        os.writeLong(di.getLastBusy());
-                    }
-                    os.writeInt(stopEvents.size());
-                    for (DaemonStopEvent dse : stopEvents) {
-                        os.writeUTF(dse.getDaemonId());
-                        os.writeLong(dse.getTimestamp());
-                        os.writeByte((byte)
-                                (dse.getStatus() == null ? -1 : 
dse.getStatus().ordinal()));
-                        os.writeUTF(dse.getReason());
+                        os.writeInt(stopEvents.size());
+                        for (DaemonStopEvent dse : stopEvents) {
+                            os.writeUTF(dse.getDaemonId());
+                            os.writeLong(dse.getTimestamp());
+                            os.writeByte((byte)
+                                    (dse.getStatus() == null
+                                            ? -1
+                                            : dse.getStatus().ordinal()));
+                            os.writeUTF(dse.getReason());
+                        }
+                        os.flush();
                     }
-                    os.flush();
+                } catch (DaemonException e) {
+                    throw e;
+                } catch (Exception e) {
+                    LOGGER.warn("Invalid daemon registry info at [{}], trying 
to recover.", registryFile, e);
+                    this.reset();
                 }
-            } catch (DaemonException e) {
-                throw e;
-            } catch (Exception e) {
-                LOGGER.warn("Invalid daemon registry info at [{}], trying to 
recover.", registryFile, e);
-                this.reset();
+            } catch (IOException e) {
+                throw new DaemonException("Could not release the lock on " + 
registryFile, e);
             }
         }
     }
@@ -309,6 +315,7 @@ public class DaemonRegistry implements AutoCloseable {
     private void reset() {
         infosMap.clear();
         stopEvents.clear();
+        saveCorrupt();
         try {
             channel.truncate(0);
         } catch (IOException e) {
@@ -316,6 +323,35 @@ public class DaemonRegistry implements AutoCloseable {
         }
     }
 
+    /**
+     * Keeps a copy of the unreadable registry next to it, replacing an older 
copy, before it is truncated.
+     * The copy is owner-only like the registry, as it still holds the daemon 
tokens.
+     */
+    private void saveCorrupt() {
+        Path corrupt = registryFile.resolveSibling(registryFile.getFileName() 
+ ".corrupt");
+        try {
+            Files.deleteIfExists(corrupt);
+            if 
(corrupt.getFileSystem().supportedFileAttributeViews().contains("posix")) {
+                Files.createFile(
+                        corrupt, 
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
+            }
+            long size = channel.size();
+            try (FileChannel out = FileChannel.open(corrupt, 
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
+                long pos = 0;
+                while (pos < size) {
+                    long n = channel.transferTo(pos, size - pos, out);
+                    if (n <= 0) {
+                        break;
+                    }
+                    pos += n;
+                }
+            }
+            LOGGER.warn("Copied the invalid daemon registry to [{}] before 
resetting it.", corrupt);
+        } catch (IOException e) {
+            LOGGER.warn("Could not copy the invalid daemon registry to [{}]", 
corrupt, e);
+        }
+    }
+
     private static final int PROCESS_ID = getProcessId0();
 
     private static int getProcessId0() {
diff --git 
a/common/src/test/java/org/mvndaemon/mvnd/common/DaemonRegistryTest.java 
b/common/src/test/java/org/mvndaemon/mvnd/common/DaemonRegistryTest.java
index 2d2ffd4d..cb0d9ad3 100644
--- a/common/src/test/java/org/mvndaemon/mvnd/common/DaemonRegistryTest.java
+++ b/common/src/test/java/org/mvndaemon/mvnd/common/DaemonRegistryTest.java
@@ -40,6 +40,7 @@ import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -310,4 +311,40 @@ public class DaemonRegistryTest {
         Path link = Files.createSymbolicLink(base.resolve("link.bin"), 
existing);
         assertThrows(DaemonException.class, () -> new DaemonRegistry(link));
     }
+
+    @Test
+    public void testInvalidRegistryIsCopiedBeforeReset() throws IOException {
+        Path dir = Files.createTempDirectory("reg");
+        Path file = dir.resolve("registry.bin");
+        Path corrupt = dir.resolve("registry.bin.corrupt");
+        Files.write(corrupt, new byte[] {42});
+        byte[] bad = {0, 0, 0, 5, 1, 2, 3};
+        Files.write(file, bad);
+
+        try (DaemonRegistry reg = new DaemonRegistry(file)) {
+            assertEquals(0, reg.getAll().size());
+            assertArrayEquals(bad, Files.readAllBytes(corrupt));
+            assertEquals(0, Files.size(file));
+
+            reg.store(newDaemonInfo("12345678"));
+            assertEquals(1, reg.getAll().size());
+        }
+    }
+
+    private static DaemonInfo newDaemonInfo(String id) {
+        byte[] token = new byte[16];
+        new Random().nextBytes(token);
+        return new DaemonInfo(
+                id,
+                "/java/home/",
+                "/data/reg/",
+                0x12345678,
+                "inet:/127.0.0.1:7502",
+                token,
+                Locale.getDefault().toLanguageTag(),
+                Arrays.asList("-Xmx"),
+                DaemonState.Idle,
+                System.currentTimeMillis(),
+                System.currentTimeMillis());
+    }
 }

Reply via email to