e82267cefaf6c39543a1fd748b6f94f413c39975
[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          */
68         public void addReaction(String name, Reaction reaction) {
69                 synchronized (reactions) {
70                         reactions.put(name, reaction);
71                         reactions.notifyAll();
72                 }
73         }
74
75         /**
76          * Removes the reaction with the given name.
77          *
78          * @param name
79          *            The name of the reaction to remove
80          */
81         public void removeReaction(String name) {
82                 synchronized (reactions) {
83                         if (!reactions.containsKey(name)) {
84                                 return;
85                         }
86                         reactions.remove(name);
87                         reactions.notifyAll();
88                 }
89         }
90
91         //
92         // ABSTRACTSERVICE METHODS
93         //
94
95         /**
96          * {@inheritDoc}
97          */
98         @Override
99         public void run() {
100                 while (isRunning()) {
101
102                         /* delay if we have no reactions. */
103                         synchronized (reactions) {
104                                 if (reactions.isEmpty()) {
105                                         logger.debug("Sleeping while no Reactions available.");
106                                         try {
107                                                 reactions.wait();
108                                         } catch (InterruptedException ie1) {
109                                                 /* ignore, we’re looping anyway. */
110                                         }
111                                         continue;
112                                 }
113                         }
114
115                         /* find next reaction. */
116                         SortedMap<Long, Pair<String, Reaction>> nextReactions = Maps.newTreeMap();
117                         String reactionName;
118                         Reaction nextReaction;
119                         synchronized (reactions) {
120                                 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
121                                         net.pterodactylus.reactor.State state = stateManager.loadLastState(reactionEntry.getKey());
122                                         long stateTime = (state != null) ? state.time() : 0;
123                                         nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
124                                 }
125                                 reactionName = nextReactions.get(nextReactions.firstKey()).getLeft();
126                                 nextReaction = nextReactions.get(nextReactions.firstKey()).getRight();
127                         }
128                         logger.debug(String.format("Next Reaction: %s.", nextReaction));
129
130                         /* wait until the next reaction has to run. */
131                         net.pterodactylus.reactor.State lastState = stateManager.loadLastState(reactionName);
132                         long lastStateTime = (lastState != null) ? lastState.time() : 0;
133                         int lastStateFailCount = (lastState != null) ? lastState.failCount() : 0;
134                         long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
135                         logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
136                         if (waitTime > 0) {
137                                 synchronized (reactions) {
138                                         try {
139                                                 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
140                                                 reactions.wait(waitTime);
141                                         } catch (InterruptedException ie1) {
142                                                 /* we’re looping! */
143                                         }
144                                 }
145
146                                 /* re-start loop to check for new reactions. */
147                                 continue;
148                         }
149
150                         /* run reaction. */
151                         logger.info(String.format("Running Query for %s...", reactionName));
152                         Query query = nextReaction.query();
153                         net.pterodactylus.reactor.State state;
154                         try {
155                                 logger.debug("Querying system...");
156                                 state = query.state();
157                                 if (state == null) {
158                                         state = FailedState.INSTANCE;
159                                 }
160                                 logger.debug("System queried.");
161                         } catch (Throwable t1) {
162                                 logger.warn("Querying system failed!", t1);
163                                 state = new AbstractState(t1) {
164                                         /* no further state. */
165                                 };
166                         }
167                         logger.debug(String.format("State is %s.", state));
168
169                         /* convert states. */
170                         for (Filter filter : nextReaction.filters()) {
171                                 if (state.success()) {
172                                         net.pterodactylus.reactor.State newState = filter.filter(state);
173                                         logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
174                                         state = newState;
175                                 }
176                         }
177                         if (!state.success()) {
178                                 state.setFailCount(lastStateFailCount + 1);
179                         }
180                         stateManager.saveState(reactionName, state);
181
182                         /* only run trigger if we have collected two successful states. */
183                         Trigger trigger = nextReaction.trigger();
184                         boolean triggerHit = false;
185                         if ((lastState != null) && lastState.success() && state.success()) {
186                                 logger.debug("Checking Trigger for changes...");
187                                 triggerHit = trigger.triggers(state, lastState);
188                         }
189
190                         /* run action if trigger was hit. */
191                         logger.debug(String.format("Trigger was hit: %s.", triggerHit));
192                         if (triggerHit) {
193                                 logger.info("Executing Action...");
194                                 nextReaction.action().execute(trigger.output());
195                         }
196
197                 }
198         }
199
200 }