source: src/Actions/ActionQueue.cpp@ 5169d1b

Candidate_v1.7.1 stable v1.7.1
Last change on this file since 5169d1b 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
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", NotificationType_MAX),
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
76ActionQueue::~ActionQueue()
77{
78#ifdef HAVE_ACTION_THREAD
79 stop();
80
81 clearTempQueue();
82#endif
83
84 clearQueue();
85
86 delete history;
87 delete AR;
88}
89
90void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
91{
92 const Action & registryaction = AR->getActionByName(name);
93 queueAction(&registryaction, state);
94}
95
96void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
97{
98 Action *newaction = _action->clone(state);
99 newaction->prepare(state);
100#ifdef HAVE_ACTION_THREAD
101 mtx_queue.lock();
102#endif
103 actionqueue.push_back( newaction );
104#ifndef HAVE_ACTION_THREAD
105 try {
106 if (!isDryRun(newaction)) {
107 CurrentAction = actionqueue.size()-1;
108 newaction->call();
109 CurrentAction = actionqueue.size();
110 }
111 lastActionOk = true;
112 } catch(ActionFailureException &e) {
113 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
114 World::getInstance().setExitFlag(5);
115 clearQueue(actionqueue.size()-1);
116 lastActionOk = false;
117 std::cerr << "Remaining Actions cleared from queue." << std::endl;
118 } catch (std::exception &e) {
119 pushStatus("FAIL: General exception caught, aborting.");
120 World::getInstance().setExitFlag(134);
121 clearQueue(actionqueue.size()-1);
122 lastActionOk = false;
123 std::cerr << "Remaining Actions cleared from queue." << std::endl;
124 }
125 if (lastActionOk) {
126 OBSERVE;
127 NOTIFY(ActionQueued);
128 _lastchangedaction = newaction;
129 }
130#else
131 mtx_queue.unlock();
132 setRunThreadIdle(isIdle());
133#endif
134}
135
136void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
137{
138#ifndef HAVE_ACTION_THREAD
139 queueAction(_action, state);
140#else
141 Action *newaction = _action->clone(state);
142 newaction->prepare(state);
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 }
149 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
150#endif
151}
152
153bool ActionQueue::isIdle() const
154{
155#ifdef HAVE_ACTION_THREAD
156 boost::recursive_mutex::scoped_lock lock(mtx_queue);
157#endif
158 bool status = (CurrentAction == actionqueue.size());
159 return status;
160}
161
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{
186#ifdef HAVE_ACTION_THREAD
187 boost::recursive_mutex::scoped_lock lock(mtx_queue);
188#endif
189 return *const_cast<const Action *>(actionqueue[CurrentAction]);
190}
191
192#ifdef HAVE_ACTION_THREAD
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
202 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
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();
211 bool status = !isIdle();
212 while (status) {
213 // boost::this_thread::disable_interruption di;
214 try {
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.");
226 lastActionOk = true;
227 } catch(ActionFailureException &e) {
228 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
229 World::getInstance().setExitFlag(5);
230 clearQueue(CurrentAction);
231 clearTempQueue();
232 lastActionOk = false;
233 std::cerr << "Remaining Actions cleared from queue." << std::endl;
234 } catch (std::exception &e) {
235 pushStatus("FAIL: General exception caught, aborting.");
236 World::getInstance().setExitFlag(134);
237 clearQueue(CurrentAction);
238 clearTempQueue();
239 lastActionOk = false;
240 std::cerr << "Remaining Actions cleared from queue." << std::endl;
241 }
242 if (lastActionOk) {
243 OBSERVE;
244 NOTIFY(ActionQueued);
245 stepOnToNextAction();
246 }
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();
251 status = !isIdle();
252 }
253 bool tempqueue_notempty;
254 {
255 boost::recursive_mutex::scoped_lock lock(mtx_queue);
256 tempqueue_notempty = !tempqueue.empty();
257 }
258 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
259 cond_idle.notify_one();
260// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
261 } while (!Interrupted);
262}
263
264void ActionQueue::stepOnToNextAction()
265{
266 boost::recursive_mutex::scoped_lock lock(mtx_queue);
267 _lastchangedaction = actionqueue[CurrentAction];
268 CurrentAction++;
269}
270
271void ActionQueue::insertTempQueue()
272{
273 if (!tempqueue.empty()) {
274 // access actionqueue, hence using mutex
275 boost::recursive_mutex::scoped_lock lock(mtx_queue);
276 actionqueue.insert( actionqueue.end(), tempqueue.begin(), tempqueue.end() );
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}
289#endif
290
291#ifdef HAVE_ACTION_THREAD
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();
298}
299#endif
300
301const Action& ActionQueue::getActionByName(const std::string &name)
302{
303 return AR->getActionByName(name);
304}
305
306bool ActionQueue::isActionKnownByName(const std::string &name) const
307{
308 return AR->isActionPresentByName(name);
309}
310
311void ActionQueue::registerAction(Action *_action)
312{
313 AR->registerInstance(_action);
314}
315
316void ActionQueue::outputAsCLI(std::ostream &output) const
317{
318 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
319 iter != actionqueue.end();
320 ++iter) {
321 // skip store-session in printed list
322 if ( ((*iter)->getName() != std::string("store-session"))
323 && ((*iter)->getName() != std::string("load-session"))) {
324 if (iter != actionqueue.begin())
325 output << " ";
326 (*iter)->outputAsCLI(output);
327 }
328 }
329 output << std::endl;
330}
331
332void ActionQueue::outputAsPython(std::ostream &output) const
333{
334 const std::string prefix("pyMoleCuilder");
335 output << "import " << prefix << std::endl;
336 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
337 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
338 iter != actionqueue.end();
339 ++iter) {
340 // skip store-session in printed list
341 if ( ((*iter)->getName() != std::string("store-session"))
342 && ((*iter)->getName() != std::string("load-session")))
343 (*iter)->outputAsPython(output, prefix);
344 }
345 output << "# =========================== Stored Session END ===========================" << std::endl;
346}
347
348const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
349{
350 // this const_cast is just required as long as we have a non-const getActionByName
351 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
352 return action.Traits;
353}
354
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
365void ActionQueue::clearQueue(const size_t _fromAction)
366{
367#ifdef HAVE_ACTION_THREAD
368 boost::recursive_mutex::scoped_lock lock(mtx_queue);
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)
375 delete *iter;
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{
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 }
392}
393
394void ActionQueue::setRunThreadIdle(const bool _flag)
395{
396 {
397 boost::unique_lock<boost::mutex> lock(mtx_idle);
398 run_thread_isIdle = _flag;
399 }
400}
401#endif
402
403const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
404{
405 ActionTokens_t returnlist;
406
407 returnlist.insert(
408 returnlist.end(),
409 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
410 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
411
412 return returnlist;
413}
414
415void ActionQueue::undoLast()
416{
417 history->undoLast();
418}
419
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
433bool ActionQueue::canUndo() const
434{
435 return history->hasUndo();
436}
437
438void ActionQueue::redoLast()
439{
440 history->redoLast();
441}
442
443bool ActionQueue::canRedo() const
444{
445 return history->hasRedo();
446}
447
448bool ActionQueue::isDryRun(const Action *_nextaction) const
449{
450 bool status = dryrun_flag;
451 status &= (_nextaction->getName() != "no-dry-run");
452 return status;
453}
454
455CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.