|
16 | 16 |
|
17 | 17 | package org.springframework.boot.diagnostics.analyzer;
|
18 | 18 |
|
| 19 | +import java.io.BufferedReader; |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.InputStreamReader; |
| 22 | +import java.util.ArrayList; |
| 23 | +import java.util.List; |
| 24 | +import java.util.concurrent.TimeUnit; |
| 25 | + |
| 26 | +import org.apache.commons.logging.Log; |
| 27 | +import org.apache.commons.logging.LogFactory; |
| 28 | + |
19 | 29 | import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
|
20 | 30 | import org.springframework.boot.diagnostics.FailureAnalysis;
|
21 | 31 | import org.springframework.boot.web.server.PortInUseException;
|
22 | 32 |
|
23 | 33 | /**
|
24 | 34 | * A {@code FailureAnalyzer} that performs analysis of failures caused by a
|
25 |
| - * {@code PortInUseException}. |
| 35 | + * {@code PortInUseException}. <br/> |
| 36 | + * The analyzer attempts to find the process that is using the port and provides |
| 37 | + * information about it in the failure analysis. |
26 | 38 | *
|
27 | 39 | * @author Andy Wilkinson
|
| 40 | + * @author Yonatan Graber |
28 | 41 | */
|
29 | 42 | class PortInUseFailureAnalyzer extends AbstractFailureAnalyzer<PortInUseException> {
|
30 | 43 |
|
| 44 | + private static final Log logger = LogFactory.getLog(PortInUseFailureAnalyzer.class); |
| 45 | + |
31 | 46 | @Override
|
32 | 47 | protected FailureAnalysis analyze(Throwable rootFailure, PortInUseException cause) {
|
33 |
| - return new FailureAnalysis("Web server failed to start. Port " + cause.getPort() + " was already in use.", |
34 |
| - "Identify and stop the process that's listening on port " + cause.getPort() + " or configure this " |
35 |
| - + "application to listen on another port.", |
36 |
| - cause); |
| 48 | + ProcessInfo processInfo = findProcessUsingPort(cause.getPort()); |
| 49 | + |
| 50 | + String description = buildDescription(cause.getPort(), processInfo); |
| 51 | + String action = buildAction(cause.getPort(), processInfo); |
| 52 | + return new FailureAnalysis(description, action, cause); |
| 53 | + } |
| 54 | + |
| 55 | + private String buildDescription(int port, ProcessInfo processInfo) { |
| 56 | + StringBuilder message = new StringBuilder(); |
| 57 | + message.append("Web server failed to start. Port ").append(port).append(" was already in use"); |
| 58 | + if (processInfo != null) { |
| 59 | + message.append(" by ").append(processInfo.command).append(" (PID: ").append(processInfo.pid).append(")"); |
| 60 | + } |
| 61 | + message.append("."); |
| 62 | + return message.toString(); |
| 63 | + } |
| 64 | + |
| 65 | + private String buildAction(int port, ProcessInfo processInfo) { |
| 66 | + StringBuilder message = new StringBuilder(); |
| 67 | + if (processInfo != null) { |
| 68 | + message.append("Stop the process ") |
| 69 | + .append(processInfo.command) |
| 70 | + .append(" (PID: ") |
| 71 | + .append(processInfo.pid) |
| 72 | + .append(")"); |
| 73 | + } |
| 74 | + else { |
| 75 | + message.append("Identify and stop the process"); |
| 76 | + } |
| 77 | + message.append(" that's listening on port ") |
| 78 | + .append(port) |
| 79 | + .append(" or configure this application to listen on another port."); |
| 80 | + return message.toString(); |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Find the process using the given port. Will invoke OS-specific commands to |
| 85 | + * determine the process ID and command name. |
| 86 | + * @param port the port to check |
| 87 | + * @return the process information or {@code null} if the process cannot be found for |
| 88 | + * any reason |
| 89 | + */ |
| 90 | + private ProcessInfo findProcessUsingPort(int port) { |
| 91 | + String os = System.getProperty("os.name").toLowerCase(); |
| 92 | + try { |
| 93 | + if (os.contains("win")) { |
| 94 | + return findProcessOnWindows(port); |
| 95 | + } |
| 96 | + else if (os.contains("mac") || os.contains("nix") || os.contains("nux")) { |
| 97 | + return findProcessOnUnix(port); |
| 98 | + } |
| 99 | + else { |
| 100 | + logger.debug("Could not find process using port " + port + " in OS " + os); |
| 101 | + } |
| 102 | + } |
| 103 | + catch (Exception ex) { |
| 104 | + logger.warn("Unable to find process using port " + port, ex); |
| 105 | + } |
| 106 | + return null; |
| 107 | + } |
| 108 | + |
| 109 | + private ProcessInfo findProcessOnWindows(int port) throws Exception { |
| 110 | + Process process = new ProcessBuilder("cmd.exe", "/c", "netstat -ano | findstr :" + port).start(); |
| 111 | + waitForProcess(process); |
| 112 | + List<String> lines = readOutput(process); |
| 113 | + for (String line : lines) { |
| 114 | + line = line.trim(); |
| 115 | + if (line.contains("LISTENING") || line.contains("ESTABLISHED")) { |
| 116 | + String[] parts = line.split("\\s+"); |
| 117 | + if (parts.length >= 5) { |
| 118 | + String pid = parts[4]; |
| 119 | + String command = getWindowsCommandByPid(pid); |
| 120 | + return new ProcessInfo(pid, command); |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + return null; |
| 125 | + } |
| 126 | + |
| 127 | + private String getWindowsCommandByPid(String pid) throws Exception { |
| 128 | + Process process = new ProcessBuilder("cmd.exe", "/c", "tasklist /FI \"PID eq " + pid + "\"").start(); |
| 129 | + waitForProcess(process); |
| 130 | + List<String> lines = readOutput(process); |
| 131 | + for (String line : lines) { |
| 132 | + if (line.startsWith("Image Name")) { |
| 133 | + continue; |
| 134 | + } |
| 135 | + if (line.toLowerCase().contains(pid)) { |
| 136 | + return line.split("\\s+")[0]; |
| 137 | + } |
| 138 | + } |
| 139 | + return null; |
| 140 | + } |
| 141 | + |
| 142 | + private ProcessInfo findProcessOnUnix(int port) throws IOException { |
| 143 | + Process process = new ProcessBuilder("lsof", "-nP", "-i", ":" + port).start(); |
| 144 | + waitForProcess(process); |
| 145 | + List<String> lines = readOutput(process); |
| 146 | + for (String line : lines) { |
| 147 | + if (line.startsWith("COMMAND")) { |
| 148 | + continue; // header |
| 149 | + } |
| 150 | + String[] parts = line.trim().split("\\s+"); |
| 151 | + if (parts.length >= 2) { |
| 152 | + return new ProcessInfo(parts[1], parts[0]); |
| 153 | + } |
| 154 | + } |
| 155 | + return null; |
| 156 | + } |
| 157 | + |
| 158 | + private void waitForProcess(Process process) throws IOException { |
| 159 | + try { |
| 160 | + if (!process.waitFor(1, TimeUnit.SECONDS)) { |
| 161 | + process.destroy(); |
| 162 | + throw new IOException("Process timed out"); |
| 163 | + } |
| 164 | + } |
| 165 | + catch (InterruptedException ex) { |
| 166 | + Thread.currentThread().interrupt(); |
| 167 | + throw new IOException("Process interrupted", ex); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + private List<String> readOutput(Process process) throws IOException { |
| 172 | + List<String> lines = new ArrayList<>(); |
| 173 | + try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { |
| 174 | + String line; |
| 175 | + while ((line = reader.readLine()) != null) { |
| 176 | + lines.add(line); |
| 177 | + } |
| 178 | + } |
| 179 | + return lines; |
| 180 | + } |
| 181 | + |
| 182 | + private record ProcessInfo(String pid, String command) { |
37 | 183 | }
|
38 | 184 |
|
39 | 185 | }
|
0 commit comments