|
| 1 | +/* |
| 2 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | + * you may not use this file except in compliance with the License. |
| 4 | + * See the NOTICE file distributed with this work for additional |
| 5 | + * information regarding copyright ownership. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.appium.java_client.internal.process; |
| 18 | + |
| 19 | +import org.jspecify.annotations.Nullable; |
| 20 | +import org.slf4j.Logger; |
| 21 | +import org.slf4j.LoggerFactory; |
| 22 | + |
| 23 | +import java.io.IOException; |
| 24 | +import java.io.InputStream; |
| 25 | +import java.io.OutputStream; |
| 26 | +import java.nio.charset.Charset; |
| 27 | +import java.time.Duration; |
| 28 | +import java.util.ArrayList; |
| 29 | +import java.util.List; |
| 30 | +import java.util.Map; |
| 31 | + |
| 32 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; |
| 33 | + |
| 34 | +/** |
| 35 | + * A child process whose combined stdout/stderr is forwarded to a stream and |
| 36 | + * also retained (last bytes only) for diagnostics. Trimmed from Selenium's |
| 37 | + * {@code org.openqa.selenium.os.ExternalProcess} (Apache License 2.0). |
| 38 | + */ |
| 39 | +public final class ExternalProcess { |
| 40 | + private static final Logger LOG = LoggerFactory.getLogger(ExternalProcess.class); |
| 41 | + private static final int OUTPUT_BUFFER_SIZE = 32768; |
| 42 | + private static final Duration DEFAULT_SHUTDOWN_TIMEOUT = Duration.ofSeconds(4); |
| 43 | + |
| 44 | + private final Process process; |
| 45 | + private final TailBuffer output; |
| 46 | + private final Thread worker; |
| 47 | + |
| 48 | + private ExternalProcess(Process process, TailBuffer output, Thread worker) { |
| 49 | + this.process = process; |
| 50 | + this.output = output; |
| 51 | + this.worker = worker; |
| 52 | + } |
| 53 | + |
| 54 | + public static Builder builder() { |
| 55 | + return new Builder(); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * The last bytes of the combined stdout and stderr. |
| 60 | + * |
| 61 | + * @return the output decoded with the default charset |
| 62 | + */ |
| 63 | + public String getOutput() { |
| 64 | + return output.toString(Charset.defaultCharset()); |
| 65 | + } |
| 66 | + |
| 67 | + public boolean isAlive() { |
| 68 | + return process.isAlive(); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Waits for the process to exit and its output to be fully forwarded. |
| 73 | + * |
| 74 | + * @param timeout how long to wait |
| 75 | + * @return true if the process has exited |
| 76 | + */ |
| 77 | + public boolean waitFor(Duration timeout) { |
| 78 | + boolean exited = awaitExit(timeout); |
| 79 | + if (exited) { |
| 80 | + stopWorker(); |
| 81 | + } |
| 82 | + return exited; |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Terminates the process gracefully, then forcibly if it is still alive after the default timeout. |
| 87 | + */ |
| 88 | + public void shutdown() { |
| 89 | + shutdown(DEFAULT_SHUTDOWN_TIMEOUT); |
| 90 | + } |
| 91 | + |
| 92 | + /** |
| 93 | + * Terminates the process gracefully, then forcibly if it is still alive after the given timeout. |
| 94 | + * |
| 95 | + * @param timeout how long to wait for each termination attempt |
| 96 | + */ |
| 97 | + public void shutdown(Duration timeout) { |
| 98 | + try { |
| 99 | + // Use the handle to avoid closing the process streams |
| 100 | + var handle = process.toHandle(); |
| 101 | + if (handle.supportsNormalTermination()) { |
| 102 | + handle.destroy(); |
| 103 | + if (awaitExit(timeout)) { |
| 104 | + return; |
| 105 | + } |
| 106 | + } |
| 107 | + handle.destroyForcibly(); |
| 108 | + awaitExit(timeout); |
| 109 | + } finally { |
| 110 | + stopWorker(); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + private boolean awaitExit(Duration timeout) { |
| 115 | + try { |
| 116 | + return process.waitFor(timeout.toMillis(), MILLISECONDS); |
| 117 | + } catch (InterruptedException e) { |
| 118 | + Thread.currentThread().interrupt(); |
| 119 | + return false; |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + private void stopWorker() { |
| 124 | + try { |
| 125 | + worker.join(8000); |
| 126 | + } catch (InterruptedException e) { |
| 127 | + Thread.currentThread().interrupt(); |
| 128 | + } finally { |
| 129 | + // No-op if the worker has finished, otherwise unblocks it |
| 130 | + worker.interrupt(); |
| 131 | + try { |
| 132 | + worker.join(2000); |
| 133 | + } catch (InterruptedException e) { |
| 134 | + Thread.currentThread().interrupt(); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + public static final class Builder { |
| 140 | + private final ProcessBuilder builder = new ProcessBuilder(); |
| 141 | + private @Nullable OutputStream copyOutputTo; |
| 142 | + |
| 143 | + private Builder() { |
| 144 | + } |
| 145 | + |
| 146 | + /** |
| 147 | + * Sets the executable and its arguments. |
| 148 | + * |
| 149 | + * @param executable the executable path |
| 150 | + * @param arguments the executable arguments |
| 151 | + * @return this instance |
| 152 | + */ |
| 153 | + public Builder command(String executable, List<String> arguments) { |
| 154 | + var command = new ArrayList<String>(arguments.size() + 1); |
| 155 | + command.add(executable); |
| 156 | + command.addAll(arguments); |
| 157 | + builder.command(command); |
| 158 | + return this; |
| 159 | + } |
| 160 | + |
| 161 | + public Builder environment(String name, String value) { |
| 162 | + builder.environment().put(name, value); |
| 163 | + return this; |
| 164 | + } |
| 165 | + |
| 166 | + public Builder environment(Map<String, String> environment) { |
| 167 | + environment.forEach(this::environment); |
| 168 | + return this; |
| 169 | + } |
| 170 | + |
| 171 | + /** |
| 172 | + * Sets where to forward the combined stdout and stderr. |
| 173 | + * The stream is never closed by the process. |
| 174 | + * |
| 175 | + * @param stream the destination stream |
| 176 | + * @return this instance |
| 177 | + */ |
| 178 | + public Builder copyOutputTo(OutputStream stream) { |
| 179 | + copyOutputTo = stream; |
| 180 | + return this; |
| 181 | + } |
| 182 | + |
| 183 | + /** |
| 184 | + * Starts the process. |
| 185 | + * |
| 186 | + * @return the running process |
| 187 | + * @throws IOException if the process cannot be started |
| 188 | + */ |
| 189 | + public ExternalProcess start() throws IOException { |
| 190 | + builder.redirectErrorStream(true); |
| 191 | + var process = builder.start(); |
| 192 | + try { |
| 193 | + var buffer = new TailBuffer(OUTPUT_BUFFER_SIZE); |
| 194 | + var worker = new Thread( |
| 195 | + () -> forwardOutput(process, buffer, copyOutputTo), |
| 196 | + "External Process Output Forwarder - " + builder.command().get(0) |
| 197 | + ); |
| 198 | + worker.setDaemon(true); |
| 199 | + worker.start(); |
| 200 | + return new ExternalProcess(process, buffer, worker); |
| 201 | + } catch (Throwable t) { |
| 202 | + // Do not leak the process if the worker could not be started |
| 203 | + process.destroyForcibly(); |
| 204 | + throw t; |
| 205 | + } |
| 206 | + } |
| 207 | + |
| 208 | + private static void forwardOutput(Process process, TailBuffer buffer, @Nullable OutputStream target) { |
| 209 | + // The process output must always be drained, otherwise the process may block |
| 210 | + InputStream input = process.getInputStream(); |
| 211 | + var chunk = new byte[8192]; |
| 212 | + try { |
| 213 | + int count; |
| 214 | + while ((count = input.read(chunk)) != -1) { |
| 215 | + buffer.write(chunk, 0, count); |
| 216 | + if (target != null) { |
| 217 | + target.write(chunk, 0, count); |
| 218 | + } |
| 219 | + } |
| 220 | + } catch (IOException e) { |
| 221 | + LOG.warn("Failed to copy the output of process {}", process.pid(), e); |
| 222 | + } |
| 223 | + LOG.debug("Completed copying the output of process {}", process.pid()); |
| 224 | + } |
| 225 | + } |
| 226 | + |
| 227 | + /** |
| 228 | + * Keeps the last N bytes written to it. |
| 229 | + */ |
| 230 | + private static final class TailBuffer extends OutputStream { |
| 231 | + private final byte[] buffer; |
| 232 | + private int end; |
| 233 | + private boolean filled; |
| 234 | + |
| 235 | + TailBuffer(int size) { |
| 236 | + this.buffer = new byte[size]; |
| 237 | + } |
| 238 | + |
| 239 | + @Override |
| 240 | + public synchronized void write(int b) { |
| 241 | + if (end == buffer.length) { |
| 242 | + filled = true; |
| 243 | + end = 0; |
| 244 | + } |
| 245 | + buffer[end++] = (byte) b; |
| 246 | + } |
| 247 | + |
| 248 | + @Override |
| 249 | + public synchronized void write(byte[] b, int off, int len) { |
| 250 | + // Only the last buffer.length bytes can survive |
| 251 | + int skip = Math.max(0, len - buffer.length); |
| 252 | + for (int i = off + skip; i < off + len; i++) { |
| 253 | + write(b[i]); |
| 254 | + } |
| 255 | + } |
| 256 | + |
| 257 | + synchronized String toString(Charset encoding) { |
| 258 | + if (!filled) { |
| 259 | + return new String(buffer, 0, end, encoding); |
| 260 | + } |
| 261 | + var result = new byte[buffer.length]; |
| 262 | + int tail = buffer.length - end; |
| 263 | + System.arraycopy(buffer, end, result, 0, tail); |
| 264 | + System.arraycopy(buffer, 0, result, tail, end); |
| 265 | + return new String(result, encoding); |
| 266 | + } |
| 267 | + } |
| 268 | +} |
0 commit comments