-
Notifications
You must be signed in to change notification settings - Fork 292
#2134 fetcher.thread.timeout: cancel the okhttp call, bounded helper pool for other protocols #2135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
GGraziadei
wants to merge
2
commits into
apache:main
Choose a base branch
from
GGraziadei:perf/fetch-timeout-call-cancel
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
204 changes: 204 additions & 0 deletions
204
core/src/main/java/org/apache/stormcrawler/bolt/FetchTimeoutHelpers.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF 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.apache.stormcrawler.bolt; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.concurrent.Callable; | ||
| import java.util.concurrent.CancellationException; | ||
| import java.util.concurrent.ExecutionException; | ||
| import java.util.concurrent.Future; | ||
| import java.util.concurrent.LinkedBlockingQueue; | ||
| import java.util.concurrent.RejectedExecutionException; | ||
| import java.util.concurrent.Semaphore; | ||
| import java.util.concurrent.ThreadPoolExecutor; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.TimeoutException; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
| import org.apache.storm.task.TopologyContext; | ||
| import org.apache.stormcrawler.Constants; | ||
| import org.apache.stormcrawler.Metadata; | ||
| import org.apache.stormcrawler.metrics.CrawlerMetrics; | ||
| import org.apache.stormcrawler.protocol.FetchTimeout; | ||
| import org.apache.stormcrawler.protocol.FetchTimeoutException; | ||
| import org.apache.stormcrawler.protocol.Protocol; | ||
| import org.apache.stormcrawler.util.ConfUtils; | ||
|
|
||
| /** | ||
| * Enforces {@code fetcher.thread.timeout} on protocol calls (robots.txt lookup and fetch) for the | ||
| * fetcher bolts. | ||
| * | ||
| * <p>When the timeout is off, or the protocol enforces it itself for the URL (see {@link | ||
| * Protocol#supportsFetchTimeout(String, Metadata)}, true for the default okhttp protocol), the call | ||
| * runs on the calling thread. Otherwise it runs on a helper thread and is abandoned there when the | ||
| * deadline passes: the helper stays busy until the protocol gives up on its own, so the pool is | ||
| * bounded ({@code fetcher.thread.timeout.helpers}) and a call that finds every helper busy fails at | ||
| * once with {@link SaturatedException}. Helper threads are created on demand and released after a | ||
| * minute of inactivity: with the default protocol none is ever created. | ||
| * | ||
| * <p>The bound is a {@link Semaphore} of in-flight calls in front of a queueing executor, not the | ||
| * executor's own rejection: a worker hands its result back before it is back polling for work, so a | ||
| * pool with a {@code SynchronousQueue} would reject the page fetch submitted right after the | ||
| * robots.txt lookup whenever it is at its maximum. A permit is released when the call completes on | ||
| * the helper, whether the caller is still waiting for it or has given up. | ||
| * | ||
| * <p>The deadline is the one of {@link FetchTimeout#secs(Map)}, clamped to the message timeout on | ||
| * both paths. | ||
| */ | ||
| final class FetchTimeoutHelpers { | ||
|
|
||
| /** Thrown when no helper thread is available to run a call with a timeout. */ | ||
| static final class SaturatedException extends Exception { | ||
| SaturatedException(String url) { | ||
| super("No fetch helper available for " + url); | ||
| } | ||
| } | ||
|
|
||
| private final long timeoutSecs; | ||
| private final ThreadPoolExecutor helpers; | ||
|
|
||
| /** One permit per helper: a call runs only if it gets one, and holds it until it completes. */ | ||
| private final Semaphore permits; | ||
|
|
||
| /** | ||
| * @param conf the bolt configuration | ||
| * @param defaultMaxHelpers pool bound used unless {@code fetcher.thread.timeout.helpers} is set | ||
| * @param threadNamePrefix prefix of the helper thread names | ||
| */ | ||
| FetchTimeoutHelpers(Map<String, Object> conf, int defaultMaxHelpers, String threadNamePrefix) { | ||
| this.timeoutSecs = FetchTimeout.secs(conf); | ||
| final int maxHelpers = | ||
| ConfUtils.getInt( | ||
| conf, Constants.FETCH_TIMEOUT_HELPERS_PARAM_KEY, defaultMaxHelpers); | ||
| final AtomicInteger helperNum = new AtomicInteger(); | ||
| final int bound = Math.max(1, maxHelpers); | ||
| this.permits = new Semaphore(bound); | ||
| // core == max so a thread is started for every call while fewer than the bound exist; | ||
| // the queue only ever holds a call whose helper is between two tasks | ||
| this.helpers = | ||
| new ThreadPoolExecutor( | ||
| bound, | ||
| bound, | ||
| 60L, | ||
| TimeUnit.SECONDS, | ||
| new LinkedBlockingQueue<>(), | ||
| r -> { | ||
| Thread t = | ||
| new Thread(r, threadNamePrefix + helperNum.incrementAndGet()); | ||
| t.setDaemon(true); | ||
| return t; | ||
| }); | ||
| this.helpers.allowCoreThreadTimeOut(true); | ||
| } | ||
|
|
||
| /** Registers the {@code fetchhelpers} gauge: number of helpers busy with a call. */ | ||
| void registerMetrics(TopologyContext context, Map<String, Object> conf, int bucketSecs) { | ||
| CrawlerMetrics.registerGauge(context, conf, "fetchhelpers", this::busy, bucketSecs); | ||
| } | ||
|
|
||
| /** Number of calls in flight on the helpers, abandoned ones included. */ | ||
| int busy() { | ||
| return helpers.getMaximumPoolSize() - permits.availablePermits(); | ||
| } | ||
|
|
||
| /** Whether a timeout is configured at all. */ | ||
| boolean enabled() { | ||
| return timeoutSecs > 0; | ||
| } | ||
|
|
||
| /** Timeout in seconds, -1 when disabled. */ | ||
| long timeoutSecs() { | ||
| return timeoutSecs; | ||
| } | ||
|
|
||
| /** Pool bound. */ | ||
| int maxHelpers() { | ||
| return helpers.getMaximumPoolSize(); | ||
| } | ||
|
|
||
| /** Largest number of helper threads ever alive. */ | ||
| int largestPoolSize() { | ||
| return helpers.getLargestPoolSize(); | ||
| } | ||
|
|
||
| /** | ||
| * Runs a protocol call under the timeout. | ||
| * | ||
| * @param call the robots.txt lookup or the fetch | ||
| * @param protocol the protocol the call goes to | ||
| * @param url the URL being fetched, or whose robots.txt is looked up | ||
| * @param metadata the metadata of that URL, possibly null | ||
| * @throws SaturatedException when every helper is busy | ||
| * @throws FetchTimeoutException when the deadline passed | ||
| * @throws Exception the protocol's own exception | ||
| */ | ||
| <T> T call(Callable<T> call, Protocol protocol, String url, Metadata metadata) | ||
| throws Exception { | ||
| if (timeoutSecs <= 0 || protocol.supportsFetchTimeout(url, metadata)) { | ||
| return call.call(); | ||
| } | ||
| if (!permits.tryAcquire()) { | ||
| throw new SaturatedException(url); | ||
| } | ||
| // the permit is given back by whoever knows the call is over: the helper once the call | ||
| // has run, or the caller if it cancelled the call before the helper ever started it | ||
| final AtomicBoolean started = new AtomicBoolean(false); | ||
| final Future<T> future; | ||
| try { | ||
| future = | ||
| helpers.submit( | ||
| () -> { | ||
| started.set(true); | ||
| try { | ||
| return call.call(); | ||
| } finally { | ||
| permits.release(); | ||
| } | ||
| }); | ||
| } catch (RejectedExecutionException e) { | ||
| // shut down | ||
| permits.release(); | ||
| throw new SaturatedException(url); | ||
| } | ||
| try { | ||
| return future.get(timeoutSecs, TimeUnit.SECONDS); | ||
| } catch (TimeoutException e) { | ||
| // a courtesy for protocols which do honour interruption | ||
| future.cancel(true); | ||
| // once cancelled the task can no longer start: if it had not, nobody else will | ||
| // release the permit | ||
| if (!started.get()) { | ||
| permits.release(); | ||
| } | ||
| throw new FetchTimeoutException(url, timeoutSecs); | ||
| } catch (CancellationException e) { | ||
| throw new Exception("Fetch cancelled for " + url); | ||
| } catch (ExecutionException e) { | ||
| // unwrap the real cause so the bolts' classification sees it | ||
| Throwable cause = e.getCause(); | ||
| if (cause instanceof Exception) { | ||
| throw (Exception) cause; | ||
| } | ||
| throw new Exception(cause); | ||
| } | ||
| } | ||
|
|
||
| void shutdown() { | ||
| helpers.shutdownNow(); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FetcherBolt.FETCH_TIMEOUT_PARAM_KEYshipped in 3.6.0 and 3.7.0, so code that used it stops compiling. Keep a deprecated alias, or note it for 4.0?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Kept
FetcherBolt.FETCH_TIMEOUT_PARAM_KEYas a deprecated alias ofConstants.FETCH_TIMEOUT_PARAM_KEY, marked for removal, so existing code keeps compiling.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Grazie Gianluca, the alias does it. Only since should read 4.0, 3.8 will not exist. Necessary since this is a public API
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks Davide. I am fixing it :-) ;