2 * Copyright 2013 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "folly/Subprocess.h"
20 #include <sys/types.h>
23 #include <boost/container/flat_set.hpp>
24 #include <glog/logging.h>
25 #include <gtest/gtest.h>
27 #include "folly/Exception.h"
28 #include "folly/Format.h"
29 #include "folly/String.h"
30 #include "folly/experimental/Gen.h"
31 #include "folly/experimental/FileGen.h"
32 #include "folly/experimental/StringGen.h"
33 #include "folly/experimental/io/FsUtil.h"
35 using namespace folly;
37 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
38 Subprocess proc(std::vector<std::string>{ "/bin/true" });
39 EXPECT_EQ(0, proc.wait().exitStatus());
42 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
43 Subprocess proc(std::vector<std::string>{ "/bin/true" });
47 TEST(SimpleSubprocessTest, ExitsWithError) {
48 Subprocess proc(std::vector<std::string>{ "/bin/false" });
49 EXPECT_EQ(1, proc.wait().exitStatus());
52 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
53 Subprocess proc(std::vector<std::string>{ "/bin/false" });
54 EXPECT_THROW(proc.waitChecked(), CalledProcessError);
57 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
60 Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
61 ADD_FAILURE() << "expected an error when running " << (cmd); \
62 } catch (const SubprocessSpawnError& ex) { \
63 EXPECT_EQ((err), ex.errnoValue()); \
64 if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
65 ADD_FAILURE() << "failed to find \"" << (errMsg) << \
66 "\" in exception: \"" << ex.what() << "\""; \
71 TEST(SimpleSubprocessTest, ExecFails) {
72 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
74 EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
76 EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
77 "/etc/passwd/not/a/file");
80 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
81 Subprocess proc("true");
82 EXPECT_EQ(0, proc.wait().exitStatus());
85 TEST(SimpleSubprocessTest, ShellExitsWithError) {
86 Subprocess proc("false");
87 EXPECT_EQ(1, proc.wait().exitStatus());
91 boost::container::flat_set<int> getOpenFds() {
93 auto dirname = to<std::string>("/proc/", pid, "/fd");
95 boost::container::flat_set<int> fds;
96 for (fs::directory_iterator it(dirname);
97 it != fs::directory_iterator();
99 int fd = to<int>(it->path().filename().native());
105 template<class Runnable>
106 void checkFdLeak(const Runnable& r) {
107 // Get the currently open fds. Check that they are the same both before and
108 // after calling the specified function. We read the open fds from /proc.
109 // (If we wanted to work even on systems that don't have /proc, we could
110 // perhaps create and immediately close a socket both before and after
111 // running the function, and make sure we got the same fd number both times.)
112 auto fdsBefore = getOpenFds();
114 auto fdsAfter = getOpenFds();
115 EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
119 // Make sure Subprocess doesn't leak any file descriptors
120 TEST(SimpleSubprocessTest, FdLeakTest) {
123 Subprocess proc("true");
124 EXPECT_EQ(0, proc.wait().exitStatus());
126 // Normal execution with pipes
128 Subprocess proc("echo foo; echo bar >&2",
129 Subprocess::pipeStdout() | Subprocess::pipeStderr());
130 auto p = proc.communicate();
131 EXPECT_EQ("foo\n", p.first);
132 EXPECT_EQ("bar\n", p.second);
136 // Test where the exec call fails()
138 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
140 // Test where the exec call fails() with pipes
143 Subprocess proc(std::vector<std::string>({"/no/such/file"}),
144 Subprocess::pipeStdout().stderr(Subprocess::PIPE));
145 ADD_FAILURE() << "expected an error when running /no/such/file";
146 } catch (const SubprocessSpawnError& ex) {
147 EXPECT_EQ(ENOENT, ex.errnoValue());
152 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
153 // Find out where we are.
154 static constexpr size_t pathLength = 2048;
155 char buf[pathLength + 1];
156 int r = readlink("/proc/self/exe", buf, pathLength);
160 fs::path helper(buf);
161 helper.remove_filename();
162 helper /= "subprocess_test_parent_death_helper";
164 fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
166 std::vector<std::string> args {helper.string(), tempFile.string()};
167 Subprocess proc(args);
168 // The helper gets killed by its child, see details in
169 // SubprocessTestParentDeathHelper.cpp
170 ASSERT_EQ(SIGKILL, proc.wait().killSignal());
172 // Now wait for the file to be created, see details in
173 // SubprocessTestParentDeathHelper.cpp
174 while (!fs::exists(tempFile)) {
175 usleep(20000); // 20ms
178 fs::remove(tempFile);
181 TEST(PopenSubprocessTest, PopenRead) {
182 Subprocess proc("ls /", Subprocess::pipeStdout());
184 gen::byLine(proc.stdout()) |
185 [&] (StringPiece line) {
186 if (line == "etc" || line == "bin" || line == "usr") {
194 TEST(CommunicateSubprocessTest, SimpleRead) {
195 Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
196 Subprocess::pipeStdout());
197 auto p = proc.communicate();
198 EXPECT_EQ("foo bar", p.first);
202 TEST(CommunicateSubprocessTest, BigWrite) {
203 const int numLines = 1 << 20;
204 std::string line("hello\n");
206 data.reserve(numLines * line.size());
207 for (int i = 0; i < numLines; ++i) {
211 Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
212 auto p = proc.communicate(data);
213 EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
217 TEST(CommunicateSubprocessTest, Duplex) {
218 // Take 10MB of data and pass them through a filter.
219 // One line, as tr is line-buffered
220 const int bytes = 10 << 20;
221 std::string line(bytes, 'x');
223 Subprocess proc("tr a-z A-Z",
224 Subprocess::pipeStdin() | Subprocess::pipeStdout());
225 auto p = proc.communicate(line);
226 EXPECT_EQ(bytes, p.first.size());
227 EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
231 TEST(CommunicateSubprocessTest, Duplex2) {
233 // Pipe 200,000 lines through sed
234 const size_t numCopies = 100000;
235 auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
237 for (int n = 0; n < numCopies; ++n) {
238 input.append(iobuf->clone());
241 std::vector<std::string> cmd({
243 "-e", "s/a test/a successful test/",
244 "-e", "/^another line/w/dev/stderr",
246 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
247 Subprocess proc(cmd, options);
248 auto out = proc.communicateIOBuf(std::move(input));
251 // Convert stdout and stderr to strings so we can call split() on them.
253 if (out.first.front()) {
254 stdoutStr = out.first.move()->moveToFbString();
257 if (out.second.front()) {
258 stderrStr = out.second.move()->moveToFbString();
261 // stdout should be a copy of stdin, with "a test" replaced by
262 // "a successful test"
263 std::vector<StringPiece> stdoutLines;
264 split('\n', stdoutStr, stdoutLines);
265 EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
266 // Strip off the trailing empty line
267 if (!stdoutLines.empty()) {
268 EXPECT_EQ("", stdoutLines.back());
269 stdoutLines.pop_back();
272 for (const auto& line : stdoutLines) {
273 if ((linenum & 1) == 0) {
274 EXPECT_EQ("this is a successful test", line);
276 EXPECT_EQ("another line", line);
281 // stderr should only contain the lines containing "another line"
282 std::vector<StringPiece> stderrLines;
283 split('\n', stderrStr, stderrLines);
284 EXPECT_EQ(numCopies + 1, stderrLines.size());
285 // Strip off the trailing empty line
286 if (!stderrLines.empty()) {
287 EXPECT_EQ("", stderrLines.back());
288 stderrLines.pop_back();
290 for (const auto& line : stderrLines) {
291 EXPECT_EQ("another line", line);