2 * Copyright 2016 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>
19 #include <sys/types.h>
21 #include <boost/container/flat_set.hpp>
22 #include <glog/logging.h>
23 #include <gtest/gtest.h>
25 #include <folly/Exception.h>
26 #include <folly/Format.h>
27 #include <folly/FileUtil.h>
28 #include <folly/String.h>
29 #include <folly/gen/Base.h>
30 #include <folly/gen/File.h>
31 #include <folly/gen/String.h>
32 #include <folly/experimental/TestUtil.h>
33 #include <folly/experimental/io/FsUtil.h>
34 #include <folly/portability/Unistd.h>
36 using namespace folly;
38 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
39 Subprocess proc(std::vector<std::string>{ "/bin/true" });
40 EXPECT_EQ(0, proc.wait().exitStatus());
43 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
44 Subprocess proc(std::vector<std::string>{ "/bin/true" });
48 TEST(SimpleSubprocessTest, ExitsWithError) {
49 Subprocess proc(std::vector<std::string>{ "/bin/false" });
50 EXPECT_EQ(1, proc.wait().exitStatus());
53 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
54 Subprocess proc(std::vector<std::string>{ "/bin/false" });
55 EXPECT_THROW(proc.waitChecked(), CalledProcessError);
58 TEST(SimpleSubprocessTest, DefaultConstructibleProcessReturnCode) {
59 ProcessReturnCode retcode;
60 EXPECT_TRUE(retcode.notStarted());
63 TEST(SimpleSubprocessTest, MoveSubprocess) {
64 Subprocess old_proc(std::vector<std::string>{ "/bin/true" });
65 EXPECT_TRUE(old_proc.returnCode().running());
66 auto new_proc = std::move(old_proc);
67 EXPECT_TRUE(old_proc.returnCode().notStarted());
68 EXPECT_TRUE(new_proc.returnCode().running());
69 EXPECT_EQ(0, new_proc.wait().exitStatus());
70 // Now old_proc is destroyed, but we don't crash.
73 TEST(SimpleSubprocessTest, DefaultConstructor) {
75 EXPECT_TRUE(proc.returnCode().notStarted());
78 auto p1 = Subprocess(std::vector<std::string>{"/bin/true"});
82 EXPECT_TRUE(proc.returnCode().running());
83 EXPECT_EQ(0, proc.wait().exitStatus());
86 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
89 Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
90 ADD_FAILURE() << "expected an error when running " << (cmd); \
91 } catch (const SubprocessSpawnError& ex) { \
92 EXPECT_EQ((err), ex.errnoValue()); \
93 if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
94 ADD_FAILURE() << "failed to find \"" << (errMsg) << \
95 "\" in exception: \"" << ex.what() << "\""; \
100 TEST(SimpleSubprocessTest, ExecFails) {
101 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
103 EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
105 EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
106 "/etc/passwd/not/a/file");
109 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
110 Subprocess proc("true");
111 EXPECT_EQ(0, proc.wait().exitStatus());
114 TEST(SimpleSubprocessTest, ShellExitsWithError) {
115 Subprocess proc("false");
116 EXPECT_EQ(1, proc.wait().exitStatus());
119 TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
120 // The filesystem root normally lacks a 'true' binary
121 EXPECT_EQ(0, chdir("/"));
122 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
123 // The child can fix that by moving to /bin before exec().
124 Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
125 EXPECT_EQ(0, proc.wait().exitStatus());
128 TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
131 std::vector<std::string>{"/bin/true"},
132 Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
134 ADD_FAILURE() << "expected to fail when changing the child's directory";
135 } catch (const SubprocessSpawnError& ex) {
136 EXPECT_EQ(ENOENT, ex.errnoValue());
137 const std::string expectedError =
138 "error preparing to execute /bin/true: No such file or directory";
139 if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
140 ADD_FAILURE() << "failed to find \"" << expectedError <<
141 "\" in exception: \"" << ex.what() << "\"";
147 boost::container::flat_set<int> getOpenFds() {
149 auto dirname = to<std::string>("/proc/", pid, "/fd");
151 boost::container::flat_set<int> fds;
152 for (fs::directory_iterator it(dirname);
153 it != fs::directory_iterator();
155 int fd = to<int>(it->path().filename().native());
161 template<class Runnable>
162 void checkFdLeak(const Runnable& r) {
163 // Get the currently open fds. Check that they are the same both before and
164 // after calling the specified function. We read the open fds from /proc.
165 // (If we wanted to work even on systems that don't have /proc, we could
166 // perhaps create and immediately close a socket both before and after
167 // running the function, and make sure we got the same fd number both times.)
168 auto fdsBefore = getOpenFds();
170 auto fdsAfter = getOpenFds();
171 EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
175 // Make sure Subprocess doesn't leak any file descriptors
176 TEST(SimpleSubprocessTest, FdLeakTest) {
179 Subprocess proc("true");
180 EXPECT_EQ(0, proc.wait().exitStatus());
182 // Normal execution with pipes
184 Subprocess proc("echo foo; echo bar >&2",
185 Subprocess::pipeStdout() | Subprocess::pipeStderr());
186 auto p = proc.communicate();
187 EXPECT_EQ("foo\n", p.first);
188 EXPECT_EQ("bar\n", p.second);
192 // Test where the exec call fails()
194 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
196 // Test where the exec call fails() with pipes
199 Subprocess proc(std::vector<std::string>({"/no/such/file"}),
200 Subprocess::pipeStdout().stderr(Subprocess::PIPE));
201 ADD_FAILURE() << "expected an error when running /no/such/file";
202 } catch (const SubprocessSpawnError& ex) {
203 EXPECT_EQ(ENOENT, ex.errnoValue());
208 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
209 // Find out where we are.
210 const auto basename = "subprocess_test_parent_death_helper";
211 auto helper = fs::executable_path();
212 helper.remove_filename() /= basename;
213 if (!fs::exists(helper)) {
214 helper = helper.parent_path().parent_path() / basename / basename;
217 fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
219 std::vector<std::string> args {helper.string(), tempFile.string()};
220 Subprocess proc(args);
221 // The helper gets killed by its child, see details in
222 // SubprocessTestParentDeathHelper.cpp
223 ASSERT_EQ(SIGKILL, proc.wait().killSignal());
225 // Now wait for the file to be created, see details in
226 // SubprocessTestParentDeathHelper.cpp
227 while (!fs::exists(tempFile)) {
228 usleep(20000); // 20ms
231 fs::remove(tempFile);
234 TEST(PopenSubprocessTest, PopenRead) {
235 Subprocess proc("ls /", Subprocess::pipeStdout());
237 gen::byLine(File(proc.stdout())) |
238 [&] (StringPiece line) {
239 if (line == "etc" || line == "bin" || line == "usr") {
247 // DANGER: This class runs after fork in a child processes. Be fast, the
248 // parent thread is waiting, but remember that other parent threads are
249 // running and may mutate your state. Avoid mutating any data belonging to
250 // the parent. Avoid interacting with non-POD data that originated in the
251 // parent. Avoid any libraries that may internally reference non-POD data.
252 // Especially beware parent mutexes -- for example, glog's LOG() uses one.
253 struct WriteFileAfterFork
254 : public Subprocess::DangerousPostForkPreExecCallback {
255 explicit WriteFileAfterFork(std::string filename)
256 : filename_(std::move(filename)) {}
257 virtual ~WriteFileAfterFork() {}
258 int operator()() override {
259 return writeFile(std::string("ok"), filename_.c_str()) ? 0 : errno;
261 const std::string filename_;
264 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackSuccess) {
265 test::ChangeToTempDir td;
266 // Trigger a file write from the child.
267 WriteFileAfterFork write_cob("good_file");
269 std::vector<std::string>{"/bin/echo"},
270 Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
272 // The file gets written immediately.
274 EXPECT_TRUE(readFile(write_cob.filename_.c_str(), s));
279 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackError) {
280 test::ChangeToTempDir td;
281 // The child will try to write to a file, whose directory does not exist.
282 WriteFileAfterFork write_cob("bad/file");
285 std::vector<std::string>{"/bin/echo"},
286 Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
290 EXPECT_FALSE(fs::exists(write_cob.filename_));
293 TEST(CommunicateSubprocessTest, SimpleRead) {
294 Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
295 Subprocess::pipeStdout());
296 auto p = proc.communicate();
297 EXPECT_EQ("foo bar", p.first);
301 TEST(CommunicateSubprocessTest, BigWrite) {
302 const int numLines = 1 << 20;
303 std::string line("hello\n");
305 data.reserve(numLines * line.size());
306 for (int i = 0; i < numLines; ++i) {
310 Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
311 auto p = proc.communicate(data);
312 EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
316 TEST(CommunicateSubprocessTest, Duplex) {
317 // Take 10MB of data and pass them through a filter.
318 // One line, as tr is line-buffered
319 const int bytes = 10 << 20;
320 std::string line(bytes, 'x');
322 Subprocess proc("tr a-z A-Z",
323 Subprocess::pipeStdin() | Subprocess::pipeStdout());
324 auto p = proc.communicate(line);
325 EXPECT_EQ(bytes, p.first.size());
326 EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
330 TEST(CommunicateSubprocessTest, ProcessGroupLeader) {
331 const auto testIsLeader = "test $(cut -d ' ' -f 5 /proc/$$/stat) = $$";
332 Subprocess nonLeader(testIsLeader);
333 EXPECT_THROW(nonLeader.waitChecked(), CalledProcessError);
334 Subprocess leader(testIsLeader, Subprocess::Options().processGroupLeader());
335 leader.waitChecked();
338 TEST(CommunicateSubprocessTest, Duplex2) {
340 // Pipe 200,000 lines through sed
341 const size_t numCopies = 100000;
342 auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
344 for (size_t n = 0; n < numCopies; ++n) {
345 input.append(iobuf->clone());
348 std::vector<std::string> cmd({
350 "-e", "s/a test/a successful test/",
351 "-e", "/^another line/w/dev/stderr",
353 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
354 Subprocess proc(cmd, options);
355 auto out = proc.communicateIOBuf(std::move(input));
358 // Convert stdout and stderr to strings so we can call split() on them.
360 if (out.first.front()) {
361 stdoutStr = out.first.move()->moveToFbString();
364 if (out.second.front()) {
365 stderrStr = out.second.move()->moveToFbString();
368 // stdout should be a copy of stdin, with "a test" replaced by
369 // "a successful test"
370 std::vector<StringPiece> stdoutLines;
371 split('\n', stdoutStr, stdoutLines);
372 EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
373 // Strip off the trailing empty line
374 if (!stdoutLines.empty()) {
375 EXPECT_EQ("", stdoutLines.back());
376 stdoutLines.pop_back();
379 for (const auto& line : stdoutLines) {
380 if ((linenum & 1) == 0) {
381 EXPECT_EQ("this is a successful test", line);
383 EXPECT_EQ("another line", line);
388 // stderr should only contain the lines containing "another line"
389 std::vector<StringPiece> stderrLines;
390 split('\n', stderrStr, stderrLines);
391 EXPECT_EQ(numCopies + 1, stderrLines.size());
392 // Strip off the trailing empty line
393 if (!stderrLines.empty()) {
394 EXPECT_EQ("", stderrLines.back());
395 stderrLines.pop_back();
397 for (const auto& line : stderrLines) {
398 EXPECT_EQ("another line", line);
405 bool readToString(int fd, std::string& buf, size_t maxSize) {
407 char* dest = &buf.front();
408 size_t remaining = maxSize;
412 n = ::read(fd, dest, remaining);
414 if (errno == EINTR) {
417 if (errno == EAGAIN) {
420 PCHECK("read failed");
428 buf.resize(dest - buf.data());
434 TEST(CommunicateSubprocessTest, Chatty) {
436 const int lineCount = 1000;
441 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
442 std::vector<std::string> cmd {
446 "s/a test/a successful test/",
449 Subprocess proc(cmd, options);
451 auto writeCallback = [&] (int pfd, int cfd) -> bool {
452 EXPECT_EQ(0, cfd); // child stdin
453 EXPECT_EQ(rcount, wcount); // chatty, one read for every write
455 auto msg = folly::to<std::string>("a test ", wcount, "\n");
457 // Not entirely kosher, we should handle partial writes, but this is
458 // fine for writes <= PIPE_BUF
459 EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
462 proc.enableNotifications(0, false);
464 return (wcount == lineCount);
467 bool eofSeen = false;
469 auto readCallback = [&] (int pfd, int cfd) -> bool {
474 EXPECT_TRUE(readToString(pfd, lineBuf, 1));
475 EXPECT_EQ(0, lineBuf.size());
479 EXPECT_FALSE(eofSeen);
481 std::string expected;
483 if (rcount < lineCount) {
484 expected = folly::to<std::string>("a successful test ", rcount++, "\n");
487 EXPECT_EQ(wcount, rcount);
489 // Not entirely kosher, we should handle partial reads, but this is
490 // fine for reads <= PIPE_BUF
491 bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
493 // EOF only expected after we finished reading
494 EXPECT_EQ(lineCount, rcount);
498 EXPECT_EQ(expected, lineBuf);
500 if (wcount != lineCount) { // still more to write...
501 proc.enableNotifications(0, true);
507 proc.communicate(readCallback, writeCallback);
509 EXPECT_EQ(lineCount, wcount);
510 EXPECT_EQ(lineCount, rcount);
511 EXPECT_TRUE(eofSeen);
513 EXPECT_EQ(0, proc.wait().exitStatus());
517 TEST(CommunicateSubprocessTest, TakeOwnershipOfPipes) {
518 std::vector<Subprocess::ChildPipe> pipes;
521 "echo $'oh\\nmy\\ncat' | wc -l &", Subprocess::pipeStdout()
523 pipes = proc.takeOwnershipOfPipes();
526 EXPECT_EQ(1, pipes.size());
527 EXPECT_EQ(1, pipes[0].childFd);
530 EXPECT_EQ(2, readFull(pipes[0].pipe.fd(), buf, 10));
532 EXPECT_EQ("3\n", std::string(buf));