source: src/Actions/ActionQueue.cpp@ 91c409

Candidate_v1.7.0 stable
Last change on this file since 91c409 was 0427d1, checked in by Frederik Heber <frederik.heber@…>, 20 months ago

FIX: ActionQueue no locked on CurrentAction access.

  • actionqueue[CurrentAction] without mutex locking.
  • getCurrentAction() without mutex locking.
  • extracted stepOnToNextAction().
  • using recursive_mutex instead of normal to allow nested locks.
  • Property mode set to 100644
File size: 12.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
[9eb71b3]35//#include "CodePatterns/MemDebug.hpp"
[628577]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>
[0427d1]45#include <boost/thread/recursive_mutex.hpp>
[415ddd]46#include <boost/version.hpp>
[601ef8]47#include <iterator>
[46b181]48#include <string>
49#include <sstream>
[690741]50#include <vector>
51
[0d4168]52#include "Actions/ActionExceptions.hpp"
[6367dd]53#include "Actions/ActionHistory.hpp"
[ed3944]54#include "Actions/ActionRegistry.hpp"
[559293]55#include "Actions/MakroAction.hpp"
56#include "Actions/Process.hpp"
[0d4168]57#include "World.hpp"
[ed3944]58
[628577]59using namespace MoleCuilder;
60
[29b52b]61const Action* ActionQueue::_lastchangedaction = NULL;
62
[ed3944]63ActionQueue::ActionQueue() :
[29b52b]64 Observable("ActionQueue"),
[6367dd]65 AR(new ActionRegistry()),
[af5384]66 history(new ActionHistory),
[f3db60]67 lastActionOk(true),
[601ef8]68 CurrentAction(0),
[a87d1e2]69#ifdef HAVE_ACTION_THREAD
[415ddd]70 run_thread(boost::bind(&ActionQueue::run, this)),
[f3db60]71 run_thread_isIdle(true),
[74459a]72#endif
[f3db60]73 dryrun_flag(false)
[29b52b]74{
75 // channels of observable
76 Channels *OurChannel = new Channels;
[574d377]77 Observable::insertNotificationChannel( std::make_pair(static_cast<Observable *>(this), OurChannel) );
[29b52b]78 // add instance for each notification type
79 for (size_t type = 0; type < NotificationType_MAX; ++type)
80 OurChannel->addChannel(type);
81}
[628577]82
83ActionQueue::~ActionQueue()
[ed3944]84{
[74459a]85#ifdef HAVE_ACTION_THREAD
[415ddd]86 stop();
[601ef8]87
88 clearTempQueue();
[74459a]89#endif
[415ddd]90
[7f1a1a]91 clearQueue();
[af5384]92
[6367dd]93 delete history;
[ed3944]94 delete AR;
95}
[628577]96
[f54cda]97void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
[05c989]98{
[10aee4]99 const Action & registryaction = AR->getActionByName(name);
100 queueAction(&registryaction, state);
[f54cda]101}
102
[7f1a1a]103void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
[f54cda]104{
[af5384]105 Action *newaction = _action->clone(state);
106 newaction->prepare(state);
[74459a]107#ifdef HAVE_ACTION_THREAD
[415ddd]108 mtx_queue.lock();
[74459a]109#endif
[7fc447]110 actionqueue.push_back( newaction );
[74459a]111#ifndef HAVE_ACTION_THREAD
112 try {
[a87d1e2]113 if (!isDryRun(newaction)) {
114 CurrentAction = actionqueue.size()-1;
[f3db60]115 newaction->call();
[a87d1e2]116 CurrentAction = actionqueue.size();
117 }
[a61dbb]118 lastActionOk = true;
[74459a]119 } catch(ActionFailureException &e) {
120 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
121 World::getInstance().setExitFlag(5);
[601ef8]122 clearQueue(actionqueue.size()-1);
[a61dbb]123 lastActionOk = false;
[601ef8]124 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]125 } catch (std::exception &e) {
126 pushStatus("FAIL: General exception caught, aborting.");
127 World::getInstance().setExitFlag(134);
[601ef8]128 clearQueue(actionqueue.size()-1);
[11d433]129 lastActionOk = false;
[601ef8]130 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[74459a]131 }
[cfb9c5]132 if (lastActionOk) {
133 OBSERVE;
134 NOTIFY(ActionQueued);
135 _lastchangedaction = newaction;
136 }
[74459a]137#else
[415ddd]138 mtx_queue.unlock();
[a87d1e2]139 setRunThreadIdle(isIdle());
[74459a]140#endif
[05c989]141}
142
[975b83]143void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
144{
[74459a]145#ifndef HAVE_ACTION_THREAD
146 queueAction(_action, state);
147#else
[415ddd]148 Action *newaction = _action->clone(state);
149 newaction->prepare(state);
[0427d1]150 bool tempqueue_notempty;
151 {
152 boost::recursive_mutex::scoped_lock lock(mtx_queue);
153 tempqueue.push_back( newaction );
154 tempqueue_notempty = !tempqueue.empty();
155 }
[a87d1e2]156 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
157#endif
158}
159
160bool ActionQueue::isIdle() const
161{
162#ifdef HAVE_ACTION_THREAD
[0427d1]163 boost::recursive_mutex::scoped_lock lock(mtx_queue);
[74459a]164#endif
[a87d1e2]165 bool status = (CurrentAction == actionqueue.size());
166 return status;
[415ddd]167}
168
[559293]169bool ActionQueue::isProcess() const
170{
171 if (isIdle())
172 return false;
173 const Process *possibleprocess = dynamic_cast<const Process *>(&getCurrentAction());
174 if (possibleprocess == NULL)
175 return false;
176 else
177 return true;
178}
179
180bool ActionQueue::isMakroAction() const
181{
182 if (isIdle())
183 return false;
184 const MakroAction *possiblemakroaction = dynamic_cast<const MakroAction *>(&getCurrentAction());
185 if (possiblemakroaction == NULL)
186 return false;
187 else
188 return true;
189}
190
191const Action& ActionQueue::getCurrentAction() const
192{
[0427d1]193#ifdef HAVE_ACTION_THREAD
194 boost::recursive_mutex::scoped_lock lock(mtx_queue);
195#endif
[559293]196 return *const_cast<const Action *>(actionqueue[CurrentAction]);
197}
198
[74459a]199#ifdef HAVE_ACTION_THREAD
[415ddd]200void ActionQueue::run()
201{
202 bool Interrupted = false;
203 do {
204 // sleep for some time and wait for queue to fill up again
205 try {
206#if BOOST_VERSION < 105000
207 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
208#else
[d93b4b3]209 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
[415ddd]210#endif
211 } catch(boost::thread_interrupted &e) {
212 LOG(2, "INFO: ActionQueue has received stop signal.");
213 Interrupted = true;
214 }
215// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
216 // call all currently present Actions
217 insertTempQueue();
[a87d1e2]218 bool status = !isIdle();
[415ddd]219 while (status) {
220 // boost::this_thread::disable_interruption di;
221 try {
[0427d1]222 // pick next action to run
223 Action * action_to_run;
224 {
225 boost::recursive_mutex::scoped_lock lock(mtx_queue);
226 action_to_run = actionqueue[CurrentAction];
227 }
228 LOG(0, "Calling Action " << action_to_run->getName() << " ... ");
229 // run action
230 if (!isDryRun(action_to_run))
231 action_to_run->call();
232 pushStatus("SUCCESS: Action "+action_to_run->getName()+" successful.");
[a61dbb]233 lastActionOk = true;
[415ddd]234 } catch(ActionFailureException &e) {
[0b6b77]235 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
[415ddd]236 World::getInstance().setExitFlag(5);
[601ef8]237 clearQueue(CurrentAction);
238 clearTempQueue();
[a61dbb]239 lastActionOk = false;
[601ef8]240 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]241 } catch (std::exception &e) {
242 pushStatus("FAIL: General exception caught, aborting.");
243 World::getInstance().setExitFlag(134);
[601ef8]244 clearQueue(CurrentAction);
245 clearTempQueue();
[d8255b]246 lastActionOk = false;
[601ef8]247 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[415ddd]248 }
[cfb9c5]249 if (lastActionOk) {
250 OBSERVE;
251 NOTIFY(ActionQueued);
[0427d1]252 stepOnToNextAction();
[cfb9c5]253 }
[415ddd]254 // insert new actions (before [CurrentAction]) if they have been spawned
255 // we must have an extra vector for this, as we cannot change actionqueue
256 // while an action instance is "in-use"
257 insertTempQueue();
[a87d1e2]258 status = !isIdle();
[415ddd]259 }
[0427d1]260 bool tempqueue_notempty;
261 {
262 boost::recursive_mutex::scoped_lock lock(mtx_queue);
263 tempqueue_notempty = !tempqueue.empty();
264 }
[a87d1e2]265 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
[415ddd]266 cond_idle.notify_one();
267// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
268 } while (!Interrupted);
269}
270
[0427d1]271void ActionQueue::stepOnToNextAction()
272{
273 boost::recursive_mutex::scoped_lock lock(mtx_queue);
274 _lastchangedaction = actionqueue[CurrentAction];
275 CurrentAction++;
276}
277
[415ddd]278void ActionQueue::insertTempQueue()
279{
280 if (!tempqueue.empty()) {
[0427d1]281 // access actionqueue, hence using mutex
282 boost::recursive_mutex::scoped_lock lock(mtx_queue);
283 actionqueue.insert( actionqueue.end(), tempqueue.begin(), tempqueue.end() );
[415ddd]284 tempqueue.clear();
285 }
286}
287
288void ActionQueue::wait()
289{
290 boost::unique_lock<boost::mutex> lock(mtx_idle);
291 while(!run_thread_isIdle)
292 {
293 cond_idle.wait(lock);
294 }
295}
[74459a]296#endif
[415ddd]297
[74459a]298#ifdef HAVE_ACTION_THREAD
[415ddd]299void ActionQueue::stop()
300{
301 // notify actionqueue thread that we wish to terminate
302 run_thread.interrupt();
303 // wait till it ends
304 run_thread.join();
[975b83]305}
[74459a]306#endif
[975b83]307
[10aee4]308const Action& ActionQueue::getActionByName(const std::string &name)
[1d3563]309{
[ed3944]310 return AR->getActionByName(name);
[1d3563]311}
312
[a6ceab]313bool ActionQueue::isActionKnownByName(const std::string &name) const
[1d3563]314{
[ed3944]315 return AR->isActionPresentByName(name);
[1d3563]316}
317
[126867]318void ActionQueue::registerAction(Action *_action)
319{
320 AR->registerInstance(_action);
321}
322
[46b181]323void ActionQueue::outputAsCLI(std::ostream &output) const
324{
[7fc447]325 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
326 iter != actionqueue.end();
[46b181]327 ++iter) {
[bad589]328 // skip store-session in printed list
[12d946]329 if ( ((*iter)->getName() != std::string("store-session"))
330 && ((*iter)->getName() != std::string("load-session"))) {
[7fc447]331 if (iter != actionqueue.begin())
[bad589]332 output << " ";
333 (*iter)->outputAsCLI(output);
334 }
[46b181]335 }
336 output << std::endl;
337}
338
[477012]339void ActionQueue::outputAsPython(std::ostream &output) const
340{
341 const std::string prefix("pyMoleCuilder");
342 output << "import " << prefix << std::endl;
[9e4655]343 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
[7fc447]344 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
345 iter != actionqueue.end();
[477012]346 ++iter) {
347 // skip store-session in printed list
[12d946]348 if ( ((*iter)->getName() != std::string("store-session"))
349 && ((*iter)->getName() != std::string("load-session")))
[477012]350 (*iter)->outputAsPython(output, prefix);
351 }
[9e4655]352 output << "# =========================== Stored Session END ===========================" << std::endl;
[477012]353}
354
[a6ceab]355const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
[690741]356{
357 // this const_cast is just required as long as we have a non-const getActionByName
[10aee4]358 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
359 return action.Traits;
[690741]360}
361
[6367dd]362void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
363{
364 history->addElement(_Action, _state);
365}
366
367void ActionQueue::clear()
368{
369 history->clear();
370}
371
[601ef8]372void ActionQueue::clearQueue(const size_t _fromAction)
[7f1a1a]373{
[601ef8]374#ifdef HAVE_ACTION_THREAD
[0427d1]375 boost::recursive_mutex::scoped_lock lock(mtx_queue);
[601ef8]376#endif
377 LOG(1, "Removing all Actions from position " << _fromAction << " onward.");
378 // free all actions still to be called contained in actionqueue
379 ActionQueue_t::iterator inititer = actionqueue.begin();
380 std::advance(inititer, _fromAction);
381 for (ActionQueue_t::iterator iter = inititer; iter != actionqueue.end(); ++iter)
[7f1a1a]382 delete *iter;
[601ef8]383 actionqueue.erase(inititer, actionqueue.end());
384 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
385#ifdef HAVE_ACTION_THREAD
386 CurrentAction = actionqueue.size();
387#endif
388}
389
390#ifdef HAVE_ACTION_THREAD
391void ActionQueue::clearTempQueue()
392{
[7f1a1a]393 // free all actions contained in tempqueue
394 for (ActionQueue_t::iterator iter = tempqueue.begin();
395 !tempqueue.empty(); iter = tempqueue.begin()) {
396 delete *iter;
397 tempqueue.erase(iter);
398 }
[601ef8]399}
400
401void ActionQueue::setRunThreadIdle(const bool _flag)
402{
[06b5df]403 {
404 boost::unique_lock<boost::mutex> lock(mtx_idle);
[601ef8]405 run_thread_isIdle = _flag;
[06b5df]406 }
[7f1a1a]407}
[601ef8]408#endif
[6367dd]409
[690741]410const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
411{
412 ActionTokens_t returnlist;
413
414 returnlist.insert(
415 returnlist.end(),
[ed3944]416 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
417 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
[690741]418
419 return returnlist;
420}
421
[6367dd]422void ActionQueue::undoLast()
423{
424 history->undoLast();
425}
426
[0ec9f5]427void ActionQueue::setMark() {
428 history->setMark();
429}
430
431void ActionQueue::unsetMark() {
432 history->unsetMark();
433}
434
435void ActionQueue::undoTillMark()
436{
437 history->undoTillMark();
438}
439
[c01fec]440bool ActionQueue::canUndo() const
441{
442 return history->hasUndo();
443}
444
[6367dd]445void ActionQueue::redoLast()
446{
447 history->redoLast();
448}
449
[c01fec]450bool ActionQueue::canRedo() const
451{
452 return history->hasRedo();
453}
454
[f3db60]455bool ActionQueue::isDryRun(const Action *_nextaction) const
456{
457 bool status = dryrun_flag;
458 status &= (_nextaction->getName() != "no-dry-run");
459 return status;
460}
[6367dd]461
[628577]462CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.