2 * Sone - SoneInserter.java - Copyright © 2010–2020 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static java.lang.String.format;
21 import static java.lang.System.currentTimeMillis;
22 import static java.util.concurrent.TimeUnit.*;
23 import static java.util.logging.Logger.getLogger;
24 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
26 import java.io.Closeable;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.StringWriter;
30 import java.net.MalformedURLException;
31 import java.nio.charset.Charset;
32 import java.util.HashMap;
33 import java.util.HashSet;
36 import java.util.concurrent.atomic.AtomicInteger;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
40 import com.codahale.metrics.*;
41 import com.google.common.base.*;
42 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
43 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
44 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
45 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
46 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
47 import net.pterodactylus.sone.data.Album;
48 import net.pterodactylus.sone.data.Post;
49 import net.pterodactylus.sone.data.Reply;
50 import net.pterodactylus.sone.data.Sone;
51 import net.pterodactylus.sone.data.Sone.SoneStatus;
52 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
53 import net.pterodactylus.sone.main.SonePlugin;
54 import net.pterodactylus.util.io.Closer;
55 import net.pterodactylus.util.service.AbstractService;
56 import net.pterodactylus.util.template.HtmlFilter;
57 import net.pterodactylus.util.template.ReflectionAccessor;
58 import net.pterodactylus.util.template.Template;
59 import net.pterodactylus.util.template.TemplateContext;
60 import net.pterodactylus.util.template.TemplateContextFactory;
61 import net.pterodactylus.util.template.TemplateException;
62 import net.pterodactylus.util.template.TemplateParser;
63 import net.pterodactylus.util.template.XmlFilter;
65 import com.google.common.annotations.VisibleForTesting;
66 import com.google.common.collect.FluentIterable;
67 import com.google.common.collect.Ordering;
68 import com.google.common.eventbus.EventBus;
69 import com.google.common.eventbus.Subscribe;
71 import freenet.keys.FreenetURI;
72 import freenet.support.api.Bucket;
73 import freenet.support.api.ManifestElement;
74 import freenet.support.api.RandomAccessBucket;
75 import freenet.support.io.ArrayBucket;
78 * A Sone inserter is responsible for inserting a Sone if it has changed.
80 public class SoneInserter extends AbstractService {
83 private static final Logger logger = getLogger(SoneInserter.class.getName());
85 /** The insertion delay (in seconds). */
86 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
88 /** The template factory used to create the templates. */
89 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
92 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
93 templateContextFactory.addFilter("xml", new XmlFilter());
94 templateContextFactory.addFilter("html", new HtmlFilter());
97 /** The UTF-8 charset. */
98 private static final Charset utf8Charset = Charset.forName("UTF-8");
101 private final Core core;
103 /** The event bus. */
104 private final EventBus eventBus;
106 /** The Freenet interface. */
107 private final FreenetInterface freenetInterface;
109 private final SoneModificationDetector soneModificationDetector;
110 private final long delay;
111 private final String soneId;
112 private final Histogram soneInsertDurationHistogram;
113 private final Meter soneInsertErrorMeter;
116 * Creates a new Sone inserter.
122 * @param freenetInterface
123 * The freenet interface
125 * The ID of the Sone to insert
127 public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, final String soneId) {
128 this(core, eventBus, freenetInterface, metricRegistry, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
130 public boolean isLocked() {
131 Sone sone = core.getSone(soneId);
135 return core.isLocked(sone);
139 public String getFingerprint() {
140 Sone sone = core.getSone(soneId);
144 return sone.getFingerprint();
146 }, insertionDelay), 1000);
150 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, MetricRegistry metricRegistry, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
151 super("Sone Inserter for “" + soneId + "”", false);
153 this.eventBus = eventBus;
154 this.freenetInterface = freenetInterface;
155 this.soneInsertDurationHistogram = metricRegistry.histogram("sone.insert.duration", () -> new Histogram(new ExponentiallyDecayingReservoir(3000, 0)));
156 this.soneInsertErrorMeter = metricRegistry.meter("sone.insert.errors");
157 this.soneId = soneId;
158 this.soneModificationDetector = soneModificationDetector;
167 static AtomicInteger getInsertionDelay() {
168 return insertionDelay;
172 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
173 * has noticed a Sone modification before it starts the insert.
175 * @param insertionDelay
176 * The insertion delay (in seconds)
178 private static void setInsertionDelay(int insertionDelay) {
179 SoneInserter.insertionDelay.set(insertionDelay);
183 * Returns the fingerprint of the last insert.
185 * @return The fingerprint of the last insert
187 public String getLastInsertFingerprint() {
188 return soneModificationDetector.getLastInsertFingerprint();
192 * Sets the fingerprint of the last insert.
194 * @param lastInsertFingerprint
195 * The fingerprint of the last insert
197 public void setLastInsertFingerprint(String lastInsertFingerprint) {
198 soneModificationDetector.setFingerprint(lastInsertFingerprint);
202 * Returns whether the Sone inserter has detected a modification of the
205 * @return {@code true} if the Sone has been modified, {@code false}
208 public boolean isModified() {
209 return soneModificationDetector.isModified();
220 protected void serviceRun() {
221 while (!shouldStop()) {
223 /* check every second. */
226 if (soneModificationDetector.isEligibleForInsert()) {
227 Sone sone = core.getSone(soneId);
229 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
232 InsertInformation insertInformation = new InsertInformation(sone);
233 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
235 boolean success = false;
237 sone.setStatus(SoneStatus.inserting);
238 long insertTime = currentTimeMillis();
239 eventBus.post(new SoneInsertingEvent(sone));
240 Stopwatch stopwatch = Stopwatch.createStarted();
241 FreenetURI finalUri = freenetInterface.insertDirectory(getSoneInsertUri(sone), insertInformation.generateManifestEntries(), "index.html");
243 soneInsertDurationHistogram.update(stopwatch.elapsed(MICROSECONDS));
244 eventBus.post(new SoneInsertedEvent(sone, stopwatch.elapsed(MILLISECONDS), insertInformation.getFingerprint()));
245 /* at this point we might already be stopped. */
247 /* if so, bail out, don’t change anything. */
250 sone.setTime(insertTime);
251 sone.setLatestEdition(finalUri.getEdition());
252 core.touchConfiguration();
254 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
255 } catch (SoneException se1) {
256 soneInsertErrorMeter.mark();
257 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
258 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
260 insertInformation.close();
261 sone.setStatus(SoneStatus.idle);
265 * reset modification counter if Sone has not been modified
266 * while it was inserted.
269 synchronized (sone) {
270 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
271 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
272 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
273 core.touchConfiguration();
278 } catch (Throwable t1) {
279 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
285 public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
286 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
289 private FreenetURI getSoneInsertUri(Sone sone) throws MalformedURLException {
290 return new FreenetURI(((OwnIdentity) sone.getIdentity()).getInsertUri())
293 .setMetaString(new String[0])
294 .setSuggestedEdition(sone.getLatestEdition());
298 * Container for information that are required to insert a Sone. This
299 * container merely exists to copy all relevant data without holding a lock
300 * on the {@link Sone} object for too long.
303 class InsertInformation implements Closeable {
305 /** All properties of the Sone, copied for thread safety. */
306 private final Map<String, Object> soneProperties = new HashMap<>();
307 private final String fingerprint;
308 private final ManifestCreator manifestCreator;
311 * Creates a new insert information container.
316 public InsertInformation(Sone sone) {
317 this.fingerprint = sone.getFingerprint();
318 Map<String, Object> soneProperties = new HashMap<>();
319 soneProperties.put("id", sone.getId());
320 soneProperties.put("name", sone.getName());
321 soneProperties.put("time", currentTimeMillis());
322 soneProperties.put("requestUri", sone.getRequestUri());
323 soneProperties.put("profile", sone.getProfile());
324 soneProperties.put("posts", Ordering.from(Post.NEWEST_FIRST).sortedCopy(sone.getPosts()));
325 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
326 soneProperties.put("likedPostIds", new HashSet<>(sone.getLikedPostIds()));
327 soneProperties.put("likedReplyIds", new HashSet<>(sone.getLikedReplyIds()));
328 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
329 manifestCreator = new ManifestCreator(core, soneProperties);
337 String getFingerprint() {
346 * Generates all manifest entries required to insert this Sone.
348 * @return The manifest entries for the Sone insert
350 public HashMap<String, Object> generateManifestEntries() {
351 HashMap<String, Object> manifestEntries = new HashMap<>();
353 /* first, create an index.html. */
354 manifestEntries.put("index.html", manifestCreator.createManifestElement(
355 "index.html", "text/html; charset=utf-8",
356 "/templates/insert/index.html"));
358 /* now, store the sone. */
359 manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
360 "sone.xml", "text/xml; charset=utf-8",
361 "/templates/insert/sone.xml"));
363 return manifestEntries;
367 public void close() {
368 manifestCreator.close();
374 * Creates manifest elements for an insert by rendering a template.
377 static class ManifestCreator implements Closeable {
379 private final Core core;
380 private final Map<String, Object> soneProperties;
381 private final Set<Bucket> buckets = new HashSet<>();
383 ManifestCreator(Core core, Map<String, Object> soneProperties) {
385 this.soneProperties = soneProperties;
388 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
389 InputStreamReader templateInputStreamReader = null;
390 InputStream templateInputStream = null;
393 templateInputStream = getClass().getResourceAsStream(templateName);
394 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
395 template = TemplateParser.parse(templateInputStreamReader);
396 } catch (TemplateException te1) {
397 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
400 Closer.close(templateInputStreamReader);
401 Closer.close(templateInputStream);
404 TemplateContext templateContext = templateContextFactory.createTemplateContext();
405 templateContext.set("core", core);
406 templateContext.set("currentSone", soneProperties);
407 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
408 templateContext.set("version", SonePlugin.getPluginVersion());
409 StringWriter writer = new StringWriter();
411 template.render(templateContext, writer);
412 RandomAccessBucket bucket = new ArrayBucket(writer.toString().getBytes(Charsets.UTF_8));
414 return new ManifestElement(name, bucket, contentType, bucket.size());
415 } catch (TemplateException te1) {
416 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
419 Closer.close(writer);
423 public void close() {
424 for (Bucket bucket : buckets) {