From 2b2ae5251fa499dca9ded660a9762a1a76218412 Mon Sep 17 00:00:00 2001 From: Chad Wilson <29788154+chadlwilson@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:12:44 +0800 Subject: [PATCH] feat: improve API & datafeed downloading to acknowledge and process downloads as they complete Currently all downloads are processed only in the submitted order. There's no reason for this because each are for a separate year. We can acknowledge them and process them as they complete using a CompletionService, rather than using static ordering of Futures. Signed-off-by: Chad Wilson <29788154+chadlwilson@users.noreply.github.com> --- .../data/update/NvdApiDataSource.java | 297 +++++++++--------- .../data/update/nvd/api/DownloadTask.java | 48 +-- .../data/update/nvd/api/NvdApiProcessor.java | 32 +- .../main/resources/dependencycheck.properties | 2 +- .../owasp/dependencycheck/utils/Settings.java | 2 +- 5 files changed, 180 insertions(+), 201 deletions(-) diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java index 4b98b000b3..0a5124bdbb 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java @@ -57,27 +57,27 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; -import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; +import java.util.Collections; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.zip.GZIPOutputStream; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.concurrent.TimeUnit.MINUTES; /** * @@ -92,7 +92,7 @@ public class NvdApiDataSource implements CachedWebDataSource { /** * The thread pool size to use for CPU-intense tasks. */ - private static final int PROCESSING_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors(); + private static final int DEFAULT_PROCESSING_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors(); /** * The configured settings. */ @@ -141,54 +141,59 @@ private boolean processDatafeed(String nvdDataFeedUrl) throws UpdateException { urlData = urlData.withPattern(p -> p.orElse(cacheProperties.getProperty("prefix", FeedUrl.DEFAULT_FILE_PATTERN_PREFIX) + FeedUrl.DEFAULT_FILE_PATTERN_SUFFIX)); final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); - final Map updateable = getUpdatesNeeded(urlData, cacheProperties, now); - if (!updateable.isEmpty()) { - final int max = settings.getInt(Settings.KEYS.MAX_DOWNLOAD_THREAD_POOL_SIZE, 1); - final int downloadPoolSize = Math.min(Runtime.getRuntime().availableProcessors(), max); - // going over 2 threads does not appear to improve performance - final int execPoolSize = Math.min(PROCESSING_THREAD_POOL_SIZE, 2); - - ExecutorService processingExecutorService = null; - ExecutorService downloadExecutorService = null; - final AtomicBoolean cancelled = new AtomicBoolean(false); + final SortedMap updatable = getUpdatesNeeded(urlData, cacheProperties, now); + if (!updatable.isEmpty()) { + final int downloadPoolSize = Math.min( + Runtime.getRuntime().availableProcessors(), + settings.getInt(Settings.KEYS.MAX_DOWNLOAD_THREAD_POOL_SIZE, 2) + ); + // going over 2 threads does not appear to improve performance for the large data feed files + final int processingPoolSize = Math.min(DEFAULT_PROCESSING_THREAD_POOL_SIZE, 2); + + ExecutorService downloadExecutorService = Executors.newFixedThreadPool(downloadPoolSize); + CancellableProcessorCompletions processorCompletions = new CancellableProcessorCompletions(Executors.newFixedThreadPool(processingPoolSize)); try { - downloadExecutorService = Executors.newFixedThreadPool(downloadPoolSize); - processingExecutorService = Executors.newFixedThreadPool(execPoolSize); + CompletionService downloadCompletions = scheduleAllDownloads(updatable, downloadExecutorService); - DownloadTask runLast = null; - final Set>> downloadFutures = new HashSet<>(updateable.size()); - runLast = startDownloads(updateable, processingExecutorService, runLast, downloadFutures, downloadExecutorService, cancelled); + int awaitingProcessing = 0; + Optional processLast = Optional.empty(); - //complete downloads - final Set> processFutures = new HashSet<>(updateable.size()); - for (Future> future : downloadFutures) { - processDownload(future, processFutures); + // Schedule processing as downloads complete, but delay the modified data until last if possible + for (int i = 0; i < updatable.size(); i++) { + NvdApiProcessor toBeProcessed = awaitNextCompletedDownload(downloadCompletions); + + if (toBeProcessed.shouldProcessLast()) { + processLast = Optional.of(toBeProcessed); + } else { + awaitingProcessing++; + processorCompletions.submit(toBeProcessed); + } + } + + // Wait for all processing to complete + for (int i = 0; i < awaitingProcessing; i++) { + awaitNextProcessedDownload(processorCompletions); } - //process the data - processFuture(processFutures); - processFutures.clear(); //download and process the modified as the last entry - if (runLast != null) { - final Future> modified = downloadExecutorService.submit(runLast); - processDownload(modified, processFutures); - processFuture(processFutures); + if (processLast.isPresent()) { + processorCompletions.submit(processLast.get()); + awaitNextProcessedDownload(processorCompletions); } } finally { - cancelled.set(true); - if (downloadExecutorService != null) { - downloadExecutorService.shutdownNow(); - awaitTermination(downloadExecutorService); - } - if (processingExecutorService != null) { - processingExecutorService.shutdown(); - awaitTermination(processingExecutorService); - } + downloadExecutorService.shutdownNow(); + + // Cancel processors safely to avoid interrupting DB writes + processorCompletions.shutdown(); + + // Wait for them to complete, where + awaitTerminations(downloadExecutorService, "NVD datafeed download"); + processorCompletions.awaitTerminations("NVD datafeed processing"); } updatesMade = true; } - storeLastModifiedDates(now, cacheProperties, updateable); + storeLastModifiedDates(now, cacheProperties, updatable); if (updatesMade) { cveDb.persistEcosystemCache(); } @@ -198,15 +203,6 @@ private boolean processDatafeed(String nvdDataFeedUrl) throws UpdateException { cveDb.cleanupDatabase(); } } - } catch (UpdateException ex) { - if (ex.getCause() != null && ex.getCause() instanceof DownloadFailedException) { - final String jre = System.getProperty("java.version"); - if (jre == null || jre.startsWith("1.4") || jre.startsWith("1.5") || jre.startsWith("1.6") || jre.startsWith("1.7")) { - LOGGER.error("An old JRE is being used ({} {}), and likely does not have the correct root certificates or algorithms " - + "to connect to the NVD - consider upgrading your JRE.", System.getProperty("java.vendor"), jre); - } - } - throw ex; } catch (DatabaseException ex) { throw new UpdateException("Database Exception, unable to update the data to use the most current data.", ex); } @@ -214,7 +210,7 @@ private boolean processDatafeed(String nvdDataFeedUrl) throws UpdateException { } private void storeLastModifiedDates(final ZonedDateTime now, final Properties cacheProperties, - final Map updateable) throws UpdateException { + final Map updatable) { final ZonedDateTime lastModifiedRequest = DatabaseProperties.getTimestamp(cacheProperties, NVD_API_CACHE_MODIFIED_DATE + ".modified"); @@ -224,53 +220,24 @@ private void storeLastModifiedDates(final ZonedDateTime now, final Properties ca dbProperties.save(DatabaseProperties.NVD_API_LAST_CHECKED, now); dbProperties.save(DatabaseProperties.NVD_API_LAST_MODIFIED, lastModifiedRequest); - for (String entry : updateable.keySet()) { + for (String entry : updatable.keySet()) { final ZonedDateTime date = DatabaseProperties.getTimestamp(cacheProperties, NVD_API_CACHE_MODIFIED_DATE + "." + entry); dbProperties.save(DatabaseProperties.NVD_CACHE_LAST_MODIFIED + "." + entry, date); } } - private DownloadTask startDownloads(final Map updateable, ExecutorService processingExecutorService, DownloadTask runLast, - final Set>> downloadFutures, ExecutorService downloadExecutorService, - AtomicBoolean cancelled) throws UpdateException { - DownloadTask lastCall = runLast; - for (Map.Entry cve : updateable.entrySet()) { - final DownloadTask call = new DownloadTask(cve.getValue(), processingExecutorService, cveDb, settings, cancelled); - if (call.isModified()) { - lastCall = call; - } else { - final boolean added = downloadFutures.add(downloadExecutorService.submit(call)); - if (!added) { - throw new UpdateException("Unable to add the download task for " + cve); - } - } - } - return lastCall; - } - - private void processFuture(final Set> processFutures) throws UpdateException { - //complete processing - for (Future future : processFutures) { - try { - final NvdApiProcessor task = future.get(); - } catch (InterruptedException ex) { - LOGGER.debug("Thread was interrupted during processing", ex); - Thread.currentThread().interrupt(); - throw new UpdateException(ex); - } catch (ExecutionException ex) { - LOGGER.debug("Execution Exception during process", ex); - throw new UpdateException(ex); - } + private CompletionService scheduleAllDownloads(final SortedMap updatable, ExecutorService downloadExecutorService) { + final CompletionService downloadCompletions = new ExecutorCompletionService<>(downloadExecutorService); + for (Map.Entry cve : updatable.entrySet()) { + final DownloadTask call = new DownloadTask(cve.getValue(), cveDb, settings); + downloadCompletions.submit(call); } + return downloadCompletions; } - private void processDownload(Future> future, final Set> processFutures) throws UpdateException { - final Future task; + private NvdApiProcessor awaitNextCompletedDownload(CompletionService downloadCompletions) throws UpdateException { try { - task = future.get(); - if (task != null) { - processFutures.add(task); - } + return downloadCompletions.take().get(); } catch (InterruptedException ex) { LOGGER.debug("Thread was interrupted during download", ex); Thread.currentThread().interrupt(); @@ -281,6 +248,19 @@ private void processDownload(Future> future, final Set> submitted = new ArrayList<>(); - int max = -1; - int ctr = 0; + int totalBatches = 0; try (NvdCveClient api = builder.build()) { + int resultsAvailable = 0; while (api.hasNext()) { final Collection items = api.next(); - max = api.getTotalAvailable(); - if (ctr == 0) { - LOGGER.info(String.format("NVD API has %,d records in this update", max)); + resultsAvailable = api.getTotalAvailable(); + if (totalBatches == 0) { + LOGGER.info(String.format("NVD API has %,d records in this update", resultsAvailable)); } if (items != null && !items.isEmpty()) { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); final File outputFile = settings.getTempFile("nvd-data-", ".jsonarray.gz"); - try (FileOutputStream fos = new FileOutputStream(outputFile); GZIPOutputStream out = new GZIPOutputStream(fos);) { + try (FileOutputStream fos = new FileOutputStream(outputFile); GZIPOutputStream out = new GZIPOutputStream(fos)) { objectMapper.writeValue(out, items); - final Future f = processingExecutorService.submit( - new NvdApiProcessor(cveDb, outputFile, System.currentTimeMillis(), cancelled)); - submitted.add(f); + processorCompletions.submit(new NvdApiProcessor(cveDb, outputFile)); } - ctr += 1; - if ((ctr % 5) == 0) { + totalBatches += 1; + if ((totalBatches % 5) == 0) { //TODO get results per page from the API as it could adjust automatically - final double percent = (double) (ctr * resultsPerPage) / max * 100; + final double percent = (double) (totalBatches * resultsPerPage) / resultsAvailable * 100; if (percent < 100) { - LOGGER.info(String.format("Downloaded %,d/%,d (%.0f%%)", ctr * resultsPerPage, max, percent)); + LOGGER.info(String.format("Downloaded %,d/%,d (%.0f%%)", totalBatches * resultsPerPage, resultsAvailable, percent)); } } } @@ -378,10 +353,10 @@ private boolean processApi() throws UpdateException { lastModifiedRequest = last; } } + LOGGER.info(String.format("Downloaded %,d/%,d (%.0f%%)", resultsAvailable, resultsAvailable, 100f)); } catch (Exception e) { - if (e instanceof NvdApiException && (e.getMessage().equals("NVD Returned Status Code: 404") - || e.getMessage().equals("NVD Returned Status Code: 403"))) { + if (e instanceof NvdApiException && e.getMessage().matches("NVD Returned Status Code: 40[34].*")) { final String msg; if (key != null) { msg = "Error updating the NVD Data; the NVD returned a 403 or 404 error\n\nPlease ensure your API Key is valid; " @@ -392,21 +367,17 @@ private boolean processApi() throws UpdateException { msg = "Error updating the NVD Data; the NVD returned a 403 or 404 error\n\nConsider using an NVD API Key; " + "see https://github.com/dependency-check/DependencyCheck?tab=readme-ov-file#nvd-api-key-highly-recommended"; } - throw new UpdateException(msg); + throw new UpdateException(msg, e); } else { throw new UpdateException("Error updating the NVD Data", e); } } - LOGGER.info(String.format("Downloaded %,d/%,d (%.0f%%)", max, max, 100f)); - max = submitted.size(); - final boolean updated = max > 0; - ctr = 0; - for (Future f : submitted) { + + for (int processingBatch = 1; processingBatch <= totalBatches; processingBatch++) { try { - final NvdApiProcessor proc = f.get(); - ctr += 1; - final double percent = (double) ctr / max * 100; - LOGGER.info(String.format("Completed processing batch %d/%d (%.0f%%) in %,dms", ctr, max, percent, proc.getDurationMillis())); + final NvdApiProcessor proc = processorCompletions.take(); + final double percent = (double) processingBatch / totalBatches * 100; + LOGGER.info(String.format("Completed processing batch %d/%d (%.0f%%) in %,dms", processingBatch, totalBatches, percent, proc.getDurationMillis())); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); @@ -419,35 +390,19 @@ private boolean processApi() throws UpdateException { dbProperties.save(DatabaseProperties.NVD_API_LAST_CHECKED, ZonedDateTime.now()); dbProperties.save(DatabaseProperties.NVD_API_LAST_MODIFIED, lastModifiedRequest); } - return updated; + return totalBatches > 0; } finally { - cancelled.set(true); - if (processingExecutorService != null) { - processingExecutorService.shutdown(); - awaitTermination(processingExecutorService); - } + processorCompletions.shutdown(); + processorCompletions.awaitTerminations("NVD API processing"); } } - /** - * Waits for a shut down executor to terminate. Processors are not - * interrupted, as interrupting H2 file I/O closes the database file; they - * stop after the CVE they are writing once the update is cancelled. This - * does not return early if the caller is interrupted, since the database - * may be closed straight afterwards. - * - * @param service the executor to wait for - */ - private static void awaitTermination(ExecutorService service) { - boolean interrupted = false; - while (!service.isTerminated()) { - try { - service.awaitTermination(1, TimeUnit.MINUTES); - } catch (InterruptedException ex) { - interrupted = true; + private static void awaitTerminations(ExecutorService executorService, String taskDescription) { + try { + if (!executorService.awaitTermination(1, MINUTES)) { + LOGGER.warn("Interrupted {} tasks did not complete safely within 1 minute; shutdown may be unsafe.", taskDescription); } - } - if (interrupted) { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @@ -511,10 +466,8 @@ public boolean purge(Engine engine) { * optimization, we can avoid repetitive checks against the NVD cache. * * @return true to proceed with the check, or false to skip - * @throws UpdateException thrown when there is an issue checking for - * updates */ - private boolean checkUpdate() throws UpdateException { + private boolean checkUpdate() { boolean proceed = true; // If the valid setting has not been specified, then we proceed to check... final int validForHours = settings.getInt(Settings.KEYS.NVD_API_VALID_FOR_HOURS, 0); @@ -550,7 +503,7 @@ private boolean dataExists() { /** * Determines if the index needs to be updated. This is done by fetching the - * NVD CVE meta data and checking the last update date. If the data needs to + * NVD CVE metadata and checking the last update date. If the data needs to * be refreshed this method will return the NvdCveUrl for the files that * need to be updated. * @@ -558,12 +511,10 @@ private boolean dataExists() { * @param cacheProperties the properties from the remote NVD API cache or data feed * @param now the start time of the update process * @return the map of key to URLs - where the key is the year or `modified` - * @throws UpdateException Is thrown if there is an issue with the last - * updated properties file */ - protected final Map getUpdatesNeeded(FeedUrl feedUrl, Properties cacheProperties, ZonedDateTime now) throws UpdateException { + protected final SortedMap getUpdatesNeeded(FeedUrl feedUrl, Properties cacheProperties, ZonedDateTime now) { LOGGER.debug("starting getUpdatesNeeded() ..."); - final Map updates = new HashMap<>(); + final SortedMap updates = new TreeMap<>(); if (dbProperties != null && !dbProperties.isEmpty()) { Pair yearRange = FeedUrl.toYearRange(settings, now); int startYear = yearRange.getLeft(); @@ -797,4 +748,40 @@ private static boolean isAfterJanuary1InEveryTZ(ZonedDateTime now, int targetYea return now.isAfter(LocalDate.of(targetYear, 1, 2).atStartOfDay().atZone(ZONE_GLOBAL_LATEST)); } } + + private static class CancellableProcessorCompletions { + private final Set tasks = Collections.newSetFromMap(new IdentityHashMap<>()); + private final ExecutorService executorService; + private final CompletionService completions; + + public CancellableProcessorCompletions(ExecutorService executorService) { + this.executorService = executorService; + this.completions = new ExecutorCompletionService<>(this.executorService); + } + + public void submit(@NonNull NvdApiProcessor task) { + tasks.add(task); + completions.submit(task); + } + + public NvdApiProcessor take() throws InterruptedException, ExecutionException { + NvdApiProcessor result = completions.take().get(); + tasks.remove(result); + return result; + } + + /** + * Shuts down NvdApiProcessor tasks safely without thread interruption; to avoid causing accidental + * premature database closure. + */ + public void shutdown() { + tasks.forEach(NvdApiProcessor::cancel); + tasks.clear(); + executorService.shutdown(); + } + + public void awaitTerminations(String taskDescription) { + NvdApiDataSource.awaitTerminations(executorService, taskDescription); + } + } } diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/DownloadTask.java b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/DownloadTask.java index d8e7773ec7..69747427b7 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/DownloadTask.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/DownloadTask.java @@ -17,13 +17,6 @@ */ package org.owasp.dependencycheck.data.update.nvd.api; -import java.io.File; -import java.net.URL; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; -import javax.annotation.concurrent.ThreadSafe; import org.apache.commons.lang3.StringUtils; import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.utils.Downloader; @@ -31,6 +24,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.concurrent.ThreadSafe; +import java.io.File; +import java.net.URL; +import java.util.concurrent.Callable; + /** * A callable object to download the NVD API cache files and start the * NvdApiProcessor. @@ -38,7 +36,7 @@ * @author Jeremy Long */ @ThreadSafe -public class DownloadTask implements Callable> { +public class DownloadTask implements Callable { /** * The Logger. @@ -48,10 +46,6 @@ public class DownloadTask implements Callable> { * The CVE DB to use when processing the files. */ private final CveDB cveDB; - /** - * The processor service to pass the results of the download to. - */ - private final ExecutorService processorService; /** * The NVD API Cache file URL. */ @@ -60,33 +54,24 @@ public class DownloadTask implements Callable> { * A reference to the global settings object. */ private final Settings settings; - /** - * Set when the update has been stopped and the download should not be processed. - */ - private final AtomicBoolean cancelled; /** * Simple constructor for the callable download task. * - * @param url the file to download - * @param processor the processor service to submit the downloaded files to - * @param cveDB the CVE DB to use to store the vulnerability data + * @param url the file to download + * @param cveDB the CVE DB to use to store the vulnerability data * @param settings a reference to the global settings object; this is - * necessary so that when the thread is started the dependencies have a - * correct reference to the global settings. - * @param cancelled set to true to skip processing the download + * necessary so that when the thread is started the dependencies have a + * correct reference to the global settings. */ - public DownloadTask(String url, ExecutorService processor, CveDB cveDB, Settings settings, AtomicBoolean cancelled) { + public DownloadTask(String url, CveDB cveDB, Settings settings) { this.url = url; - this.processorService = processor; this.cveDB = cveDB; this.settings = settings; - this.cancelled = cancelled; } - @SuppressWarnings("BusyWait") @Override - public Future call() throws Exception { + public NvdApiProcessor call() throws Exception { try { final URL u = new URL(url); LOGGER.info("Download Started for NVD Cache - {}", url); @@ -94,12 +79,7 @@ public Future call() throws Exception { final File outputFile = settings.getTempFile("nvd-datafeed-", "json.gz"); Downloader.getInstance().fetchFile(u, outputFile, true, Settings.KEYS.NVD_API_DATAFEED_USER, Settings.KEYS.NVD_API_DATAFEED_PASSWORD, Settings.KEYS.NVD_API_DATAFEED_BEARER_TOKEN); - if (this.processorService == null || cancelled.get()) { - return null; - } - final NvdApiProcessor task = new NvdApiProcessor(cveDB, outputFile, startDownload, cancelled); - final Future val = this.processorService.submit(task); - return val; + return new NvdApiProcessor(cveDB, outputFile, startDownload, isModified()); } catch (Throwable ex) { LOGGER.error("Error downloading NVD CVE - {} Reason: {}", url, ex.getMessage()); throw ex; @@ -115,7 +95,7 @@ public Future call() throws Exception { * @return true if the process task is for the modified data; * otherwise false */ - public boolean isModified() { + private boolean isModified() { return StringUtils.containsIgnoreCase(url, "modified"); } } diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java index 62cb5953eb..5af62ef3bd 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java @@ -18,6 +18,10 @@ package org.owasp.dependencycheck.data.update.nvd.api; import io.github.jeremylong.openvulnerability.client.nvd.DefCveItem; +import org.owasp.dependencycheck.data.nvd.ecosystem.CveEcosystemMapper; +import org.owasp.dependencycheck.data.nvdcve.CveDB; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.BufferedInputStream; import java.io.File; @@ -28,11 +32,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPInputStream; -import org.owasp.dependencycheck.data.nvd.ecosystem.CveEcosystemMapper; -import org.owasp.dependencycheck.data.nvdcve.CveDB; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Stores a collection of NVD CVE Data from the NVD API into the database. * @@ -67,7 +66,12 @@ public class NvdApiProcessor implements Callable { /** * Set when the update has been stopped and no more CVEs should be written. */ - private final AtomicBoolean cancelled; + private final AtomicBoolean cancelled = new AtomicBoolean(false); + + /** + * whether executing this processor should be delayed until the end, where possible. + */ + private final boolean processLast; /** * Create a new processor to put the NVD data into the database. @@ -75,13 +79,13 @@ public class NvdApiProcessor implements Callable { * @param cveDB a reference to the database. * @param jsonFile the JSON data file to inject. * @param startTime the start time of the update process. - * @param cancelled set to true to stop before the next CVE is written. + * @param processLast whether executing this processor should be delayed until the end, where possible. */ - public NvdApiProcessor(final CveDB cveDB, File jsonFile, long startTime, AtomicBoolean cancelled) { + public NvdApiProcessor(final CveDB cveDB, File jsonFile, long startTime, boolean processLast) { this.cveDB = cveDB; this.jsonFile = jsonFile; this.startTime = startTime; - this.cancelled = cancelled; + this.processLast = processLast; } /** @@ -91,7 +95,7 @@ public NvdApiProcessor(final CveDB cveDB, File jsonFile, long startTime, AtomicB * @param jsonFile the JSON data file to inject. */ public NvdApiProcessor(final CveDB cveDB, File jsonFile) { - this(cveDB, jsonFile, System.currentTimeMillis(), new AtomicBoolean(false)); + this(cveDB, jsonFile, System.currentTimeMillis(), false); } @Override @@ -138,4 +142,12 @@ private void updateCveDb(CveItemSource itemSource) throws IOExceptio public long getDurationMillis() { return endTime - startTime; } + + public void cancel() { + cancelled.set(true); + } + + public boolean shouldProcessLast() { + return processLast; + } } diff --git a/core/src/main/resources/dependencycheck.properties b/core/src/main/resources/dependencycheck.properties index 081a8fcdbc..3bb62f0e77 100644 --- a/core/src/main/resources/dependencycheck.properties +++ b/core/src/main/resources/dependencycheck.properties @@ -66,7 +66,7 @@ nvd.api.requestsperthirtysecondswithapikey=50 #nvd.api.datafeed.password= cve.cpe.startswith.filter=cpe:2.3:a: -max.download.threads=1 +max.download.threads=2 #Known Exploited Vulnerabilities kev.url=https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json diff --git a/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java b/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java index 29e85101cf..68f31a806a 100644 --- a/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java +++ b/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java @@ -291,7 +291,7 @@ public static final class KEYS { */ public static final String TEMP_DIRECTORY = "temp.directory"; /** - * The maximum number of threads to allocate when downloading files. + * The maximum number of threads to allocate when downloading NVD datafeed files. */ public static final String MAX_DOWNLOAD_THREAD_POOL_SIZE = "max.download.threads"; /**