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
RevLine 
[628577]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
[1d3563]37#include "Actions/ActionQueue.hpp"
[628577]38
[690741]39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
[46b181]41#include "CodePatterns/Log.hpp"
[628577]42#include "CodePatterns/Singleton_impl.hpp"
43
[415ddd]44#include <boost/date_time/posix_time/posix_time.hpp>
45#include <boost/version.hpp>
[601ef8]46#include <iterator>
[46b181]47#include <string>
48#include <sstream>
[690741]49#include <vector>
50
[0d4168]51#include "Actions/ActionExceptions.hpp"
[6367dd]52#include "Actions/ActionHistory.hpp"
[ed3944]53#include "Actions/ActionRegistry.hpp"
[0d4168]54#include "World.hpp"
[ed3944]55
[628577]56using namespace MoleCuilder;
57
[29b52b]58const Action* ActionQueue::_lastchangedaction = NULL;
59
[ed3944]60ActionQueue::ActionQueue() :
[29b52b]61 Observable("ActionQueue"),
[6367dd]62 AR(new ActionRegistry()),
[af5384]63 history(new ActionHistory),
[f3db60]64 lastActionOk(true),
[601ef8]65 CurrentAction(0),
[a87d1e2]66#ifdef HAVE_ACTION_THREAD
[415ddd]67 run_thread(boost::bind(&ActionQueue::run, this)),
[f3db60]68 run_thread_isIdle(true),
[74459a]69#endif
[f3db60]70 dryrun_flag(false)
[29b52b]71{
72 // channels of observable
73 Channels *OurChannel = new Channels;
[574d377]74 Observable::insertNotificationChannel( std::make_pair(static_cast<Observable *>(this), OurChannel) );
[29b52b]75 // add instance for each notification type
76 for (size_t type = 0; type < NotificationType_MAX; ++type)
77 OurChannel->addChannel(type);
78}
[628577]79
80ActionQueue::~ActionQueue()
[ed3944]81{
[74459a]82#ifdef HAVE_ACTION_THREAD
[415ddd]83 stop();
[601ef8]84
85 clearTempQueue();
[74459a]86#endif
[415ddd]87
[7f1a1a]88 clearQueue();
[af5384]89
[6367dd]90 delete history;
[ed3944]91 delete AR;
92}
[628577]93
[f54cda]94void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
[05c989]95{
[10aee4]96 const Action & registryaction = AR->getActionByName(name);
97 queueAction(&registryaction, state);
[f54cda]98}
99
[7f1a1a]100void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
[f54cda]101{
[af5384]102 Action *newaction = _action->clone(state);
103 newaction->prepare(state);
[74459a]104#ifdef HAVE_ACTION_THREAD
[415ddd]105 mtx_queue.lock();
[74459a]106#endif
[7fc447]107 actionqueue.push_back( newaction );
[74459a]108#ifndef HAVE_ACTION_THREAD
109 try {
[a87d1e2]110 if (!isDryRun(newaction)) {
111 CurrentAction = actionqueue.size()-1;
[f3db60]112 newaction->call();
[a87d1e2]113 CurrentAction = actionqueue.size();
114 }
[a61dbb]115 lastActionOk = true;
[74459a]116 } catch(ActionFailureException &e) {
117 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
118 World::getInstance().setExitFlag(5);
[601ef8]119 clearQueue(actionqueue.size()-1);
[a61dbb]120 lastActionOk = false;
[601ef8]121 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]122 } catch (std::exception &e) {
123 pushStatus("FAIL: General exception caught, aborting.");
124 World::getInstance().setExitFlag(134);
[601ef8]125 clearQueue(actionqueue.size()-1);
[11d433]126 lastActionOk = false;
[601ef8]127 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[74459a]128 }
[cfb9c5]129 if (lastActionOk) {
130 OBSERVE;
131 NOTIFY(ActionQueued);
132 _lastchangedaction = newaction;
133 }
[74459a]134#else
[415ddd]135 mtx_queue.unlock();
[a87d1e2]136 setRunThreadIdle(isIdle());
[74459a]137#endif
[05c989]138}
139
[975b83]140void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
141{
[74459a]142#ifndef HAVE_ACTION_THREAD
143 queueAction(_action, state);
144#else
[415ddd]145 Action *newaction = _action->clone(state);
146 newaction->prepare(state);
147 mtx_queue.lock();
148 tempqueue.push_back( newaction );
[a87d1e2]149 const bool tempqueue_notempty = !tempqueue.empty();
[415ddd]150 mtx_queue.unlock();
[a87d1e2]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);
[74459a]159#endif
[a87d1e2]160 bool status = (CurrentAction == actionqueue.size());
161 return status;
[415ddd]162}
163
[74459a]164#ifdef HAVE_ACTION_THREAD
[415ddd]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
[d93b4b3]174 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
[415ddd]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();
[a87d1e2]185 bool status = !isIdle();
[415ddd]186 while (status) {
187 // boost::this_thread::disable_interruption di;
188 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
189 try {
[f3db60]190 if (!isDryRun(actionqueue[CurrentAction]))
191 actionqueue[CurrentAction]->call();
[0b6b77]192 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
[a61dbb]193 lastActionOk = true;
[415ddd]194 } catch(ActionFailureException &e) {
[0b6b77]195 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
[415ddd]196 World::getInstance().setExitFlag(5);
[601ef8]197 clearQueue(CurrentAction);
198 clearTempQueue();
[a61dbb]199 lastActionOk = false;
[601ef8]200 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]201 } catch (std::exception &e) {
202 pushStatus("FAIL: General exception caught, aborting.");
203 World::getInstance().setExitFlag(134);
[601ef8]204 clearQueue(CurrentAction);
205 clearTempQueue();
[d8255b]206 lastActionOk = false;
[601ef8]207 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[415ddd]208 }
[cfb9c5]209 if (lastActionOk) {
210 OBSERVE;
211 NOTIFY(ActionQueued);
212 _lastchangedaction = actionqueue[CurrentAction];
[601ef8]213 mtx_queue.lock();
214 CurrentAction++;
215 mtx_queue.unlock();
[cfb9c5]216 }
[cadaa0]217 if (lastActionOk) {
218 OBSERVE;
219 NOTIFY(ActionQueued);
220 _lastchangedaction = actionqueue[CurrentAction];
221 }
[415ddd]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();
[a87d1e2]229 status = !isIdle();
[415ddd]230 }
[a87d1e2]231 mtx_queue.lock();
232 const bool tempqueue_notempty = !tempqueue.empty();
233 mtx_queue.unlock();
234 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
[415ddd]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}
[74459a]258#endif
[415ddd]259
[74459a]260#ifdef HAVE_ACTION_THREAD
[415ddd]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();
[975b83]267}
[74459a]268#endif
[975b83]269
[10aee4]270const Action& ActionQueue::getActionByName(const std::string &name)
[1d3563]271{
[ed3944]272 return AR->getActionByName(name);
[1d3563]273}
274
[a6ceab]275bool ActionQueue::isActionKnownByName(const std::string &name) const
[1d3563]276{
[ed3944]277 return AR->isActionPresentByName(name);
[1d3563]278}
279
[126867]280void ActionQueue::registerAction(Action *_action)
281{
282 AR->registerInstance(_action);
283}
284
[46b181]285void ActionQueue::outputAsCLI(std::ostream &output) const
286{
[7fc447]287 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
288 iter != actionqueue.end();
[46b181]289 ++iter) {
[bad589]290 // skip store-session in printed list
[12d946]291 if ( ((*iter)->getName() != std::string("store-session"))
292 && ((*iter)->getName() != std::string("load-session"))) {
[7fc447]293 if (iter != actionqueue.begin())
[bad589]294 output << " ";
295 (*iter)->outputAsCLI(output);
296 }
[46b181]297 }
298 output << std::endl;
299}
300
[477012]301void ActionQueue::outputAsPython(std::ostream &output) const
302{
303 const std::string prefix("pyMoleCuilder");
304 output << "import " << prefix << std::endl;
[9e4655]305 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
[7fc447]306 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
307 iter != actionqueue.end();
[477012]308 ++iter) {
309 // skip store-session in printed list
[12d946]310 if ( ((*iter)->getName() != std::string("store-session"))
311 && ((*iter)->getName() != std::string("load-session")))
[477012]312 (*iter)->outputAsPython(output, prefix);
313 }
[9e4655]314 output << "# =========================== Stored Session END ===========================" << std::endl;
[477012]315}
316
[a6ceab]317const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
[690741]318{
319 // this const_cast is just required as long as we have a non-const getActionByName
[10aee4]320 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
321 return action.Traits;
[690741]322}
323
[6367dd]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
[601ef8]334void ActionQueue::clearQueue(const size_t _fromAction)
[7f1a1a]335{
[601ef8]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)
[7f1a1a]344 delete *iter;
[601ef8]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{
[7f1a1a]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 }
[601ef8]362}
363
364void ActionQueue::setRunThreadIdle(const bool _flag)
365{
[06b5df]366 {
367 boost::unique_lock<boost::mutex> lock(mtx_idle);
[601ef8]368 run_thread_isIdle = _flag;
[06b5df]369 }
[7f1a1a]370}
[601ef8]371#endif
[6367dd]372
[690741]373const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
374{
375 ActionTokens_t returnlist;
376
377 returnlist.insert(
378 returnlist.end(),
[ed3944]379 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
380 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
[690741]381
382 return returnlist;
383}
384
[6367dd]385void ActionQueue::undoLast()
386{
387 history->undoLast();
388}
389
[c01fec]390bool ActionQueue::canUndo() const
391{
392 return history->hasUndo();
393}
394
[6367dd]395void ActionQueue::redoLast()
396{
397 history->redoLast();
398}
399
[c01fec]400bool ActionQueue::canRedo() const
401{
402 return history->hasRedo();
403}
404
[f3db60]405bool ActionQueue::isDryRun(const Action *_nextaction) const
406{
407 bool status = dryrun_flag;
408 status &= (_nextaction->getName() != "no-dry-run");
409 return status;
410}
[6367dd]411
[628577]412CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.