Clean up logger on shutdown
[Sone.git] / src / main / java / net / pterodactylus / sone / main / SonePlugin.java
1 /*
2  * Sone - SonePlugin.java - Copyright © 2010–2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.main;
19
20 import static com.google.common.base.Optional.of;
21 import static java.util.logging.Logger.getLogger;
22
23 import java.io.File;
24 import java.util.logging.Handler;
25 import java.util.logging.Level;
26 import java.util.logging.LogRecord;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.core.Core;
30 import net.pterodactylus.sone.fcp.FcpInterface;
31 import net.pterodactylus.sone.freenet.PluginStoreConfigurationBackend;
32 import net.pterodactylus.sone.freenet.wot.Context;
33 import net.pterodactylus.sone.freenet.wot.WebOfTrustConnector;
34 import net.pterodactylus.sone.web.WebInterface;
35 import net.pterodactylus.util.config.Configuration;
36 import net.pterodactylus.util.config.ConfigurationException;
37 import net.pterodactylus.util.config.MapConfigurationBackend;
38 import net.pterodactylus.util.version.Version;
39
40 import com.google.common.base.Optional;
41 import com.google.common.cache.CacheBuilder;
42 import com.google.common.cache.CacheLoader;
43 import com.google.common.cache.LoadingCache;
44 import com.google.common.eventbus.EventBus;
45 import com.google.inject.AbstractModule;
46 import com.google.inject.Guice;
47 import com.google.inject.Injector;
48 import com.google.inject.Singleton;
49 import com.google.inject.TypeLiteral;
50 import com.google.inject.matcher.Matchers;
51 import com.google.inject.spi.InjectionListener;
52 import com.google.inject.spi.TypeEncounter;
53 import com.google.inject.spi.TypeListener;
54
55 import freenet.client.async.PersistenceDisabledException;
56 import freenet.l10n.BaseL10n.LANGUAGE;
57 import freenet.l10n.PluginL10n;
58 import freenet.node.Node;
59 import freenet.pluginmanager.FredPlugin;
60 import freenet.pluginmanager.FredPluginBaseL10n;
61 import freenet.pluginmanager.FredPluginFCP;
62 import freenet.pluginmanager.FredPluginL10n;
63 import freenet.pluginmanager.FredPluginThreadless;
64 import freenet.pluginmanager.FredPluginVersioned;
65 import freenet.pluginmanager.PluginReplySender;
66 import freenet.pluginmanager.PluginRespirator;
67 import freenet.support.SimpleFieldSet;
68 import freenet.support.api.Bucket;
69
70 /**
71  * This class interfaces with Freenet. It is the class that is loaded by the
72  * node and starts up the whole Sone system.
73  *
74  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75  */
76 public class SonePlugin implements FredPlugin, FredPluginFCP, FredPluginL10n, FredPluginBaseL10n, FredPluginThreadless, FredPluginVersioned {
77
78         private static final Logger soneLogger = getLogger("net.pterodactylus.sone");
79
80         static {
81                 /* initialize logging. */
82                 soneLogger.setUseParentHandlers(false);
83                 soneLogger.addHandler(new Handler() {
84                         private final LoadingCache<String, Class<?>> classCache = CacheBuilder.newBuilder()
85                                         .build(new CacheLoader<String, Class<?>>() {
86                                                 @Override
87                                                 public Class<?> load(String key) throws Exception {
88                                                         return Class.forName(key);
89                                                 }
90                                         });
91                         
92                         @Override
93                         public void publish(LogRecord logRecord) {
94                                 int recordLevel = logRecord.getLevel().intValue();
95                                 Class<?> loggingClass = classCache.getUnchecked(logRecord.getLoggerName());
96                                 if (recordLevel < Level.FINE.intValue()) {
97                                         freenet.support.Logger.debug(loggingClass, logRecord.getMessage(), logRecord.getThrown());
98                                 } else if (recordLevel < Level.INFO.intValue()) {
99                                         freenet.support.Logger.minor(loggingClass, logRecord.getMessage(), logRecord.getThrown());
100                                 } else if (recordLevel < Level.WARNING.intValue()) {
101                                         freenet.support.Logger.normal(loggingClass, logRecord.getMessage(), logRecord.getThrown());
102                                 } else if (recordLevel < Level.SEVERE.intValue()) {
103                                         freenet.support.Logger.warning(loggingClass, logRecord.getMessage(), logRecord.getThrown());
104                                 } else {
105                                         freenet.support.Logger.error(loggingClass, logRecord.getMessage(), logRecord.getThrown());
106                                 }
107                         }
108
109                         @Override
110                         public void flush() {
111                         }
112
113                         @Override
114                         public void close() {
115                         }
116                 });
117         }
118
119         /** The version. */
120         public static final Version VERSION = new Version(0, 9, 2);
121
122         /** The current year at time of release. */
123         private static final int YEAR = 2015;
124         private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
125         private static final int LATEST_EDITION = 69;
126
127         /** The logger. */
128         private static final Logger logger = getLogger(SonePlugin.class.getName());
129
130         /** The plugin respirator. */
131         private PluginRespirator pluginRespirator;
132
133         /** The core. */
134         private Core core;
135
136         /** The web interface. */
137         private WebInterface webInterface;
138
139         /** The FCP interface. */
140         private FcpInterface fcpInterface;
141
142         /** The l10n helper. */
143         private PluginL10n l10n;
144
145         /** The web of trust connector. */
146         private WebOfTrustConnector webOfTrustConnector;
147
148         //
149         // ACCESSORS
150         //
151
152         /**
153          * Returns the plugin respirator for this plugin.
154          *
155          * @return The plugin respirator
156          */
157         public PluginRespirator pluginRespirator() {
158                 return pluginRespirator;
159         }
160
161         /**
162          * Returns the core started by this plugin.
163          *
164          * @return The core
165          */
166         public Core core() {
167                 return core;
168         }
169
170         /**
171          * Returns the plugin’s l10n helper.
172          *
173          * @return The plugin’s l10n helper
174          */
175         public PluginL10n l10n() {
176                 return l10n;
177         }
178
179         public static int getYear() {
180                 return YEAR;
181         }
182
183         public static String getHomepage() {
184                 return SONE_HOMEPAGE + LATEST_EDITION;
185         }
186
187         //
188         // FREDPLUGIN METHODS
189         //
190
191         /**
192          * {@inheritDoc}
193          */
194         @Override
195         public void runPlugin(PluginRespirator pluginRespirator) {
196                 this.pluginRespirator = pluginRespirator;
197
198                 /* create a configuration. */
199                 Configuration oldConfiguration;
200                 Configuration newConfiguration = null;
201                 boolean firstStart = !new File("sone.properties").exists();
202                 boolean newConfig = false;
203                 try {
204                         oldConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), false));
205                         newConfiguration = oldConfiguration;
206                 } catch (ConfigurationException ce1) {
207                         newConfig = true;
208                         logger.log(Level.INFO, "Could not load configuration file, trying plugin store…", ce1);
209                         try {
210                                 newConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), true));
211                                 logger.log(Level.INFO, "Created new configuration file.");
212                         } catch (ConfigurationException ce2) {
213                                 logger.log(Level.SEVERE, "Could not create configuration file, using Plugin Store!", ce2);
214                         }
215                         try {
216                                 oldConfiguration = new Configuration(new PluginStoreConfigurationBackend(pluginRespirator));
217                                 logger.log(Level.INFO, "Plugin store loaded.");
218                         } catch (PersistenceDisabledException pde1) {
219                                 logger.log(Level.SEVERE, "Could not load any configuration, using empty configuration!");
220                                 oldConfiguration = new Configuration(new MapConfigurationBackend());
221                         }
222                 }
223
224                 final Configuration startConfiguration;
225                 if ((newConfiguration != null) && (oldConfiguration != newConfiguration)) {
226                         logger.log(Level.INFO, "Setting configuration to file-based configuration.");
227                         startConfiguration = newConfiguration;
228                 } else {
229                         startConfiguration = oldConfiguration;
230                 }
231                 final EventBus eventBus = new EventBus();
232
233                 /* Freenet injector configuration. */
234                 AbstractModule freenetModule = new AbstractModule() {
235
236                         @Override
237                         @SuppressWarnings("synthetic-access")
238                         protected void configure() {
239                                 bind(PluginRespirator.class).toInstance(SonePlugin.this.pluginRespirator);
240                                 bind(Node.class).toInstance(SonePlugin.this.pluginRespirator.getNode());
241                         }
242                 };
243                 /* Sone injector configuration. */
244                 AbstractModule soneModule = new AbstractModule() {
245
246                         @Override
247                         protected void configure() {
248                                 bind(EventBus.class).toInstance(eventBus);
249                                 bind(Configuration.class).toInstance(startConfiguration);
250                                 Context context = new Context("Sone");
251                                 bind(Context.class).toInstance(context);
252                                 bind(getOptionalContextTypeLiteral()).toInstance(of(context));
253                                 bind(SonePlugin.class).toInstance(SonePlugin.this);
254                                 bindListener(Matchers.any(), new TypeListener() {
255
256                                         @Override
257                                         public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
258                                                 typeEncounter.register(new InjectionListener<I>() {
259
260                                                         @Override
261                                                         public void afterInjection(I injectee) {
262                                                                 eventBus.register(injectee);
263                                                         }
264                                                 });
265                                         }
266                                 });
267                         }
268
269                         private TypeLiteral<Optional<Context>> getOptionalContextTypeLiteral() {
270                                 return new TypeLiteral<Optional<Context>>() {
271                                 };
272                         }
273
274                 };
275                 Injector injector = Guice.createInjector(freenetModule, soneModule);
276                 core = injector.getInstance(Core.class);
277
278                 /* create web of trust connector. */
279                 webOfTrustConnector = injector.getInstance(WebOfTrustConnector.class);
280
281                 /* create FCP interface. */
282                 fcpInterface = injector.getInstance(FcpInterface.class);
283
284                 /* create the web interface. */
285                 webInterface = injector.getInstance(WebInterface.class);
286
287                 /* start core! */
288                 core.start();
289                 webInterface.start();
290                 webInterface.setFirstStart(firstStart);
291                 webInterface.setNewConfig(newConfig);
292         }
293
294         /**
295          * {@inheritDoc}
296          */
297         @Override
298         public void terminate() {
299                 deregisterLoggerHandlers();
300                 try {
301                         /* stop the web interface. */
302                         webInterface.stop();
303
304                         /* stop the core. */
305                         core.stop();
306
307                         /* stop the web of trust connector. */
308                         webOfTrustConnector.stop();
309                 } catch (Throwable t1) {
310                         logger.log(Level.SEVERE, "Error while shutting down!", t1);
311                 }
312         }
313
314         private void deregisterLoggerHandlers() {
315                 for (Handler handler : soneLogger.getHandlers()) {
316                         soneLogger.removeHandler(handler);
317                 }
318         }
319
320         //
321         // INTERFACE FredPluginFCP
322         //
323
324         /**
325          * {@inheritDoc}
326          */
327         @Override
328         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
329                 fcpInterface.handle(pluginReplySender, parameters, data, accessType);
330         }
331
332         //
333         // INTERFACE FredPluginL10n
334         //
335
336         /**
337          * {@inheritDoc}
338          */
339         @Override
340         public String getString(String key) {
341                 return l10n.getBase().getString(key);
342         }
343
344         /**
345          * {@inheritDoc}
346          */
347         @Override
348         public void setLanguage(LANGUAGE newLanguage) {
349                 l10n = new PluginL10n(this, newLanguage);
350         }
351
352         //
353         // INTERFACE FredPluginBaseL10n
354         //
355
356         /**
357          * {@inheritDoc}
358          */
359         @Override
360         public String getL10nFilesBasePath() {
361                 return "i18n";
362         }
363
364         /**
365          * {@inheritDoc}
366          */
367         @Override
368         public String getL10nFilesMask() {
369                 return "sone.${lang}.properties";
370         }
371
372         /**
373          * {@inheritDoc}
374          */
375         @Override
376         public String getL10nOverrideFilesMask() {
377                 return "sone.${lang}.override.properties";
378         }
379
380         /**
381          * {@inheritDoc}
382          */
383         @Override
384         public ClassLoader getPluginClassLoader() {
385                 return SonePlugin.class.getClassLoader();
386         }
387
388         //
389         // INTERFACE FredPluginVersioned
390         //
391
392         /**
393          * {@inheritDoc}
394          */
395         @Override
396         public String getVersion() {
397                 return VERSION.toString();
398         }
399
400 }