mirror of
https://github.com/internetarchive/heritrix3.git
synced 2026-11-22 21:57:17 +00:00
Merge pull request #819 from internetarchive/browser-ssh
BrowserProcessor: launch browsers on other machines over SSH
This commit is contained in:
12 files changed
+925
-143
No files matched your search
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
* This file is part of the Heritrix web crawler (crawler.archive.org).
|
||||
*
|
||||
* Licensed to the Internet Archive (IA) by one or more individual
|
||||
* contributors.
|
||||
*
|
||||
* The IA licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.archive.net.webdriver;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* A running browser (or ChromeDriver) process and the WebDriver BiDi WebSocket URL it reports in its output.
|
||||
*/
|
||||
public class BrowserProcess {
|
||||
private static final System.Logger logger = System.getLogger(BrowserProcess.class.getName());
|
||||
static final int LAUNCH_TIMEOUT_SECONDS = 60;
|
||||
private static final String[] BROWSERS = new String[]{
|
||||
"firefox", "/Applications/Firefox.app/Contents/MacOS/firefox", "chromedriver"};
|
||||
protected final Process process;
|
||||
private final Thread shutdownHook;
|
||||
private final Consumer<String> outputListener;
|
||||
private final CompletableFuture<String> webSocketUrl = new CompletableFuture<>();
|
||||
|
||||
/**
|
||||
* Takes ownership of a started process whose stderr is redirected to its stdout.
|
||||
*/
|
||||
BrowserProcess(Process process) {
|
||||
this(process, line -> {});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param outputListener called with each line of the process's output
|
||||
*/
|
||||
BrowserProcess(Process process, Consumer<String> outputListener) {
|
||||
this.process = process;
|
||||
this.outputListener = outputListener;
|
||||
shutdownHook = new Thread(process::destroyForcibly);
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
var outputThread = new Thread(this::handleOutput, "BrowserProcess-output");
|
||||
outputThread.setDaemon(true);
|
||||
outputThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Launches a browser on this machine. If executable is null tries several common paths.
|
||||
*/
|
||||
public static BrowserProcess launchLocal(String executable, List<String> options, Path profileDir)
|
||||
throws IOException {
|
||||
return new BrowserProcess(executable == null ? launchAnyBrowser(options, profileDir)
|
||||
: launchBrowser(executable, options, profileDir));
|
||||
}
|
||||
|
||||
private static Process launchAnyBrowser(List<String> options, Path profileDir) throws IOException {
|
||||
IOException lastException = null;
|
||||
for (String executable : BROWSERS) {
|
||||
try {
|
||||
return launchBrowser(executable, options, profileDir);
|
||||
} catch (IOException e) {
|
||||
lastException = e;
|
||||
}
|
||||
}
|
||||
throw new IOException("Failed to launch any of: " + List.of(BROWSERS), lastException);
|
||||
}
|
||||
|
||||
private static Process launchBrowser(String executable, List<String> options, Path profileDir) throws IOException {
|
||||
var command = new ArrayList<String>();
|
||||
command.add(executable);
|
||||
command.add("--remote-debugging-port=0");
|
||||
if (executable.contains("firefox")) {
|
||||
command.add("--profile");
|
||||
command.add(profileDir.toAbsolutePath().toString());
|
||||
} else {
|
||||
command.add("--user-data-dir=" + profileDir.toAbsolutePath());
|
||||
}
|
||||
command.addAll(options);
|
||||
return new ProcessBuilder(command)
|
||||
.redirectInput(ProcessBuilder.Redirect.INHERIT)
|
||||
.redirectOutput(ProcessBuilder.Redirect.PIPE)
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
}
|
||||
|
||||
private void handleOutput() {
|
||||
String firefoxListening = "WebDriver BiDi listening on ";
|
||||
String chromeDriverListening = "ChromeDriver was started successfully on port ";
|
||||
try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
|
||||
outputListener.accept(line);
|
||||
if (line.startsWith(firefoxListening)) {
|
||||
webSocketUrl.complete(line.substring(firefoxListening.length()));
|
||||
} else if (line.startsWith(chromeDriverListening)) {
|
||||
webSocketUrl.complete("ws://127.0.0.1:" + line.substring(chromeDriverListening.length(), line.length() - 1));
|
||||
} else if (line.startsWith("DevTools listening on ")) {
|
||||
webSocketUrl.completeExceptionally(new WebDriverException("Chrome does not directly implement WebDriver BiDi. Please run ChromeDriver instead of running Chrome directly."));
|
||||
} else if (line.contains("Missing response info, network.responseCompleted will be skipped for URL:")) {
|
||||
continue; // suppress noisy Firefox logs
|
||||
}
|
||||
logger.log(System.Logger.Level.INFO, "Browser: {0}", line);
|
||||
}
|
||||
webSocketUrl.completeExceptionally(new EOFException("EOF waiting for start message"));
|
||||
} catch (Exception e) {
|
||||
webSocketUrl.completeExceptionally(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for the browser to report the URL of its WebDriver BiDi endpoint.
|
||||
*/
|
||||
public String awaitWebSocketUrl() throws ExecutionException, InterruptedException, IOException {
|
||||
try {
|
||||
return webSocketUrl.get(LAUNCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (TimeoutException e) {
|
||||
throw new IOException("Browser did not start within " + LAUNCH_TIMEOUT_SECONDS + " seconds", e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAlive() {
|
||||
return process.isAlive();
|
||||
}
|
||||
|
||||
public void destroyForcibly() {
|
||||
// ChromeDriver's browser is its child and would survive it, keeping the profile locked
|
||||
process.descendants().forEach(ProcessHandle::destroyForcibly);
|
||||
process.destroyForcibly();
|
||||
removeShutdownHook();
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the process to exit, killing it if it hasn't after ten seconds.
|
||||
*/
|
||||
public void close() {
|
||||
List<ProcessHandle> descendants = process.descendants().toList();
|
||||
process.destroy();
|
||||
try {
|
||||
if (!process.waitFor(10, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
// ChromeDriver doesn't wait for the browser it launched to exit
|
||||
CompletableFuture.allOf(descendants.stream().map(ProcessHandle::onExit)
|
||||
.toArray(CompletableFuture[]::new)).get(10, TimeUnit.SECONDS);
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
descendants.forEach(ProcessHandle::destroyForcibly);
|
||||
} catch (InterruptedException e) {
|
||||
process.destroyForcibly();
|
||||
descendants.forEach(ProcessHandle::destroyForcibly);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
removeShutdownHook();
|
||||
}
|
||||
|
||||
private void removeShutdownHook() {
|
||||
try {
|
||||
Runtime.getRuntime().removeShutdownHook(shutdownHook);
|
||||
} catch (IllegalStateException ignored) {
|
||||
// JVM is already shutting down
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@ public interface BrowsingContext extends BiDiModule {
|
||||
record Info(Context context, String url) {
|
||||
}
|
||||
|
||||
record DownloadWillBegin(Context context, String url) implements BiDiEvent {
|
||||
}
|
||||
|
||||
record Load(Context context, Navigation navigation, long timestamp, String url) implements BiDiEvent {
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,8 @@ import org.json.JSONObject;
|
||||
import org.json.JSONTokener;
|
||||
import org.json.JSONWriter;
|
||||
|
||||
import java.io.*;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.*;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
@@ -45,8 +46,7 @@ import java.util.function.Consumer;
|
||||
*/
|
||||
public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable {
|
||||
private final System.Logger logger = System.getLogger(getClass().getName());
|
||||
private final Process process;
|
||||
private final CompletableFuture<String> webSocketUrl = new CompletableFuture<>();
|
||||
private final BrowserProcess process;
|
||||
private final WebSocket webSocket;
|
||||
private final AtomicLong requestId = new AtomicLong(0);
|
||||
private final Map<Long, CompletableFuture<JSONObject>> commands = new ConcurrentHashMap<>();
|
||||
@@ -56,99 +56,37 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable {
|
||||
.setDaemon(true)
|
||||
.build());
|
||||
private final String sessionId;
|
||||
private final Thread shutdownHook;
|
||||
private final Object sendLock = new Object();
|
||||
private CompletableFuture<?> sendChain = CompletableFuture.completedFuture(null);
|
||||
private volatile Duration commandTimeout = Duration.ofSeconds(30);
|
||||
private static final int LAUNCH_TIMEOUT_SECONDS = 60;
|
||||
private static final String[] BROWSERS = new String[]{
|
||||
"firefox", "/Applications/Firefox.app/Contents/MacOS/firefox", "chromedriver"};
|
||||
private static final int CONNECT_TIMEOUT_SECONDS = 60;
|
||||
|
||||
public LocalWebDriverBiDi(String executable, List<String> options, Session.CapabilitiesRequest capabilities, Path profileDir)
|
||||
throws ExecutionException, InterruptedException, IOException {
|
||||
this.process = executable == null ? launchAnyBrowser(options, profileDir) : launchBrowser(executable, options, profileDir);
|
||||
shutdownHook = new Thread(this.process::destroyForcibly);
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
var stderrThread = new Thread(this::handleStderr, "LocalWebDriverBiDi-stderr");
|
||||
stderrThread.setDaemon(true);
|
||||
stderrThread.start();
|
||||
this(BrowserProcess.launchLocal(executable, options, profileDir), capabilities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to a launched browser and starts a session. Kills the browser if that fails.
|
||||
*/
|
||||
public LocalWebDriverBiDi(BrowserProcess process, Session.CapabilitiesRequest capabilities)
|
||||
throws ExecutionException, InterruptedException, IOException {
|
||||
this.process = process;
|
||||
try {
|
||||
String url = webSocketUrl.get(LAUNCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
String url = process.awaitWebSocketUrl();
|
||||
webSocket = HttpClient.newHttpClient().newWebSocketBuilder()
|
||||
.buildAsync(URI.create(url + "/session"), new Listener())
|
||||
.get(LAUNCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
sessionId = session().newAsync(capabilities).get(LAUNCH_TIMEOUT_SECONDS, TimeUnit.SECONDS).sessionId();
|
||||
.get(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
sessionId = session().newAsync(capabilities).get(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS).sessionId();
|
||||
} catch (TimeoutException e) {
|
||||
destroyProcess();
|
||||
throw new IOException("Browser did not start within " + LAUNCH_TIMEOUT_SECONDS + " seconds", e);
|
||||
process.destroyForcibly();
|
||||
throw new IOException("Browser did not start within " + CONNECT_TIMEOUT_SECONDS + " seconds", e);
|
||||
} catch (Exception e) {
|
||||
destroyProcess();
|
||||
process.destroyForcibly();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void destroyProcess() {
|
||||
process.descendants().forEach(ProcessHandle::destroyForcibly);
|
||||
process.destroyForcibly();
|
||||
try {
|
||||
Runtime.getRuntime().removeShutdownHook(shutdownHook);
|
||||
} catch (IllegalStateException ignored) {
|
||||
// JVM is already shutting down
|
||||
}
|
||||
}
|
||||
|
||||
private static Process launchAnyBrowser(List<String> options, Path profileDir) throws IOException {
|
||||
IOException lastException = null;
|
||||
for (String executable : BROWSERS) {
|
||||
try {
|
||||
return launchBrowser(executable, options, profileDir);
|
||||
} catch (IOException e) {
|
||||
lastException = e;
|
||||
}
|
||||
}
|
||||
throw new IOException("Failed to launch any of: " + List.of(BROWSERS), lastException);
|
||||
}
|
||||
|
||||
private static Process launchBrowser(String executable, List<String> options, Path profileDir) throws IOException {
|
||||
var command = new ArrayList<String>();
|
||||
command.add(executable);
|
||||
command.add("--remote-debugging-port=0");
|
||||
if (executable.contains("firefox")) {
|
||||
command.add("--profile");
|
||||
command.add(profileDir.toAbsolutePath().toString());
|
||||
} else {
|
||||
command.add("--user-data-dir=" + profileDir.toAbsolutePath());
|
||||
}
|
||||
command.addAll(options);
|
||||
return new ProcessBuilder(command)
|
||||
.redirectInput(ProcessBuilder.Redirect.INHERIT)
|
||||
.redirectOutput(ProcessBuilder.Redirect.PIPE)
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
}
|
||||
|
||||
private void handleStderr() {
|
||||
String firefoxListening = "WebDriver BiDi listening on ";
|
||||
String chromeDriverListening = "ChromeDriver was started successfully on port ";
|
||||
try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
|
||||
if (line.startsWith(firefoxListening)) {
|
||||
webSocketUrl.complete(line.substring(firefoxListening.length()));
|
||||
} else if (line.startsWith(chromeDriverListening)) {
|
||||
webSocketUrl.complete("ws://127.0.0.1:" + line.substring(chromeDriverListening.length(), line.length() - 1));
|
||||
} else if (line.startsWith("DevTools listening on ")) {
|
||||
webSocketUrl.completeExceptionally(new WebDriverException("Chrome does not directly implement WebDriver BiDi. Please run ChromeDriver instead of running Chrome directly."));
|
||||
} else if (line.contains("Missing response info, network.responseCompleted will be skipped for URL:")) {
|
||||
continue; // suppress noisy Firefox logs
|
||||
}
|
||||
logger.log(System.Logger.Level.INFO, "Browser: {0}", line);
|
||||
}
|
||||
webSocketUrl.completeExceptionally(new EOFException("EOF waiting for start message"));
|
||||
} catch (Exception e) {
|
||||
webSocketUrl.completeExceptionally(e);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<JSONObject> send(String method, Map<String, Object> params) {
|
||||
long id = requestId.incrementAndGet();
|
||||
var command = new JSONObject();
|
||||
@@ -206,8 +144,6 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable {
|
||||
}
|
||||
|
||||
private void kill() {
|
||||
// ChromeDriver's browser is its child and would survive it, keeping the profile locked
|
||||
process.descendants().forEach(ProcessHandle::destroyForcibly);
|
||||
process.destroyForcibly();
|
||||
webSocket.abort();
|
||||
failPendingCommands(new WebDriverException("Browser stopped responding"));
|
||||
@@ -279,7 +215,6 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
List<ProcessHandle> descendants = process.descendants().toList();
|
||||
try {
|
||||
if (isAlive()) {
|
||||
browser().close();
|
||||
@@ -287,26 +222,7 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable {
|
||||
} catch (Exception e) {
|
||||
logger.log(System.Logger.Level.ERROR, "Error closing browser", e);
|
||||
}
|
||||
process.destroy();
|
||||
try {
|
||||
if (!process.waitFor(10, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
// ChromeDriver doesn't wait for the browser it launched to exit
|
||||
CompletableFuture.allOf(descendants.stream().map(ProcessHandle::onExit)
|
||||
.toArray(CompletableFuture[]::new)).get(10, TimeUnit.SECONDS);
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
descendants.forEach(ProcessHandle::destroyForcibly);
|
||||
} catch (InterruptedException e) {
|
||||
process.destroyForcibly();
|
||||
descendants.forEach(ProcessHandle::destroyForcibly);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
try {
|
||||
Runtime.getRuntime().removeShutdownHook(shutdownHook);
|
||||
} catch (IllegalStateException ignored) {
|
||||
// JVM is already shutting down
|
||||
}
|
||||
process.close();
|
||||
failPendingCommands(new WebDriverException("WebDriver connection closed"));
|
||||
eventExecutor.shutdown();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
/*
|
||||
* This file is part of the Heritrix web crawler (crawler.archive.org).
|
||||
*
|
||||
* Licensed to the Internet Archive (IA) by one or more individual
|
||||
* contributors.
|
||||
*
|
||||
* The IA licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.archive.net.webdriver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* A browser launched on another machine by an ssh client process. The ssh client forwards a port
|
||||
* on the remote machine to the recording proxy and the browser's WebDriver BiDi port to the same
|
||||
* port on this machine.
|
||||
*/
|
||||
public class SshBrowserProcess extends BrowserProcess {
|
||||
private static final Pattern ALLOCATED_PORT =
|
||||
Pattern.compile("Allocated port (\\d+) for remote forward to .*");
|
||||
private static final Pattern AUTHORITY =
|
||||
Pattern.compile("(?:(.+)@)?(?:\\[([^]]+)]|([^@:\\[\\]]+))(?::(\\d+))?");
|
||||
private static final String WRAPPER_SCRIPT = """
|
||||
base=${XDG_CACHE_HOME:-$HOME/.cache}/heritrix-browser
|
||||
mkdir -p "$base" && cd "$base" && mkdir "$profile" || exit 1
|
||||
printf '%s' "$user_js" > "$profile/user.js"
|
||||
if [ -z "$exe" ]; then
|
||||
exe=$(command -v firefox || command -v chromedriver) || {
|
||||
echo 'Neither firefox nor chromedriver is on the PATH' >&2
|
||||
rm -rf "$profile"
|
||||
rmdir "$base" 2>/dev/null
|
||||
exit 1
|
||||
}
|
||||
fi
|
||||
# sshd closes our stdin when the ssh client exits or is killed. Background jobs get
|
||||
# /dev/null as stdin, so keep ours as fd 3 for the watcher below and don't pass it to
|
||||
# the browser.
|
||||
exec 3<&0
|
||||
case $exe in
|
||||
*firefox*) set -- --remote-debugging-port=$port --profile "$PWD/$profile" "$@" ;;
|
||||
*) set -- --port=$port "$@" ;;
|
||||
esac
|
||||
# With setsid the browser gets its own process group, so whatever it starts, like
|
||||
# chromedriver's Chrome, can be killed along with it.
|
||||
setsid=$(command -v setsid)
|
||||
$setsid "$exe" "$@" </dev/null 3<&- &
|
||||
browser=$!
|
||||
target=$browser
|
||||
[ -n "$setsid" ] && target=-$browser
|
||||
# Once ssh is gone our stdout and stderr are broken pipes, and the shell reporting
|
||||
# that the browser was killed would get SIGPIPE before cleaning up.
|
||||
exec >/dev/null 2>&1
|
||||
# When stdin reaches EOF, ask the browser to exit and kill it if it hasn't after ten
|
||||
# seconds. If the browser exits first, the watcher is killed instead.
|
||||
{ cat >/dev/null; kill -TERM $target; sleep 10; kill -KILL $target; } <&3 &
|
||||
watcher=$!
|
||||
wait $browser
|
||||
status=$?
|
||||
kill $watcher 2>/dev/null
|
||||
[ -n "$setsid" ] && kill -KILL $target
|
||||
rm -rf "$profile"
|
||||
rmdir "$base" 2>/dev/null
|
||||
exit $status
|
||||
""";
|
||||
private final int proxyPort;
|
||||
private final String profileName;
|
||||
|
||||
private SshBrowserProcess(Process process, CompletableFuture<Integer> allocatedPort,
|
||||
String profileName) throws IOException, InterruptedException {
|
||||
super(process, line -> {
|
||||
Matcher matcher = ALLOCATED_PORT.matcher(line);
|
||||
if (matcher.matches()) allocatedPort.complete(Integer.parseInt(matcher.group(1)));
|
||||
});
|
||||
process.onExit().thenRun(() -> allocatedPort.completeExceptionally(
|
||||
new IOException("ssh exited with status " + process.exitValue())));
|
||||
this.profileName = profileName;
|
||||
try {
|
||||
this.proxyPort = allocatedPort.get(LAUNCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
destroyForcibly();
|
||||
throw new IOException("ssh did not report the port forwarded to the proxy", e);
|
||||
} catch (InterruptedException e) {
|
||||
destroyForcibly();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Launches a browser over ssh.
|
||||
*
|
||||
* @param sshCommand the ssh client to run
|
||||
* @param uri ssh://[user@]host[:port]
|
||||
* @param executable the browser to run on the remote machine, or null for firefox or
|
||||
* chromedriver from the PATH
|
||||
* @param proxyPort the port of the recording proxy on this machine
|
||||
* @param userJs contents of the user.js file to write into the Firefox profile
|
||||
*/
|
||||
public static SshBrowserProcess launch(String sshCommand, URI uri, String executable,
|
||||
List<String> options, int proxyPort, String userJs)
|
||||
throws IOException, InterruptedException {
|
||||
// Firefox rejects a WebSocket handshake whose Host header has a different port than it
|
||||
// listens on, so the BiDi port is forwarded to the same port number. If that's taken on
|
||||
// the remote machine the launch fails and is retried.
|
||||
int bidiPort;
|
||||
try (var socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
bidiPort = socket.getLocalPort();
|
||||
}
|
||||
String profileName = "profile-" + UUID.randomUUID();
|
||||
String script = wrapperScript(executable, options, bidiPort, profileName, userJs);
|
||||
// stdin is left as a pipe from this JVM so that it reaches EOF if the JVM dies
|
||||
var process = new ProcessBuilder(command(sshCommand, uri, proxyPort, bidiPort, script))
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
return new SshBrowserProcess(process, new CompletableFuture<>(), profileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that uri is ssh://[user@]host[:port]. The host may be an IPv6 literal in brackets
|
||||
* or an alias from the ssh config.
|
||||
*
|
||||
* @throws IllegalArgumentException if it isn't
|
||||
*/
|
||||
public static void checkUri(URI uri) {
|
||||
parseAuthority(uri);
|
||||
}
|
||||
|
||||
private static Matcher parseAuthority(URI uri) {
|
||||
Matcher matcher;
|
||||
if (!"ssh".equals(uri.getScheme()) || uri.getAuthority() == null
|
||||
|| !uri.getRawPath().isEmpty() || uri.getRawQuery() != null
|
||||
|| !(matcher = AUTHORITY.matcher(uri.getAuthority())).matches()) {
|
||||
throw new IllegalArgumentException("Expected ssh://[user@]host[:port] but got " + uri);
|
||||
}
|
||||
return matcher;
|
||||
}
|
||||
|
||||
static List<String> command(String sshCommand, URI uri, int proxyPort, int bidiPort,
|
||||
String script) {
|
||||
Matcher authority = parseAuthority(uri);
|
||||
var command = new ArrayList<>(List.of(sshCommand,
|
||||
"-o", "BatchMode=yes",
|
||||
// the Allocated port message is logged at INFO
|
||||
"-o", "LogLevel=INFO",
|
||||
// a shared connection wouldn't report the port and would keep the forwards open
|
||||
"-o", "ControlMaster=no",
|
||||
"-o", "ControlPath=none",
|
||||
"-o", "ExitOnForwardFailure=yes",
|
||||
"-o", "ServerAliveInterval=15",
|
||||
"-o", "ServerAliveCountMax=3",
|
||||
"-o", "ConnectTimeout=10",
|
||||
"-R", "0:127.0.0.1:" + proxyPort,
|
||||
"-L", "127.0.0.1:" + bidiPort + ":127.0.0.1:" + bidiPort));
|
||||
if (authority.group(1) != null) {
|
||||
command.add("-l");
|
||||
command.add(authority.group(1));
|
||||
}
|
||||
if (authority.group(4) != null) {
|
||||
command.add("-p");
|
||||
command.add(authority.group(4));
|
||||
}
|
||||
command.add("--");
|
||||
command.add(authority.group(2) != null ? authority.group(2) : authority.group(3));
|
||||
command.add("sh -c " + shellQuote(script));
|
||||
return command;
|
||||
}
|
||||
|
||||
static String wrapperScript(String executable, List<String> options, int port,
|
||||
String profileName, String userJs) {
|
||||
String args = options.stream().map(option -> " " + shellQuote(option))
|
||||
.collect(Collectors.joining());
|
||||
return "profile=" + shellQuote(profileName) + "\n" +
|
||||
"exe=" + shellQuote(executable == null ? "" : executable) + "\n" +
|
||||
"port=" + port + "\n" +
|
||||
"user_js=" + shellQuote(userJs) + "\n" +
|
||||
"set --" + args + "\n" +
|
||||
WRAPPER_SCRIPT;
|
||||
}
|
||||
|
||||
static String shellQuote(String value) {
|
||||
return "'" + value.replace("'", "'\\''") + "'";
|
||||
}
|
||||
|
||||
/**
|
||||
* The port on the remote machine that is forwarded to the recording proxy.
|
||||
*/
|
||||
public int proxyPort() {
|
||||
return proxyPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of the browser's profile directory, relative to the browser's working directory.
|
||||
*/
|
||||
public String profileName() {
|
||||
return profileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes ssh's stdin so the remote side stops the browser and removes its profile, then waits
|
||||
* for ssh to exit.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
process.getOutputStream().close();
|
||||
process.waitFor(15, TimeUnit.SECONDS);
|
||||
} catch (IOException e) {
|
||||
// fall back to killing ssh
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package org.archive.net.webdriver;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.archive.net.webdriver.SshBrowserProcess.shellQuote;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SshBrowserProcessTest {
|
||||
private static final List<String> AWKWARD_VALUES = List.of("", "plain", "with space", "it's",
|
||||
"\"double\"", "$HOME `id` $(id) \\ * ;", "'", "line\nbreak");
|
||||
|
||||
@Test
|
||||
void shellQuoteSurvivesShell() throws Exception {
|
||||
for (String value : AWKWARD_VALUES) {
|
||||
assertEquals(value, runShell("printf %s " + shellQuote(value)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shellQuoteSurvivesNesting() throws Exception {
|
||||
// ssh joins the remote command's words with spaces and gives them to the remote user's
|
||||
// shell, which runs the wrapper with sh -c.
|
||||
for (String value : AWKWARD_VALUES) {
|
||||
assertEquals(value, runShell("sh -c " + shellQuote("printf %s " + shellQuote(value))));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void command() {
|
||||
var command = SshBrowserProcess.command("ssh", URI.create("ssh://alice@example.org:2222"),
|
||||
8443, 40000, "script");
|
||||
assertEquals(List.of("ssh",
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "LogLevel=INFO",
|
||||
"-o", "ControlMaster=no",
|
||||
"-o", "ControlPath=none",
|
||||
"-o", "ExitOnForwardFailure=yes",
|
||||
"-o", "ServerAliveInterval=15",
|
||||
"-o", "ServerAliveCountMax=3",
|
||||
"-o", "ConnectTimeout=10",
|
||||
"-R", "0:127.0.0.1:8443",
|
||||
"-L", "127.0.0.1:40000:127.0.0.1:40000",
|
||||
"-l", "alice",
|
||||
"-p", "2222",
|
||||
"--",
|
||||
"example.org",
|
||||
"sh -c 'script'"), command);
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandWithoutUserOrPort() {
|
||||
var command = SshBrowserProcess.command("ssh", URI.create("ssh://example.org"), 8443, 40000,
|
||||
"script");
|
||||
assertEquals(List.of("--", "example.org", "sh -c 'script'"),
|
||||
command.subList(command.size() - 3, command.size()));
|
||||
assertFalse(command.contains("-p"));
|
||||
assertFalse(command.contains("-l"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandHosts() {
|
||||
assertEquals(List.of("-l", "-oProxyCommand=x", "--", "::1"),
|
||||
destination("ssh://-oProxyCommand=x@[::1]"));
|
||||
assertEquals(List.of("-l", "bob", "-p", "22", "--", "my_box"),
|
||||
destination("ssh://bob@my_box:22"));
|
||||
}
|
||||
|
||||
private static List<String> destination(String uri) {
|
||||
var command = SshBrowserProcess.command("ssh", URI.create(uri), 8443, 40000, "script");
|
||||
return command.subList(command.indexOf("-L") + 2, command.size() - 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandRejectsOtherUris() {
|
||||
for (String uri : List.of("http://example.org", "ssh:example.org", "ssh://example.org/path",
|
||||
"ssh://example.org?query", "ssh://example.org:port")) {
|
||||
assertThrows(IllegalArgumentException.class, () -> SshBrowserProcess.command("ssh",
|
||||
URI.create(uri), 8443, 40000, "script"), uri);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrapperScriptSetsVariables() throws Exception {
|
||||
String script = SshBrowserProcess.wrapperScript("/opt/my browser/firefox",
|
||||
List.of("--headless", "it's"), 50000, "profile-1", "user_pref('a', \"b\");\n");
|
||||
String output = runShell(script.substring(0, script.indexOf("base=")) +
|
||||
"printf '%s|' \"$profile\" \"$exe\" \"$port\" \"$user_js\" \"$@\"");
|
||||
assertEquals("profile-1|/opt/my browser/firefox|50000|user_pref('a', \"b\");\n" +
|
||||
"|--headless|it's|", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedLaunchKillsSsh(@TempDir Path tempDir) throws Exception {
|
||||
Path fakeSsh = tempDir.resolve("fake-ssh");
|
||||
Files.writeString(fakeSsh, "#!/bin/sh\nexec sleep 60\n");
|
||||
Files.setPosixFilePermissions(fakeSsh, PosixFilePermissions.fromString("rwx------"));
|
||||
var before = ProcessHandle.current().children().toList();
|
||||
var launching = Thread.currentThread();
|
||||
new Thread(() -> {
|
||||
while (ProcessHandle.current().children().count() == before.size()) Thread.onSpinWait();
|
||||
launching.interrupt();
|
||||
}).start();
|
||||
assertThrows(InterruptedException.class, () -> SshBrowserProcess.launch(fakeSsh.toString(),
|
||||
URI.create("ssh://example.org"), null, List.of(), 8443, ""));
|
||||
var ssh = ProcessHandle.current().children().filter(c -> !before.contains(c)).toList();
|
||||
for (var child : ssh) child.onExit().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledIfSystemProperty(named = "runBrowserTests", matches = "true")
|
||||
void launch(@TempDir Path tempDir) throws Exception {
|
||||
Path cache = tempDir.resolve("cache");
|
||||
Path fakeSsh = tempDir.resolve("fake-ssh");
|
||||
// Stands in for ssh by running the remote command on this machine. Neither forward exists:
|
||||
// it reports the proxy's own port as allocated, and the browser listens on the BiDi port
|
||||
// directly.
|
||||
Files.writeString(fakeSsh, """
|
||||
#!/bin/sh
|
||||
while [ "$1" != -- ]; do
|
||||
if [ "$1" = -R ]; then proxy_port=${2##*:}; fi
|
||||
shift
|
||||
done
|
||||
shift 2
|
||||
echo "Allocated port $proxy_port for remote forward to 127.0.0.1:$proxy_port" >&2
|
||||
export XDG_CACHE_HOME=%s
|
||||
exec sh -c "$*"
|
||||
""".formatted(shellQuote(cache.toString())));
|
||||
Files.setPosixFilePermissions(fakeSsh, PosixFilePermissions.fromString("rwx------"));
|
||||
|
||||
try (var proxy = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
var process = SshBrowserProcess.launch(fakeSsh.toString(),
|
||||
URI.create("ssh://example.invalid"), null, List.of("--headless"),
|
||||
proxy.getLocalPort(), "// it's user.js\n");
|
||||
assertEquals(proxy.getLocalPort(), process.proxyPort());
|
||||
var driver = new LocalWebDriverBiDi(process,
|
||||
new Session.CapabilitiesRequest(Map.of(), List.of(Map.of())));
|
||||
Path profile = cache.resolve("heritrix-browser").resolve(process.profileName());
|
||||
assertEquals("// it's user.js\n", Files.readString(profile.resolve("user.js"), UTF_8));
|
||||
assertNotNull(driver.browsingContext().getTreeAsync(0).get(30, TimeUnit.SECONDS));
|
||||
driver.close();
|
||||
assertFalse(process.isAlive());
|
||||
assertFalse(Files.exists(profile.getParent()),
|
||||
"profile and heritrix-browser directories should have been removed");
|
||||
}
|
||||
}
|
||||
|
||||
private static String runShell(String script) throws IOException, InterruptedException {
|
||||
var process = new ProcessBuilder("sh", "-c", script).redirectErrorStream(true).start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), UTF_8);
|
||||
assertEquals(0, process.waitFor(), output);
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -546,6 +546,16 @@ BrowserProcessor
|
||||
|
||||
.. bean-doc:: org.archive.crawler.processor.BrowserProcessor
|
||||
|
||||
LocalBrowser
|
||||
~~~~~~~~~~~~
|
||||
|
||||
.. bean-doc:: org.archive.crawler.processor.LocalBrowser
|
||||
|
||||
SshBrowser
|
||||
~~~~~~~~~~
|
||||
|
||||
.. bean-doc:: org.archive.crawler.processor.SshBrowser
|
||||
|
||||
ExtractLinksBehavior
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* This file is part of the Heritrix web crawler (crawler.archive.org).
|
||||
*
|
||||
* Licensed to the Internet Archive (IA) by one or more individual
|
||||
* contributors.
|
||||
*
|
||||
* The IA licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.archive.crawler.processor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Settings for one of the {@link BrowserProcessor#setBrowsers browsers} of a BrowserProcessor.
|
||||
* Settings left unset take the value of the BrowserProcessor's property of the same name.
|
||||
*/
|
||||
public abstract class BrowserConfig {
|
||||
private Integer concurrency;
|
||||
private String executable;
|
||||
private List<String> options;
|
||||
|
||||
/**
|
||||
* Parses a {@link BrowserProcessor#setBrowsers browsers} entry given as a string into a config
|
||||
* with nothing overridden.
|
||||
*/
|
||||
static BrowserConfig parse(String browser) {
|
||||
if (browser.equals("local")) return new LocalBrowser();
|
||||
try {
|
||||
var ssh = new SshBrowser();
|
||||
ssh.setUri(browser);
|
||||
return ssh;
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalArgumentException("Unsupported browser '" + browser +
|
||||
"': expected 'local' or 'ssh://[user@]host[:port]'");
|
||||
}
|
||||
}
|
||||
|
||||
public Integer getConcurrency() {
|
||||
return concurrency;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maximum number of web pages that can be open in this browser at once.
|
||||
*/
|
||||
public void setConcurrency(Integer concurrency) {
|
||||
this.concurrency = concurrency;
|
||||
}
|
||||
|
||||
public String getExecutable() {
|
||||
return executable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Webdriver executable to launch for this browser.
|
||||
*/
|
||||
public void setExecutable(String executable) {
|
||||
this.executable = executable;
|
||||
}
|
||||
|
||||
public List<String> getOptions() {
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra command-line options to be passed to this browser's webdriver executable.
|
||||
*/
|
||||
public void setOptions(List<String> options) {
|
||||
this.options = options;
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -82,13 +83,26 @@ import static org.archive.modules.fetcher.FetchErrors.LENGTH_TRUNC;
|
||||
import static org.archive.modules.fetcher.FetchErrors.TIMER_TRUNC;
|
||||
|
||||
/**
|
||||
* Opens a web page in a local web browser via WebDriver BiDi and runs {@link Behavior}s to interact with the page.
|
||||
* Opens a web page in a web browser via WebDriver BiDi and runs {@link Behavior}s to interact with the page.
|
||||
* Subresources loaded by the browser are recorded using a HTTP proxy. Must be used in conjunction with
|
||||
* {@link FetchHTTP2}. Normally defined in the FetchChain after the link extractors.
|
||||
*/
|
||||
public class BrowserProcessor extends Processor {
|
||||
private static final System.Logger logger = System.getLogger(BrowserProcessor.class.getName());
|
||||
protected static final String PAGE_ID_HEADER = "Heritrix-Request-ID";
|
||||
// Firefox doesn't seem to allow setting prefs via capabilities with bidi
|
||||
// so drop them in user.js instead
|
||||
private static final String USER_JS = """
|
||||
// send localhost requests via the proxy too (for tests and local crawling)
|
||||
user_pref('network.proxy.allow_hijacking_localhost', true);
|
||||
|
||||
// disable downloads by setting to something that can't be created as a directory
|
||||
user_pref('browser.download.dir', '/dev/null');
|
||||
user_pref('browser.download.folderList', 2);
|
||||
|
||||
// Firefox 153 ESR on Linux kills tabs' content processes mid-load with site isolation on
|
||||
user_pref('fission.autostart', false);
|
||||
""";
|
||||
protected final CrawlController crawlController;
|
||||
protected MitmProxy proxy;
|
||||
protected final FetchHTTP2 fetcher;
|
||||
@@ -104,7 +118,7 @@ public class BrowserProcessor extends Processor {
|
||||
protected String executable;
|
||||
protected List<String> options = List.of("--headless");
|
||||
protected int concurrency = 20;
|
||||
protected List<String> browsers = List.of("local");
|
||||
protected List<?> browsers = List.of("local");
|
||||
protected int minBrowsers = 1;
|
||||
protected int browserIdleTimeoutSeconds = 300;
|
||||
|
||||
@@ -248,13 +262,14 @@ public class BrowserProcessor extends Processor {
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private void visit(CrawlURI curi, LocalWebDriverBiDi driver) throws InterruptedException {
|
||||
private void visit(CrawlURI curi, WebDriverBiDi driver) throws InterruptedException {
|
||||
String pageId = UUID.randomUUID().toString();
|
||||
var tab = driver.browsingContext().create(BrowsingContext.CreateType.tab).context();
|
||||
try {
|
||||
String userAgent = curi.getUserAgent();
|
||||
if (userAgent == null) userAgent = fetcher.getUserAgentProvider().getUserAgent();
|
||||
BrowserPage page = new BrowserPage(curi, new IdleBarrier(), driver, tab, fetcher.getProxy(), userAgent);
|
||||
BrowserPage page = new BrowserPage(curi, new IdleBarrier(), driver, tab, fetcher.getProxy(), userAgent,
|
||||
new CompletableFuture<>());
|
||||
pages.put(pageId, page);
|
||||
pageIdsByContext.put(tab, pageId);
|
||||
driver.network().addIntercept(List.of(Network.InterceptPhase.beforeRequestSent), List.of(tab),
|
||||
@@ -268,7 +283,14 @@ public class BrowserProcessor extends Processor {
|
||||
if ("net::ERR_ABORTED".equals(e.getMessage())) return; // Chrome: probably download started
|
||||
throw e;
|
||||
}
|
||||
if (navigation.url().equals("about:blank")) return; // Firefox: probably download started
|
||||
if (navigation.url().equals("about:blank")) {
|
||||
try {
|
||||
page.downloadStarted().get(1, TimeUnit.SECONDS);
|
||||
return; // Firefox: download started
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
throw new WebDriverException("Navigation ended at about:blank, the tab may have crashed");
|
||||
}
|
||||
}
|
||||
|
||||
logger.log(System.Logger.Level.DEBUG, "Navigated to {0}", navigation);
|
||||
|
||||
@@ -303,11 +325,7 @@ public class BrowserProcessor extends Processor {
|
||||
public void start() {
|
||||
if (isRunning) return;
|
||||
if (browsers.isEmpty()) throw new IllegalArgumentException("browsers must not be empty");
|
||||
for (String browser : browsers) {
|
||||
if (!browser.equals("local")) {
|
||||
throw new IllegalArgumentException("Unsupported browser '" + browser + "': only 'local' is supported");
|
||||
}
|
||||
}
|
||||
List<BrowserConfig> configs = browsers.stream().map(BrowserProcessor::toConfig).toList();
|
||||
if (minBrowsers > browsers.size()) {
|
||||
throw new IllegalArgumentException("minBrowsers is " + minBrowsers + " but only " + browsers.size()
|
||||
+ " browsers are configured");
|
||||
@@ -338,7 +356,7 @@ public class BrowserProcessor extends Processor {
|
||||
.setNameFormat("BrowserProcessor-launcher-%d").setDaemon(true).build());
|
||||
pool.clear();
|
||||
for (int i = 0; i < browsers.size(); i++) {
|
||||
pool.add(new Browser(i));
|
||||
pool.add(new Browser(i, configs.get(i)));
|
||||
}
|
||||
CompletableFuture.allOf(pool.stream()
|
||||
.map(browser -> CompletableFuture.runAsync(browser::launch, launcher))
|
||||
@@ -356,7 +374,21 @@ public class BrowserProcessor extends Processor {
|
||||
}
|
||||
}
|
||||
|
||||
private void handleBeforeRequestSent(LocalWebDriverBiDi driver, Network.BeforeRequestSent event) {
|
||||
private static BrowserConfig toConfig(Object browser) {
|
||||
BrowserConfig config = browser instanceof String string ? BrowserConfig.parse(string) : (BrowserConfig) browser;
|
||||
if (config instanceof SshBrowser ssh && ssh.uri() == null) {
|
||||
throw new IllegalArgumentException("SshBrowser uri must be set");
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private void handleDownloadWillBegin(BrowsingContext.DownloadWillBegin event) {
|
||||
String pageId = pageIdsByContext.get(event.context());
|
||||
BrowserPage page = pageId == null ? null : pages.get(pageId);
|
||||
if (page != null) page.downloadStarted().complete(null);
|
||||
}
|
||||
|
||||
private void handleBeforeRequestSent(WebDriverBiDi driver, Network.BeforeRequestSent event) {
|
||||
if (event.request().url().startsWith("data:") || !event.isBlocked()) return;
|
||||
List<Network.Header> requestHeaders = event.request().headers();
|
||||
String pageId = pageIdsByContext.get(event.context());
|
||||
@@ -415,7 +447,8 @@ public class BrowserProcessor extends Processor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Webdriver executable to launch. If null, will try several common paths.
|
||||
* Webdriver executable to launch. If null, will try several common paths, or on a remote machine firefox and
|
||||
* then chromedriver on the PATH.
|
||||
* <p>
|
||||
* Firefox can be used directly as it implements WebDriver BiDI natively. To use Chrome set this to a
|
||||
* <a href="https://developer.chrome.com/docs/chromedriver">ChromeDriver</a> executable.
|
||||
@@ -474,16 +507,29 @@ public class BrowserProcessor extends Processor {
|
||||
this.browserIdleTimeoutSeconds = browserIdleTimeoutSeconds;
|
||||
}
|
||||
|
||||
public List<String> getBrowsers() {
|
||||
public List<?> getBrowsers() {
|
||||
return browsers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Browsers to open pages in, one per entry. The only supported value is currently {@code local}, which
|
||||
* launches {@link #setExecutable(String) executable} on this machine. Pages from the same queue are opened in
|
||||
* the same browser while it has a free tab, so that a site keeps one browser's cookies and cache.
|
||||
* Browsers to open pages in, one per entry. Pages from the same queue are opened in the same browser while it
|
||||
* has a free tab, so that a site keeps one browser's cookies and cache.
|
||||
* <p>
|
||||
* Each entry is a string or a {@link LocalBrowser} or {@link SshBrowser} bean. A bean can override
|
||||
* {@code concurrency}, {@code executable} and {@code options} for that browser. The strings are shorthand for a
|
||||
* bean with nothing overridden:
|
||||
* <ul>
|
||||
* <li>{@code local} launches {@link #setExecutable(String) executable} on this machine.</li>
|
||||
* <li>{@code ssh://[user@]host[:port]} launches it on another machine using the ssh command, which carries the
|
||||
* WebDriver BiDi connection and the browser's requests to the recording proxy. The remote machine needs sshd, a
|
||||
* POSIX login shell and the browser on the PATH of a non-interactive login (or {@code executable} set). Login must
|
||||
* work without a prompt, for example with a key in ssh-agent, and the host key must already be known. Settings in
|
||||
* ~/.ssh/config apply. The browser gets a fresh profile directory under ~/.cache/heritrix-browser on the remote
|
||||
* machine, removed when it exits. The remote machine can't be this one, as the WebDriver BiDi port is forwarded to
|
||||
* the same port number here.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public void setBrowsers(List<String> browsers) {
|
||||
public void setBrowsers(List<?> browsers) {
|
||||
this.browsers = browsers;
|
||||
}
|
||||
|
||||
@@ -637,6 +683,7 @@ public class BrowserProcessor extends Processor {
|
||||
private static final long MAX_RETRY_DELAY_SECONDS = 600;
|
||||
protected enum State { UP, IDLE, WAKING, DOWN }
|
||||
protected final int id;
|
||||
private final BrowserConfig config;
|
||||
protected volatile LocalWebDriverBiDi driver;
|
||||
protected volatile State state = State.DOWN;
|
||||
protected volatile String lastFailure;
|
||||
@@ -646,12 +693,25 @@ public class BrowserProcessor extends Processor {
|
||||
private volatile long idleSince;
|
||||
private long retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; // guarded by this
|
||||
|
||||
Browser(int id) {
|
||||
Browser(int id, BrowserConfig config) {
|
||||
this.id = id;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
int concurrency() {
|
||||
return config.getConcurrency() != null ? config.getConcurrency() : concurrency;
|
||||
}
|
||||
|
||||
private String executable() {
|
||||
return config.getExecutable() != null ? config.getExecutable() : executable;
|
||||
}
|
||||
|
||||
private List<String> options() {
|
||||
return config.getOptions() != null ? config.getOptions() : options;
|
||||
}
|
||||
|
||||
private boolean hasFreeTabSlot() {
|
||||
return state == State.UP && openTabs < concurrency;
|
||||
return state == State.UP && openTabs < concurrency();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -734,22 +794,25 @@ public class BrowserProcessor extends Processor {
|
||||
}
|
||||
|
||||
private LocalWebDriverBiDi createWebDriver() throws Exception {
|
||||
Path scratchDir = crawlController.getScratchDir().getFile().toPath();
|
||||
Path profileDir = scratchDir.resolve("profile-" + id);
|
||||
Files.createDirectories(profileDir);
|
||||
BrowserProcess process;
|
||||
int proxyPort;
|
||||
String profileDir;
|
||||
if (!(config instanceof SshBrowser ssh)) {
|
||||
Path scratchDir = crawlController.getScratchDir().getFile().toPath();
|
||||
Path localProfileDir = scratchDir.resolve("profile-" + id);
|
||||
Files.createDirectories(localProfileDir);
|
||||
Files.writeString(localProfileDir.resolve("user.js"), USER_JS);
|
||||
process = BrowserProcess.launchLocal(executable(), options(), localProfileDir);
|
||||
proxyPort = proxy.getPort();
|
||||
profileDir = localProfileDir.toString();
|
||||
} else {
|
||||
var sshProcess = SshBrowserProcess.launch("ssh", ssh.uri(), executable(), options(), proxy.getPort(),
|
||||
USER_JS);
|
||||
process = sshProcess;
|
||||
proxyPort = sshProcess.proxyPort();
|
||||
profileDir = sshProcess.profileName();
|
||||
}
|
||||
|
||||
// Firefox doesn't seem to allow setting prefs via capabilities with bidi
|
||||
// so drop them in user.js instead
|
||||
Files.writeString(profileDir.resolve("user.js"), """
|
||||
// send localhost requests via the proxy too (for tests and local crawling)
|
||||
user_pref('network.proxy.allow_hijacking_localhost', true);
|
||||
|
||||
// disable downloads by setting to something that can't be created as a directory
|
||||
user_pref('browser.download.dir', '/dev/null');
|
||||
user_pref('browser.download.folderList', 2);
|
||||
""");
|
||||
|
||||
int proxyPort = proxy.getPort();
|
||||
var alwaysMatch = Map.of("acceptInsecureCerts", true,
|
||||
"proxy", new Session.ProxyConfiguration("manual",
|
||||
"127.0.0.1:" + proxyPort, "127.0.0.1:" + proxyPort));
|
||||
@@ -765,11 +828,12 @@ public class BrowserProcessor extends Processor {
|
||||
);
|
||||
var capabilities = new Session.CapabilitiesRequest(alwaysMatch, firstMatch);
|
||||
|
||||
var driver = new LocalWebDriverBiDi(executable, options, capabilities, profileDir);
|
||||
var driver = new LocalWebDriverBiDi(process, capabilities);
|
||||
try {
|
||||
driver.session().subscribe(List.of("browsingContext.contextCreated",
|
||||
"network.beforeRequestSent"), null);
|
||||
"browsingContext.downloadWillBegin", "network.beforeRequestSent"), null);
|
||||
driver.on(Network.BeforeRequestSent.class, event -> handleBeforeRequestSent(driver, event));
|
||||
driver.on(BrowsingContext.DownloadWillBegin.class, event -> handleDownloadWillBegin(event));
|
||||
} catch (Exception e) {
|
||||
driver.close();
|
||||
throw e;
|
||||
@@ -803,7 +867,8 @@ public class BrowserProcessor extends Processor {
|
||||
WebDriverBiDi webdriver,
|
||||
BrowsingContext.Context context,
|
||||
ProxyConfiguration.Proxy proxy,
|
||||
String userAgent
|
||||
String userAgent,
|
||||
CompletableFuture<Void> downloadStarted
|
||||
) implements Page {
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* This file is part of the Heritrix web crawler (crawler.archive.org).
|
||||
*
|
||||
* Licensed to the Internet Archive (IA) by one or more individual
|
||||
* contributors.
|
||||
*
|
||||
* The IA licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.archive.crawler.processor;
|
||||
|
||||
/**
|
||||
* A browser of a {@link BrowserProcessor} launched on this machine. The {@code browsers} entry
|
||||
* {@code local} is shorthand for this bean with nothing set.
|
||||
*/
|
||||
public class LocalBrowser extends BrowserConfig {
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* This file is part of the Heritrix web crawler (crawler.archive.org).
|
||||
*
|
||||
* Licensed to the Internet Archive (IA) by one or more individual
|
||||
* contributors.
|
||||
*
|
||||
* The IA licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.archive.crawler.processor;
|
||||
|
||||
import org.archive.net.webdriver.SshBrowserProcess;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
/**
|
||||
* A browser of a {@link BrowserProcessor} launched on another machine over ssh, as described under
|
||||
* {@link BrowserProcessor#setBrowsers browsers}. The {@code browsers} entry
|
||||
* {@code ssh://[user@]host[:port]} is shorthand for this bean with only {@code uri} set.
|
||||
*/
|
||||
public class SshBrowser extends BrowserConfig {
|
||||
private URI uri;
|
||||
|
||||
public String getUri() {
|
||||
return uri == null ? null : uri.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The machine to launch the browser on, as {@code ssh://[user@]host[:port]}.
|
||||
*/
|
||||
public void setUri(String uri) {
|
||||
URI parsed;
|
||||
try {
|
||||
parsed = new URI(uri);
|
||||
} catch (URISyntaxException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Expected ssh://[user@]host[:port] but got '" + uri + "'", e);
|
||||
}
|
||||
SshBrowserProcess.checkUri(parsed);
|
||||
this.uri = parsed;
|
||||
}
|
||||
|
||||
URI uri() {
|
||||
return uri;
|
||||
}
|
||||
}
|
||||
@@ -327,6 +327,16 @@ http://example.example/example
|
||||
</list>
|
||||
</property>
|
||||
<property name="concurrency" value="20" />
|
||||
<property name="browsers">
|
||||
<list>
|
||||
<value>local</value>
|
||||
<value>ssh://crawler@browser1.example.org</value>
|
||||
<bean class="org.archive.crawler.processor.SshBrowser">
|
||||
<property name="uri" value="ssh://crawler@browser2.example.org" />
|
||||
<property name="concurrency" value="40" />
|
||||
</bean>
|
||||
</list>
|
||||
</property>
|
||||
<property name="executable" value="firefox" />
|
||||
<property name="options">
|
||||
<list>
|
||||
|
||||
@@ -232,6 +232,33 @@ class BrowserProcessorTest {
|
||||
assertFalse(processor.isRunning());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBrowserBeanOverrides() {
|
||||
var failing = new LocalBrowser();
|
||||
failing.setExecutable("/nonexistent/firefox");
|
||||
var narrow = new LocalBrowser();
|
||||
narrow.setConcurrency(1);
|
||||
var processor = newBrowserProcessor("overrides", List.of(failing, narrow, "local"));
|
||||
processor.start();
|
||||
try {
|
||||
assertEquals(BrowserProcessor.Browser.State.DOWN, processor.pool.get(0).state);
|
||||
assertTrue(processor.pool.get(0).lastFailure.contains("/nonexistent/firefox"),
|
||||
processor.pool.get(0).lastFailure);
|
||||
assertEquals(1, processor.pool.get(1).concurrency());
|
||||
assertEquals(processor.getConcurrency(), processor.pool.get(2).concurrency());
|
||||
} finally {
|
||||
processor.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRejectsUnsupportedBrowser() {
|
||||
for (String browser : List.of("remote", "ssh:host", "http://host")) {
|
||||
var processor = newBrowserProcessor("unsupported", List.of(browser));
|
||||
assertThrows(IllegalArgumentException.class, processor::start, browser);
|
||||
}
|
||||
}
|
||||
|
||||
private static void awaitUp(BrowserProcessor processor, int browserId) throws InterruptedException {
|
||||
synchronized (processor.tabsLock) {
|
||||
while (processor.pool.get(browserId).state != BrowserProcessor.Browser.State.UP) {
|
||||
@@ -454,7 +481,7 @@ class BrowserProcessorTest {
|
||||
browserProcessor.start();
|
||||
}
|
||||
|
||||
private static BrowserProcessor newBrowserProcessor(String name, List<String> browsers) {
|
||||
private static BrowserProcessor newBrowserProcessor(String name, List<?> browsers) {
|
||||
var crawlController = new CrawlController();
|
||||
crawlController.getScratchDir().setPath(tempDir.resolve(name).toString());
|
||||
FetchChain fetchChain = new FetchChain();
|
||||
|
||||
Reference in new issue
Block a user