Persist states across reruns.
[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                         long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
140                         logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
141                         if (waitTime > 0) {
142                                 synchronized (reactions) {
143                                         try {
144                                                 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
145                                                 reactions.wait(waitTime);
146                                         } catch (InterruptedException ie1) {
147                                                 /* we’re looping! */
148                                         }
149                                 }
150
151                                 /* re-start loop to check for new reactions. */
152                                 continue;
153                         }
154
155                         /* run reaction. */
156                         Query query = nextReaction.query();
157                         net.pterodactylus.reactor.State state;
158                         try {
159                                 logger.debug("Querying system...");
160                                 state = query.state();
161                                 if (state == null) {
162                                         state = FailedState.INSTANCE;
163                                 }
164                                 logger.debug("System queried.");
165                         } catch (Throwable t1) {
166                                 logger.warn("Querying system failed!", t1);
167                                 state = new AbstractState(t1) {
168                                         /* no further state. */
169                                 };
170                         }
171                         logger.debug(String.format("State is %s.", state));
172
173                         /* convert states. */
174                         for (Filter filter : nextReaction.filters()) {
175                                 if (state.success()) {
176                                         net.pterodactylus.reactor.State newState = filter.filter(state);
177                                         logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
178                                         state = newState;
179                                 }
180                         }
181                         if (state.success()) {
182                                 stateManager.saveState(reactionName, state);
183                         }
184
185                         /* only run trigger if we have collected two states. */
186                         Trigger trigger = nextReaction.trigger();
187                         boolean triggerHit = false;
188                         if ((lastState != null) && state.success()) {
189                                 logger.debug("Checking Trigger for changes...");
190                                 triggerHit = trigger.triggers(state, lastState);
191                         }
192
193                         /* run action if trigger was hit. */
194                         logger.debug(String.format("Trigger was hit: %s.", triggerHit));
195                         if (triggerHit) {
196                                 logger.info("Executing Action...");
197                                 nextReaction.action().execute(trigger.output());
198                         }
199
200                 }
201         }
202
203 }