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