2 * Rhynodge - 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.rhynodge.engine;
20 import java.util.HashMap;
22 import java.util.Map.Entry;
23 import java.util.SortedMap;
25 import net.pterodactylus.rhynodge.Filter;
26 import net.pterodactylus.rhynodge.Query;
27 import net.pterodactylus.rhynodge.Reaction;
28 import net.pterodactylus.rhynodge.Trigger;
29 import net.pterodactylus.rhynodge.states.AbstractState;
30 import net.pterodactylus.rhynodge.states.FailedState;
31 import net.pterodactylus.rhynodge.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 * Rhynodge 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;
52 /** All defined reactions. */
53 /* synchronize on itself. */
54 private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
57 * Creates a new engine.
62 public Engine(StateManager stateManager) {
63 this.stateManager = stateManager;
71 * Adds the given reaction to this engine.
74 * The name of the reaction
76 * The reaction to add to this engine
78 public void addReaction(String name, Reaction reaction) {
79 synchronized (reactions) {
80 reactions.put(name, reaction);
81 reactions.notifyAll();
86 * Removes the reaction with the given name.
89 * The name of the reaction to remove
91 public void removeReaction(String name) {
92 synchronized (reactions) {
93 if (!reactions.containsKey(name)) {
96 reactions.remove(name);
97 reactions.notifyAll();
102 // ABSTRACTSERVICE METHODS
110 while (isRunning()) {
112 /* delay if we have no reactions. */
113 synchronized (reactions) {
114 if (reactions.isEmpty()) {
115 logger.debug("Sleeping while no Reactions available.");
118 } catch (InterruptedException ie1) {
119 /* ignore, we’re looping anyway. */
125 /* find next reaction. */
126 SortedMap<Long, Pair<String, Reaction>> nextReactions = Maps.newTreeMap();
128 Reaction nextReaction;
129 synchronized (reactions) {
130 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
131 net.pterodactylus.rhynodge.State state = stateManager.loadLastState(reactionEntry.getKey());
132 long stateTime = (state != null) ? state.time() : 0;
133 nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
135 reactionName = nextReactions.get(nextReactions.firstKey()).getLeft();
136 nextReaction = nextReactions.get(nextReactions.firstKey()).getRight();
138 logger.debug(String.format("Next Reaction: %s.", reactionName));
140 /* wait until the next reaction has to run. */
141 net.pterodactylus.rhynodge.State lastState = stateManager.loadLastState(reactionName);
142 long lastStateTime = (lastState != null) ? lastState.time() : 0;
143 int lastStateFailCount = (lastState != null) ? lastState.failCount() : 0;
144 long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
145 logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
147 synchronized (reactions) {
149 logger.info(String.format("Waiting until %tc.", lastStateTime + nextReaction.updateInterval()));
150 reactions.wait(waitTime);
151 } catch (InterruptedException ie1) {
156 /* re-start loop to check for new reactions. */
161 logger.info(String.format("Running Query for %s...", reactionName));
162 Query query = nextReaction.query();
163 net.pterodactylus.rhynodge.State state;
165 logger.debug("Querying system...");
166 state = query.state();
168 state = FailedState.INSTANCE;
170 logger.debug("System queried.");
171 } catch (Throwable t1) {
172 logger.warn("Querying system failed!", t1);
173 state = new AbstractState(t1) {
174 /* no further state. */
177 logger.debug(String.format("State is %s.", state));
179 /* convert states. */
180 for (Filter filter : nextReaction.filters()) {
181 if (state.success()) {
182 net.pterodactylus.rhynodge.State newState = filter.filter(state);
183 logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
187 if (!state.success()) {
188 state.setFailCount(lastStateFailCount + 1);
190 net.pterodactylus.rhynodge.State lastSuccessfulState = stateManager.loadLastSuccessfulState(reactionName);
193 boolean triggerHit = false;
194 Trigger trigger = nextReaction.trigger();
195 if ((lastSuccessfulState != null) && lastSuccessfulState.success() && state.success()) {
196 net.pterodactylus.rhynodge.State newState = trigger.mergeStates(lastSuccessfulState, state);
198 /* save new state. */
199 stateManager.saveState(reactionName, newState);
201 triggerHit = trigger.triggers();
203 /* save first or error state. */
204 stateManager.saveState(reactionName, state);
207 /* run action if trigger was hit. */
208 logger.debug(String.format("Trigger was hit: %s.", triggerHit));
210 logger.info("Executing Action...");
211 nextReaction.action().execute(trigger.output(nextReaction));