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>
20 #include <sys/types.h>
22 #include <boost/container/flat_set.hpp>
23 #include <glog/logging.h>
24 #include <gtest/gtest.h>
26 #include <folly/Exception.h>
27 #include <folly/Format.h>
28 #include <folly/FileUtil.h>
29 #include <folly/String.h>
30 #include <folly/gen/Base.h>
31 #include <folly/gen/File.h>
32 #include <folly/gen/String.h>
33 #include <folly/experimental/TestUtil.h>
34 #include <folly/experimental/io/FsUtil.h>
35 #include <folly/portability/Dirent.h>
37 using namespace folly;
39 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
40 Subprocess proc(std::vector<std::string>{ "/bin/true" });
41 EXPECT_EQ(0, proc.wait().exitStatus());
44 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
45 Subprocess proc(std::vector<std::string>{ "/bin/true" });
49 TEST(SimpleSubprocessTest, ExitsWithError) {
50 Subprocess proc(std::vector<std::string>{ "/bin/false" });
51 EXPECT_EQ(1, proc.wait().exitStatus());
54 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
55 Subprocess proc(std::vector<std::string>{ "/bin/false" });
56 EXPECT_THROW(proc.waitChecked(), CalledProcessError);
59 TEST(SimpleSubprocessTest, DefaultConstructibleProcessReturnCode) {
60 ProcessReturnCode retcode;
61 EXPECT_TRUE(retcode.notStarted());
64 TEST(SimpleSubprocessTest, MoveSubprocess) {
65 Subprocess old_proc(std::vector<std::string>{ "/bin/true" });
66 EXPECT_TRUE(old_proc.returnCode().running());
67 auto new_proc = std::move(old_proc);
68 EXPECT_TRUE(old_proc.returnCode().notStarted());
69 EXPECT_TRUE(new_proc.returnCode().running());
70 EXPECT_EQ(0, new_proc.wait().exitStatus());
71 // Now old_proc is destroyed, but we don't crash.
74 TEST(SimpleSubprocessTest, DefaultConstructor) {
76 EXPECT_TRUE(proc.returnCode().notStarted());
79 auto p1 = Subprocess(std::vector<std::string>{"/bin/true"});
83 EXPECT_TRUE(proc.returnCode().running());
84 EXPECT_EQ(0, proc.wait().exitStatus());
87 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
90 Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
91 ADD_FAILURE() << "expected an error when running " << (cmd); \
92 } catch (const SubprocessSpawnError& ex) { \
93 EXPECT_EQ((err), ex.errnoValue()); \
94 if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
95 ADD_FAILURE() << "failed to find \"" << (errMsg) << \
96 "\" in exception: \"" << ex.what() << "\""; \
101 TEST(SimpleSubprocessTest, ExecFails) {
102 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
104 EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
106 EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
107 "/etc/passwd/not/a/file");
110 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
111 Subprocess proc("true");
112 EXPECT_EQ(0, proc.wait().exitStatus());
115 TEST(SimpleSubprocessTest, ShellExitsWithError) {
116 Subprocess proc("false");
117 EXPECT_EQ(1, proc.wait().exitStatus());
120 TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
121 // The filesystem root normally lacks a 'true' binary
122 EXPECT_EQ(0, chdir("/"));
123 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
124 // The child can fix that by moving to /bin before exec().
125 Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
126 EXPECT_EQ(0, proc.wait().exitStatus());
129 TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
132 std::vector<std::string>{"/bin/true"},
133 Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
135 ADD_FAILURE() << "expected to fail when changing the child's directory";
136 } catch (const SubprocessSpawnError& ex) {
137 EXPECT_EQ(ENOENT, ex.errnoValue());
138 const std::string expectedError =
139 "error preparing to execute /bin/true: No such file or directory";
140 if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
141 ADD_FAILURE() << "failed to find \"" << expectedError <<
142 "\" in exception: \"" << ex.what() << "\"";
148 boost::container::flat_set<int> getOpenFds() {
150 auto dirname = to<std::string>("/proc/", pid, "/fd");
152 boost::container::flat_set<int> fds;
153 for (fs::directory_iterator it(dirname);
154 it != fs::directory_iterator();
156 int fd = to<int>(it->path().filename().native());
162 template<class Runnable>
163 void checkFdLeak(const Runnable& r) {
164 // Get the currently open fds. Check that they are the same both before and
165 // after calling the specified function. We read the open fds from /proc.
166 // (If we wanted to work even on systems that don't have /proc, we could
167 // perhaps create and immediately close a socket both before and after
168 // running the function, and make sure we got the same fd number both times.)
169 auto fdsBefore = getOpenFds();
171 auto fdsAfter = getOpenFds();
172 EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
176 // Make sure Subprocess doesn't leak any file descriptors
177 TEST(SimpleSubprocessTest, FdLeakTest) {
180 Subprocess proc("true");
181 EXPECT_EQ(0, proc.wait().exitStatus());
183 // Normal execution with pipes
185 Subprocess proc("echo foo; echo bar >&2",
186 Subprocess::pipeStdout() | Subprocess::pipeStderr());
187 auto p = proc.communicate();
188 EXPECT_EQ("foo\n", p.first);
189 EXPECT_EQ("bar\n", p.second);
193 // Test where the exec call fails()
195 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
197 // Test where the exec call fails() with pipes
200 Subprocess proc(std::vector<std::string>({"/no/such/file"}),
201 Subprocess::pipeStdout().stderr(Subprocess::PIPE));
202 ADD_FAILURE() << "expected an error when running /no/such/file";
203 } catch (const SubprocessSpawnError& ex) {
204 EXPECT_EQ(ENOENT, ex.errnoValue());
209 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
210 // Find out where we are.
211 const auto basename = "subprocess_test_parent_death_helper";
212 auto helper = fs::executable_path();
213 helper.remove_filename() /= basename;
214 if (!fs::exists(helper)) {
215 helper = helper.parent_path().parent_path() / basename / basename;
218 fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
220 std::vector<std::string> args {helper.string(), tempFile.string()};
221 Subprocess proc(args);
222 // The helper gets killed by its child, see details in
223 // SubprocessTestParentDeathHelper.cpp
224 ASSERT_EQ(SIGKILL, proc.wait().killSignal());
226 // Now wait for the file to be created, see details in
227 // SubprocessTestParentDeathHelper.cpp
228 while (!fs::exists(tempFile)) {
229 usleep(20000); // 20ms
232 fs::remove(tempFile);
235 TEST(PopenSubprocessTest, PopenRead) {
236 Subprocess proc("ls /", Subprocess::pipeStdout());
238 gen::byLine(File(proc.stdout())) |
239 [&] (StringPiece line) {
240 if (line == "etc" || line == "bin" || line == "usr") {
248 // DANGER: This class runs after fork in a child processes. Be fast, the
249 // parent thread is waiting, but remember that other parent threads are
250 // running and may mutate your state. Avoid mutating any data belonging to
251 // the parent. Avoid interacting with non-POD data that originated in the
252 // parent. Avoid any libraries that may internally reference non-POD data.
253 // Especially beware parent mutexes -- for example, glog's LOG() uses one.
254 struct WriteFileAfterFork
255 : public Subprocess::DangerousPostForkPreExecCallback {
256 explicit WriteFileAfterFork(std::string filename)
257 : filename_(std::move(filename)) {}
258 virtual ~WriteFileAfterFork() {}
259 int operator()() override {
260 return writeFile(std::string("ok"), filename_.c_str()) ? 0 : errno;
262 const std::string filename_;
265 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackSuccess) {
266 test::ChangeToTempDir td;
267 // Trigger a file write from the child.
268 WriteFileAfterFork write_cob("good_file");
270 std::vector<std::string>{"/bin/echo"},
271 Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
273 // The file gets written immediately.
275 EXPECT_TRUE(readFile(write_cob.filename_.c_str(), s));
280 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackError) {
281 test::ChangeToTempDir td;
282 // The child will try to write to a file, whose directory does not exist.
283 WriteFileAfterFork write_cob("bad/file");
286 std::vector<std::string>{"/bin/echo"},
287 Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
291 EXPECT_FALSE(fs::exists(write_cob.filename_));
294 TEST(CommunicateSubprocessTest, SimpleRead) {
295 Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
296 Subprocess::pipeStdout());
297 auto p = proc.communicate();
298 EXPECT_EQ("foo bar", p.first);
302 TEST(CommunicateSubprocessTest, BigWrite) {
303 const int numLines = 1 << 20;
304 std::string line("hello\n");
306 data.reserve(numLines * line.size());
307 for (int i = 0; i < numLines; ++i) {
311 Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
312 auto p = proc.communicate(data);
313 EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
317 TEST(CommunicateSubprocessTest, Duplex) {
318 // Take 10MB of data and pass them through a filter.
319 // One line, as tr is line-buffered
320 const int bytes = 10 << 20;
321 std::string line(bytes, 'x');
323 Subprocess proc("tr a-z A-Z",
324 Subprocess::pipeStdin() | Subprocess::pipeStdout());
325 auto p = proc.communicate(line);
326 EXPECT_EQ(bytes, p.first.size());
327 EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
331 TEST(CommunicateSubprocessTest, ProcessGroupLeader) {
332 const auto testIsLeader = "test $(cut -d ' ' -f 5 /proc/$$/stat) = $$";
333 Subprocess nonLeader(testIsLeader);
334 EXPECT_THROW(nonLeader.waitChecked(), CalledProcessError);
335 Subprocess leader(testIsLeader, Subprocess::Options().processGroupLeader());
336 leader.waitChecked();
339 TEST(CommunicateSubprocessTest, Duplex2) {
341 // Pipe 200,000 lines through sed
342 const size_t numCopies = 100000;
343 auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
345 for (size_t n = 0; n < numCopies; ++n) {
346 input.append(iobuf->clone());
349 std::vector<std::string> cmd({
351 "-e", "s/a test/a successful test/",
352 "-e", "/^another line/w/dev/stderr",
354 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
355 Subprocess proc(cmd, options);
356 auto out = proc.communicateIOBuf(std::move(input));
359 // Convert stdout and stderr to strings so we can call split() on them.
361 if (out.first.front()) {
362 stdoutStr = out.first.move()->moveToFbString();
365 if (out.second.front()) {
366 stderrStr = out.second.move()->moveToFbString();
369 // stdout should be a copy of stdin, with "a test" replaced by
370 // "a successful test"
371 std::vector<StringPiece> stdoutLines;
372 split('\n', stdoutStr, stdoutLines);
373 EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
374 // Strip off the trailing empty line
375 if (!stdoutLines.empty()) {
376 EXPECT_EQ("", stdoutLines.back());
377 stdoutLines.pop_back();
380 for (const auto& line : stdoutLines) {
381 if ((linenum & 1) == 0) {
382 EXPECT_EQ("this is a successful test", line);
384 EXPECT_EQ("another line", line);
389 // stderr should only contain the lines containing "another line"
390 std::vector<StringPiece> stderrLines;
391 split('\n', stderrStr, stderrLines);
392 EXPECT_EQ(numCopies + 1, stderrLines.size());
393 // Strip off the trailing empty line
394 if (!stderrLines.empty()) {
395 EXPECT_EQ("", stderrLines.back());
396 stderrLines.pop_back();
398 for (const auto& line : stderrLines) {
399 EXPECT_EQ("another line", line);
406 bool readToString(int fd, std::string& buf, size_t maxSize) {
408 char* dest = &buf.front();
409 size_t remaining = maxSize;
413 n = ::read(fd, dest, remaining);
415 if (errno == EINTR) {
418 if (errno == EAGAIN) {
421 PCHECK("read failed");
429 buf.resize(dest - buf.data());
435 TEST(CommunicateSubprocessTest, Chatty) {
437 const int lineCount = 1000;
442 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
443 std::vector<std::string> cmd {
447 "s/a test/a successful test/",
450 Subprocess proc(cmd, options);
452 auto writeCallback = [&] (int pfd, int cfd) -> bool {
453 EXPECT_EQ(0, cfd); // child stdin
454 EXPECT_EQ(rcount, wcount); // chatty, one read for every write
456 auto msg = folly::to<std::string>("a test ", wcount, "\n");
458 // Not entirely kosher, we should handle partial writes, but this is
459 // fine for writes <= PIPE_BUF
460 EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
463 proc.enableNotifications(0, false);
465 return (wcount == lineCount);
468 bool eofSeen = false;
470 auto readCallback = [&] (int pfd, int cfd) -> bool {
475 EXPECT_TRUE(readToString(pfd, lineBuf, 1));
476 EXPECT_EQ(0, lineBuf.size());
480 EXPECT_FALSE(eofSeen);
482 std::string expected;
484 if (rcount < lineCount) {
485 expected = folly::to<std::string>("a successful test ", rcount++, "\n");
488 EXPECT_EQ(wcount, rcount);
490 // Not entirely kosher, we should handle partial reads, but this is
491 // fine for reads <= PIPE_BUF
492 bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
494 // EOF only expected after we finished reading
495 EXPECT_EQ(lineCount, rcount);
499 EXPECT_EQ(expected, lineBuf);
501 if (wcount != lineCount) { // still more to write...
502 proc.enableNotifications(0, true);
508 proc.communicate(readCallback, writeCallback);
510 EXPECT_EQ(lineCount, wcount);
511 EXPECT_EQ(lineCount, rcount);
512 EXPECT_TRUE(eofSeen);
514 EXPECT_EQ(0, proc.wait().exitStatus());
518 TEST(CommunicateSubprocessTest, TakeOwnershipOfPipes) {
519 std::vector<Subprocess::ChildPipe> pipes;
522 "echo $'oh\\nmy\\ncat' | wc -l &", Subprocess::pipeStdout()
524 pipes = proc.takeOwnershipOfPipes();
527 EXPECT_EQ(1, pipes.size());
528 EXPECT_EQ(1, pipes[0].childFd);
531 EXPECT_EQ(2, readFull(pipes[0].pipe.fd(), buf, 10));
533 EXPECT_EQ("3\n", std::string(buf));