|
| 1 | +package org.jabref.logic.search; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 4 | +import org.slf4j.Logger; |
| 5 | +import org.slf4j.LoggerFactory; |
| 6 | + |
| 7 | +import java.io.BufferedReader; |
| 8 | +import java.io.IOException; |
| 9 | +import java.io.InputStreamReader; |
| 10 | +import java.net.Socket; |
| 11 | +import java.nio.file.Files; |
| 12 | +import java.util.HashMap; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.Optional; |
| 15 | + |
| 16 | +import static org.jabref.logic.os.OS.getHostName; |
| 17 | +import static org.jabref.logic.search.PostgreServer.POSTGRES_METADATA_FILE; |
| 18 | + |
| 19 | +public class PostgreProcessCleaner { |
| 20 | + private static final Logger LOGGER = LoggerFactory.getLogger(PostgreProcessCleaner.class); |
| 21 | + private static final PostgreProcessCleaner INSTANCE = new PostgreProcessCleaner(); |
| 22 | + |
| 23 | + private PostgreProcessCleaner() {} |
| 24 | + |
| 25 | + public static PostgreProcessCleaner getInstance() { |
| 26 | + return INSTANCE; |
| 27 | + } |
| 28 | + |
| 29 | + public void checkAndCleanupOldInstance() { |
| 30 | + if (!Files.exists(POSTGRES_METADATA_FILE)) |
| 31 | + return; |
| 32 | + |
| 33 | + try { |
| 34 | + Map<String, Object> metadata = new HashMap<>(new ObjectMapper() |
| 35 | + .readValue(Files.readAllBytes(POSTGRES_METADATA_FILE), HashMap.class)); |
| 36 | + if(!metadata.isEmpty()) { |
| 37 | + int port = ((Number) metadata.get("postgresPort")).intValue(); |
| 38 | + destroyPreviousJavaProcess(metadata); |
| 39 | + destroyPostgresProcess(port); |
| 40 | + } |
| 41 | + Files.deleteIfExists(POSTGRES_METADATA_FILE); |
| 42 | + } catch (IOException e) { |
| 43 | + LOGGER.warn("Failed to read Postgres metadata file: {}", e.getMessage()); |
| 44 | + } catch (InterruptedException e) { |
| 45 | + LOGGER.warn("Thread sleep was interrupted while Postgres cleanup: {}", e.getMessage()); |
| 46 | + Thread.currentThread().interrupt(); |
| 47 | + } catch (Exception e) { |
| 48 | + LOGGER.warn("Failed to clean up old embedded Postgres: {}", e.getMessage()); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private void destroyPreviousJavaProcess(Map<String, Object> meta) throws InterruptedException { |
| 53 | + long javaPid = ((Number) meta.get("javaPid")).longValue(); |
| 54 | + destroyProcessByPID(javaPid, 1000); |
| 55 | + } |
| 56 | + |
| 57 | + private void destroyPostgresProcess(int port) throws InterruptedException { |
| 58 | + if (isPortOpen(getHostName(), port)) { |
| 59 | + long pid = getPidUsingPort(port); |
| 60 | + if (pid != -1) { |
| 61 | + LOGGER.info("Old Postgres instance found on port {} (PID {}). Killing it...", port, pid); |
| 62 | + destroyProcessByPID(pid, 1500); |
| 63 | + } else { |
| 64 | + LOGGER.warn("Could not determine PID using port {}. Skipping kill step.", port); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + private void destroyProcessByPID(long pid, int millis) throws InterruptedException { |
| 70 | + Optional<ProcessHandle> handle = ProcessHandle.of(pid); |
| 71 | + if (handle.isPresent() && handle.get().isAlive()) { |
| 72 | + handle.get().destroy(); |
| 73 | + Thread.sleep(millis); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + private boolean isPortOpen(String host, int port) { |
| 78 | + try (Socket _ = new Socket(host, port)) { |
| 79 | + return true; |
| 80 | + } catch (IOException ex) { |
| 81 | + return false; |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + private long getPidUsingPort(int port) { |
| 86 | + String os = System.getProperty("os.name").toLowerCase(); |
| 87 | + try { |
| 88 | + Process process = createPortLookupProcess(os, port); |
| 89 | + if (process == null) { |
| 90 | + LOGGER.warn("Unsupported OS for port-based PID lookup."); |
| 91 | + return -1; |
| 92 | + } |
| 93 | + |
| 94 | + try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { |
| 95 | + return extractPidFromOutput(os, reader); |
| 96 | + } |
| 97 | + } catch (Exception e) { |
| 98 | + LOGGER.warn("Failed to get PID for port {}: {}", port, e.getMessage()); |
| 99 | + } |
| 100 | + |
| 101 | + return -1; |
| 102 | + } |
| 103 | + |
| 104 | + private Process createPortLookupProcess(String os, int port) throws IOException { |
| 105 | + if (os.contains("mac") || os.contains("nix") || os.contains("nux")) { |
| 106 | + return new ProcessBuilder("lsof", "-i", "tcp:" + port, "-sTCP:LISTEN", "-Pn") |
| 107 | + .redirectErrorStream(true).start(); |
| 108 | + } else if (os.contains("win")) { |
| 109 | + return new ProcessBuilder("cmd.exe", "/c", "netstat -ano | findstr :" + port) |
| 110 | + .redirectErrorStream(true).start(); |
| 111 | + } |
| 112 | + return null; |
| 113 | + } |
| 114 | + |
| 115 | + private long extractPidFromOutput(String os, BufferedReader reader) throws IOException { |
| 116 | + String line; |
| 117 | + while ((line = reader.readLine()) != null) { |
| 118 | + if (os.contains("nix") || os.contains("nux") || os.contains("mac")) { |
| 119 | + Long pid = parseUnixPidFromLine(line); |
| 120 | + if (pid != null) return pid; |
| 121 | + } else if (os.contains("win")) { |
| 122 | + Long pid = parseWindowsPidFromLine(line); |
| 123 | + if (pid != null) return pid; |
| 124 | + } |
| 125 | + } |
| 126 | + return -1; |
| 127 | + } |
| 128 | + |
| 129 | + private Long parseUnixPidFromLine(String line) { |
| 130 | + String[] parts = line.trim().split("\\s+"); |
| 131 | + if (parts.length > 1 && parts[1].matches("\\d+")) |
| 132 | + return Long.parseLong(parts[1]); |
| 133 | + return null; |
| 134 | + } |
| 135 | + |
| 136 | + private Long parseWindowsPidFromLine(String line) { |
| 137 | + String[] parts = line.trim().split("\\s+"); |
| 138 | + if (parts.length >= 5 && parts[parts.length - 1].matches("\\d+")) |
| 139 | + return Long.parseLong(parts[parts.length - 1]); |
| 140 | + return null; |
| 141 | + } |
| 142 | + |
| 143 | +} |
0 commit comments