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 <fstream>
26 #include <unistd.h>
27 #include <dirent.h>
28 #include <fcntl.h>
29 #include <sys/wait.h>
30 
31 #include <boost/shared_ptr.hpp>
32 #include <boost/ptr_container/ptr_deque.hpp>
33 
34 // user include files
38 
42 
45 
50 
54 
57 
59 
60 //
61 // class declaration
62 //
63 
64 class ExternalLHEProducer : public edm::one::EDProducer<edm::BeginRunProducer,
65  edm::EndRunProducer> {
66 public:
67  explicit ExternalLHEProducer(const edm::ParameterSet& iConfig);
68  virtual ~ExternalLHEProducer();
69 
70  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
71 
72 private:
73 
74  virtual void produce(edm::Event&, const edm::EventSetup&) 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.getUntrackedParameter<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  throw edm::Exception(edm::errors::EventGenerationFailure) << "No lhe event found in ExternalLHEProducer::produce(). "
156  << "The likely cause is that the lhe file contains fewer events than were requested, which is possible "
157  << "in case of phase space integration or uneweighting efficiency problems.";
158  }
159 
160  std::auto_ptr<LHEEventProduct> product(
161  new LHEEventProduct(*partonLevel->getHEPEUP(),
162  partonLevel->originalXWGTUP())
163  );
164  if (partonLevel->getPDF()) {
165  product->setPDF(*partonLevel->getPDF());
166  }
167  std::for_each(partonLevel->weights().begin(),
168  partonLevel->weights().end(),
169  boost::bind(&LHEEventProduct::addWeight,
170  product.get(), _1));
171  product->setScales(partonLevel->scales());
172  product->setNpLO(partonLevel->npLO());
173  product->setNpNLO(partonLevel->npNLO());
174  std::for_each(partonLevel->getComments().begin(),
175  partonLevel->getComments().end(),
176  boost::bind(&LHEEventProduct::addComment,
177  product.get(), _1));
178 
179  iEvent.put(product);
180 
181  if (runInfo) {
182  std::auto_ptr<LHERunInfoProduct> product(new LHERunInfoProduct(*runInfo->getHEPRUP()));
183  std::for_each(runInfo->getHeaders().begin(),
184  runInfo->getHeaders().end(),
185  boost::bind(&LHERunInfoProduct::addHeader,
186  product.get(), _1));
187  std::for_each(runInfo->getComments().begin(),
188  runInfo->getComments().end(),
189  boost::bind(&LHERunInfoProduct::addComment,
190  product.get(), _1));
191 
192  if (!runInfoProducts.empty()) {
193  runInfoProducts.front().mergeProduct(*product);
194  if (!wasMerged) {
195  runInfoProducts.pop_front();
196  runInfoProducts.push_front(product);
197  wasMerged = true;
198  }
199  }
200 
201  runInfo.reset();
202  }
203 
204  partonLevel.reset();
205  return;
206 }
207 
208 // ------------ method called when starting to processes a run ------------
209 void
211 {
212 
213  // pass the number of events as previous to last argument
214 
215  std::ostringstream eventStream;
216  eventStream << nEvents_;
217  // args_.push_back(eventStream.str());
218  args_.insert(args_.begin() + 1, eventStream.str());
219 
220  // pass the random number generator seed as last argument
221 
223 
224  if ( ! rng.isAvailable()) {
225  throw cms::Exception("Configuration")
226  << "The ExternalLHEProducer module requires the RandomNumberGeneratorService\n"
227  "which is not present in the configuration file. You must add the service\n"
228  "in the configuration file if you want to run ExternalLHEProducer";
229  }
230  std::ostringstream randomStream;
231  randomStream << rng->mySeed();
232  // args_.push_back(randomStream.str());
233  args_.insert(args_.begin() + 2, randomStream.str());
234 
235  for ( unsigned int iArg = 0; iArg < args_.size() ; iArg++ ) {
236  LogDebug("LHEInputArgs") << "arg [" << iArg << "] = " << args_[iArg];
237  }
238 
239  executeScript();
240 
241  //fill LHEXMLProduct (streaming read directly into compressed buffer to save memory)
242  std::auto_ptr<LHEXMLStringProduct> p(new LHEXMLStringProduct);
243  std::ifstream instream(outputFile_);
244  if (!instream) {
245  throw cms::Exception("OutputOpenError") << "Unable to open script output file " << outputFile_ << ".";
246  }
247  instream.seekg (0, instream.end);
248  int insize = instream.tellg();
249  instream.seekg (0, instream.beg);
250  p->fillCompressedContent(instream, 0.25*insize);
251  instream.close();
252  run.put(p, "LHEScriptOutput");
253 
254  // LHE C++ classes translation
255  // (read back uncompressed file from disk in streaming mode again to save memory)
256 
257  std::vector<std::string> infiles(1, outputFile_);
258  unsigned int skip = 0;
259  std::auto_ptr<lhef::LHEReader> thisRead( new lhef::LHEReader(infiles, skip ) );
260  reader_ = thisRead;
261 
262  nextEvent();
263  if (runInfoLast) {
265 
266  std::auto_ptr<LHERunInfoProduct> product(new LHERunInfoProduct(*runInfo->getHEPRUP()));
267  std::for_each(runInfo->getHeaders().begin(),
268  runInfo->getHeaders().end(),
269  boost::bind(&LHERunInfoProduct::addHeader,
270  product.get(), _1));
271  std::for_each(runInfo->getComments().begin(),
272  runInfo->getComments().end(),
273  boost::bind(&LHERunInfoProduct::addComment,
274  product.get(), _1));
275 
276  // keep a copy around in case of merging
277  runInfoProducts.push_back(new LHERunInfoProduct(*product));
278  wasMerged = false;
279 
280  run.put(product);
281 
282  runInfo.reset();
283  }
284 
285 }
286 
287 // ------------ method called when ending the processing of a run ------------
288 void
290 {
291 
292  if (!runInfoProducts.empty()) {
293  std::auto_ptr<LHERunInfoProduct> product(runInfoProducts.pop_front().release());
294  run.put(product);
295  }
296 
297  nextEvent();
298  if (partonLevel) {
299  throw edm::Exception(edm::errors::EventGenerationFailure) << "Error in ExternalLHEProducer::endRunProduce(). "
300  << "Event loop is over, but there are still lhe events to process."
301  << "This could happen if lhe file contains more events than requested. This is never expected to happen.";
302  }
303 
304  reader_.reset();
305 
306  if (unlink(outputFile_.c_str())) {
307  throw cms::Exception("OutputDeleteError") << "Unable to delete original script output file " << outputFile_ << " (errno=" << errno << ", " << strerror(errno) << ").";
308  }
309 
310 }
311 
312 // ------------ Close all the open file descriptors ------------
313 int
315 {
316  int maxfd = 1024;
317  int fd;
318 #ifdef __linux__
319  DIR * dir;
320  struct dirent *dp;
321  maxfd = preserve;
322  if ((dir = opendir("/proc/self/fd"))) {
323  errno = 0;
324  while ((dp = readdir (dir)) != NULL) {
325  if ((strcmp(dp->d_name, ".") == 0) || (strcmp(dp->d_name, "..") == 0)) {
326  continue;
327  }
328  if (sscanf(dp->d_name, "%d", &fd) != 1) {
329  //throw cms::Exception("closeDescriptors") << "Found unexpected filename in /proc/self/fd: " << dp->d_name;
330  return -1;
331  }
332  if (fd > maxfd) {
333  maxfd = fd;
334  }
335  }
336  if (errno) {
337  //throw cms::Exception("closeDescriptors") << "Unable to determine the number of fd (errno=" << errno << ", " << strerror(errno) << ").";
338  return errno;
339  }
340  closedir(dir);
341  }
342 #endif
343  // TODO: assert for an unreasonable number of fds?
344  for (fd=3; fd<maxfd+1; fd++) {
345  if (fd != preserve)
346  close(fd);
347  }
348  return 0;
349 }
350 
351 // ------------ Execute the script associated with this producer ------------
352 void
354 {
355 
356  // Fork a script, wait until it finishes.
357 
358  int rc = 0, rc2 = 0;
359  int filedes[2], fd_flags;
360  unsigned int argc;
361 
362  if (pipe(filedes)) {
363  throw cms::Exception("Unable to create a new pipe");
364  }
365  FileCloseSentry sentry1(filedes[0]), sentry2(filedes[1]);
366 
367  if ((fd_flags = fcntl(filedes[1], F_GETFD, NULL)) == -1) {
368  throw cms::Exception("ExternalLHEProducer") << "Failed to get pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")";
369  }
370  if (fcntl(filedes[1], F_SETFD, fd_flags | FD_CLOEXEC) == -1) {
371  throw cms::Exception("ExternalLHEProducer") << "Failed to set pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")";
372  }
373 
374  argc = 1 + args_.size();
375  // TODO: assert that we have a reasonable number of arguments
376  char **argv = new char *[argc+1];
377  argv[0] = strdup(scriptName_.c_str());
378  for (unsigned int i=1; i<argc; i++) {
379  argv[i] = strdup(args_[i-1].c_str());
380  }
381  argv[argc] = NULL;
382 
383  pid_t pid = fork();
384  if (pid == 0) {
385  // The child process
386  if (!(rc = closeDescriptors(filedes[1]))) {
387  execvp(argv[0], argv); // If execv returns, we have an error.
388  rc = errno;
389  }
390  while ((write(filedes[1], &rc, sizeof(int)) == -1) && (errno == EINTR)) {}
391  _exit(1);
392  }
393 
394  // Free the arg vector ASAP
395  for (unsigned int i=0; i<args_.size()+1; i++) {
396  free(argv[i]);
397  }
398  delete [] argv;
399 
400  if (pid == -1) {
401  throw cms::Exception("ForkException") << "Unable to fork a child (errno=" << errno << ", " << strerror(errno) << ")";
402  }
403 
404  close(filedes[1]);
405  // If the exec succeeds, the read will fail.
406  while (((rc2 = read(filedes[0], &rc, sizeof(int))) == -1) && (errno == EINTR)) { rc2 = 0; }
407  if ((rc2 == sizeof(int)) && rc) {
408  throw cms::Exception("ExternalLHEProducer") << "Failed to execute script (errno=" << rc << ", " << strerror(rc) << ")";
409  }
410  close(filedes[0]);
411 
412  int status = 0;
413  errno = 0;
414  do {
415  if (waitpid(pid, &status, 0) < 0) {
416  if (errno == EINTR) {
417  continue;
418  } else {
419  throw cms::Exception("ExternalLHEProducer") << "Failed to read child status (errno=" << errno << ", " << strerror(errno) << ")";
420  }
421  }
422  if (WIFSIGNALED(status)) {
423  throw cms::Exception("ExternalLHEProducer") << "Child exited due to signal " << WTERMSIG(status) << ".";
424  }
425  if (WIFEXITED(status)) {
426  rc = WEXITSTATUS(status);
427  break;
428  }
429  } while (true);
430  if (rc) {
431  throw cms::Exception("ExternalLHEProducer") << "Child failed with exit code " << rc << ".";
432  }
433 
434 }
435 
436 // ------------ Read the output script ------------
437 #define BUFSIZE 4096
438 std::auto_ptr<std::string> ExternalLHEProducer::readOutput()
439 {
440  int fd;
441  ssize_t n;
442  char buf[BUFSIZE];
443 
444  if ((fd = open(outputFile_.c_str(), O_RDONLY)) == -1) {
445  throw cms::Exception("OutputOpenError") << "Unable to open script output file " << outputFile_ << " (errno=" << errno << ", " << strerror(errno) << ").";
446  }
447 
448  std::stringstream ss;
449  while ((n = read(fd, buf, BUFSIZE)) > 0 || (n == -1 && errno == EINTR)) {
450  if (n > 0)
451  ss.write(buf, n);
452  }
453  if (n == -1) {
454  throw cms::Exception("OutputOpenError") << "Unable to read from script output file " << outputFile_ << " (errno=" << errno << ", " << strerror(errno) << ").";
455  }
456 
457  if (unlink(outputFile_.c_str())) {
458  throw cms::Exception("OutputDeleteError") << "Unable to delete original script output file " << outputFile_ << " (errno=" << errno << ", " << strerror(errno) << ").";
459  }
460 
461  return std::auto_ptr<std::string>(new std::string(ss.str()));
462 }
463 
464 // ------------ method fills 'descriptions' with the allowed parameters for the module ------------
465 void
467  //The following says we do not know what parameters are allowed so do no validation
468  // Please change this to state exactly what you do use, even if it is no parameters
470  desc.setComment("Executes an external script and places its output file into an EDM collection");
471 
472  edm::FileInPath thePath;
473  desc.add<edm::FileInPath>("scriptName", thePath);
474  desc.add<std::string>("outputFile", "myoutput");
475  desc.add<std::vector<std::string> >("args");
476  desc.add<uint32_t>("numberOfParameters");
477  desc.addUntracked<uint32_t>("nEvents");
478 
479  descriptions.addDefault(desc);
480 }
481 
483 {
484 
485  if (partonLevel)
486  return;
487 
488  partonLevel = reader_->next();
489  if (!partonLevel)
490  return;
491 
492  boost::shared_ptr<lhef::LHERunInfo> runInfoThis = partonLevel->getRunInfo();
493  if (runInfoThis != runInfoLast) {
494  runInfo = runInfoThis;
495  runInfoLast = runInfoThis;
496  }
497 }
498 
499 //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
ParameterDescriptionBase * addUntracked(U const &iLabel, T const &value)
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
void addWeight(const WGT &wgt)
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:230
void addDefault(ParameterSetDescription const &psetDescription)
virtual std::uint32_t mySeed() const =0
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)
boost::shared_ptr< lhef::LHERunInfo > runInfo
void addComment(const std::string &line)
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
ExternalLHEProducer(const edm::ParameterSet &iConfig)
Definition: Run.h:41