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