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 static com.google.common.base.Optional.absent;
21 import static com.google.common.base.Optional.of;
22 import static com.google.common.collect.Maps.newTreeMap;
23 import static java.lang.String.format;
25 import java.util.HashMap;
27 import java.util.Map.Entry;
28 import java.util.SortedMap;
30 import net.pterodactylus.rhynodge.Filter;
31 import net.pterodactylus.rhynodge.Query;
32 import net.pterodactylus.rhynodge.Reaction;
33 import net.pterodactylus.rhynodge.State;
34 import net.pterodactylus.rhynodge.Trigger;
35 import net.pterodactylus.rhynodge.states.AbstractState;
36 import net.pterodactylus.rhynodge.states.FailedState;
37 import net.pterodactylus.rhynodge.states.StateManager;
39 import com.google.common.base.Optional;
40 import com.google.common.collect.Maps;
41 import com.google.common.util.concurrent.AbstractExecutionThreadService;
42 import org.apache.commons.lang3.tuple.Pair;
43 import org.apache.log4j.Logger;
46 * Rhynodge main engine.
48 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50 public class Engine extends AbstractExecutionThreadService {
53 private static final Logger logger = Logger.getLogger(Engine.class);
55 /** The state manager. */
56 private final StateManager stateManager;
58 /** All defined reactions. */
59 /* synchronize on itself. */
60 private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
63 * Creates a new engine.
68 public Engine(StateManager stateManager) {
69 this.stateManager = stateManager;
77 * Adds the given reaction to this engine.
80 * The name of the reaction
82 * The reaction to add to this engine
84 public void addReaction(String name, Reaction reaction) {
85 synchronized (reactions) {
86 reactions.put(name, reaction);
87 reactions.notifyAll();
92 * Removes the reaction with the given name.
95 * The name of the reaction to remove
97 public void removeReaction(String name) {
98 synchronized (reactions) {
99 if (!reactions.containsKey(name)) {
102 reactions.remove(name);
103 reactions.notifyAll();
108 // ABSTRACTSERVICE METHODS
116 while (isRunning()) {
117 Optional<Pair<String, Reaction>> nextReaction = getNextReaction();
118 if (!nextReaction.isPresent()) {
122 String reactionName = nextReaction.get().getLeft();
123 logger.debug(format("Next Reaction: %s.", reactionName));
125 /* wait until the next reaction has to run. */
126 Optional<net.pterodactylus.rhynodge.State> lastState = stateManager.loadLastState(reactionName);
127 long lastStateTime = lastState.isPresent() ? lastState.get().time() : 0;
128 int lastStateFailCount = lastState.isPresent() ? lastState.get().failCount() : 0;
129 long waitTime = (lastStateTime + nextReaction.get().getRight().updateInterval()) - System.currentTimeMillis();
130 logger.debug(format("Time to wait for next Reaction: %d millseconds.", waitTime));
132 synchronized (reactions) {
134 logger.info(format("Waiting until %tc.", lastStateTime + nextReaction.get().getRight().updateInterval()));
135 reactions.wait(waitTime);
136 } catch (InterruptedException ie1) {
141 /* re-start loop to check for new reactions. */
146 logger.info(format("Running Query for %s...", reactionName));
147 Query query = nextReaction.get().getRight().query();
148 net.pterodactylus.rhynodge.State state;
150 logger.debug("Querying system...");
151 state = query.state();
153 state = FailedState.INSTANCE;
155 logger.debug("System queried.");
156 } catch (Throwable t1) {
157 logger.warn("Querying system failed!", t1);
158 state = new AbstractState(t1) {
159 /* no further state. */
162 logger.debug(format("State is %s.", state));
164 /* convert states. */
165 for (Filter filter : nextReaction.get().getRight().filters()) {
166 if (state.success()) {
167 net.pterodactylus.rhynodge.State newState = filter.filter(state);
168 //logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
172 if (!state.success()) {
173 state.setFailCount(lastStateFailCount + 1);
175 Optional<net.pterodactylus.rhynodge.State> lastSuccessfulState = stateManager.loadLastSuccessfulState(reactionName);
178 boolean triggerHit = false;
179 Trigger trigger = nextReaction.get().getRight().trigger();
180 if (lastSuccessfulState.isPresent() && lastSuccessfulState.get().success() && state.success()) {
181 net.pterodactylus.rhynodge.State newState = trigger.mergeStates(lastSuccessfulState.get(), state);
183 /* save new state. */
184 stateManager.saveState(reactionName, newState);
186 triggerHit = trigger.triggers();
188 /* save first or error state. */
189 stateManager.saveState(reactionName, state);
192 /* run action if trigger was hit. */
193 logger.debug(format("Trigger was hit: %s.", triggerHit));
195 logger.info("Executing Action...");
196 nextReaction.get().getRight().action().execute(trigger.output(nextReaction.get().getRight()));
202 private Optional<Pair<String, Reaction>> getNextReaction() {
203 while (isRunning()) {
204 synchronized (reactions) {
205 if (reactions.isEmpty()) {
206 logger.debug("Sleeping while no Reactions available.");
209 } catch (InterruptedException ie1) {
210 /* ignore, we’re looping anyway. */
216 /* find next reaction. */
217 SortedMap<Long, Pair<String, Reaction>> nextReactions = newTreeMap();
218 synchronized (reactions) {
219 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
220 Optional<net.pterodactylus.rhynodge.State> state = stateManager.loadLastState(reactionEntry.getKey());
221 long stateTime = state.isPresent() ? state.get().time() : 0;
222 nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
224 return of(nextReactions.get(nextReactions.firstKey()));