1// Copyright 2015 The Kyua Authors.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9//   notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright
11//   notice, this list of conditions and the following disclaimer in the
12//   documentation and/or other materials provided with the distribution.
13// * Neither the name of Google Inc. nor the names of its contributors
14//   may be used to endorse or promote products derived from this software
15//   without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29#if !defined(UTILS_PROCESS_EXECUTOR_IPP)
30#define UTILS_PROCESS_EXECUTOR_IPP
31
32#include "utils/process/executor.hpp"
33
34#include "utils/fs/path.hpp"
35#include "utils/optional.ipp"
36#include "utils/passwd.hpp"
37#include "utils/process/child.ipp"
38
39namespace utils {
40namespace process {
41
42
43namespace executor {
44namespace detail {
45
46/// Functor to execute a hook in a child process.
47///
48/// The hook is executed after the process has been isolated per the logic in
49/// utils::process::isolation based on the input parameters at construction
50/// time.
51template< class Hook >
52class run_child {
53    /// Function or functor to invoke in the child.
54    Hook _hook;
55
56    /// Directory where the hook may place control files.
57    const fs::path& _control_directory;
58
59    /// Directory to enter when running the subprocess.
60    ///
61    /// This is a subdirectory of _control_directory but is separate so that
62    /// subprocess operations do not inadvertently affect our files.
63    const fs::path& _work_directory;
64
65    /// User to switch to when running the subprocess.
66    ///
67    /// If not none, the subprocess will be executed as the provided user and
68    /// the control and work directories will be writable by this user.
69    const optional< passwd::user > _unprivileged_user;
70
71public:
72    /// Constructor.
73    ///
74    /// \param hook Function or functor to invoke in the child.
75    /// \param control_directory Directory where control files can be placed.
76    /// \param work_directory Directory to enter when running the subprocess.
77    /// \param unprivileged_user If set, user to switch to before execution.
78    run_child(Hook hook,
79              const fs::path& control_directory,
80              const fs::path& work_directory,
81              const optional< passwd::user > unprivileged_user) :
82        _hook(hook),
83        _control_directory(control_directory),
84        _work_directory(work_directory),
85        _unprivileged_user(unprivileged_user)
86    {
87    }
88
89    /// Body of the subprocess.
90    void
91    operator()(void)
92    {
93        executor::detail::setup_child(_unprivileged_user,
94                                      _control_directory, _work_directory);
95        _hook(_control_directory);
96    }
97};
98
99}  // namespace detail
100}  // namespace executor
101
102
103/// Forks and executes a subprocess asynchronously.
104///
105/// \tparam Hook Type of the hook.
106/// \param hook Function or functor to run in the subprocess.
107/// \param timeout Maximum amount of time the subprocess can run for.
108/// \param unprivileged_user If not none, user to switch to before execution.
109/// \param stdout_target If not none, file to which to write the stdout of the
110///     test case.
111/// \param stderr_target If not none, file to which to write the stderr of the
112///     test case.
113///
114/// \return A handle for the background operation.  Used to match the result of
115/// the execution returned by wait_any() with this invocation.
116template< class Hook >
117executor::exec_handle
118executor::executor_handle::spawn(
119    Hook hook,
120    const datetime::delta& timeout,
121    const optional< passwd::user > unprivileged_user,
122    const optional< fs::path > stdout_target,
123    const optional< fs::path > stderr_target)
124{
125    const fs::path unique_work_directory = spawn_pre();
126
127    const fs::path stdout_path = stdout_target ?
128        stdout_target.get() : (unique_work_directory / detail::stdout_name);
129    const fs::path stderr_path = stderr_target ?
130        stderr_target.get() : (unique_work_directory / detail::stderr_name);
131
132    std::auto_ptr< process::child > child = process::child::fork_files(
133        detail::run_child< Hook >(hook,
134                                  unique_work_directory,
135                                  unique_work_directory / detail::work_subdir,
136                                  unprivileged_user),
137        stdout_path, stderr_path);
138
139    return spawn_post(unique_work_directory, stdout_path, stderr_path,
140                      timeout, unprivileged_user, child);
141}
142
143
144/// Forks and executes a subprocess asynchronously in the context of another.
145///
146/// By context we understand the on-disk state of a previously-executed process,
147/// thus the new subprocess spawned by this function will run with the same
148/// control and work directories as another process.
149///
150/// \tparam Hook Type of the hook.
151/// \param hook Function or functor to run in the subprocess.
152/// \param base Context of the subprocess in which to run this one.  The
153///     exit_handle provided here must remain alive throughout the existence of
154///     this other object because the original exit_handle is the one that owns
155///     the on-disk state.
156/// \param timeout Maximum amount of time the subprocess can run for.
157///
158/// \return A handle for the background operation.  Used to match the result of
159/// the execution returned by wait_any() with this invocation.
160template< class Hook >
161executor::exec_handle
162executor::executor_handle::spawn_followup(Hook hook,
163                                          const exit_handle& base,
164                                          const datetime::delta& timeout)
165{
166    spawn_followup_pre();
167
168    std::auto_ptr< process::child > child = process::child::fork_files(
169        detail::run_child< Hook >(hook,
170                                  base.control_directory(),
171                                  base.work_directory(),
172                                  base.unprivileged_user()),
173        base.stdout_file(), base.stderr_file());
174
175    return spawn_followup_post(base, timeout, child);
176}
177
178
179}  // namespace process
180}  // namespace utils
181
182#endif  // !defined(UTILS_PROCESS_EXECUTOR_IPP)
183