ebfa26613bf4a9dbb4db7fae4f801a34f6af10c6
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlineprogramcontext.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::CommandLineProgramContext.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_commandline
41  */
42 #include "gmxpre.h"
43
44 #include "cmdlineprogramcontext.h"
45
46 #include "config.h"
47
48 #include <cstdlib>
49 #include <cstring>
50
51 #include <string>
52 #include <vector>
53
54 #include <boost/scoped_ptr.hpp>
55
56 #include "thread_mpi/mutex.h"
57
58 #include "buildinfo.h"
59 #include "gromacs/utility/exceptions.h"
60 #include "gromacs/utility/file.h"
61 #include "gromacs/utility/gmxassert.h"
62 #include "gromacs/utility/path.h"
63 #include "gromacs/utility/stringutil.h"
64
65 namespace gmx
66 {
67
68 namespace
69 {
70
71 //! \addtogroup module_commandline
72 //! \{
73
74 /*! \brief
75  * Quotes a string if it contains spaces.
76  */
77 std::string quoteIfNecessary(const char *str)
78 {
79     const bool bSpaces = (std::strchr(str, ' ') != NULL);
80     if (bSpaces)
81     {
82         return formatString("'%s'", str);
83     }
84     return str;
85 }
86
87 /*! \brief
88  * Default implementation for ExecutableEnvironmentInterface.
89  *
90  * Used if ExecutableEnvironmentInterface is not explicitly provided when
91  * constructing CommandLineProgramContext.
92  */
93 class DefaultExecutableEnvironment : public ExecutableEnvironmentInterface
94 {
95     public:
96         //! Allocates a default environment.
97         static ExecutableEnvironmentPointer create()
98         {
99             return ExecutableEnvironmentPointer(new DefaultExecutableEnvironment());
100         }
101
102         DefaultExecutableEnvironment()
103             : initialWorkingDirectory_(Path::getWorkingDirectory())
104         {
105         }
106
107         virtual std::string getWorkingDirectory() const
108         {
109             return initialWorkingDirectory_;
110         }
111         virtual std::vector<std::string> getExecutablePaths() const
112         {
113             return Path::getExecutablePaths();
114         }
115
116     private:
117         std::string   initialWorkingDirectory_;
118 };
119
120 /*! \brief
121  * Finds the absolute path of the binary from \c argv[0].
122  *
123  * \param[in] invokedName \c argv[0] the binary was invoked with.
124  * \param[in] env         Executable environment.
125  * \returns   The full path of the binary.
126  *
127  * If a binary with the given name cannot be located, \p invokedName is
128  * returned.
129  */
130 std::string findFullBinaryPath(const std::string                    &invokedName,
131                                const ExecutableEnvironmentInterface &env)
132 {
133     std::string searchName = invokedName;
134     // On Windows & Cygwin we need to add the .exe extension,
135     // or we wont be able to detect that the file exists.
136 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
137     if (!endsWith(searchName, ".exe"))
138     {
139         searchName.append(".exe");
140     }
141 #endif
142     if (!Path::containsDirectory(searchName))
143     {
144         // No directory in name means it must be in the path - search it!
145         std::vector<std::string>                 pathEntries = env.getExecutablePaths();
146         std::vector<std::string>::const_iterator i;
147         for (i = pathEntries.begin(); i != pathEntries.end(); ++i)
148         {
149             const std::string &dir      = i->empty() ? env.getWorkingDirectory() : *i;
150             std::string        testPath = Path::join(dir, searchName);
151             if (File::exists(testPath))
152             {
153                 return testPath;
154             }
155         }
156     }
157     else if (!Path::isAbsolute(searchName))
158     {
159         // Name contains directories, but is not absolute, i.e.,
160         // it is relative to the current directory.
161         std::string cwd      = env.getWorkingDirectory();
162         std::string testPath = Path::join(cwd, searchName);
163         return testPath;
164     }
165     return searchName;
166 }
167
168 /*! \brief
169  * Returns whether given path contains files from `share/top/`.
170  *
171  * Only checks for a single file that has an uncommon enough name.
172  */
173 bool isAcceptableLibraryPath(const std::string &path)
174 {
175     return Path::exists(Path::join(path, "gurgle.dat"));
176 }
177
178 /*! \brief
179  * Returns whether given path prefix contains files from `share/top/`.
180  *
181  * \param[in]  path   Path prefix to check.
182  * \returns  `true` if \p path contains the data files.
183  *
184  * Checks whether \p path could be the installation prefix where `share/top/`
185  * files have been installed:  appends the relative installation path of the
186  * data files and calls isAcceptableLibraryPath().
187  */
188 bool isAcceptableLibraryPathPrefix(const std::string &path)
189 {
190     std::string testPath = Path::join(path, DATA_INSTALL_DIR, "top");
191     if (isAcceptableLibraryPath(testPath))
192     {
193         return true;
194     }
195     return false;
196 }
197
198 /*! \brief
199  * Returns a fallback installation prefix path.
200  *
201  * Checks a few standard locations for the data files before returning a
202  * configure-time hard-coded path.  The hard-coded path is preferred if it
203  * actually contains the data files, though.
204  */
205 std::string findFallbackInstallationPrefixPath()
206 {
207 #ifndef GMX_NATIVE_WINDOWS
208     if (!isAcceptableLibraryPathPrefix(CMAKE_INSTALL_PREFIX))
209     {
210         if (isAcceptableLibraryPathPrefix("/usr/local"))
211         {
212             return "/usr/local";
213         }
214         if (isAcceptableLibraryPathPrefix("/usr"))
215         {
216             return "/usr";
217         }
218         if (isAcceptableLibraryPathPrefix("/opt"))
219         {
220             return "/opt";
221         }
222     }
223 #endif
224     return CMAKE_INSTALL_PREFIX;
225 }
226
227 /*! \brief
228  * Finds the library data files based on path of the binary.
229  *
230  * \param[in]  binaryPath     Absolute path to the binary.
231  * \param[out] bSourceLayout  Set to `true` if the binary is run from
232  *     the build tree and the original source directory can be found.
233  * \returns  Path to the `share/top/` data files.
234  *
235  * The search based on the path only works if the binary is in the same
236  * relative path as the installed \Gromacs binaries.  If the binary is
237  * somewhere else, a hard-coded fallback is used.  This doesn't work if the
238  * binaries are somewhere else than the path given during configure time...
239  *
240  * Extra logic is present to allow running binaries from the build tree such
241  * that they use up-to-date data files from the source tree.
242  */
243 std::string findInstallationPrefixPath(const std::string &binaryPath,
244                                        bool              *bSourceLayout)
245 {
246     *bSourceLayout = false;
247     // Don't search anything if binary cannot be found.
248     if (Path::exists(binaryPath))
249     {
250         // Remove the executable name.
251         std::string searchPath = Path::getParentPath(binaryPath);
252         // If running directly from the build tree, try to use the source
253         // directory.
254 #if (defined CMAKE_SOURCE_DIR && defined CMAKE_BINARY_DIR)
255         std::string buildBinPath;
256 #ifdef CMAKE_INTDIR
257         buildBinPath = Path::join(CMAKE_BINARY_DIR, "bin", CMAKE_INTDIR);
258 #else
259         buildBinPath = Path::join(CMAKE_BINARY_DIR, "bin");
260 #endif
261         if (Path::isEquivalent(searchPath, buildBinPath))
262         {
263             std::string testPath = Path::join(CMAKE_SOURCE_DIR, "share/top");
264             if (isAcceptableLibraryPath(testPath))
265             {
266                 *bSourceLayout = true;
267                 return CMAKE_SOURCE_DIR;
268             }
269         }
270 #endif
271
272         // Use the executable path to (try to) find the library dir.
273         // TODO: Consider only going up exactly the required number of levels.
274         while (!searchPath.empty())
275         {
276             if (isAcceptableLibraryPathPrefix(searchPath))
277             {
278                 return searchPath;
279             }
280             searchPath = Path::getParentPath(searchPath);
281         }
282     }
283
284     // End of smart searching. If we didn't find it in our parent tree,
285     // or if the program name wasn't set, return a fallback.
286     return findFallbackInstallationPrefixPath();
287 }
288
289 //! \}
290
291 }   // namespace
292
293 /********************************************************************
294  * CommandLineProgramContext::Impl
295  */
296
297 class CommandLineProgramContext::Impl
298 {
299     public:
300         Impl();
301         Impl(int argc, const char *const argv[],
302              ExecutableEnvironmentPointer env);
303
304         /*! \brief
305          * Finds the full binary path if it isn't searched yet.
306          *
307          * Sets \a fullBinaryPath_ if it isn't set yet.
308          *
309          * The \a binaryPathMutex_ should be locked by the caller before
310          * calling this function.
311          */
312         void findBinaryPath() const;
313
314         ExecutableEnvironmentPointer  executableEnv_;
315         std::string                   invokedName_;
316         std::string                   programName_;
317         std::string                   displayName_;
318         std::string                   commandLine_;
319         mutable std::string           fullBinaryPath_;
320         mutable std::string           installationPrefix_;
321         mutable bool                  bSourceLayout_;
322         mutable tMPI::mutex           binaryPathMutex_;
323 };
324
325 CommandLineProgramContext::Impl::Impl()
326     : programName_("GROMACS"), bSourceLayout_(false)
327 {
328 }
329
330 CommandLineProgramContext::Impl::Impl(int argc, const char *const argv[],
331                                       ExecutableEnvironmentPointer env)
332     : executableEnv_(env), bSourceLayout_(false)
333 {
334     invokedName_ = (argc != 0 ? argv[0] : "");
335     programName_ = Path::getFilename(invokedName_);
336     programName_ = stripSuffixIfPresent(programName_, ".exe");
337
338     commandLine_ = quoteIfNecessary(programName_.c_str());
339     for (int i = 1; i < argc; ++i)
340     {
341         commandLine_.append(" ");
342         commandLine_.append(quoteIfNecessary(argv[i]));
343     }
344 }
345
346 void CommandLineProgramContext::Impl::findBinaryPath() const
347 {
348     if (fullBinaryPath_.empty())
349     {
350         fullBinaryPath_ = findFullBinaryPath(invokedName_, *executableEnv_);
351         fullBinaryPath_ = Path::normalize(Path::resolveSymlinks(fullBinaryPath_));
352         // TODO: Investigate/Consider using a dladdr()-based solution.
353         // Potentially less portable, but significantly simpler, and also works
354         // with user binaries even if they are located in some arbitrary location,
355         // as long as shared libraries are used.
356     }
357 }
358
359 /********************************************************************
360  * CommandLineProgramContext
361  */
362
363 CommandLineProgramContext::CommandLineProgramContext()
364     : impl_(new Impl)
365 {
366 }
367
368 CommandLineProgramContext::CommandLineProgramContext(const char *binaryName)
369     : impl_(new Impl(1, &binaryName, DefaultExecutableEnvironment::create()))
370 {
371 }
372
373 CommandLineProgramContext::CommandLineProgramContext(
374         int argc, const char *const argv[])
375     : impl_(new Impl(argc, argv, DefaultExecutableEnvironment::create()))
376 {
377 }
378
379 CommandLineProgramContext::CommandLineProgramContext(
380         int argc, const char *const argv[], ExecutableEnvironmentPointer env)
381     : impl_(new Impl(argc, argv, env))
382 {
383 }
384
385 CommandLineProgramContext::~CommandLineProgramContext()
386 {
387 }
388
389 void CommandLineProgramContext::setDisplayName(const std::string &name)
390 {
391     GMX_RELEASE_ASSERT(impl_->displayName_.empty(),
392                        "Can only set display name once");
393     impl_->displayName_ = name;
394 }
395
396 const char *CommandLineProgramContext::programName() const
397 {
398     return impl_->programName_.c_str();
399 }
400
401 const char *CommandLineProgramContext::displayName() const
402 {
403     return impl_->displayName_.empty()
404            ? impl_->programName_.c_str()
405            : impl_->displayName_.c_str();
406 }
407
408 const char *CommandLineProgramContext::commandLine() const
409 {
410     return impl_->commandLine_.c_str();
411 }
412
413 const char *CommandLineProgramContext::fullBinaryPath() const
414 {
415     tMPI::lock_guard<tMPI::mutex> lock(impl_->binaryPathMutex_);
416     impl_->findBinaryPath();
417     return impl_->fullBinaryPath_.c_str();
418 }
419
420 InstallationPrefixInfo CommandLineProgramContext::installationPrefix() const
421 {
422     tMPI::lock_guard<tMPI::mutex> lock(impl_->binaryPathMutex_);
423     if (impl_->installationPrefix_.empty())
424     {
425         impl_->findBinaryPath();
426         impl_->installationPrefix_ =
427             Path::normalize(findInstallationPrefixPath(impl_->fullBinaryPath_,
428                                                        &impl_->bSourceLayout_));
429     }
430     return InstallationPrefixInfo(
431             impl_->installationPrefix_.c_str(),
432             impl_->bSourceLayout_);
433 }
434
435 } // namespace gmx