source: src/Actions/ActionQueue.cpp@ c742bb1

Candidate_v1.7.1 stable
Last change on this file since c742bb1 was c8cb0d, checked in by Frederik Heber <frederik.heber@…>, 6 weeks ago

Streamlines channel creation in Observables.

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