Merge branch release-5-0
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlinemodulemanager.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::CommandLineModuleManager.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_commandline
41  */
42 #include "gmxpre.h"
43
44 #include "cmdlinemodulemanager.h"
45
46 #include <cstdio>
47
48 #include <string>
49 #include <utility>
50
51 #include "gromacs/commandline/cmdlinehelpcontext.h"
52 #include "gromacs/commandline/cmdlineinit.h"
53 #include "gromacs/commandline/cmdlinemodule.h"
54 #include "gromacs/commandline/cmdlineparser.h"
55 #include "gromacs/commandline/cmdlineprogramcontext.h"
56 #include "gromacs/legacyheaders/copyrite.h"
57 #include "gromacs/math/utilities.h"
58 #include "gromacs/options/basicoptions.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/utility/basenetwork.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/fatalerror.h"
63 #include "gromacs/utility/futil.h"
64 #include "gromacs/utility/gmxassert.h"
65 #include "gromacs/utility/stringutil.h"
66 #include "gromacs/utility/sysinfo.h"
67
68 #include "cmdlinehelpmodule.h"
69 #include "cmdlinemodulemanager-impl.h"
70
71 namespace gmx
72 {
73
74 namespace
75 {
76
77 //! \addtogroup module_commandline
78 //! \{
79
80 /********************************************************************
81  * CMainCommandLineModule
82  */
83
84 /*! \brief
85  * Implements a CommandLineModuleInterface, given a function with C/C++ main()
86  * signature.
87  */
88 class CMainCommandLineModule : public CommandLineModuleInterface
89 {
90     public:
91         //! \copydoc gmx::CommandLineModuleManager::CMainFunction
92         typedef CommandLineModuleManager::CMainFunction CMainFunction;
93
94         /*! \brief
95          * Creates a wrapper module for the given main function.
96          *
97          * \param[in] name             Name for the module.
98          * \param[in] shortDescription One-line description for the module.
99          * \param[in] mainFunction     Main function to wrap.
100          *
101          * Does not throw.  This is essential for correct implementation of
102          * CommandLineModuleManager::runAsMainCMain().
103          */
104         CMainCommandLineModule(const char *name, const char *shortDescription,
105                                CMainFunction mainFunction)
106             : name_(name), shortDescription_(shortDescription),
107               mainFunction_(mainFunction)
108         {
109         }
110
111         virtual const char *name() const
112         {
113             return name_;
114         }
115         virtual const char *shortDescription() const
116         {
117             return shortDescription_;
118         }
119
120         virtual void init(CommandLineModuleSettings * /*settings*/)
121         {
122         }
123         virtual int run(int argc, char *argv[])
124         {
125             return mainFunction_(argc, argv);
126         }
127         virtual void writeHelp(const CommandLineHelpContext &context) const
128         {
129             writeCommandLineHelpCMain(context, name_, mainFunction_);
130         }
131
132     private:
133         const char             *name_;
134         const char             *shortDescription_;
135         CMainFunction           mainFunction_;
136 };
137
138 //! \}
139
140 }   // namespace
141
142 /********************************************************************
143  * CommandLineCommonOptionsHolder
144  */
145
146 CommandLineCommonOptionsHolder::CommandLineCommonOptionsHolder()
147     : options_(NULL, NULL), bHelp_(false), bHidden_(false),
148       bQuiet_(false), bVersion_(false), bCopyright_(true),
149       niceLevel_(19), bBackup_(true), bFpexcept_(false), debugLevel_(0)
150 {
151     binaryInfoSettings_.copyright(true);
152 }
153
154 CommandLineCommonOptionsHolder::~CommandLineCommonOptionsHolder()
155 {
156 }
157
158 void CommandLineCommonOptionsHolder::initOptions()
159 {
160     options_.addOption(BooleanOption("h").store(&bHelp_)
161                            .description("Print help and quit"));
162     options_.addOption(BooleanOption("hidden").store(&bHidden_)
163                            .hidden()
164                            .description("Show hidden options in help"));
165     options_.addOption(BooleanOption("quiet").store(&bQuiet_)
166                            .description("Do not print common startup info or quotes"));
167     options_.addOption(BooleanOption("version").store(&bVersion_)
168                            .description("Print extended version information and quit"));
169     options_.addOption(BooleanOption("copyright").store(&bCopyright_)
170                            .description("Print copyright information on startup"));
171     options_.addOption(IntegerOption("nice").store(&niceLevel_)
172                            .description("Set the nicelevel (default depends on command)"));
173     options_.addOption(BooleanOption("backup").store(&bBackup_)
174                            .description("Write backups if output files exist"));
175     options_.addOption(BooleanOption("fpexcept").store(&bFpexcept_)
176                            .hidden().description("Enable floating-point exceptions"));
177     options_.addOption(IntegerOption("debug").store(&debugLevel_)
178                            .hidden().defaultValueIfSet(1)
179                            .description("Write file with debug information, "
180                                         "1: short (default), 2: also x and f"));
181 }
182
183 bool CommandLineCommonOptionsHolder::finishOptions()
184 {
185     options_.finish();
186     binaryInfoSettings_.extendedInfo(bVersion_);
187     // The latter condition suppresses the copyright with
188     // -quiet -version.
189     binaryInfoSettings_.copyright(bCopyright_ && !bQuiet_);
190     return !bVersion_;
191 }
192
193 void CommandLineCommonOptionsHolder::adjustFromSettings(
194         const CommandLineModuleSettings &settings)
195 {
196     if (!options_.isSet("nice"))
197     {
198         niceLevel_ = settings.defaultNiceLevel();
199     }
200 }
201
202 /********************************************************************
203  * CommandLineModuleManager::Impl
204  */
205
206 /*! \internal \brief
207  * Private implementation class for CommandLineModuleManager.
208  *
209  * \ingroup module_commandline
210  */
211 class CommandLineModuleManager::Impl
212 {
213     public:
214         /*! \brief
215          * Initializes the implementation class.
216          *
217          * \param[in] binaryName     Name of the running binary
218          *     (without Gromacs binary suffix or .exe on Windows).
219          * \param     programContext Program information for the running binary.
220          */
221         Impl(const char *binaryName, CommandLineProgramContext *programContext);
222
223         /*! \brief
224          * Helper method that adds a given module to the module manager.
225          *
226          * \throws    std::bad_alloc if out of memory.
227          */
228         void addModule(CommandLineModulePointer module);
229         /*! \brief
230          * Creates the help module if it does not yet exist.
231          *
232          * \throws    std::bad_alloc if out of memory.
233          *
234          * This method should be called before accessing \a helpModule_.
235          */
236         void ensureHelpModuleExists();
237
238         /*! \brief
239          * Finds a module that matches a name.
240          *
241          * \param[in] name  Module name to find.
242          * \returns   Iterator to the found module, or
243          *      \c modules_.end() if not found.
244          *
245          * Does not throw.
246          */
247         CommandLineModuleMap::const_iterator
248         findModuleByName(const std::string &name) const;
249
250         /*! \brief
251          * Processes command-line options for the wrapper binary.
252          *
253          * \param[in,out] optionsHolder Common options.
254          * \param[in,out] argc          On input, argc passed to run().
255          *     On output, argc to be passed to the module.
256          * \param[in,out] argv          On input, argv passed to run().
257          *     On output, argv to be passed to the module.
258          * \throws    InvalidInputError if there are invalid options.
259          * \returns   The module that should be run.
260          *
261          * Handles command-line options that affect the wrapper binary
262          * (potentially changing the members of \c this in response to the
263          * options).  Also finds the module that should be run and the
264          * arguments that should be passed to it.
265          */
266         CommandLineModuleInterface *
267         processCommonOptions(CommandLineCommonOptionsHolder *optionsHolder,
268                              int *argc, char ***argv);
269
270         /*! \brief
271          * Maps module names to module objects.
272          *
273          * Owns the contained modules.
274          */
275         CommandLineModuleMap         modules_;
276         /*! \brief
277          * List of groupings for modules for help output.
278          *
279          * Owns the contained module group data objects.
280          * CommandLineModuleGroup objects point to the data objects contained
281          * here.
282          */
283         CommandLineModuleGroupList   moduleGroups_;
284         //! Information about the currently running program.
285         CommandLineProgramContext   &programContext_;
286         //! Name of the binary.
287         std::string                  binaryName_;
288         /*! \brief
289          * Module that implements help for the binary.
290          *
291          * The pointed module is owned by the \a modules_ container.
292          */
293         CommandLineHelpModule       *helpModule_;
294         //! If non-NULL, run this module in single-module mode.
295         CommandLineModuleInterface  *singleModule_;
296         //! Stores the value set with setQuiet().
297         bool                         bQuiet_;
298
299     private:
300         GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
301 };
302
303 CommandLineModuleManager::Impl::Impl(const char                *binaryName,
304                                      CommandLineProgramContext *programContext)
305     : programContext_(*programContext),
306       binaryName_(binaryName != NULL ? binaryName : ""),
307       helpModule_(NULL), singleModule_(NULL),
308       bQuiet_(false)
309 {
310     GMX_RELEASE_ASSERT(binaryName_.find('-') == std::string::npos,
311                        "Help export does not currently work with binary names with dashes");
312 }
313
314 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
315 {
316     GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
317                "Attempted to register a duplicate module name");
318     ensureHelpModuleExists();
319     HelpTopicPointer helpTopic(helpModule_->createModuleHelpTopic(*module));
320     modules_.insert(std::make_pair(std::string(module->name()),
321                                    move(module)));
322     helpModule_->addTopic(move(helpTopic));
323 }
324
325 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
326 {
327     if (helpModule_ == NULL)
328     {
329         helpModule_ = new CommandLineHelpModule(programContext_, binaryName_,
330                                                 modules_, moduleGroups_);
331         addModule(CommandLineModulePointer(helpModule_));
332     }
333 }
334
335 CommandLineModuleMap::const_iterator
336 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
337 {
338     // TODO: Accept unambiguous prefixes?
339     return modules_.find(name);
340 }
341
342 CommandLineModuleInterface *
343 CommandLineModuleManager::Impl::processCommonOptions(
344         CommandLineCommonOptionsHolder *optionsHolder, int *argc, char ***argv)
345 {
346     // Check if we are directly invoking a certain module.
347     CommandLineModuleInterface *module = singleModule_;
348
349     // TODO: It would be nice to propagate at least the -quiet option to
350     // the modules so that they can also be quiet in response to this.
351
352     if (module == NULL)
353     {
354         // If not in single-module mode, process options to the wrapper binary.
355         // TODO: Ideally, this could be done by CommandLineParser.
356         int argcForWrapper = 1;
357         while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
358         {
359             ++argcForWrapper;
360         }
361         if (argcForWrapper > 1)
362         {
363             CommandLineParser(optionsHolder->options())
364                 .parse(&argcForWrapper, *argv);
365         }
366         // If no action requested and there is a module specified, process it.
367         if (argcForWrapper < *argc && !optionsHolder->shouldIgnoreActualModule())
368         {
369             const char *moduleName = (*argv)[argcForWrapper];
370             CommandLineModuleMap::const_iterator moduleIter
371                 = findModuleByName(moduleName);
372             if (moduleIter == modules_.end())
373             {
374                 std::string message =
375                     formatString("'%s' is not a GROMACS command.", moduleName);
376                 GMX_THROW(InvalidInputError(message));
377             }
378             module = moduleIter->second.get();
379             *argc -= argcForWrapper;
380             *argv += argcForWrapper;
381             // After this point, argc and argv are the same independent of
382             // which path is taken: (*argv)[0] is the module name.
383         }
384     }
385     if (module != NULL)
386     {
387         if (singleModule_ == NULL)
388         {
389             programContext_.setDisplayName(binaryName_ + " " + module->name());
390         }
391         // Recognize the common options also after the module name.
392         // TODO: It could be nicer to only recognize -h/-hidden if module is not
393         // null.
394         CommandLineParser(optionsHolder->options())
395             .skipUnknown(true).parse(argc, *argv);
396     }
397     if (!optionsHolder->finishOptions())
398     {
399         return NULL;
400     }
401     // If no module specified and no other action, show the help.
402     // Also explicitly specifying -h for the wrapper binary goes here.
403     if (module == NULL || optionsHolder->shouldShowHelp())
404     {
405         ensureHelpModuleExists();
406         if (module != NULL)
407         {
408             helpModule_->setModuleOverride(*module);
409         }
410         *argc  = 1;
411         module = helpModule_;
412     }
413     if (module == helpModule_)
414     {
415         helpModule_->setShowHidden(optionsHolder->shouldShowHidden());
416     }
417     return module;
418 }
419
420 /********************************************************************
421  * CommandLineModuleManager
422  */
423
424 CommandLineModuleManager::CommandLineModuleManager(
425         const char *binaryName, CommandLineProgramContext *programContext)
426     : impl_(new Impl(binaryName, programContext))
427 {
428 }
429
430 CommandLineModuleManager::~CommandLineModuleManager()
431 {
432 }
433
434 void CommandLineModuleManager::setQuiet(bool bQuiet)
435 {
436     impl_->bQuiet_ = bQuiet;
437 }
438
439 void CommandLineModuleManager::setOutputRedirect(File *output)
440 {
441     impl_->ensureHelpModuleExists();
442     impl_->helpModule_->setOutputRedirect(output);
443 }
444
445 void CommandLineModuleManager::setSingleModule(CommandLineModuleInterface *module)
446 {
447     impl_->singleModule_ = module;
448 }
449
450 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
451 {
452     impl_->addModule(move(module));
453 }
454
455 void CommandLineModuleManager::addModuleCMain(
456         const char *name, const char *shortDescription,
457         CMainFunction mainFunction)
458 {
459     CommandLineModulePointer module(
460             new CMainCommandLineModule(name, shortDescription, mainFunction));
461     addModule(move(module));
462 }
463
464 CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
465         const char *title)
466 {
467     const char *const                 binaryName = impl_->binaryName_.c_str();
468     CommandLineModuleGroupDataPointer group(
469             new CommandLineModuleGroupData(impl_->modules_, binaryName, title));
470     impl_->moduleGroups_.push_back(move(group));
471     return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
472 }
473
474 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
475 {
476     impl_->ensureHelpModuleExists();
477     impl_->helpModule_->addTopic(move(topic));
478 }
479
480 int CommandLineModuleManager::run(int argc, char *argv[])
481 {
482     CommandLineModuleInterface    *module;
483     const bool                     bMaster = (gmx_node_rank() == 0);
484     bool                           bQuiet  = impl_->bQuiet_ || !bMaster;
485     CommandLineCommonOptionsHolder optionsHolder;
486     try
487     {
488         optionsHolder.initOptions();
489         module = impl_->processCommonOptions(&optionsHolder, &argc, &argv);
490     }
491     catch (const std::exception &)
492     {
493         bQuiet |= optionsHolder.shouldBeQuiet();
494         if (!bQuiet)
495         {
496             printBinaryInformation(stderr, impl_->programContext_,
497                                    optionsHolder.binaryInfoSettings());
498         }
499         throw;
500     }
501     bQuiet |= optionsHolder.shouldBeQuiet();
502     if (!bQuiet)
503     {
504         FILE *out = optionsHolder.startupInfoFile();
505         printBinaryInformation(out, impl_->programContext_,
506                                optionsHolder.binaryInfoSettings());
507         fprintf(out, "\n");
508     }
509     if (module == NULL)
510     {
511         return 0;
512     }
513
514     CommandLineModuleSettings settings;
515     module->init(&settings);
516     optionsHolder.adjustFromSettings(settings);
517
518     gmx_set_max_backup_count(optionsHolder.shouldBackup() ? -1 : 0);
519
520     // Open the debug file.
521     if (optionsHolder.debugLevel() > 0)
522     {
523         std::string filename(impl_->programContext_.programName());
524         if (gmx_node_num() > 1)
525         {
526             filename.append(formatString("%d", gmx_node_rank()));
527         }
528         filename.append(".debug");
529
530         fprintf(stderr, "Will write debug log file: %s\n", filename.c_str());
531         gmx_init_debug(optionsHolder.debugLevel(), filename.c_str());
532     }
533     // Set the nice level unless disabled in the configuration.
534     if (optionsHolder.niceLevel() != 0)
535     {
536         static bool bNiceSet = false; // Only set it once.
537         if (!bNiceSet)
538         {
539             // TODO: Diagnostic if this fails and the user explicitly requested it.
540             gmx_set_nice(optionsHolder.niceLevel());
541             bNiceSet = true;
542         }
543     }
544     if (optionsHolder.enableFPExceptions())
545     {
546         //TODO: currently it is always enabled for mdrun (verlet) and tests.
547         gmx_feenableexcept();
548     }
549
550     int rc = 0;
551     if (!(module == impl_->helpModule_ && !bMaster))
552     {
553         rc = module->run(argc, argv);
554     }
555     if (!bQuiet)
556     {
557         gmx_thanx(stderr);
558     }
559     return rc;
560 }
561
562 // static
563 int CommandLineModuleManager::runAsMainSingleModule(
564         int argc, char *argv[], CommandLineModuleInterface *module)
565 {
566     CommandLineProgramContext &programContext = gmx::initForCommandLine(&argc, &argv);
567     try
568     {
569         CommandLineModuleManager manager(NULL, &programContext);
570         manager.setSingleModule(module);
571         int rc = manager.run(argc, argv);
572         gmx::finalizeForCommandLine();
573         return rc;
574     }
575     catch (const std::exception &ex)
576     {
577         printFatalErrorMessage(stderr, ex);
578         return processExceptionAtExitForCommandLine(ex);
579     }
580 }
581
582 // static
583 int CommandLineModuleManager::runAsMainCMain(
584         int argc, char *argv[], CMainFunction mainFunction)
585 {
586     CMainCommandLineModule module(argv[0], NULL, mainFunction);
587     return runAsMainSingleModule(argc, argv, &module);
588 }
589
590 /********************************************************************
591  * CommandLineModuleGroupData
592  */
593
594 void CommandLineModuleGroupData::addModule(const char *name,
595                                            const char *description)
596 {
597     CommandLineModuleMap::const_iterator moduleIter = allModules_.find(name);
598     GMX_RELEASE_ASSERT(moduleIter != allModules_.end(),
599                        "Non-existent module added to a group");
600     if (description == NULL)
601     {
602         description = moduleIter->second->shortDescription();
603         GMX_RELEASE_ASSERT(description != NULL,
604                            "Module without a description added to a group");
605     }
606     std::string       tag(formatString("%s-%s", binaryName_, name));
607     modules_.push_back(std::make_pair(tag, description));
608 }
609
610 /********************************************************************
611  * CommandLineModuleGroup
612  */
613
614 void CommandLineModuleGroup::addModule(const char *name)
615 {
616     impl_->addModule(name, NULL);
617 }
618
619 void CommandLineModuleGroup::addModuleWithDescription(const char *name,
620                                                       const char *description)
621 {
622     impl_->addModule(name, description);
623 }
624
625 } // namespace gmx