source: src/Actions/ActionQueue.cpp@ b73545

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since b73545 was 11d433, checked in by Frederik Heber <heber@…>, 10 years ago

MEMFIX: ActionQueue was not stopped() when argument parsing failed.

  • this just caused an exception and the ActionQueue thread would be aborted uncleanly. This is only affected --enable-action-thread.
  • CommandLineParser calls ActionQueue::stop() on catching exception.
  • CommandLineParser also rethrows std::exception when parsing of command-line arguments went wrong (not faulty but completely missing values).
  • ActionQueue uses exitflag of 134 on std::exception.
  • Property mode set to 100644
File size: 9.3 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/version.hpp>
46#include <string>
47#include <sstream>
48#include <vector>
49
50#include "Actions/ActionExceptions.hpp"
51#include "Actions/ActionHistory.hpp"
52#include "Actions/ActionRegistry.hpp"
53#include "World.hpp"
54
55using namespace MoleCuilder;
56
57ActionQueue::ActionQueue() :
58 AR(new ActionRegistry()),
59 history(new ActionHistory),
60 CurrentAction(0),
61#ifndef HAVE_ACTION_THREAD
62 lastActionOk(true)
63#else
64 lastActionOk(true),
65 run_thread(boost::bind(&ActionQueue::run, this)),
66 run_thread_isIdle(true)
67#endif
68{}
69
70ActionQueue::~ActionQueue()
71{
72#ifdef HAVE_ACTION_THREAD
73 stop();
74#endif
75
76 clearQueue();
77
78 delete history;
79 delete AR;
80}
81
82void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
83{
84 const Action * const registryaction = AR->getActionByName(name);
85 queueAction(registryaction, state);
86}
87
88void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
89{
90 Action *newaction = _action->clone(state);
91 newaction->prepare(state);
92#ifdef HAVE_ACTION_THREAD
93 mtx_queue.lock();
94#endif
95 actionqueue.push_back( newaction );
96#ifndef HAVE_ACTION_THREAD
97 try {
98 newaction->call();
99 lastActionOk = true;
100 } catch(ActionFailureException &e) {
101 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
102 World::getInstance().setExitFlag(5);
103 clearQueue();
104 lastActionOk = false;
105 std::cerr << "ActionQueue cleared." << std::endl;
106 } catch (std::exception &e) {
107 pushStatus("FAIL: General exception caught, aborting.");
108 World::getInstance().setExitFlag(134);
109 clearQueue();
110 lastActionOk = false;
111 std::cerr << "ActionQueue cleared." << std::endl;
112 }
113#else
114 {
115 boost::lock_guard<boost::mutex> lock(mtx_idle);
116 run_thread_isIdle = (CurrentAction == actionqueue.size());
117 }
118 mtx_queue.unlock();
119#endif
120}
121
122void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
123{
124#ifndef HAVE_ACTION_THREAD
125 queueAction(_action, state);
126#else
127 Action *newaction = _action->clone(state);
128 newaction->prepare(state);
129 mtx_queue.lock();
130 tempqueue.push_back( newaction );
131 {
132 boost::lock_guard<boost::mutex> lock(mtx_idle);
133 run_thread_isIdle = !((CurrentAction != actionqueue.size()) || !tempqueue.empty());
134 }
135 mtx_queue.unlock();
136#endif
137}
138
139#ifdef HAVE_ACTION_THREAD
140void ActionQueue::run()
141{
142 bool Interrupted = false;
143 do {
144 // sleep for some time and wait for queue to fill up again
145 try {
146#if BOOST_VERSION < 105000
147 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
148#else
149 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
150#endif
151 } catch(boost::thread_interrupted &e) {
152 LOG(2, "INFO: ActionQueue has received stop signal.");
153 Interrupted = true;
154 }
155// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
156 // call all currently present Actions
157 mtx_queue.lock();
158 insertTempQueue();
159 bool status = (CurrentAction != actionqueue.size());
160 mtx_queue.unlock();
161 while (status) {
162 // boost::this_thread::disable_interruption di;
163 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
164 try {
165 actionqueue[CurrentAction]->call();
166 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
167 lastActionOk = true;
168 } catch(ActionFailureException &e) {
169 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
170 World::getInstance().setExitFlag(5);
171 clearQueue();
172 lastActionOk = false;
173 std::cerr << "ActionQueue cleared." << std::endl;
174 CurrentAction = (size_t)-1;
175 } catch (std::exception &e) {
176 pushStatus("FAIL: General exception caught, aborting.");
177 World::getInstance().setExitFlag(134);
178 clearQueue();
179 std::cerr << "ActionQueue cleared." << std::endl;
180 CurrentAction = (size_t)-1;
181 }
182 // access actionqueue, hence using mutex
183 mtx_queue.lock();
184 // step on to next action and check for end
185 CurrentAction++;
186 // insert new actions (before [CurrentAction]) if they have been spawned
187 // we must have an extra vector for this, as we cannot change actionqueue
188 // while an action instance is "in-use"
189 insertTempQueue();
190 status = (CurrentAction != actionqueue.size());
191 mtx_queue.unlock();
192 }
193 {
194 boost::lock_guard<boost::mutex> lock(mtx_idle);
195 run_thread_isIdle = !((CurrentAction != actionqueue.size()) || !tempqueue.empty());
196 }
197 cond_idle.notify_one();
198// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
199 } while (!Interrupted);
200}
201#endif
202
203void ActionQueue::insertTempQueue()
204{
205 if (!tempqueue.empty()) {
206 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
207 std::advance(InsertionIter, CurrentAction);
208 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
209 tempqueue.clear();
210 }
211}
212
213#ifdef HAVE_ACTION_THREAD
214void ActionQueue::wait()
215{
216 boost::unique_lock<boost::mutex> lock(mtx_idle);
217 while(!run_thread_isIdle)
218 {
219 cond_idle.wait(lock);
220 }
221}
222#endif
223
224#ifdef HAVE_ACTION_THREAD
225void ActionQueue::stop()
226{
227 // notify actionqueue thread that we wish to terminate
228 run_thread.interrupt();
229 // wait till it ends
230 run_thread.join();
231}
232#endif
233
234Action* ActionQueue::getActionByName(const std::string &name)
235{
236 return AR->getActionByName(name);
237}
238
239bool ActionQueue::isActionKnownByName(const std::string &name) const
240{
241 return AR->isActionPresentByName(name);
242}
243
244void ActionQueue::registerAction(Action *_action)
245{
246 AR->registerInstance(_action);
247}
248
249void ActionQueue::outputAsCLI(std::ostream &output) const
250{
251 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
252 iter != actionqueue.end();
253 ++iter) {
254 // skip store-session in printed list
255 if ( ((*iter)->getName() != std::string("store-session"))
256 && ((*iter)->getName() != std::string("load-session"))) {
257 if (iter != actionqueue.begin())
258 output << " ";
259 (*iter)->outputAsCLI(output);
260 }
261 }
262 output << std::endl;
263}
264
265void ActionQueue::outputAsPython(std::ostream &output) const
266{
267 const std::string prefix("pyMoleCuilder");
268 output << "import " << prefix << std::endl;
269 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
270 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
271 iter != actionqueue.end();
272 ++iter) {
273 // skip store-session in printed list
274 if ( ((*iter)->getName() != std::string("store-session"))
275 && ((*iter)->getName() != std::string("load-session")))
276 (*iter)->outputAsPython(output, prefix);
277 }
278 output << "# =========================== Stored Session END ===========================" << std::endl;
279}
280
281const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
282{
283 // this const_cast is just required as long as we have a non-const getActionByName
284 const Action * const action = const_cast<ActionQueue *>(this)->getActionByName(name);
285 return action->Traits;
286}
287
288void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
289{
290 history->addElement(_Action, _state);
291}
292
293void ActionQueue::clear()
294{
295 history->clear();
296}
297
298void ActionQueue::clearQueue()
299{
300 // free all actions contained in actionqueue
301 for (ActionQueue_t::iterator iter = actionqueue.begin();
302 !actionqueue.empty(); iter = actionqueue.begin()) {
303 delete *iter;
304 actionqueue.erase(iter);
305 }
306 // free all actions contained in tempqueue
307 for (ActionQueue_t::iterator iter = tempqueue.begin();
308 !tempqueue.empty(); iter = tempqueue.begin()) {
309 delete *iter;
310 tempqueue.erase(iter);
311 }
312}
313
314const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
315{
316 ActionTokens_t returnlist;
317
318 returnlist.insert(
319 returnlist.end(),
320 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
321 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
322
323 return returnlist;
324}
325
326void ActionQueue::undoLast()
327{
328 history->undoLast();
329}
330
331void ActionQueue::redoLast()
332{
333 history->redoLast();
334}
335
336
337CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.