Fix javadoc.
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / engine / Engine.java
1 /*
2  * Rhynodge - 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.rhynodge.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.rhynodge.Filter;
26 import net.pterodactylus.rhynodge.Query;
27 import net.pterodactylus.rhynodge.Reaction;
28 import net.pterodactylus.rhynodge.Trigger;
29 import net.pterodactylus.rhynodge.states.AbstractState;
30 import net.pterodactylus.rhynodge.states.FailedState;
31 import net.pterodactylus.rhynodge.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  * Rhynodge 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;
51
52         /** All defined reactions. */
53         /* synchronize on itself. */
54         private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
55
56         /**
57          * Creates a new engine.
58          *
59          * @param stateManager
60          *            The state manager
61          */
62         public Engine(StateManager stateManager) {
63                 this.stateManager = stateManager;
64         }
65
66         //
67         // ACCESSORS
68         //
69
70         /**
71          * Adds the given reaction to this engine.
72          *
73          * @param name
74          *            The name of the reaction
75          * @param reaction
76          *            The reaction to add to this engine
77          */
78         public void addReaction(String name, Reaction reaction) {
79                 synchronized (reactions) {
80                         reactions.put(name, reaction);
81                         reactions.notifyAll();
82                 }
83         }
84
85         /**
86          * Removes the reaction with the given name.
87          *
88          * @param name
89          *            The name of the reaction to remove
90          */
91         public void removeReaction(String name) {
92                 synchronized (reactions) {
93                         if (!reactions.containsKey(name)) {
94                                 return;
95                         }
96                         reactions.remove(name);
97                         reactions.notifyAll();
98                 }
99         }
100
101         //
102         // ABSTRACTSERVICE METHODS
103         //
104
105         /**
106          * {@inheritDoc}
107          */
108         @Override
109         public void run() {
110                 while (isRunning()) {
111
112                         /* delay if we have no reactions. */
113                         synchronized (reactions) {
114                                 if (reactions.isEmpty()) {
115                                         logger.debug("Sleeping while no Reactions available.");
116                                         try {
117                                                 reactions.wait();
118                                         } catch (InterruptedException ie1) {
119                                                 /* ignore, we’re looping anyway. */
120                                         }
121                                         continue;
122                                 }
123                         }
124
125                         /* find next reaction. */
126                         SortedMap<Long, Pair<String, Reaction>> nextReactions = Maps.newTreeMap();
127                         String reactionName;
128                         Reaction nextReaction;
129                         synchronized (reactions) {
130                                 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
131                                         net.pterodactylus.rhynodge.State state = stateManager.loadLastState(reactionEntry.getKey());
132                                         long stateTime = (state != null) ? state.time() : 0;
133                                         nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
134                                 }
135                                 reactionName = nextReactions.get(nextReactions.firstKey()).getLeft();
136                                 nextReaction = nextReactions.get(nextReactions.firstKey()).getRight();
137                         }
138                         logger.debug(String.format("Next Reaction: %s.", reactionName));
139
140                         /* wait until the next reaction has to run. */
141                         net.pterodactylus.rhynodge.State lastState = stateManager.loadLastState(reactionName);
142                         long lastStateTime = (lastState != null) ? lastState.time() : 0;
143                         int lastStateFailCount = (lastState != null) ? lastState.failCount() : 0;
144                         long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
145                         logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
146                         if (waitTime > 0) {
147                                 synchronized (reactions) {
148                                         try {
149                                                 logger.info(String.format("Waiting until %tc.", lastStateTime + nextReaction.updateInterval()));
150                                                 reactions.wait(waitTime);
151                                         } catch (InterruptedException ie1) {
152                                                 /* we’re looping! */
153                                         }
154                                 }
155
156                                 /* re-start loop to check for new reactions. */
157                                 continue;
158                         }
159
160                         /* run reaction. */
161                         logger.info(String.format("Running Query for %s...", reactionName));
162                         Query query = nextReaction.query();
163                         net.pterodactylus.rhynodge.State state;
164                         try {
165                                 logger.debug("Querying system...");
166                                 state = query.state();
167                                 if (state == null) {
168                                         state = FailedState.INSTANCE;
169                                 }
170                                 logger.debug("System queried.");
171                         } catch (Throwable t1) {
172                                 logger.warn("Querying system failed!", t1);
173                                 state = new AbstractState(t1) {
174                                         /* no further state. */
175                                 };
176                         }
177                         logger.debug(String.format("State is %s.", state));
178
179                         /* convert states. */
180                         for (Filter filter : nextReaction.filters()) {
181                                 if (state.success()) {
182                                         net.pterodactylus.rhynodge.State newState = filter.filter(state);
183                                         logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
184                                         state = newState;
185                                 }
186                         }
187                         if (!state.success()) {
188                                 state.setFailCount(lastStateFailCount + 1);
189                         }
190                         net.pterodactylus.rhynodge.State lastSuccessfulState = stateManager.loadLastSuccessfulState(reactionName);
191
192                         /* merge states. */
193                         boolean triggerHit = false;
194                         Trigger trigger = nextReaction.trigger();
195                         if ((lastSuccessfulState != null) && lastSuccessfulState.success() && state.success()) {
196                                 net.pterodactylus.rhynodge.State newState = trigger.mergeStates(lastSuccessfulState, state);
197
198                                 /* save new state. */
199                                 stateManager.saveState(reactionName, newState);
200
201                                 triggerHit = trigger.triggers();
202                         } else {
203                                 /* save first or error state. */
204                                 stateManager.saveState(reactionName, state);
205                         }
206
207                         /* run action if trigger was hit. */
208                         logger.debug(String.format("Trigger was hit: %s.", triggerHit));
209                         if (triggerHit) {
210                                 logger.info("Executing Action...");
211                                 nextReaction.action().execute(trigger.output(nextReaction));
212                         }
213
214                 }
215         }
216
217 }