Files
Athou_commafeed/src/main/java/com/commafeed/backend/feeds/FeedRefreshTaskGiver.java

237 lines
6.7 KiB
Java
Raw Normal View History

package com.commafeed.backend.feeds;
import java.util.Date;
import java.util.List;
2013-05-28 12:55:47 +02:00
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
2013-08-11 11:45:32 +02:00
import lombok.extern.slf4j.Slf4j;
2013-07-02 14:33:53 +02:00
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.time.DateUtils;
2013-12-10 14:02:06 +01:00
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.commafeed.backend.dao.FeedDAO;
import com.commafeed.backend.model.Feed;
import com.commafeed.backend.services.ApplicationSettingsService;
2013-07-05 08:23:18 +02:00
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
2013-04-16 12:36:36 +02:00
import com.google.common.collect.Queues;
2013-07-26 16:00:02 +02:00
/**
* Infinite loop fetching feeds from the database and queuing them to the {@link FeedRefreshWorker} pool. Also handles feed database updates
* at the end of the cycle through {@link #giveBack(Feed)}.
*
*/
@ApplicationScoped
2013-08-11 11:45:32 +02:00
@Slf4j
public class FeedRefreshTaskGiver {
@Inject
FeedDAO feedDAO;
@Inject
ApplicationSettingsService applicationSettingsService;
2013-04-16 13:52:20 +02:00
@Inject
MetricRegistry metrics;
2013-04-16 13:52:20 +02:00
@Inject
FeedRefreshWorker worker;
private int backgroundThreads;
2013-05-21 16:40:37 +02:00
private Queue<FeedRefreshContext> addQueue = Queues.newConcurrentLinkedQueue();
private Queue<FeedRefreshContext> takeQueue = Queues.newConcurrentLinkedQueue();
2013-05-22 00:07:13 +02:00
private Queue<Feed> giveBackQueue = Queues.newConcurrentLinkedQueue();
2013-04-16 12:36:36 +02:00
private ExecutorService executor;
private Meter feedRefreshed;
private Meter threadWaited;
2013-08-18 17:19:01 +02:00
private Meter refill;
@PostConstruct
public void init() {
2013-07-25 09:17:33 +02:00
backgroundThreads = applicationSettingsService.get().getBackgroundThreads();
executor = Executors.newFixedThreadPool(1);
feedRefreshed = metrics.meter(MetricRegistry.name(getClass(), "feedRefreshed"));
threadWaited = metrics.meter(MetricRegistry.name(getClass(), "threadWaited"));
2013-08-18 17:19:01 +02:00
refill = metrics.meter(MetricRegistry.name(getClass(), "refill"));
2013-12-10 14:02:06 +01:00
metrics.register(MetricRegistry.name(getClass(), "addQueue"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return addQueue.size();
}
});
metrics.register(MetricRegistry.name(getClass(), "takeQueue"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return takeQueue.size();
}
});
metrics.register(MetricRegistry.name(getClass(), "giveBackQueue"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return giveBackQueue.size();
}
});
}
@PreDestroy
public void shutdown() {
executor.shutdownNow();
while (!executor.isTerminated()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
log.error("interrupted while waiting for threads to finish.");
}
}
}
public void start() {
try {
// sleeping for a little while, let everything settle
Thread.sleep(5000);
} catch (InterruptedException e) {
log.error("interrupted while sleeping");
}
log.info("starting feed refresh task giver");
executor.execute(new Runnable() {
@Override
public void run() {
while (!executor.isShutdown()) {
try {
FeedRefreshContext context = take();
if (context != null) {
feedRefreshed.mark();
worker.updateFeed(context);
} else {
log.debug("nothing to do, sleeping for 15s");
threadWaited.mark();
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
log.error("interrupted while sleeping");
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
});
}
2013-07-29 09:45:31 +02:00
/**
* take a feed from the refresh queue
*/
private FeedRefreshContext take() {
FeedRefreshContext context = takeQueue.poll();
2013-05-28 12:55:47 +02:00
if (context == null) {
2013-05-30 13:18:26 +02:00
refill();
context = takeQueue.poll();
2013-05-30 13:18:26 +02:00
}
return context;
}
public Long getUpdatableCount() {
return feedDAO.getUpdatableCount(getLastLoginThreshold());
}
2013-05-21 16:40:37 +02:00
2013-07-29 09:45:31 +02:00
/**
* add a feed to the refresh queue
*/
public void add(Feed feed, boolean urgent) {
2013-07-29 10:33:18 +02:00
int refreshInterval = applicationSettingsService.get().getRefreshIntervalMinutes();
if (feed.getLastUpdated() == null || feed.getLastUpdated().before(DateUtils.addMinutes(new Date(), -1 * refreshInterval))) {
addQueue.add(new FeedRefreshContext(feed, urgent));
2013-05-30 13:18:26 +02:00
}
}
2013-05-21 16:40:37 +02:00
2013-07-29 09:45:31 +02:00
/**
* refills the refresh queue and empties the giveBack queue while at it
*/
2013-05-30 13:18:26 +02:00
private void refill() {
2013-08-18 17:19:01 +02:00
refill.mark();
2013-07-29 09:45:31 +02:00
List<FeedRefreshContext> contexts = Lists.newArrayList();
int batchSize = Math.min(100, 3 * backgroundThreads);
// add feeds we got from the add() method
int addQueueSize = addQueue.size();
for (int i = 0; i < Math.min(batchSize, addQueueSize); i++) {
contexts.add(addQueue.poll());
2013-07-05 08:23:18 +02:00
}
2013-05-22 00:07:13 +02:00
// add feeds that are up to refresh from the database
if (!applicationSettingsService.get().isCrawlingPaused()) {
int count = batchSize - contexts.size();
if (count > 0) {
List<Feed> feeds = feedDAO.findNextUpdatable(count, getLastLoginThreshold());
for (Feed feed : feeds) {
contexts.add(new FeedRefreshContext(feed, false));
}
}
2013-05-30 13:18:26 +02:00
}
2013-05-22 10:39:03 +02:00
2013-07-29 09:45:31 +02:00
// set the disabledDate to now as we use the disabledDate in feedDAO to decide what to refresh next. We also use a map to remove
// duplicates.
Map<Long, FeedRefreshContext> map = Maps.newLinkedHashMap();
for (FeedRefreshContext context : contexts) {
Feed feed = context.getFeed();
feed.setDisabledUntil(new Date());
map.put(feed.getId(), context);
}
2013-07-29 09:45:31 +02:00
// refill the queue
2013-05-30 13:18:26 +02:00
takeQueue.addAll(map.values());
2013-07-29 09:45:31 +02:00
// add feeds from the giveBack queue to the map, overriding duplicates
int giveBackQueueSize = giveBackQueue.size();
for (int i = 0; i < giveBackQueueSize; i++) {
Feed feed = giveBackQueue.poll();
map.put(feed.getId(), new FeedRefreshContext(feed, false));
}
2013-05-30 13:18:26 +02:00
2013-07-29 09:45:31 +02:00
// update all feeds in the database
List<Feed> feeds = Lists.newArrayList();
for (FeedRefreshContext context : map.values()) {
feeds.add(context.getFeed());
}
feedDAO.saveOrUpdate(feeds);
}
2013-04-16 09:29:33 +02:00
2013-07-29 09:45:31 +02:00
/**
* give a feed back, updating it to the database during the next refill()
*/
2013-05-22 00:07:13 +02:00
public void giveBack(Feed feed) {
2013-07-02 14:33:53 +02:00
String normalized = FeedUtils.normalizeURL(feed.getUrl());
feed.setNormalizedUrl(normalized);
feed.setNormalizedUrlHash(DigestUtils.sha1Hex(normalized));
feed.setLastUpdated(new Date());
2013-05-22 00:07:13 +02:00
giveBackQueue.add(feed);
}
private Date getLastLoginThreshold() {
if (applicationSettingsService.get().isHeavyLoad()) {
return DateUtils.addDays(new Date(), -30);
} else {
return null;
}
}
}