source: src/Actions/ActionQueue.cpp@ 0427d1

Candidate_v1.7.0 stable
Last change on this file since 0427d1 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
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/thread/recursive_mutex.hpp>
46#include <boost/version.hpp>
47#include <iterator>
48#include <string>
49#include <sstream>
50#include <vector>
51
52#include "Actions/ActionExceptions.hpp"
53#include "Actions/ActionHistory.hpp"
54#include "Actions/ActionRegistry.hpp"
55#include "Actions/MakroAction.hpp"
56#include "Actions/Process.hpp"
57#include "World.hpp"
58
59using namespace MoleCuilder;
60
61const Action* ActionQueue::_lastchangedaction = NULL;
62
63ActionQueue::ActionQueue() :
64 Observable("ActionQueue"),
65 AR(new ActionRegistry()),
66 history(new ActionHistory),
67 lastActionOk(true),
68 CurrentAction(0),
69#ifdef HAVE_ACTION_THREAD
70 run_thread(boost::bind(&ActionQueue::run, this)),
71 run_thread_isIdle(true),
72#endif
73 dryrun_flag(false)
74{
75 // channels of observable
76 Channels *OurChannel = new Channels;
77 Observable::insertNotificationChannel( std::make_pair(static_cast<Observable *>(this), OurChannel) );
78 // add instance for each notification type
79 for (size_t type = 0; type < NotificationType_MAX; ++type)
80 OurChannel->addChannel(type);
81}
82
83ActionQueue::~ActionQueue()
84{
85#ifdef HAVE_ACTION_THREAD
86 stop();
87
88 clearTempQueue();
89#endif
90
91 clearQueue();
92
93 delete history;
94 delete AR;
95}
96
97void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
98{
99 const Action & registryaction = AR->getActionByName(name);
100 queueAction(&registryaction, state);
101}
102
103void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
104{
105 Action *newaction = _action->clone(state);
106 newaction->prepare(state);
107#ifdef HAVE_ACTION_THREAD
108 mtx_queue.lock();
109#endif
110 actionqueue.push_back( newaction );
111#ifndef HAVE_ACTION_THREAD
112 try {
113 if (!isDryRun(newaction)) {
114 CurrentAction = actionqueue.size()-1;
115 newaction->call();
116 CurrentAction = actionqueue.size();
117 }
118 lastActionOk = true;
119 } catch(ActionFailureException &e) {
120 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
121 World::getInstance().setExitFlag(5);
122 clearQueue(actionqueue.size()-1);
123 lastActionOk = false;
124 std::cerr << "Remaining Actions cleared from queue." << std::endl;
125 } catch (std::exception &e) {
126 pushStatus("FAIL: General exception caught, aborting.");
127 World::getInstance().setExitFlag(134);
128 clearQueue(actionqueue.size()-1);
129 lastActionOk = false;
130 std::cerr << "Remaining Actions cleared from queue." << std::endl;
131 }
132 if (lastActionOk) {
133 OBSERVE;
134 NOTIFY(ActionQueued);
135 _lastchangedaction = newaction;
136 }
137#else
138 mtx_queue.unlock();
139 setRunThreadIdle(isIdle());
140#endif
141}
142
143void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
144{
145#ifndef HAVE_ACTION_THREAD
146 queueAction(_action, state);
147#else
148 Action *newaction = _action->clone(state);
149 newaction->prepare(state);
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 }
156 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
157#endif
158}
159
160bool ActionQueue::isIdle() const
161{
162#ifdef HAVE_ACTION_THREAD
163 boost::recursive_mutex::scoped_lock lock(mtx_queue);
164#endif
165 bool status = (CurrentAction == actionqueue.size());
166 return status;
167}
168
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{
193#ifdef HAVE_ACTION_THREAD
194 boost::recursive_mutex::scoped_lock lock(mtx_queue);
195#endif
196 return *const_cast<const Action *>(actionqueue[CurrentAction]);
197}
198
199#ifdef HAVE_ACTION_THREAD
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
209 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
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();
218 bool status = !isIdle();
219 while (status) {
220 // boost::this_thread::disable_interruption di;
221 try {
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.");
233 lastActionOk = true;
234 } catch(ActionFailureException &e) {
235 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
236 World::getInstance().setExitFlag(5);
237 clearQueue(CurrentAction);
238 clearTempQueue();
239 lastActionOk = false;
240 std::cerr << "Remaining Actions cleared from queue." << std::endl;
241 } catch (std::exception &e) {
242 pushStatus("FAIL: General exception caught, aborting.");
243 World::getInstance().setExitFlag(134);
244 clearQueue(CurrentAction);
245 clearTempQueue();
246 lastActionOk = false;
247 std::cerr << "Remaining Actions cleared from queue." << std::endl;
248 }
249 if (lastActionOk) {
250 OBSERVE;
251 NOTIFY(ActionQueued);
252 stepOnToNextAction();
253 }
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();
258 status = !isIdle();
259 }
260 bool tempqueue_notempty;
261 {
262 boost::recursive_mutex::scoped_lock lock(mtx_queue);
263 tempqueue_notempty = !tempqueue.empty();
264 }
265 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
266 cond_idle.notify_one();
267// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
268 } while (!Interrupted);
269}
270
271void ActionQueue::stepOnToNextAction()
272{
273 boost::recursive_mutex::scoped_lock lock(mtx_queue);
274 _lastchangedaction = actionqueue[CurrentAction];
275 CurrentAction++;
276}
277
278void ActionQueue::insertTempQueue()
279{
280 if (!tempqueue.empty()) {
281 // access actionqueue, hence using mutex
282 boost::recursive_mutex::scoped_lock lock(mtx_queue);
283 actionqueue.insert( actionqueue.end(), tempqueue.begin(), tempqueue.end() );
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}
296#endif
297
298#ifdef HAVE_ACTION_THREAD
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();
305}
306#endif
307
308const Action& ActionQueue::getActionByName(const std::string &name)
309{
310 return AR->getActionByName(name);
311}
312
313bool ActionQueue::isActionKnownByName(const std::string &name) const
314{
315 return AR->isActionPresentByName(name);
316}
317
318void ActionQueue::registerAction(Action *_action)
319{
320 AR->registerInstance(_action);
321}
322
323void ActionQueue::outputAsCLI(std::ostream &output) const
324{
325 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
326 iter != actionqueue.end();
327 ++iter) {
328 // skip store-session in printed list
329 if ( ((*iter)->getName() != std::string("store-session"))
330 && ((*iter)->getName() != std::string("load-session"))) {
331 if (iter != actionqueue.begin())
332 output << " ";
333 (*iter)->outputAsCLI(output);
334 }
335 }
336 output << std::endl;
337}
338
339void ActionQueue::outputAsPython(std::ostream &output) const
340{
341 const std::string prefix("pyMoleCuilder");
342 output << "import " << prefix << std::endl;
343 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
344 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
345 iter != actionqueue.end();
346 ++iter) {
347 // skip store-session in printed list
348 if ( ((*iter)->getName() != std::string("store-session"))
349 && ((*iter)->getName() != std::string("load-session")))
350 (*iter)->outputAsPython(output, prefix);
351 }
352 output << "# =========================== Stored Session END ===========================" << std::endl;
353}
354
355const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
356{
357 // this const_cast is just required as long as we have a non-const getActionByName
358 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
359 return action.Traits;
360}
361
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
372void ActionQueue::clearQueue(const size_t _fromAction)
373{
374#ifdef HAVE_ACTION_THREAD
375 boost::recursive_mutex::scoped_lock lock(mtx_queue);
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)
382 delete *iter;
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{
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 }
399}
400
401void ActionQueue::setRunThreadIdle(const bool _flag)
402{
403 {
404 boost::unique_lock<boost::mutex> lock(mtx_idle);
405 run_thread_isIdle = _flag;
406 }
407}
408#endif
409
410const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
411{
412 ActionTokens_t returnlist;
413
414 returnlist.insert(
415 returnlist.end(),
416 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
417 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
418
419 return returnlist;
420}
421
422void ActionQueue::undoLast()
423{
424 history->undoLast();
425}
426
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
440bool ActionQueue::canUndo() const
441{
442 return history->hasUndo();
443}
444
445void ActionQueue::redoLast()
446{
447 history->redoLast();
448}
449
450bool ActionQueue::canRedo() const
451{
452 return history->hasRedo();
453}
454
455bool ActionQueue::isDryRun(const Action *_nextaction) const
456{
457 bool status = dryrun_flag;
458 status &= (_nextaction->getName() != "no-dry-run");
459 return status;
460}
461
462CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.