source: src/JobMarket/Jobs/SystemCommandJob.cpp@ 404d2b

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChronosMutex Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IntegrationTest JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_JobMarket Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 404d2b was 404d2b, checked in by Frederik Heber <heber@…>, 8 years ago

Squashed 'ThirdParty/JobMarket/' content from commit e194722

git-subtree-dir: ThirdParty/JobMarket
git-subtree-split: e19472277e62c493f6c10f1483fe21e64c1039e9

  • Property mode set to 100644
File size: 6.5 KB
Line 
1/*
2 * Project: JobMarket
3 * Description: asynchronous Server/Controller/Client-approach to parallel computing, based on boost::asio
4 * Copyright (C) 2010 Frederik Heber. All rights reserved.
5 *
6 */
7
8/*
9 * SystemCommandJob.cpp
10 *
11 * Created on: Feb 5, 2012
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include <boost/iostreams/device/file_descriptor.hpp>
21#include <boost/iostreams/stream.hpp>
22
23#include "CodePatterns/MemDebug.hpp"
24
25// include headers that implement a archive in simple text format
26// otherwise BOOST_CLASS_EXPORT_IMPLEMENT has no effect
27#include <boost/archive/text_oarchive.hpp>
28#include <boost/archive/text_iarchive.hpp>
29
30#include "JobMarket/Jobs/SystemCommandJob.hpp"
31
32#include <cstdio>
33#include <cstdlib>
34#include <fcntl.h>
35#include <fstream>
36#include <iostream>
37#include <string>
38#include <streambuf>
39#include <boost/filesystem.hpp>
40
41#include "CodePatterns/Chronos.hpp"
42#include "CodePatterns/Info.hpp"
43#include "CodePatterns/Log.hpp"
44#include "CodePatterns/toString.hpp"
45
46/** Constructor for class SystemCommandJob.
47 *
48 */
49SystemCommandJob::SystemCommandJob() :
50 FragmentJob(JobId::IllegalJob)
51{}
52
53/** Constructor for class SystemCommandJob.
54 *
55 * \param _command command to execute
56 * \param _outputfile configuration file for solver
57 * \param _JobId unique id of this job
58 * \param _suffix possible suffix to temporary file name, may be left empty
59 */
60SystemCommandJob::SystemCommandJob(
61 const std::string &_command,
62 const std::string &_outputfile,
63 const JobId_t _JobId,
64 const std::string &_suffix) :
65 FragmentJob(_JobId),
66 command(_command),
67 suffix(_suffix),
68 outputfile(_outputfile)
69{}
70
71/** Destructor for class SystemCommandJob.
72 *
73 */
74SystemCommandJob::~SystemCommandJob()
75{}
76
77/** Work routine of this SystemCommandJob.
78 *
79 * This function encapsulates all the work that has to be done to generate
80 * a FragmentResult. Hence, the FragmentWorker does not need to know anything
81 * about the operation: it just receives it and executes this function.
82 *
83 * We obtain FragmentResult::exitflag from std::system's return value and
84 * FragmentResult::result from the contents of the piped output file.
85 *
86 * \return result of this job
87 */
88FragmentResult::ptr SystemCommandJob::Work()
89{
90 Info info((std::string(__FUNCTION__)+std::string(", id #")+toString(getId())).c_str());
91
92 // the following is taken from http://stackoverflow.com/questions/2746168/how-to-construct-a-c-fstream-from-a-posix-file-descriptor
93 char *tmpTemplate = NULL;
94 const std::string idstring(toString(getId()));
95 const size_t idlength = idstring.length();
96 {
97 std::string Template("/tmp/XXXXXXX_");
98 ASSERT(idlength <= 8,
99 "SystemCommandJob::Work() - the id contains more than 8 digits.");
100 Template += idstring;
101 if (!suffix.empty())
102 Template += suffix;
103 LOG(2, "DEBUG: Temporary template is " << Template << ".");
104 tmpTemplate = new char[Template.length()+1];
105 strncpy(tmpTemplate, Template.c_str(), Template.length()+1);
106 }
107 const int fd = mkstemps(tmpTemplate, idlength + suffix.length()+1);
108
109 // write outputfile to temporary file
110 LOG(2, "DEBUG: Temporary file is " << tmpTemplate << ".");
111 std::ofstream output(tmpTemplate);
112 ASSERT(output.is_open(),
113 "SystemCommandJob::Work() - the temporary file could not be opened.");
114 output << outputfile << std::endl;
115 output.close();
116
117 // fork into subprocess and launch command
118 const std::string WorkName = std::string("WORK")+idstring;
119 Chronos::getInstance().startTiming(WorkName);
120 FragmentResult::ptr s;
121 {
122 // open process
123 std::string command_args = command+std::string(" ")+tmpTemplate;
124 LOG(1, "INFO: Executing '" << command_args << "'.");
125 FILE *stdoutstream = NULL;
126 while (stdoutstream == NULL) {
127 stdoutstream = popen(command_args.c_str(), "r");
128 if (stdoutstream == NULL) {
129 ELOG(2, "File descriptors are full, waiting for 1 sec...");
130 sleep(1);
131 }
132 }
133
134 int exitflag;
135 // read stdout from process
136 const int fd = fileno(stdoutstream);
137 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
138 boost::iostreams::stream<boost::iostreams::file_descriptor_source> stdoutfile(fd, boost::iostreams::never_close_handle);
139 stdoutfile.set_auto_close(false); // https://svn.boost.org/trac/boost/ticket/3517
140 std::istreambuf_iterator<char> beginiter = (std::istreambuf_iterator<char>(stdoutfile));
141 std::string resultstring( beginiter, std::istreambuf_iterator<char>());
142
143 // construct result
144 LOG(2, "DEBUG: First 50 characters of output: " << resultstring.substr(0,50));
145 s = extractResult(resultstring);
146
147 // end process
148 if ((exitflag = pclose(stdoutstream)) == -1)
149 ELOG(0, "pclose error");
150
151 if (exitflag != 0)
152 ELOG(1, "Job " << getId() << " failed on executing: " << command_args);
153 s->exitflag = exitflag;
154 }
155 Chronos::getInstance().endTiming(WorkName);
156
157 // remove temporary file
158 boost::filesystem::path tmpPath(tmpTemplate);
159 if (boost::filesystem::exists(boost::filesystem::status(tmpPath))) {
160 LOG(2, "DEBUG: Removing " << tmpPath.string());
161 boost::filesystem::remove(tmpPath);
162 }
163 delete[] tmpTemplate;
164 // close temporary file!
165 close(fd);
166
167 // obtain timing and place in FragmentResult
168 s->time_Work = Chronos::getInstance().getTime(WorkName);
169 LOG(1, "INFO: Work() required " << s->time_Work << " seconds to complete.");
170
171 // return result
172 return s;
173}
174
175/** Default function for result extraction is just copy.
176 *
177 * @param resultstring output of system command
178 * @return copy of \a resultstring
179 */
180FragmentResult::ptr SystemCommandJob::extractResult(const std::string &resultstring)
181{
182 return FragmentResult::ptr (new FragmentResult(getId(), resultstring) );
183}
184
185
186/** Comparator for class SystemCommandJob.
187 * \param other instance to compare to
188 * \return every member variable is the same, else - is not
189 */
190bool SystemCommandJob::operator==(const SystemCommandJob &other) const
191{
192 if (command != other.command) {
193 LOG(1, "INFO: command's of two SystemCommandJobs differ: " << command << " != " << other.command << ".");
194 return false;
195 }
196 if (outputfile != other.outputfile) {
197 LOG(1, "INFO: outputfile's of two SystemCommandJobs differ: " << outputfile << " != " << other.outputfile << ".");
198 return false;
199 }
200 return (dynamic_cast<const FragmentJob &>(*this) == dynamic_cast<const FragmentJob &>(other));
201}
202
203// we need to explicitly instantiate the serialization functions as
204// its is only serialized through its base class FragmentJob
205BOOST_CLASS_EXPORT_IMPLEMENT(SystemCommandJob)
Note: See TracBrowser for help on using the repository browser.