source: src/Fragmentation/Automation/FragmentScheduler.cpp@ 402bde

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 402bde was 402bde, checked in by Frederik Heber <heber@…>, 13 years ago

Placed initiating sockets from Cstor of FragmentScheduler into helper functions.

  • Property mode set to 100644
File size: 8.3 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2011 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 FragmentScheduler.cpp
10 *
11 * This file strongly follows the Serialization example from the boost::asio
12 * library (see server.cpp)
13 *
14 * Created on: Oct 19, 2011
15 * Author: heber
16 */
17
18// include config.h
19#ifdef HAVE_CONFIG_H
20#include <config.h>
21#endif
22
23// boost asio needs specific operator new
24#include <boost/asio.hpp>
25
26#include "CodePatterns/MemDebug.hpp"
27
28#include <boost/bind.hpp>
29#include <boost/lexical_cast.hpp>
30#include <iostream>
31#include <vector>
32#include "Connection.hpp" // Must come before boost/serialization headers.
33#include <boost/serialization/vector.hpp>
34#include "CodePatterns/Info.hpp"
35#include "CodePatterns/Log.hpp"
36#include "FragmentJob.hpp"
37#include "JobId.hpp"
38
39#include "FragmentScheduler.hpp"
40
41FragmentJob FragmentScheduler::NoJob(std::string("NoJob"), JobId::NoJob);
42
43/** Constructor of class FragmentScheduler.
44 *
45 * We setup both acceptors to accept connections from workers and Controller.
46 *
47 * \param io_service io_service of the asynchronous communications
48 * \param workerport port to listen for worker connections
49 * \param controllerport port to listen for controller connections.
50 */
51FragmentScheduler::FragmentScheduler(boost::asio::io_service& io_service, unsigned short workerport, unsigned short controllerport) :
52 worker_acceptor_(io_service,
53 boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), workerport)
54 ),
55 controller_acceptor_(io_service,
56 boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), controllerport)
57 ),
58 result(JobId::NoJob),
59 Exitflag(OkFlag)
60{
61 Info info(__FUNCTION__);
62
63 initiateWorkerSocket();
64
65 initiateControllerSocket();
66}
67
68/** Internal function to start worker connection.
69 *
70 */
71void FragmentScheduler::initiateWorkerSocket()
72{
73 // Start an accept operation for worker connections.
74 connection_ptr new_conn(new Connection(worker_acceptor_.get_io_service()));
75 worker_acceptor_.async_accept(new_conn->socket(),
76 boost::bind(&FragmentScheduler::handle_AcceptWorker, this,
77 boost::asio::placeholders::error, new_conn));
78}
79
80/** Internal function to start controller connection.
81 *
82 */
83void FragmentScheduler::initiateControllerSocket()
84{
85 // Start an accept operation for controller connection.
86 connection_ptr new_conn(new Connection(controller_acceptor_.get_io_service()));
87 controller_acceptor_.async_accept(new_conn->socket(),
88 boost::bind(&FragmentScheduler::handle_AcceptController, this,
89 boost::asio::placeholders::error, new_conn));
90}
91
92
93/** Handle a new worker connection.
94 *
95 * We check whether jobs are in the JobsQueue. If present, job is sent.
96 *
97 * \sa handle_SendJobtoWorker()
98 *
99 * \param e error code if something went wrong
100 * \param conn reference with the connection
101 */
102void FragmentScheduler::handle_AcceptWorker(const boost::system::error_code& e, connection_ptr conn)
103{
104 Info info(__FUNCTION__);
105 if (!e)
106 {
107 // Successfully accepted a new connection.
108 // Check whether there are jobs in the queue
109 if (JobsQueue.isJobPresent()) {
110 // pop a job and send it to the client.
111 FragmentJob job(JobsQueue.popJob());
112 // The connection::async_write() function will automatically
113 // serialize the data structure for us.
114 LOG(1, "INFO: Sending job #" << job.getId() << ".");
115 conn->async_write(job,
116 boost::bind(&FragmentScheduler::handle_SendJobtoWorker, this,
117 boost::asio::placeholders::error, conn));
118
119 // Start an accept operation for a new Connection only when there
120 // are still jobs present otherwise we quit.
121 initiateWorkerSocket();
122 } else {
123 // send the static NoJob
124 conn->async_write(NoJob,
125 boost::bind(&FragmentScheduler::handle_SendJobtoWorker, this,
126 boost::asio::placeholders::error, conn));
127
128 // then there must be no read necesary
129
130 ELOG(2, "There is currently no job present in the queue.");
131 }
132 }
133 else
134 {
135 // An error occurred. Log it and return. Since we are not starting a new
136 // accept operation the io_service will run out of work to do and the
137 // server will exit.
138 Exitflag = WorkerErrorFlag;
139 ELOG(0, e.message());
140 }
141}
142
143/** Callback function when job has been sent.
144 *
145 * After job has been sent we start async_read() for the result.
146 *
147 * \sa handle_ReceiveResultFromWorker()
148 *
149 * \param e error code if something went wrong
150 * \param conn reference with the connection
151 */
152void FragmentScheduler::handle_SendJobtoWorker(const boost::system::error_code& e, connection_ptr conn)
153{
154 Info info(__FUNCTION__);
155 LOG(1, "INFO: Job sent.");
156 // obtain result
157 LOG(1, "INFO: Receiving result for a job ...");
158 conn->async_read(result,
159 boost::bind(&FragmentScheduler::handle_ReceiveResultFromWorker, this,
160 boost::asio::placeholders::error, conn));
161}
162
163/** Callback function when result has been received.
164 *
165 * \param e error code if something went wrong
166 * \param conn reference with the connection
167 */
168void FragmentScheduler::handle_ReceiveResultFromWorker(const boost::system::error_code& e, connection_ptr conn)
169{
170 Info info(__FUNCTION__);
171 // nothing to do
172 LOG(1, "INFO: Received result for job #" << result.getId() << " ...");
173 // and push into queue
174 ASSERT(result.getId() != (JobId_t)JobId::NoJob,
175 "FragmentScheduler::handle_ReceiveResultFromWorker() - result received has NoJob id.");
176 ASSERT(result.getId() != (JobId_t)JobId::IllegalJob,
177 "FragmentScheduler::handle_ReceiveResultFromWorker() - result received has IllegalJob id.");
178 if ((result.getId() != (JobId_t)JobId::NoJob) && (result.getId() != (JobId_t)JobId::IllegalJob))
179 JobsQueue.pushResult(result);
180 // erase result
181 result = FragmentResult(JobId::NoJob);
182}
183
184/** Handle a new controller connection.
185 *
186 * \sa handle_ReceiveJobs()
187 * \sa handle_CheckResultState()
188 * \sa handle_SendResults()
189 *
190 * \param e error code if something went wrong
191 * \param conn reference with the connection
192 */
193void FragmentScheduler::handle_AcceptController(const boost::system::error_code& e, connection_ptr conn)
194{
195 Info info(__FUNCTION__);
196 if (!e)
197 {
198 if (JobsQueue.isJobPresent() || !JobsQueue.getDoneJobs()) {
199 // The connection::async_write() function will automatically
200 // serialize the data structure for us.
201 LOG(1, "INFO: Receiving bunch of jobs from a controller ...");
202 conn->async_read(jobs,
203 boost::bind(&FragmentScheduler::handle_ReceiveJobs, this,
204 boost::asio::placeholders::error, conn));
205 } else {
206 // we just give a status report ...
207 // first update number
208 doneJobs = JobsQueue.getDoneJobs();
209 // now we accept connections to check for state of calculations
210 LOG(1, "INFO: Sending state of results to controller ...");
211 conn->async_write(doneJobs,
212 boost::bind(&FragmentScheduler::handle_CheckResultState, this,
213 boost::asio::placeholders::error, conn));
214 }
215 }
216 else
217 {
218 // An error occurred. Log it and return. Since we are not starting a new
219 // accept operation the io_service will run out of work to do and the
220 // server will exit.
221 Exitflag = ControllerErrorFlag;
222 ELOG(0, e.message());
223 }
224}
225
226/** Controller callback function when job has been sent.
227 *
228 * \param e error code if something went wrong
229 * \param conn reference with the connection
230 */
231void FragmentScheduler::handle_ReceiveJobs(const boost::system::error_code& e, connection_ptr conn)
232{
233 Info info(__FUNCTION__);
234 // jobs are received, hence place in JobsQueue
235 if (!jobs.empty()) {
236 LOG(1, "INFO: Pushing " << jobs.size() << " jobs into queue.");
237 JobsQueue.pushJobs(jobs);
238 }
239 // launch new acceptor of queue has been filled/is full
240 if (JobsQueue.isJobPresent()) {
241 // Start an accept operation for a new Connection.
242 initiateControllerSocket();
243 } else {
244 LOG(1, "INFO: Shutting down controller socket.");
245 }
246
247 jobs.clear();
248}
249
250/** Controller callback function when checking on state of results.
251 *
252 * \param e error code if something went wrong
253 * \param conn reference with the connection
254 */
255void FragmentScheduler::handle_CheckResultState(const boost::system::error_code& e, connection_ptr conn)
256{
257 Info info(__FUNCTION__);
258 // do nothing
259 LOG(1, "INFO: Sent that " << doneJobs << " jobs are done.");
260}
Note: See TracBrowser for help on using the repository browser.