2 * Reactor - Engine.java - Copyright © 2013 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.reactor.engine;
20 import java.util.HashMap;
22 import java.util.Map.Entry;
23 import java.util.SortedMap;
25 import net.pterodactylus.reactor.Filter;
26 import net.pterodactylus.reactor.Query;
27 import net.pterodactylus.reactor.Reaction;
28 import net.pterodactylus.reactor.Trigger;
29 import net.pterodactylus.reactor.states.AbstractState;
30 import net.pterodactylus.reactor.states.FailedState;
31 import net.pterodactylus.reactor.states.StateManager;
33 import org.apache.commons.lang3.tuple.Pair;
34 import org.apache.log4j.Logger;
36 import com.google.common.collect.Maps;
37 import com.google.common.util.concurrent.AbstractExecutionThreadService;
40 * Reactor main engine.
42 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44 public class Engine extends AbstractExecutionThreadService {
47 private static final Logger logger = Logger.getLogger(Engine.class);
49 /** The state manager. */
50 private final StateManager stateManager = new StateManager("states");
52 /** All defined reactions. */
53 /* synchronize on itself. */
54 private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
61 * Adds the given reaction to this engine.
64 * The name of the reaction
66 * The reaction to add to this engine
68 public void addReaction(String name, Reaction reaction) {
69 synchronized (reactions) {
70 reactions.put(name, reaction);
71 reactions.notifyAll();
76 * Removes the reaction with the given name.
79 * The name of the reaction to remove
81 public void removeReaction(String name) {
82 synchronized (reactions) {
83 if (!reactions.containsKey(name)) {
86 reactions.remove(name);
87 reactions.notifyAll();
92 // ABSTRACTSERVICE METHODS
100 while (isRunning()) {
102 /* delay if we have no reactions. */
103 synchronized (reactions) {
104 if (reactions.isEmpty()) {
105 logger.debug("Sleeping while no Reactions available.");
108 } catch (InterruptedException ie1) {
109 /* ignore, we’re looping anyway. */
115 /* find next reaction. */
116 SortedMap<Long, Pair<String, Reaction>> nextReactions = Maps.newTreeMap();
118 Reaction nextReaction;
119 synchronized (reactions) {
120 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
121 net.pterodactylus.reactor.State state = stateManager.loadLastState(reactionEntry.getKey());
122 long stateTime = (state != null) ? state.time() : 0;
123 nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
125 reactionName = nextReactions.get(nextReactions.firstKey()).getLeft();
126 nextReaction = nextReactions.get(nextReactions.firstKey()).getRight();
128 logger.debug(String.format("Next Reaction: %s.", reactionName));
130 /* wait until the next reaction has to run. */
131 net.pterodactylus.reactor.State lastState = stateManager.loadLastState(reactionName);
132 long lastStateTime = (lastState != null) ? lastState.time() : 0;
133 int lastStateFailCount = (lastState != null) ? lastState.failCount() : 0;
134 long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
135 logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
137 synchronized (reactions) {
139 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
140 reactions.wait(waitTime);
141 } catch (InterruptedException ie1) {
146 /* re-start loop to check for new reactions. */
151 logger.info(String.format("Running Query for %s...", reactionName));
152 Query query = nextReaction.query();
153 net.pterodactylus.reactor.State state;
155 logger.debug("Querying system...");
156 state = query.state();
158 state = FailedState.INSTANCE;
160 logger.debug("System queried.");
161 } catch (Throwable t1) {
162 logger.warn("Querying system failed!", t1);
163 state = new AbstractState(t1) {
164 /* no further state. */
167 logger.debug(String.format("State is %s.", state));
169 /* convert states. */
170 for (Filter filter : nextReaction.filters()) {
171 if (state.success()) {
172 net.pterodactylus.reactor.State newState = filter.filter(state);
173 logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
177 if (!state.success()) {
178 state.setFailCount(lastStateFailCount + 1);
180 net.pterodactylus.reactor.State lastSuccessfulState = stateManager.loadLastSuccessfulState(reactionName);
181 stateManager.saveState(reactionName, state);
183 /* only run trigger if we have collected two successful states. */
184 Trigger trigger = nextReaction.trigger();
185 boolean triggerHit = false;
186 if ((lastSuccessfulState != null) && lastSuccessfulState.success() && state.success()) {
187 logger.debug("Checking Trigger for changes...");
188 triggerHit = trigger.triggers(state, lastSuccessfulState);
191 /* run action if trigger was hit. */
192 logger.debug(String.format("Trigger was hit: %s.", triggerHit));
194 logger.info("Executing Action...");
195 nextReaction.action().execute(trigger.output());