CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
ExternalLHEProducer.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: ExternalLHEProducer
4 // Class: ExternalLHEProducer
5 //
13 //
14 // Original Author: Brian Paul Bockelman,8 R-018,+41227670861,
15 // Created: Fri Oct 21 11:37:26 CEST 2011
16 //
17 //
18 
19 
20 // system include files
21 #include <cstdio>
22 #include <memory>
23 #include <vector>
24 #include <string>
25 #include <unistd.h>
26 #include <dirent.h>
27 #include <fcntl.h>
28 #include <sys/wait.h>
29 
30 #include <boost/shared_ptr.hpp>
31 #include <boost/ptr_container/ptr_deque.hpp>
32 
33 // user include files
37 
41 
44 
49 
53 
56 
58 
59 //
60 // class declaration
61 //
62 
63 class ExternalLHEProducer : public edm::one::EDProducer<edm::BeginRunProducer,
64  edm::EndRunProducer> {
65 public:
66  explicit ExternalLHEProducer(const edm::ParameterSet& iConfig);
67  virtual ~ExternalLHEProducer();
68 
69  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
70 
71 private:
72 
73  virtual void produce(edm::Event&, const edm::EventSetup&) override;
74  virtual void endJob() override;
75  virtual void beginRunProduce(edm::Run& run, edm::EventSetup const& es) override;
76  virtual void endRunProduce(edm::Run&, edm::EventSetup const&) override;
77 
78  int closeDescriptors(int preserve);
79  void executeScript();
80  std::auto_ptr<std::string> readOutput();
81 
82  virtual void nextEvent();
83 
84  // ----------member data ---------------------------
87  std::vector<std::string> args_;
88  uint32_t npars_;
89  uint32_t nEvents_;
91 
92  std::auto_ptr<lhef::LHEReader> reader_;
93  boost::shared_ptr<lhef::LHERunInfo> runInfoLast;
94  boost::shared_ptr<lhef::LHERunInfo> runInfo;
95  boost::shared_ptr<lhef::LHEEvent> partonLevel;
96  boost::ptr_deque<LHERunInfoProduct> runInfoProducts;
97  bool wasMerged;
98 
99  class FileCloseSentry : private boost::noncopyable {
100  public:
101  explicit FileCloseSentry(int fd) : fd_(fd) {};
102 
104  close(fd_);
105  }
106  private:
107  int fd_;
108  };
109 
110 };
111 
112 //
113 // constants, enums and typedefs
114 //
115 
116 
117 //
118 // static data member definitions
119 //
120 
121 //
122 // constructors and destructor
123 //
125  scriptName_((iConfig.getParameter<edm::FileInPath>("scriptName")).fullPath().c_str()),
126  outputFile_(iConfig.getParameter<std::string>("outputFile")),
127  args_(iConfig.getParameter<std::vector<std::string> >("args")),
128  npars_(iConfig.getParameter<uint32_t>("numberOfParameters")),
129  nEvents_(iConfig.getParameter<uint32_t>("nEvents"))
130 {
131  if (npars_ != args_.size())
132  throw cms::Exception("ExternalLHEProducer") << "Problem with configuration: " << args_.size() << " script arguments given, expected " << npars_;
133  produces<LHEXMLStringProduct, edm::InRun>("LHEScriptOutput");
134 
135  produces<LHEEventProduct>();
136  produces<LHERunInfoProduct, edm::InRun>();
137 }
138 
139 
141 {
142 }
143 
144 
145 //
146 // member functions
147 //
148 
149 // ------------ method called to produce the data ------------
150 void
152 {
153  nextEvent();
154  if (!partonLevel)
155  return;
156 
157  std::auto_ptr<LHEEventProduct> product(
158  new LHEEventProduct(*partonLevel->getHEPEUP(),
159  partonLevel->originalXWGTUP())
160  );
161  if (partonLevel->getPDF())
162  product->setPDF(*partonLevel->getPDF());
163  std::for_each(partonLevel->getComments().begin(),
164  partonLevel->getComments().end(),
165  boost::bind(&LHEEventProduct::addComment,
166  product.get(), _1));
167 
168  iEvent.put(product);
169 
170  if (runInfo) {
171  std::auto_ptr<LHERunInfoProduct> product(new LHERunInfoProduct(*runInfo->getHEPRUP()));
172  std::for_each(runInfo->getHeaders().begin(),
173  runInfo->getHeaders().end(),
174  boost::bind(&LHERunInfoProduct::addHeader,
175  product.get(), _1));
176  std::for_each(runInfo->getComments().begin(),
177  runInfo->getComments().end(),
178  boost::bind(&LHERunInfoProduct::addComment,
179  product.get(), _1));
180 
181  if (!runInfoProducts.empty()) {
182  runInfoProducts.front().mergeProduct(*product);
183  if (!wasMerged) {
184  runInfoProducts.pop_front();
185  runInfoProducts.push_front(product);
186  wasMerged = true;
187  }
188  }
189 
190  runInfo.reset();
191  }
192 
193  partonLevel.reset();
194  return;
195 }
196 
197 // ------------ method called once each job just after ending the event loop ------------
198 void
200 
201  reader_.reset();
202 }
203 
204 // ------------ method called when starting to processes a run ------------
205 void
207 {
208 
209  // pass the number of events as previous to last argument
210 
211  std::ostringstream eventStream;
212  eventStream << nEvents_;
213  args_.push_back(eventStream.str());
214 
215  // pass the random number generator seed as last argument
216 
218 
219  if ( ! rng.isAvailable()) {
220  throw cms::Exception("Configuration")
221  << "The ExternalLHEProducer module requires the RandomNumberGeneratorService\n"
222  "which is not present in the configuration file. You must add the service\n"
223  "in the configuration file if you want to run ExternalLHEProducer";
224  }
225  std::ostringstream randomStream;
226  randomStream << rng->mySeed();
227  args_.push_back(randomStream.str());
228 
229  for ( unsigned int iArg = 0; iArg < args_.size() ; iArg++ ) {
230  LogDebug("LHEInputArgs") << "arg [" << iArg << "] = " << args_[iArg];
231  }
232 
233  executeScript();
234  std::auto_ptr<std::string> localContents = readOutput();
235  outputContents_ = *localContents;
236  std::auto_ptr<LHEXMLStringProduct> p(new LHEXMLStringProduct(*localContents));
237  run.put(p, "LHEScriptOutput");
238 
239  // LHE C++ classes translation
240 
241  unsigned int skip = 0;
242  std::auto_ptr<lhef::LHEReader> thisRead( new lhef::LHEReader(outputContents_, skip ) );
243  reader_ = thisRead;
244 
245  nextEvent();
246  if (runInfoLast) {
248 
249  std::auto_ptr<LHERunInfoProduct> product(new LHERunInfoProduct(*runInfo->getHEPRUP()));
250  std::for_each(runInfo->getHeaders().begin(),
251  runInfo->getHeaders().end(),
252  boost::bind(&LHERunInfoProduct::addHeader,
253  product.get(), _1));
254  std::for_each(runInfo->getComments().begin(),
255  runInfo->getComments().end(),
256  boost::bind(&LHERunInfoProduct::addComment,
257  product.get(), _1));
258 
259  // keep a copy around in case of merging
260  runInfoProducts.push_back(new LHERunInfoProduct(*product));
261  wasMerged = false;
262 
263  run.put(product);
264 
265  runInfo.reset();
266  }
267 
268 }
269 
270 // ------------ method called when ending the processing of a run ------------
271 void
273 {
274 
275  if (!runInfoProducts.empty()) {
276  std::auto_ptr<LHERunInfoProduct> product(runInfoProducts.pop_front().release());
277  run.put(product);
278  }
279 
280 }
281 
282 // ------------ Close all the open file descriptors ------------
283 int
285 {
286  int maxfd = 1024;
287  int fd;
288 #ifdef __linux__
289  DIR * dir;
290  struct dirent *dp;
291  maxfd = preserve;
292  if ((dir = opendir("/proc/self/fd"))) {
293  errno = 0;
294  while ((dp = readdir (dir)) != NULL) {
295  if ((strcmp(dp->d_name, ".") == 0) || (strcmp(dp->d_name, "..") == 0)) {
296  continue;
297  }
298  if (sscanf(dp->d_name, "%d", &fd) != 1) {
299  //throw cms::Exception("closeDescriptors") << "Found unexpected filename in /proc/self/fd: " << dp->d_name;
300  return -1;
301  }
302  if (fd > maxfd) {
303  maxfd = fd;
304  }
305  }
306  if (errno) {
307  //throw cms::Exception("closeDescriptors") << "Unable to determine the number of fd (errno=" << errno << ", " << strerror(errno) << ").";
308  return errno;
309  }
310  closedir(dir);
311  }
312 #endif
313  // TODO: assert for an unreasonable number of fds?
314  for (fd=3; fd<maxfd+1; fd++) {
315  if (fd != preserve)
316  close(fd);
317  }
318  return 0;
319 }
320 
321 // ------------ Execute the script associated with this producer ------------
322 void
324 {
325 
326  // Fork a script, wait until it finishes.
327 
328  int rc = 0, rc2 = 0;
329  int filedes[2], fd_flags;
330  unsigned int argc;
331 
332  if (pipe(filedes)) {
333  throw cms::Exception("Unable to create a new pipe");
334  }
335  FileCloseSentry sentry1(filedes[0]), sentry2(filedes[1]);
336 
337  if ((fd_flags = fcntl(filedes[1], F_GETFD, NULL)) == -1) {
338  throw cms::Exception("ExternalLHEProducer") << "Failed to get pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")";
339  }
340  if (fcntl(filedes[1], F_SETFD, fd_flags | FD_CLOEXEC) == -1) {
341  throw cms::Exception("ExternalLHEProducer") << "Failed to set pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")";
342  }
343 
344  argc = 1 + args_.size();
345  // TODO: assert that we have a reasonable number of arguments
346  char **argv = new char *[argc+1];
347  argv[0] = strdup(scriptName_.c_str());
348  for (unsigned int i=1; i<argc; i++) {
349  argv[i] = strdup(args_[i-1].c_str());
350  }
351  argv[argc] = NULL;
352 
353  pid_t pid = fork();
354  if (pid == 0) {
355  // The child process
356  if (!(rc = closeDescriptors(filedes[1]))) {
357  execvp(argv[0], argv); // If execv returns, we have an error.
358  rc = errno;
359  }
360  while ((write(filedes[1], &rc, sizeof(int)) == -1) && (errno == EINTR)) {}
361  _exit(1);
362  }
363 
364  // Free the arg vector ASAP
365  for (unsigned int i=0; i<args_.size()+1; i++) {
366  free(argv[i]);
367  }
368  delete [] argv;
369 
370  if (pid == -1) {
371  throw cms::Exception("ForkException") << "Unable to fork a child (errno=" << errno << ", " << strerror(errno) << ")";
372  }
373 
374  close(filedes[1]);
375  // If the exec succeeds, the read will fail.
376  while (((rc2 = read(filedes[0], &rc, sizeof(int))) == -1) && (errno == EINTR)) { rc2 = 0; }
377  if ((rc2 == sizeof(int)) && rc) {
378  throw cms::Exception("ExternalLHEProducer") << "Failed to execute script (errno=" << rc << ", " << strerror(rc) << ")";
379  }
380  close(filedes[0]);
381 
382  int status = 0;
383  errno = 0;
384  do {
385  if (waitpid(pid, &status, 0) < 0) {
386  if (errno == EINTR) {
387  continue;
388  } else {
389  throw cms::Exception("ExternalLHEProducer") << "Failed to read child status (errno=" << errno << ", " << strerror(errno) << ")";
390  }
391  }
392  if (WIFSIGNALED(status)) {
393  throw cms::Exception("ExternalLHEProducer") << "Child exited due to signal " << WTERMSIG(status) << ".";
394  }
395  if (WIFEXITED(status)) {
396  rc = WEXITSTATUS(status);
397  break;
398  }
399  } while (true);
400  if (rc) {
401  throw cms::Exception("ExternalLHEProducer") << "Child failed with exit code " << rc << ".";
402  }
403 
404 }
405 
406 // ------------ Read the output script ------------
407 #define BUFSIZE 4096
408 std::auto_ptr<std::string> ExternalLHEProducer::readOutput()
409 {
410  int fd;
411  ssize_t n;
412  char buf[BUFSIZE];
413 
414  if ((fd = open(outputFile_.c_str(), O_RDONLY)) == -1) {
415  throw cms::Exception("OutputOpenError") << "Unable to open script output file " << outputFile_ << " (errno=" << errno << ", " << strerror(errno) << ").";
416  }
417 
418  std::stringstream ss;
419  while ((n = read(fd, buf, BUFSIZE)) > 0 || (n == -1 && errno == EINTR)) {
420  if (n > 0)
421  ss.write(buf, n);
422  }
423  if (n == -1) {
424  throw cms::Exception("OutputOpenError") << "Unable to read from script output file " << outputFile_ << " (errno=" << errno << ", " << strerror(errno) << ").";
425  }
426 
427  if (unlink(outputFile_.c_str())) {
428  throw cms::Exception("OutputDeleteError") << "Unable to delete original script output file " << outputFile_ << " (errno=" << errno << ", " << strerror(errno) << ").";
429  }
430 
431  return std::auto_ptr<std::string>(new std::string(ss.str()));
432 }
433 
434 // ------------ method fills 'descriptions' with the allowed parameters for the module ------------
435 void
437  //The following says we do not know what parameters are allowed so do no validation
438  // Please change this to state exactly what you do use, even if it is no parameters
440  desc.setComment("Executes an external script and places its output file into an EDM collection");
441 
442  edm::FileInPath thePath;
443  desc.add<edm::FileInPath>("scriptName", thePath);
444  desc.add<std::string>("outputFile", "myoutput");
445  desc.add<std::vector<std::string> >("args");
446  desc.add<uint32_t>("numberOfParameters");
447  desc.add<uint32_t>("nEvents");
448 
449  descriptions.addDefault(desc);
450 }
451 
453 {
454 
455  if (partonLevel)
456  return;
457 
458  partonLevel = reader_->next();
459  if (!partonLevel)
460  return;
461 
462  boost::shared_ptr<lhef::LHERunInfo> runInfoThis = partonLevel->getRunInfo();
463  if (runInfoThis != runInfoLast) {
464  runInfo = runInfoThis;
465  runInfoLast = runInfoThis;
466  }
467 }
468 
469 //define this as a plug-in
#define LogDebug(id)
boost::shared_ptr< lhef::LHEEvent > partonLevel
std::auto_ptr< std::string > readOutput()
virtual void beginRunProduce(edm::Run &run, edm::EventSetup const &es) override
int i
Definition: DBlmapReader.cc:9
virtual void endRunProduce(edm::Run &, edm::EventSetup const &) override
void addHeader(const Header &header)
void addComment(const std::string &line)
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:17
virtual void produce(edm::Event &, const edm::EventSetup &) override
def pipe
Definition: pipe.py:5
#define NULL
Definition: scimark2.h:8
std::vector< std::string > args_
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
std::auto_ptr< lhef::LHEReader > reader_
boost::shared_ptr< lhef::LHERunInfo > runInfoLast
void setComment(std::string const &value)
int closeDescriptors(int preserve)
int iEvent
Definition: GenABIO.cc:243
void addDefault(ParameterSetDescription const &psetDescription)
OrphanHandle< PROD > put(std::auto_ptr< PROD > product)
Put a new product.
Definition: Event.h:116
bool isAvailable() const
Definition: Service.h:46
#define BUFSIZE
ParameterDescriptionBase * add(U const &iLabel, T const &value)
virtual void endJob() override
boost::shared_ptr< lhef::LHERunInfo > runInfo
void addComment(const std::string &line)
auto dp
Definition: deltaR.h:24
tuple pid
Definition: sysUtil.py:22
tuple argc
Definition: dir2webdir.py:38
void put(std::auto_ptr< PROD > product)
Put a new product.
Definition: Run.h:107
boost::ptr_deque< LHERunInfoProduct > runInfoProducts
dbl *** dir
Definition: mlp_gen.cc:35
tuple status
Definition: ntuplemaker.py:245
virtual uint32_t mySeed() const =0
Exists for backward compatibility.
ExternalLHEProducer(const edm::ParameterSet &iConfig)
Definition: Run.h:41