Store failed states and fail count, too.
[rhynodge.git] / src / main / java / net / pterodactylus / reactor / engine / Engine.java
1 /*
2  * Reactor - Engine.java - Copyright © 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.reactor.engine;
19
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.SortedMap;
24
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;
32
33 import org.apache.commons.lang3.tuple.Pair;
34 import org.apache.log4j.Logger;
35
36 import com.google.common.collect.Maps;
37 import com.google.common.util.concurrent.AbstractExecutionThreadService;
38
39 /**
40  * Reactor main engine.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class Engine extends AbstractExecutionThreadService {
45
46         /** The logger. */
47         private static final Logger logger = Logger.getLogger(Engine.class);
48
49         /** The state manager. */
50         private final StateManager stateManager = new StateManager("states");
51
52         /** All defined reactions. */
53         /* synchronize on itself. */
54         private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
55
56         //
57         // ACCESSORS
58         //
59
60         /**
61          * Adds the given reaction to this engine.
62          *
63          * @param name
64          *            The name of the reaction
65          * @param reaction
66          *            The reaction to add to this engine
67          * @throws IllegalStateException
68          *             if the engine already contains a {@link Reaction} with the
69          *             given name
70          */
71         public void addReaction(String name, Reaction reaction) {
72                 synchronized (reactions) {
73                         if (reactions.containsKey(name)) {
74                                 throw new IllegalStateException(String.format("Engine already contains a Reaction named “%s!”", name));
75                         }
76                         reactions.put(name, reaction);
77                         reactions.notifyAll();
78                 }
79         }
80
81         /**
82          * Removes the reaction with the given name.
83          *
84          * @param name
85          *            The name of the reaction to remove
86          */
87         public void removeReaction(String name) {
88                 synchronized (reactions) {
89                         if (!reactions.containsKey(name)) {
90                                 return;
91                         }
92                         reactions.remove(name);
93                         reactions.notifyAll();
94                 }
95         }
96
97         //
98         // ABSTRACTSERVICE METHODS
99         //
100
101         /**
102          * {@inheritDoc}
103          */
104         @Override
105         public void run() {
106                 while (isRunning()) {
107
108                         /* delay if we have no reactions. */
109                         synchronized (reactions) {
110                                 if (reactions.isEmpty()) {
111                                         logger.debug("Sleeping while no Reactions available.");
112                                         try {
113                                                 reactions.wait();
114                                         } catch (InterruptedException ie1) {
115                                                 /* ignore, we’re looping anyway. */
116                                         }
117                                         continue;
118                                 }
119                         }
120
121                         /* find next reaction. */
122                         SortedMap<Long, Pair<String, Reaction>> nextReactions = Maps.newTreeMap();
123                         String reactionName;
124                         Reaction nextReaction;
125                         synchronized (reactions) {
126                                 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
127                                         net.pterodactylus.reactor.State state = stateManager.loadState(reactionEntry.getKey());
128                                         long stateTime = (state != null) ? state.time() : 0;
129                                         nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
130                                 }
131                                 reactionName = nextReactions.get(nextReactions.firstKey()).getLeft();
132                                 nextReaction = nextReactions.get(nextReactions.firstKey()).getRight();
133                         }
134                         logger.debug(String.format("Next Reaction: %s.", nextReaction));
135
136                         /* wait until the next reaction has to run. */
137                         net.pterodactylus.reactor.State lastState = stateManager.loadState(reactionName);
138                         long lastStateTime = (lastState != null) ? lastState.time() : 0;
139                         int lastStateFailCount = (lastState != null) ? lastState.failCount() : 0;
140                         long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
141                         logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
142                         if (waitTime > 0) {
143                                 synchronized (reactions) {
144                                         try {
145                                                 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
146                                                 reactions.wait(waitTime);
147                                         } catch (InterruptedException ie1) {
148                                                 /* we’re looping! */
149                                         }
150                                 }
151
152                                 /* re-start loop to check for new reactions. */
153                                 continue;
154                         }
155
156                         /* run reaction. */
157                         logger.info(String.format("Running Query for %s...", reactionName));
158                         Query query = nextReaction.query();
159                         net.pterodactylus.reactor.State state;
160                         try {
161                                 logger.debug("Querying system...");
162                                 state = query.state();
163                                 if (state == null) {
164                                         state = FailedState.INSTANCE;
165                                 }
166                                 logger.debug("System queried.");
167                         } catch (Throwable t1) {
168                                 logger.warn("Querying system failed!", t1);
169                                 state = new AbstractState(t1) {
170                                         /* no further state. */
171                                 };
172                         }
173                         logger.debug(String.format("State is %s.", state));
174
175                         /* convert states. */
176                         for (Filter filter : nextReaction.filters()) {
177                                 if (state.success()) {
178                                         net.pterodactylus.reactor.State newState = filter.filter(state);
179                                         logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
180                                         state = newState;
181                                 }
182                         }
183                         if (!state.success()) {
184                                 state.setFailCount(lastStateFailCount + 1);
185                         }
186                         stateManager.saveState(reactionName, state);
187
188                         /* only run trigger if we have collected two successful states. */
189                         Trigger trigger = nextReaction.trigger();
190                         boolean triggerHit = false;
191                         if ((lastState != null) && lastState.success() && state.success()) {
192                                 logger.debug("Checking Trigger for changes...");
193                                 triggerHit = trigger.triggers(state, lastState);
194                         }
195
196                         /* run action if trigger was hit. */
197                         logger.debug(String.format("Trigger was hit: %s.", triggerHit));
198                         if (triggerHit) {
199                                 logger.info("Executing Action...");
200                                 nextReaction.action().execute(trigger.output());
201                         }
202
203                 }
204         }
205
206 }