source: src/Actions/ActionQueue.cpp@ cadaa0

Last change on this file since cadaa0 was cadaa0, checked in by Frederik Heber <heber@…>, 9 years ago

FIX: Setting ActionQueue::_lastchangedaction without heeding whether Action failed is bad.

  • causes segfault when notification informs about change and _lastchangeaction is still NULL (as the very first Action failed).
  • we now only notify when action succeeded.
  • Property mode set to 100644
File size: 11.4 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 Frederik Heber. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * ActionQueue.cpp
25 *
26 * Created on: Aug 16, 2013
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include "Actions/ActionQueue.hpp"
38
39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
41#include "CodePatterns/Log.hpp"
42#include "CodePatterns/Singleton_impl.hpp"
43
44#include <boost/date_time/posix_time/posix_time.hpp>
45#include <boost/version.hpp>
46#include <iterator>
47#include <string>
48#include <sstream>
49#include <vector>
50
51#include "Actions/ActionExceptions.hpp"
52#include "Actions/ActionHistory.hpp"
53#include "Actions/ActionRegistry.hpp"
54#include "World.hpp"
55
56using namespace MoleCuilder;
57
58const Action* ActionQueue::_lastchangedaction = NULL;
59
60ActionQueue::ActionQueue() :
61 Observable("ActionQueue"),
62 AR(new ActionRegistry()),
63 history(new ActionHistory),
64 lastActionOk(true),
65 CurrentAction(0),
66#ifdef HAVE_ACTION_THREAD
67 run_thread(boost::bind(&ActionQueue::run, this)),
68 run_thread_isIdle(true),
69#endif
70 dryrun_flag(false)
71{
72 // channels of observable
73 Channels *OurChannel = new Channels;
74 Observable::insertNotificationChannel( std::make_pair(static_cast<Observable *>(this), OurChannel) );
75 // add instance for each notification type
76 for (size_t type = 0; type < NotificationType_MAX; ++type)
77 OurChannel->addChannel(type);
78}
79
80ActionQueue::~ActionQueue()
81{
82#ifdef HAVE_ACTION_THREAD
83 stop();
84
85 clearTempQueue();
86#endif
87
88 clearQueue();
89
90 delete history;
91 delete AR;
92}
93
94void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
95{
96 const Action & registryaction = AR->getActionByName(name);
97 queueAction(&registryaction, state);
98}
99
100void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
101{
102 Action *newaction = _action->clone(state);
103 newaction->prepare(state);
104#ifdef HAVE_ACTION_THREAD
105 mtx_queue.lock();
106#endif
107 actionqueue.push_back( newaction );
108#ifndef HAVE_ACTION_THREAD
109 try {
110 if (!isDryRun(newaction)) {
111 CurrentAction = actionqueue.size()-1;
112 newaction->call();
113 CurrentAction = actionqueue.size();
114 }
115 lastActionOk = true;
116 } catch(ActionFailureException &e) {
117 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
118 World::getInstance().setExitFlag(5);
119 clearQueue(actionqueue.size()-1);
120 lastActionOk = false;
121 std::cerr << "Remaining Actions cleared from queue." << std::endl;
122 } catch (std::exception &e) {
123 pushStatus("FAIL: General exception caught, aborting.");
124 World::getInstance().setExitFlag(134);
125 clearQueue(actionqueue.size()-1);
126 lastActionOk = false;
127 std::cerr << "Remaining Actions cleared from queue." << std::endl;
128 }
129 if (lastActionOk) {
130 OBSERVE;
131 NOTIFY(ActionQueued);
132 _lastchangedaction = newaction;
133 }
134#else
135 mtx_queue.unlock();
136 setRunThreadIdle(isIdle());
137#endif
138}
139
140void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
141{
142#ifndef HAVE_ACTION_THREAD
143 queueAction(_action, state);
144#else
145 Action *newaction = _action->clone(state);
146 newaction->prepare(state);
147 mtx_queue.lock();
148 tempqueue.push_back( newaction );
149 const bool tempqueue_notempty = !tempqueue.empty();
150 mtx_queue.unlock();
151 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
152#endif
153}
154
155bool ActionQueue::isIdle() const
156{
157#ifdef HAVE_ACTION_THREAD
158 boost::unique_lock<boost::mutex> lock(mtx_queue);
159#endif
160 bool status = (CurrentAction == actionqueue.size());
161 return status;
162}
163
164#ifdef HAVE_ACTION_THREAD
165void ActionQueue::run()
166{
167 bool Interrupted = false;
168 do {
169 // sleep for some time and wait for queue to fill up again
170 try {
171#if BOOST_VERSION < 105000
172 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
173#else
174 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
175#endif
176 } catch(boost::thread_interrupted &e) {
177 LOG(2, "INFO: ActionQueue has received stop signal.");
178 Interrupted = true;
179 }
180// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
181 // call all currently present Actions
182 mtx_queue.lock();
183 insertTempQueue();
184 mtx_queue.unlock();
185 bool status = !isIdle();
186 while (status) {
187 // boost::this_thread::disable_interruption di;
188 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
189 try {
190 if (!isDryRun(actionqueue[CurrentAction]))
191 actionqueue[CurrentAction]->call();
192 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
193 lastActionOk = true;
194 } catch(ActionFailureException &e) {
195 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
196 World::getInstance().setExitFlag(5);
197 clearQueue(CurrentAction);
198 clearTempQueue();
199 lastActionOk = false;
200 std::cerr << "Remaining Actions cleared from queue." << std::endl;
201 } catch (std::exception &e) {
202 pushStatus("FAIL: General exception caught, aborting.");
203 World::getInstance().setExitFlag(134);
204 clearQueue(CurrentAction);
205 clearTempQueue();
206 lastActionOk = false;
207 std::cerr << "Remaining Actions cleared from queue." << std::endl;
208 }
209 if (lastActionOk) {
210 OBSERVE;
211 NOTIFY(ActionQueued);
212 _lastchangedaction = actionqueue[CurrentAction];
213 mtx_queue.lock();
214 CurrentAction++;
215 mtx_queue.unlock();
216 }
217 if (lastActionOk) {
218 OBSERVE;
219 NOTIFY(ActionQueued);
220 _lastchangedaction = actionqueue[CurrentAction];
221 }
222 // access actionqueue, hence using mutex
223 mtx_queue.lock();
224 // insert new actions (before [CurrentAction]) if they have been spawned
225 // we must have an extra vector for this, as we cannot change actionqueue
226 // while an action instance is "in-use"
227 insertTempQueue();
228 mtx_queue.unlock();
229 status = !isIdle();
230 }
231 mtx_queue.lock();
232 const bool tempqueue_notempty = !tempqueue.empty();
233 mtx_queue.unlock();
234 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
235 cond_idle.notify_one();
236// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
237 } while (!Interrupted);
238}
239
240void ActionQueue::insertTempQueue()
241{
242 if (!tempqueue.empty()) {
243 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
244 std::advance(InsertionIter, CurrentAction);
245 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
246 tempqueue.clear();
247 }
248}
249
250void ActionQueue::wait()
251{
252 boost::unique_lock<boost::mutex> lock(mtx_idle);
253 while(!run_thread_isIdle)
254 {
255 cond_idle.wait(lock);
256 }
257}
258#endif
259
260#ifdef HAVE_ACTION_THREAD
261void ActionQueue::stop()
262{
263 // notify actionqueue thread that we wish to terminate
264 run_thread.interrupt();
265 // wait till it ends
266 run_thread.join();
267}
268#endif
269
270const Action& ActionQueue::getActionByName(const std::string &name)
271{
272 return AR->getActionByName(name);
273}
274
275bool ActionQueue::isActionKnownByName(const std::string &name) const
276{
277 return AR->isActionPresentByName(name);
278}
279
280void ActionQueue::registerAction(Action *_action)
281{
282 AR->registerInstance(_action);
283}
284
285void ActionQueue::outputAsCLI(std::ostream &output) const
286{
287 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
288 iter != actionqueue.end();
289 ++iter) {
290 // skip store-session in printed list
291 if ( ((*iter)->getName() != std::string("store-session"))
292 && ((*iter)->getName() != std::string("load-session"))) {
293 if (iter != actionqueue.begin())
294 output << " ";
295 (*iter)->outputAsCLI(output);
296 }
297 }
298 output << std::endl;
299}
300
301void ActionQueue::outputAsPython(std::ostream &output) const
302{
303 const std::string prefix("pyMoleCuilder");
304 output << "import " << prefix << std::endl;
305 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
306 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
307 iter != actionqueue.end();
308 ++iter) {
309 // skip store-session in printed list
310 if ( ((*iter)->getName() != std::string("store-session"))
311 && ((*iter)->getName() != std::string("load-session")))
312 (*iter)->outputAsPython(output, prefix);
313 }
314 output << "# =========================== Stored Session END ===========================" << std::endl;
315}
316
317const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
318{
319 // this const_cast is just required as long as we have a non-const getActionByName
320 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
321 return action.Traits;
322}
323
324void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
325{
326 history->addElement(_Action, _state);
327}
328
329void ActionQueue::clear()
330{
331 history->clear();
332}
333
334void ActionQueue::clearQueue(const size_t _fromAction)
335{
336#ifdef HAVE_ACTION_THREAD
337 mtx_queue.lock();
338#endif
339 LOG(1, "Removing all Actions from position " << _fromAction << " onward.");
340 // free all actions still to be called contained in actionqueue
341 ActionQueue_t::iterator inititer = actionqueue.begin();
342 std::advance(inititer, _fromAction);
343 for (ActionQueue_t::iterator iter = inititer; iter != actionqueue.end(); ++iter)
344 delete *iter;
345 actionqueue.erase(inititer, actionqueue.end());
346 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
347#ifdef HAVE_ACTION_THREAD
348 CurrentAction = actionqueue.size();
349 mtx_queue.unlock();
350#endif
351}
352
353#ifdef HAVE_ACTION_THREAD
354void ActionQueue::clearTempQueue()
355{
356 // free all actions contained in tempqueue
357 for (ActionQueue_t::iterator iter = tempqueue.begin();
358 !tempqueue.empty(); iter = tempqueue.begin()) {
359 delete *iter;
360 tempqueue.erase(iter);
361 }
362}
363
364void ActionQueue::setRunThreadIdle(const bool _flag)
365{
366 {
367 boost::unique_lock<boost::mutex> lock(mtx_idle);
368 run_thread_isIdle = _flag;
369 }
370}
371#endif
372
373const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
374{
375 ActionTokens_t returnlist;
376
377 returnlist.insert(
378 returnlist.end(),
379 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
380 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
381
382 return returnlist;
383}
384
385void ActionQueue::undoLast()
386{
387 history->undoLast();
388}
389
390bool ActionQueue::canUndo() const
391{
392 return history->hasUndo();
393}
394
395void ActionQueue::redoLast()
396{
397 history->redoLast();
398}
399
400bool ActionQueue::canRedo() const
401{
402 return history->hasRedo();
403}
404
405bool ActionQueue::isDryRun(const Action *_nextaction) const
406{
407 bool status = dryrun_flag;
408 status &= (_nextaction->getName() != "no-dry-run");
409 return status;
410}
411
412CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.