source: src/Fragmentation/Automation/poolworker.cpp@ af9b9ff

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 Candidate_v1.7.0 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 af9b9ff was 267b8d, checked in by Frederik Heber <heber@…>, 13 years ago

Server now also intercepts sigint and shuts down gracefully.

  • new FragmentScheduler::shutdown() function is bound and given as signal handler.
  • on signal we first remove all workers and only shutdown and close sockets when there are no workers.
  • note that we do not release the signalhandler after first received signal but after a given number as two ctrl-c are required to shut down server having poolworkers.
  • Property mode set to 100644
File size: 5.2 KB
RevLine 
[41c1b7]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * \file poolworker.cpp
10 *
11 * This file strongly follows the Serialization example from the boost::asio
12 * library (see client.cpp)
13 *
14 * Created on: Feb 28, 2012
15 * Author: heber
16 */
17
18
19// include config.h
20#ifdef HAVE_CONFIG_H
21#include <config.h>
22#endif
23
24// boost asio needs specific operator new
25#include <boost/asio.hpp>
26
27#include "CodePatterns/MemDebug.hpp"
28
29#include <iostream>
[5ac92e]30#include <boost/program_options.hpp>
[41c1b7]31#include <boost/lexical_cast.hpp>
[aec098]32#include <signal.h>
[5ac92e]33#include <vector>
[41c1b7]34
35#include "atexit.hpp"
36#include "CodePatterns/Info.hpp"
37#include "CodePatterns/Log.hpp"
38#include "Pool/PoolWorker.hpp"
39
[5ac92e]40//!> global shutdown function
[aec098]41boost::function<void (int)> shutdownfunction;
[5ac92e]42//!> global signal vector for later releasing
43std::vector<size_t> signals;
[267b8d]44//!> counter for the number of received signals
45size_t NoSignalsReceived = 0;
46//!> maximum number of received signals after which the handlers are released
47const size_t MAX_NOSIGNALSRECEIVED = 3;
[aec098]48
49void signalhandler(int sig)
50{
[267b8d]51 // increment received signal counter
52 ++NoSignalsReceived;
53
[5ac92e]54 // shutdown if we have handler
[aec098]55 if (shutdownfunction)
56 shutdownfunction(sig);
[5ac92e]57
[267b8d]58 if (NoSignalsReceived >= MAX_NOSIGNALSRECEIVED) {
59 // release signal hook again
60 for (std::vector<size_t>::const_iterator iter = signals.begin();
61 iter != signals.end(); ++iter)
62 signal(*iter, NULL);
63 }
[aec098]64}
[41c1b7]65
66int main(int argc, char* argv[])
67{
68 // from this moment on, we need to be sure to deeinitialize in the correct order
69 // this is handled by the cleanup function
70 atexit(cleanUp);
71
[5ac92e]72 // Declare the supported options.
73 boost::program_options::options_description desc("Allowed options");
74 desc.add_options()
75 ("help,h", "produce help message")
76 ("verbosity,v", boost::program_options::value<size_t>(), "set verbosity level")
77 ("signal", boost::program_options::value< std::vector<size_t> >(), "set signal to catch (can be given multiple times)")
78 ("server", boost::program_options::value< std::string>(), "connect to server at this address (host:port)")
79 ("listen", boost::program_options::value< std::string >(), "listen on this port")
80 ("hostname", boost::program_options::value< std::string>(), "name of host on which this codes runs and which server can resolve")
81 ;
82
83 boost::program_options::variables_map vm;
84 boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
85 boost::program_options::notify(vm);
86
87 if (vm.count("help")) {
88 std::cout << desc << "\n";
89 return 1;
90 }
91
92 if (vm.count("verbosity")) {
93 LOG(0, "STATUS: Verbosity level was set to " << vm["verbosity"].as<size_t>() << ".");
94 setVerbosity(vm["verbosity"].as<size_t>());
95 } else {
96 LOG(0, "STATUS: Verbosity level was not set, defaulting to 5.");
97 setVerbosity(5);
98 }
99
100 std::string server;
101 std::string serverport;
102 if (vm.count("server")) {
103 server = vm["server"].as< std::string >();
104 serverport = server.substr(server.find_last_of(':')+1, std::string::npos);
105 server = server.substr(0, server.find_last_of(':'));
106 try {
107 boost::lexical_cast<size_t>(serverport);
108 } catch (boost::bad_lexical_cast) {
109 ELOG(1, "Could not interpret " << serverport << " as server:port.");
110 return 255;
111 }
112 LOG(1, "INFO: Using " << server << ":" << serverport << " as server's address.");
113 } else {
114 ELOG(1, "Requiring server's address (host:port) to connect to.");
115 return 255;
116 }
117
118 std::string hostname("localhost");
119 if (vm.count("hostname")) {
120 hostname = vm["hostname"].as< std::string >();
121 LOG(1, "INFO: Using " << hostname << " as host's name.");
122 } else {
123 ELOG(1, "Requiring port to listen on .");
124 return 255;
125 }
126
127 std::string listenport;
128 if (vm.count("listen")) {
129 try {
130 listenport = vm["listen"].as< std::string >();
131 } catch (boost::bad_lexical_cast) {
132 ELOG(1, "Could not read " << vm["listen"].as< std::string >() << " as digits.");
133 return 255;
134 }
135 LOG(1, "INFO: Using port " << listenport << " to listen to server connects.");
136 } else {
137 ELOG(1, "Requiring port to listen on .");
138 return 255;
139 }
[41c1b7]140
141 size_t exitflag = 0;
142 try
143 {
144 boost::asio::io_service io_service;
[5ac92e]145 PoolWorker client(io_service, server, serverport, hostname, listenport);
[aec098]146
147 // catch ctrl-c and shutdown worker properly
148 shutdownfunction = boost::bind(&PoolWorker::shutdown, boost::ref(client), _1);
[5ac92e]149 if (vm.count("signal")) {
150 signals = vm["signal"].as< std::vector<size_t> >();
151 for (std::vector<size_t>::const_iterator iter = signals.begin();
152 iter != signals.end(); ++iter) {
153 LOG(0, "STATUS: Catching signal " << *iter << " via signal handler.");
154 signal(*iter, &signalhandler);
155 }
156 } else {
157 LOG(0, "STATUS: No signals are caught.");
158 }
[aec098]159
160 // process io requests
[41c1b7]161 {
162 Info info("io_service");
163 io_service.run();
164 }
165 exitflag = client.getFlag();
166 }
167 catch (std::exception& e)
168 {
169 std::cerr << e.what() << std::endl;
170 }
171
172
173 return exitflag;
174}
Note: See TracBrowser for help on using the repository browser.