diff --git a/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java b/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java index 7ddb1f48..b1c4b88a 100644 --- a/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java +++ b/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java @@ -19,6 +19,9 @@ package org.archive.net.webdriver; +import java.util.List; +import java.util.concurrent.CompletableFuture; + // https://w3c.github.io/webdriver-bidi/#module-browsingContext public interface BrowsingContext extends BiDiModule { CreateResult create(CreateType type); @@ -27,6 +30,8 @@ public interface BrowsingContext extends BiDiModule { void close(Context context); + CompletableFuture getTreeAsync(long maxDepth); + enum CreateType {tab, window} enum ReadinessState {none, interactive, complete} @@ -34,6 +39,12 @@ public interface BrowsingContext extends BiDiModule { record CreateResult(Context context) { } + record GetTreeResult(List contexts) { + } + + record Info(Context context, String url) { + } + record Load(Context context, Navigation navigation, long timestamp, String url) implements BiDiEvent { } diff --git a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java index cec07e09..ded6b59c 100644 --- a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java +++ b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java @@ -32,6 +32,7 @@ import java.net.URI; import java.net.http.HttpClient; import java.net.http.WebSocket; import java.nio.file.Path; +import java.time.Duration; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; @@ -58,6 +59,7 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { 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"}; @@ -176,12 +178,41 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { } /** - * Returns true if the browser process is running and the WebDriver connection is still open. + * How long to wait for the reply to a command before throwing {@link WebDriverTimeoutException}. + * Commands that return a {@link CompletableFuture} aren't affected. */ + public void setCommandTimeout(Duration commandTimeout) { + this.commandTimeout = commandTimeout; + } + + @Override public boolean isAlive() { return process.isAlive() && !webSocket.isInputClosed() && !webSocket.isOutputClosed(); } + private boolean isResponsive() { + try { + // not session.status, as ChromeDriver answers that itself without asking the browser + browsingContext().getTreeAsync(0).get(5, TimeUnit.SECONDS); + return true; + } catch (TimeoutException e) { + return false; + } catch (ExecutionException e) { + return true; // it answered, even if with an error + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return true; + } + } + + 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")); + } + private void failPendingCommands(Throwable failure) { for (Long id : commands.keySet()) { var future = commands.remove(id); @@ -226,14 +257,19 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { parameterizedType.getActualTypeArguments()[0] instanceof Class typeClass) { yield future.thenApply(result -> BiDiJson.fromJson(result, typeClass)); } else { - int timeout = 30; + Duration timeout = commandTimeout; try { - yield BiDiJson.fromJson(future.get(timeout, TimeUnit.SECONDS), method.getReturnType()); + yield BiDiJson.fromJson(future.get(timeout.toMillis(), TimeUnit.MILLISECONDS), + method.getReturnType()); } catch (ExecutionException e) { if (e.getCause() instanceof RuntimeException re) throw re; throw e; } catch (TimeoutException e) { - throw new WebDriverTimeoutException(prefix + methodName + " took more than " + timeout + " seconds"); + if (isAlive() && !isResponsive()) { + logger.log(System.Logger.Level.WARNING, "Browser stopped responding, killing it"); + kill(); + } + throw new WebDriverTimeoutException(prefix + methodName + " took more than " + timeout.toSeconds() + " seconds"); } } } diff --git a/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java b/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java index 7dee12b8..272620bb 100644 --- a/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java +++ b/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java @@ -22,6 +22,11 @@ package org.archive.net.webdriver; public interface WebDriverBiDi { T module(Class moduleClass); + /** + * Returns true if the browser is running and the WebDriver connection is still open. + */ + boolean isAlive(); + default Browser browser() { return module(Browser.class); } diff --git a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java index 560950e6..3791e3f2 100644 --- a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java +++ b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java @@ -19,6 +19,7 @@ package org.archive.crawler.processor; +import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.commons.lang3.StringUtils; import org.archive.crawler.event.CrawlURIDispositionEvent; import org.archive.crawler.framework.CrawlController; @@ -61,8 +62,13 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Semaphore; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; @@ -86,18 +92,21 @@ public class BrowserProcessor extends Processor { protected final CrawlController crawlController; protected MitmProxy proxy; protected final FetchHTTP2 fetcher; - protected volatile LocalWebDriverBiDi webdriver; + protected final List pool = new CopyOnWriteArrayList<>(); + protected ScheduledExecutorService launcher; + protected final Object tabsLock = new Object(); protected final ApplicationEventPublisher eventPublisher; protected final Map pages = new ConcurrentHashMap<>(); protected final Map pageIdsByContext = new ConcurrentHashMap<>(); protected final ProcessorChain extractorChain = new ProcessorChain(); protected final AtomicLong subresourcesRecorded = new AtomicLong(); - protected final AtomicLong browserRestarts = new AtomicLong(); protected List behaviors; protected String executable; protected List options = List.of("--headless"); protected int concurrency = 20; - protected Semaphore semaphore; + protected List browsers = List.of("local"); + protected int minBrowsers = 1; + protected int browserIdleTimeoutSeconds = 300; public BrowserProcessor(FetchHTTP2 fetcher, CrawlController crawlController, ApplicationEventPublisher eventPublisher, UriErrorLoggerModule uriErrorLoggerModule) { @@ -110,6 +119,7 @@ public class BrowserProcessor extends Processor { public synchronized void stop() { if (!isRunning) return; super.stop(); + if (launcher != null) launcher.shutdownNow(); if (proxy != null) { try { proxy.stop(); @@ -117,12 +127,11 @@ public class BrowserProcessor extends Processor { logger.log(ERROR, "Error stopping proxy server", e); } } - if (webdriver != null) { - try { - webdriver.close(); - } catch (Exception e) { - logger.log(ERROR, "Error closing WebDriverBiDi", e); - } + synchronized (tabsLock) { + tabsLock.notifyAll(); + } + for (Browser browser : pool) { + browser.close(); } } @@ -141,15 +150,65 @@ public class BrowserProcessor extends Processor { @Override public void innerProcess(CrawlURI curi) { try { - semaphore.acquire(); + for (int attempt = 0; ; attempt++) { + Browser browser = acquireTabSlot(curi.getClassKey()); + if (browser == null) return; // stopping + LocalWebDriverBiDi driver = browser.driver; + try { + visit(curi, driver); + return; + } catch (WebDriverException e) { + if (!driver.isAlive()) { + logger.log(WARNING, "Browser died while visiting " + curi + ", restarting it", e); + browser.restart(driver); + if (attempt == 0) continue; // retry once, possibly on another browser + } else { + logger.log(WARNING, "WebDriver exception visiting " + curi, e); + } + return; + } finally { + releaseTabSlot(browser); + } + } } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return; } - try { - visit(curi); - } finally { - semaphore.release(); + } + + /** + * Waits for a browser with a free tab slot, preferring the one the queue key hashes to so that a site + * keeps the same browser's cookies and cache. + * + * @return the browser, or null if the processor is stopping + */ + private Browser acquireTabSlot(String queueKey) throws InterruptedException { + synchronized (tabsLock) { + while (isRunning) { + Browser browser = pool.get(Math.floorMod(Objects.hashCode(queueKey), pool.size())); + if (browser.state == Browser.State.IDLE) browser.wake(); + if (browser.state != Browser.State.WAKING && !browser.hasFreeTabSlot()) { + browser = pool.stream().filter(Browser::hasFreeTabSlot) + .min(Comparator.comparingInt(b -> b.openTabs)).orElse(null); + if (browser == null) { + pool.stream().filter(b -> b.state == Browser.State.IDLE).findFirst().ifPresent(Browser::wake); + } + } + if (browser != null && browser.hasFreeTabSlot()) { + browser.openTabs++; + browser.pagesVisited++; + return browser; + } + tabsLock.wait(); + } + return null; + } + } + + private void releaseTabSlot(Browser browser) { + synchronized (tabsLock) { + browser.openTabs--; + if (browser.openTabs == 0) browser.idleSince = System.nanoTime(); + tabsLock.notifyAll(); } } @@ -170,58 +229,25 @@ public class BrowserProcessor extends Processor { builder.append(super.report()); builder.append(" Pages visited: ").append(getURICount()).append("\n"); builder.append(" Subresources recorded: ").append(subresourcesRecorded.get()).append("\n"); - builder.append(" Browser restarts: ").append(browserRestarts.get()).append("\n"); + synchronized (tabsLock) { + for (Browser browser : pool) { + builder.append(" Browser ").append(browser.id).append(": ") + .append(browser.state.name().toLowerCase()).append(", ") + .append(browser.openTabs).append(" open tabs, ") + .append(browser.pagesVisited).append(" pages visited, ") + .append(browser.restarts).append(" restarts"); + if (browser.lastFailure != null) { + builder.append(", last failure: ").append(browser.lastFailure); + } + builder.append("\n"); + } + } for (var behavior : behaviors) { builder.append(behavior.report()); } return builder.toString(); } - private void visit(CrawlURI curi) { - for (int attempt = 0; ; attempt++) { - LocalWebDriverBiDi driver = webdriver; - try { - visit(curi, driver); - return; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } catch (WebDriverException e) { - if (attempt == 0 && !driver.isAlive()) { - logger.log(WARNING, "Browser died while visiting " + curi + ", restarting it", e); - if (restartBrowser(driver)) continue; // retry once with the new browser - } - logger.log(WARNING, "WebDriver exception visiting " + curi, e); - return; - } - } - } - - /** - * Replaces a dead browser with a freshly launched one. Threads that lose the race to restart - * still return true so they retry against the browser the winner launched. - * - * @return true if a live browser is now available, false if the restart failed or the - * processor is stopping - */ - private synchronized boolean restartBrowser(LocalWebDriverBiDi deadDriver) { - if (!isRunning) return false; - if (webdriver != deadDriver) return true; // another thread already restarted it - try { - deadDriver.close(); - } catch (Exception e) { - logger.log(WARNING, "Error closing dead browser", e); - } - try { - webdriver = createWebDriver(); - browserRestarts.incrementAndGet(); - return true; - } catch (Exception e) { - logger.log(ERROR, "Failed to restart browser", e); - return false; - } - } - private void visit(CrawlURI curi, LocalWebDriverBiDi driver) throws InterruptedException { String pageId = UUID.randomUUID().toString(); var tab = driver.browsingContext().create(BrowsingContext.CreateType.tab).context(); @@ -276,9 +302,18 @@ 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"); + } + } + if (minBrowsers > browsers.size()) { + throw new IllegalArgumentException("minBrowsers is " + minBrowsers + " but only " + browsers.size() + + " browsers are configured"); + } super.start(); - semaphore = new Semaphore(concurrency); extractorChain.setProcessors(crawlController.getFetchChain().getProcessors().stream() .filter(processor -> processor instanceof Extractor).toList()); Path scratchDir = crawlController.getScratchDir().getFile().toPath(); @@ -299,56 +334,26 @@ public class BrowserProcessor extends Processor { logger.log(ERROR, "Error starting proxy server", e); throw new RuntimeException(e); } - try { - this.webdriver = createWebDriver(); - } catch (Exception e) { - logger.log(ERROR, "Error starting browser", e); - throw new RuntimeException(e); + launcher = Executors.newScheduledThreadPool(browsers.size(), new ThreadFactoryBuilder() + .setNameFormat("BrowserProcessor-launcher-%d").setDaemon(true).build()); + pool.clear(); + for (int i = 0; i < browsers.size(); i++) { + pool.add(new Browser(i)); } - } - - private LocalWebDriverBiDi createWebDriver() throws Exception { - Path scratchDir = crawlController.getScratchDir().getFile().toPath(); - Path profileDir = scratchDir.resolve("profile"); - Files.createDirectories(profileDir); - - // 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)); - - List> firstMatch = List.of( - Map.of("browserName", "chrome", - "goog:chromeOptions", Map.of( - "args", List.of("headless=new", "user-data-dir=" + profileDir, - "proxy-bypass-list=<-loopback>"), - "prefs", Map.of("download_restrictions", 3))), - // Fallback for other browsers - Map.of() - ); - var capabilities = new Session.CapabilitiesRequest(alwaysMatch, firstMatch); - - var driver = new LocalWebDriverBiDi(executable, options, capabilities, profileDir); - try { - driver.session().subscribe(List.of("browsingContext.contextCreated", - "network.beforeRequestSent"), null); - driver.on(Network.BeforeRequestSent.class, event -> handleBeforeRequestSent(driver, event)); - } catch (Exception e) { - driver.close(); - throw e; + CompletableFuture.allOf(pool.stream() + .map(browser -> CompletableFuture.runAsync(browser::launch, launcher)) + .toArray(CompletableFuture[]::new)).join(); + long up = pool.stream().filter(browser -> browser.state == Browser.State.UP).count(); + if (up < minBrowsers) { + stop(); + throw new IllegalStateException("Only " + up + " of " + pool.size() + " browsers started but minBrowsers is " + + minBrowsers + ", see the log for the errors"); + } + if (browserIdleTimeoutSeconds > 0) { + long checkSeconds = Math.min(browserIdleTimeoutSeconds, 60); + launcher.scheduleWithFixedDelay(() -> pool.forEach(Browser::closeIfIdle), + checkSeconds, checkSeconds, TimeUnit.SECONDS); } - return driver; } private void handleBeforeRequestSent(LocalWebDriverBiDi driver, Network.BeforeRequestSent event) { @@ -439,12 +444,49 @@ public class BrowserProcessor extends Processor { } /** - * Maximum number of web pages that can be open in the browser at once. + * Maximum number of web pages that can be open in each browser at once. */ public void setConcurrency(int concurrency) { this.concurrency = concurrency; } + public int getMinBrowsers() { + return minBrowsers; + } + + /** + * Minimum number of browsers that must launch for the processor to start. Browsers that fail to launch, or + * crash and fail to relaunch, are retried in the background with an increasing delay. + */ + public void setMinBrowsers(int minBrowsers) { + this.minBrowsers = minBrowsers; + } + + public int getBrowserIdleTimeoutSeconds() { + return browserIdleTimeoutSeconds; + } + + /** + * Closes a browser that has had no open pages for at least this many seconds, and launches it again when a + * page needs it. Zero keeps browsers open until the processor stops. + */ + public void setBrowserIdleTimeoutSeconds(int browserIdleTimeoutSeconds) { + this.browserIdleTimeoutSeconds = browserIdleTimeoutSeconds; + } + + 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. + */ + public void setBrowsers(List browsers) { + this.browsers = browsers; + } + /** * Records the request and response for a subresource the browser loads via the MITM proxy. */ @@ -586,6 +628,172 @@ public class BrowserProcessor extends Processor { } } + /** + * Launches a browser and restarts it if it dies. Tracks how many of its + * {@link #setConcurrency tab slots} are in use. + */ + protected class Browser { + private static final long INITIAL_RETRY_DELAY_SECONDS = 30; + private static final long MAX_RETRY_DELAY_SECONDS = 600; + protected enum State { UP, IDLE, WAKING, DOWN } + protected final int id; + protected volatile LocalWebDriverBiDi driver; + protected volatile State state = State.DOWN; + protected volatile String lastFailure; + protected volatile int restarts; + protected int openTabs; // guarded by tabsLock + protected long pagesVisited; // guarded by tabsLock + private volatile long idleSince; + private long retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; // guarded by this + + Browser(int id) { + this.id = id; + } + + private boolean hasFreeTabSlot() { + return state == State.UP && openTabs < concurrency; + } + + /** + * Launches the browser, or if that fails schedules another attempt after a delay. + */ + void launch() { + LocalWebDriverBiDi newDriver; + try { + newDriver = createWebDriver(); + } catch (Exception e) { + synchronized (this) { + if (!isRunning) return; + state = State.DOWN; + lastFailure = e.toString(); + logger.log(ERROR, "Failed to launch browser " + id + ", retrying in " + retryDelaySeconds + "s", e); + schedule(this::launch, retryDelaySeconds); + retryDelaySeconds = Math.min(retryDelaySeconds * 2, MAX_RETRY_DELAY_SECONDS); + } + synchronized (tabsLock) { + tabsLock.notifyAll(); + } + return; + } + synchronized (this) { + if (!isRunning) { + closeQuietly(newDriver); + return; + } + driver = newDriver; + idleSince = System.nanoTime(); + state = State.UP; + lastFailure = null; + retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; + } + synchronized (tabsLock) { + tabsLock.notifyAll(); + } + } + + /** + * Marks the browser down and launches a replacement, unless another thread already has. + */ + void restart(LocalWebDriverBiDi deadDriver) { + synchronized (this) { + if (driver != deadDriver || state != State.UP) return; + state = State.DOWN; + restarts++; + } + schedule(() -> { + closeQuietly(deadDriver); + launch(); + }, 0); + } + + /** + * Launches the browser again after it was closed for being idle. + */ + synchronized void wake() { + if (state != State.IDLE) return; + state = State.WAKING; + schedule(this::launch, 0); + } + + void closeIfIdle() { + LocalWebDriverBiDi idleDriver; + synchronized (tabsLock) { + synchronized (this) { + if (state != State.UP || openTabs > 0 || System.nanoTime() - idleSince + < TimeUnit.SECONDS.toNanos(browserIdleTimeoutSeconds)) return; + state = State.IDLE; + idleDriver = driver; + } + } + closeQuietly(idleDriver); + } + + synchronized void close() { + state = State.DOWN; + if (driver != null) closeQuietly(driver); + } + + private LocalWebDriverBiDi createWebDriver() throws Exception { + Path scratchDir = crawlController.getScratchDir().getFile().toPath(); + Path profileDir = scratchDir.resolve("profile-" + id); + Files.createDirectories(profileDir); + + // 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)); + + List> firstMatch = List.of( + Map.of("browserName", "chrome", + "goog:chromeOptions", Map.of( + "args", List.of("headless=new", "user-data-dir=" + profileDir, + "proxy-bypass-list=<-loopback>"), + "prefs", Map.of("download_restrictions", 3))), + // Fallback for other browsers + Map.of() + ); + var capabilities = new Session.CapabilitiesRequest(alwaysMatch, firstMatch); + + var driver = new LocalWebDriverBiDi(executable, options, capabilities, profileDir); + try { + driver.session().subscribe(List.of("browsingContext.contextCreated", + "network.beforeRequestSent"), null); + driver.on(Network.BeforeRequestSent.class, event -> handleBeforeRequestSent(driver, event)); + } catch (Exception e) { + driver.close(); + throw e; + } + return driver; + } + } + + private void schedule(Runnable task, long delaySeconds) { + try { + launcher.schedule(task, delaySeconds, TimeUnit.SECONDS); + } catch (RejectedExecutionException e) { + // stopping + } + } + + private static void closeQuietly(LocalWebDriverBiDi driver) { + try { + driver.close(); + } catch (Exception e) { + logger.log(WARNING, "Error closing browser", e); + } + } + /** * A CrawlURI that's currently loaded as a page in a browser. */ diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index 3d3896c2..bbe82591 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -22,8 +22,11 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; import java.util.*; +import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; import static java.lang.System.Logger.Level.DEBUG; @@ -41,7 +44,6 @@ class BrowserProcessorTest { private static String baseUrl; private static volatile int serverRequests; private static ArrayList subrequests; - private static CrawlController crawlController; private final Set recorders = new HashSet<>(); @TempDir static Path tempDir; @@ -104,20 +106,148 @@ class BrowserProcessorTest { @Test public void testBrowserRestart() throws IOException, InterruptedException { - long restartsBefore = browserProcessor.browserRestarts.get(); - browserProcessor.webdriver.close(); // simulate the browser dying + int restartsBefore = browserProcessor.pool.get(0).restarts; + browserProcessor.pool.get(0).driver.close(); // simulate the browser dying CrawlURI crawlURI = newCrawlURI(baseUrl); fetcher.process(crawlURI); assertEquals(200, crawlURI.getFetchStatus()); browserProcessor.innerProcess(crawlURI); - assertEquals(restartsBefore + 1, browserProcessor.browserRestarts.get(), + assertEquals(restartsBefore + 1, browserProcessor.pool.get(0).restarts, "browser should have been restarted"); assertTrue(crawlURI.getAnnotations().contains("browser"), "page should have been visited by the restarted browser"); } + @Test + public void testUnresponsiveBrowserRestart() throws IOException, InterruptedException { + var processor = newBrowserProcessor("unresponsive", List.of("local")); + processor.start(); + try { + ProcessHandle browserProcess = browserProcess("unresponsive", 0); + processor.setBehaviors(List.of(page -> { + if (browserProcess.isAlive()) { + processor.pool.get(0).driver.setCommandTimeout(Duration.ofSeconds(2)); + suspend(browserProcess); + page.eval("() => 1"); + } + })); + + CrawlURI crawlURI = visit(processor, null); + assertTrue(crawlURI.getAnnotations().contains("browser"), + "page should have been visited by the restarted browser"); + assertEquals(1, processor.pool.get(0).restarts); + assertFalse(browserProcess.isAlive(), "suspended browser should have been killed"); + } finally { + processor.stop(); + } + } + + @Test + public void testIdleBrowserIsClosedAndRelaunched() throws Exception { + var processor = newBrowserProcessor("idle", List.of("local")); + processor.setBrowserIdleTimeoutSeconds(1); + processor.start(); + try { + browserProcess("idle", 0).onExit().get(10, TimeUnit.SECONDS); + assertEquals(BrowserProcessor.Browser.State.IDLE, processor.pool.get(0).state); + + CrawlURI crawlURI = visit(processor, null); + assertTrue(crawlURI.getAnnotations().contains("browser"), + "page should have been visited by the relaunched browser"); + assertEquals(0, processor.pool.get(0).restarts); + assertNull(processor.pool.get(0).lastFailure); + } finally { + processor.stop(); + } + } + + private static ProcessHandle browserProcess(String processorName, int browserId) { + String profileDir = tempDir.resolve(processorName + "/profile-" + browserId).toString(); + return ProcessHandle.current().children() + .filter(p -> p.info().commandLine().orElse("").contains(profileDir)) + .findFirst().orElseThrow(); + } + + private static void suspend(ProcessHandle process) { + var command = new ArrayList<>(List.of("kill", "-STOP", String.valueOf(process.pid()))); + process.descendants().forEach(p -> command.add(String.valueOf(p.pid()))); + try { + assertEquals(0, new ProcessBuilder(command).start().waitFor()); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void testSeveralBrowsers() throws IOException, InterruptedException { + var processor = newBrowserProcessor("several", List.of("local", "local")); + processor.setMinBrowsers(2); + processor.start(); + try { + // queue keys "b" and "a" hash to browsers 0 and 1 + visit(processor, "b"); + visit(processor, "a"); + assertEquals(1, processor.pool.get(0).pagesVisited); + assertEquals(1, processor.pool.get(1).pagesVisited); + + processor.pool.get(1).driver.close(); // simulate the browser dying + CrawlURI crawlURI = visit(processor, "a"); + assertTrue(crawlURI.getAnnotations().contains("browser"), + "page should have been visited after the restart"); + awaitUp(processor, 1); + assertEquals(0, processor.pool.get(0).restarts); + assertEquals(1, processor.pool.get(1).restarts); + } finally { + processor.stop(); + } + } + + @Test + public void testStartWithBrowserThatFailsToLaunch() throws IOException, InterruptedException { + preventLaunch("one-fails", 1); + var processor = newBrowserProcessor("one-fails", List.of("local", "local")); + processor.start(); + try { + assertEquals(BrowserProcessor.Browser.State.UP, processor.pool.get(0).state); + assertEquals(BrowserProcessor.Browser.State.DOWN, processor.pool.get(1).state); + String report = processor.report(); + assertTrue(report.contains("Browser 1: down") && report.contains("FileAlreadyExistsException"), report); + + CrawlURI crawlURI = visit(processor, "a"); // hashes to browser 1 + assertTrue(crawlURI.getAnnotations().contains("browser")); + assertEquals(1, processor.pool.get(0).pagesVisited); + } finally { + processor.stop(); + } + } + + @Test + public void testStartFailsIfNoBrowserLaunches() throws IOException { + preventLaunch("none-start", 0); + preventLaunch("none-start", 1); + var processor = newBrowserProcessor("none-start", List.of("local", "local")); + assertThrows(IllegalStateException.class, processor::start); + assertFalse(processor.isRunning()); + } + + private static void awaitUp(BrowserProcessor processor, int browserId) throws InterruptedException { + synchronized (processor.tabsLock) { + while (processor.pool.get(browserId).state != BrowserProcessor.Browser.State.UP) { + processor.tabsLock.wait(); + } + } + } + + /** + * Puts a file where the browser's profile directory should be so launching it fails. + */ + private static void preventLaunch(String processorName, int browserId) throws IOException { + Path scratchDir = Files.createDirectories(tempDir.resolve(processorName)); + Files.createFile(scratchDir.resolve("profile-" + browserId)); + } + @Test public void testDownload() throws IOException, InterruptedException { CrawlURI crawlURI = newCrawlURI(baseUrl + "download.bin"); @@ -199,6 +329,15 @@ class BrowserProcessorTest { assertEquals(requestsBefore, serverRequests, "request should not have been forwarded"); } + private CrawlURI visit(BrowserProcessor processor, String queueKey) throws IOException, InterruptedException { + CrawlURI crawlURI = newCrawlURI(baseUrl); + crawlURI.setClassKey(queueKey); + fetcher.process(crawlURI); + assertEquals(200, crawlURI.getFetchStatus()); + processor.innerProcess(crawlURI); + return crawlURI; + } + private CrawlURI newCrawlURI(String uri) throws URIException { CrawlURI curi = new CrawlURI(UURIFactory.getInstance(uri)); Recorder recorder = new Recorder(tempDir.toFile(), "fetcher"); @@ -310,14 +449,18 @@ class BrowserProcessorTest { fetcher = new FetchHTTP2(new DefaultServerCache(), null); fetcher.setUserAgentProvider(new CrawlMetadata()); fetcher.start(); - crawlController = new CrawlController(); - crawlController.getScratchDir().setPath(tempDir.toString()); + subrequests = new ArrayList<>(); + browserProcessor = newBrowserProcessor("default", List.of("local")); + browserProcessor.start(); + } + + private static BrowserProcessor newBrowserProcessor(String name, List browsers) { + var crawlController = new CrawlController(); + crawlController.getScratchDir().setPath(tempDir.resolve(name).toString()); FetchChain fetchChain = new FetchChain(); fetchChain.setProcessors(List.of()); crawlController.setFetchChain(fetchChain); - subrequests = new ArrayList<>(); - DispositionChain dispositionChain = new DispositionChain(); dispositionChain.setProcessors(List.of(new Processor() { @Override @@ -331,9 +474,10 @@ class BrowserProcessorTest { } })); crawlController.setDispositionChain(dispositionChain); - browserProcessor = new BrowserProcessor(fetcher, crawlController, event -> {}, null); - browserProcessor.setExecutable(System.getProperty("browserExecutable")); - browserProcessor.start(); + var processor = new BrowserProcessor(fetcher, crawlController, event -> {}, null); + processor.setBrowsers(browsers); + processor.setExecutable(System.getProperty("browserExecutable")); + return processor; } @AfterAll