60bc91dc116d449a2b7b642800ea68f5d613c7c8
[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                         logger.info(String.format("Running Query for %s...", reactionName));
157                         Query query = nextReaction.query();
158                         net.pterodactylus.reactor.State state;
159                         try {
160                                 logger.debug("Querying system...");
161                                 state = query.state();
162                                 if (state == null) {
163                                         state = FailedState.INSTANCE;
164                                 }
165                                 logger.debug("System queried.");
166                         } catch (Throwable t1) {
167                                 logger.warn("Querying system failed!", t1);
168                                 state = new AbstractState(t1) {
169                                         /* no further state. */
170                                 };
171                         }
172                         logger.debug(String.format("State is %s.", state));
173
174                         /* convert states. */
175                         for (Filter filter : nextReaction.filters()) {
176                                 if (state.success()) {
177                                         net.pterodactylus.reactor.State newState = filter.filter(state);
178                                         logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
179                                         state = newState;
180                                 }
181                         }
182                         if (state.success()) {
183                                 stateManager.saveState(reactionName, state);
184                         }
185
186                         /* only run trigger if we have collected two states. */
187                         Trigger trigger = nextReaction.trigger();
188                         boolean triggerHit = false;
189                         if ((lastState != null) && state.success()) {
190                                 logger.debug("Checking Trigger for changes...");
191                                 triggerHit = trigger.triggers(state, lastState);
192                         }
193
194                         /* run action if trigger was hit. */
195                         logger.debug(String.format("Trigger was hit: %s.", triggerHit));
196                         if (triggerHit) {
197                                 logger.info("Executing Action...");
198                                 nextReaction.action().execute(trigger.output());
199                         }
200
201                 }
202         }
203
204 }