2 * Copyright 2015 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/FileUtil.h>
30 #include <folly/String.h>
31 #include <folly/gen/Base.h>
32 #include <folly/gen/File.h>
33 #include <folly/gen/String.h>
34 #include <folly/experimental/TestUtil.h>
35 #include <folly/experimental/io/FsUtil.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, MoveSubprocess) {
60 Subprocess old_proc(std::vector<std::string>{ "/bin/true" });
61 EXPECT_TRUE(old_proc.returnCode().running());
62 auto new_proc = std::move(old_proc);
63 EXPECT_TRUE(old_proc.returnCode().notStarted());
64 EXPECT_TRUE(new_proc.returnCode().running());
65 EXPECT_EQ(0, new_proc.wait().exitStatus());
66 // Now old_proc is destroyed, but we don't crash.
69 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
72 Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
73 ADD_FAILURE() << "expected an error when running " << (cmd); \
74 } catch (const SubprocessSpawnError& ex) { \
75 EXPECT_EQ((err), ex.errnoValue()); \
76 if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
77 ADD_FAILURE() << "failed to find \"" << (errMsg) << \
78 "\" in exception: \"" << ex.what() << "\""; \
83 TEST(SimpleSubprocessTest, ExecFails) {
84 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
86 EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
88 EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
89 "/etc/passwd/not/a/file");
92 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
93 Subprocess proc("true");
94 EXPECT_EQ(0, proc.wait().exitStatus());
97 TEST(SimpleSubprocessTest, ShellExitsWithError) {
98 Subprocess proc("false");
99 EXPECT_EQ(1, proc.wait().exitStatus());
102 TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
103 // The filesystem root normally lacks a 'true' binary
104 EXPECT_EQ(0, chdir("/"));
105 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
106 // The child can fix that by moving to /bin before exec().
107 Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
108 EXPECT_EQ(0, proc.wait().exitStatus());
111 TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
114 std::vector<std::string>{"/bin/true"},
115 Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
117 ADD_FAILURE() << "expected to fail when changing the child's directory";
118 } catch (const SubprocessSpawnError& ex) {
119 EXPECT_EQ(ENOENT, ex.errnoValue());
120 const std::string expectedError =
121 "error preparing to execute /bin/true: No such file or directory";
122 if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
123 ADD_FAILURE() << "failed to find \"" << expectedError <<
124 "\" in exception: \"" << ex.what() << "\"";
130 boost::container::flat_set<int> getOpenFds() {
132 auto dirname = to<std::string>("/proc/", pid, "/fd");
134 boost::container::flat_set<int> fds;
135 for (fs::directory_iterator it(dirname);
136 it != fs::directory_iterator();
138 int fd = to<int>(it->path().filename().native());
144 template<class Runnable>
145 void checkFdLeak(const Runnable& r) {
146 // Get the currently open fds. Check that they are the same both before and
147 // after calling the specified function. We read the open fds from /proc.
148 // (If we wanted to work even on systems that don't have /proc, we could
149 // perhaps create and immediately close a socket both before and after
150 // running the function, and make sure we got the same fd number both times.)
151 auto fdsBefore = getOpenFds();
153 auto fdsAfter = getOpenFds();
154 EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
158 // Make sure Subprocess doesn't leak any file descriptors
159 TEST(SimpleSubprocessTest, FdLeakTest) {
162 Subprocess proc("true");
163 EXPECT_EQ(0, proc.wait().exitStatus());
165 // Normal execution with pipes
167 Subprocess proc("echo foo; echo bar >&2",
168 Subprocess::pipeStdout() | Subprocess::pipeStderr());
169 auto p = proc.communicate();
170 EXPECT_EQ("foo\n", p.first);
171 EXPECT_EQ("bar\n", p.second);
175 // Test where the exec call fails()
177 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
179 // Test where the exec call fails() with pipes
182 Subprocess proc(std::vector<std::string>({"/no/such/file"}),
183 Subprocess::pipeStdout().stderr(Subprocess::PIPE));
184 ADD_FAILURE() << "expected an error when running /no/such/file";
185 } catch (const SubprocessSpawnError& ex) {
186 EXPECT_EQ(ENOENT, ex.errnoValue());
191 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
192 // Find out where we are.
193 auto helper = fs::executable_path();
194 helper.remove_filename() /= "subprocess_test_parent_death_helper";
196 fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
198 std::vector<std::string> args {helper.string(), tempFile.string()};
199 Subprocess proc(args);
200 // The helper gets killed by its child, see details in
201 // SubprocessTestParentDeathHelper.cpp
202 ASSERT_EQ(SIGKILL, proc.wait().killSignal());
204 // Now wait for the file to be created, see details in
205 // SubprocessTestParentDeathHelper.cpp
206 while (!fs::exists(tempFile)) {
207 usleep(20000); // 20ms
210 fs::remove(tempFile);
213 TEST(PopenSubprocessTest, PopenRead) {
214 Subprocess proc("ls /", Subprocess::pipeStdout());
216 gen::byLine(File(proc.stdout())) |
217 [&] (StringPiece line) {
218 if (line == "etc" || line == "bin" || line == "usr") {
226 TEST(CommunicateSubprocessTest, SimpleRead) {
227 Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
228 Subprocess::pipeStdout());
229 auto p = proc.communicate();
230 EXPECT_EQ("foo bar", p.first);
234 TEST(CommunicateSubprocessTest, BigWrite) {
235 const int numLines = 1 << 20;
236 std::string line("hello\n");
238 data.reserve(numLines * line.size());
239 for (int i = 0; i < numLines; ++i) {
243 Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
244 auto p = proc.communicate(data);
245 EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
249 TEST(CommunicateSubprocessTest, Duplex) {
250 // Take 10MB of data and pass them through a filter.
251 // One line, as tr is line-buffered
252 const int bytes = 10 << 20;
253 std::string line(bytes, 'x');
255 Subprocess proc("tr a-z A-Z",
256 Subprocess::pipeStdin() | Subprocess::pipeStdout());
257 auto p = proc.communicate(line);
258 EXPECT_EQ(bytes, p.first.size());
259 EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
263 TEST(CommunicateSubprocessTest, ProcessGroupLeader) {
264 const auto testIsLeader = "test $(cut -d ' ' -f 5 /proc/$$/stat) = $$";
265 Subprocess nonLeader(testIsLeader);
266 EXPECT_THROW(nonLeader.waitChecked(), CalledProcessError);
267 Subprocess leader(testIsLeader, Subprocess::Options().processGroupLeader());
268 leader.waitChecked();
271 TEST(CommunicateSubprocessTest, Duplex2) {
273 // Pipe 200,000 lines through sed
274 const size_t numCopies = 100000;
275 auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
277 for (size_t n = 0; n < numCopies; ++n) {
278 input.append(iobuf->clone());
281 std::vector<std::string> cmd({
283 "-e", "s/a test/a successful test/",
284 "-e", "/^another line/w/dev/stderr",
286 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
287 Subprocess proc(cmd, options);
288 auto out = proc.communicateIOBuf(std::move(input));
291 // Convert stdout and stderr to strings so we can call split() on them.
293 if (out.first.front()) {
294 stdoutStr = out.first.move()->moveToFbString();
297 if (out.second.front()) {
298 stderrStr = out.second.move()->moveToFbString();
301 // stdout should be a copy of stdin, with "a test" replaced by
302 // "a successful test"
303 std::vector<StringPiece> stdoutLines;
304 split('\n', stdoutStr, stdoutLines);
305 EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
306 // Strip off the trailing empty line
307 if (!stdoutLines.empty()) {
308 EXPECT_EQ("", stdoutLines.back());
309 stdoutLines.pop_back();
312 for (const auto& line : stdoutLines) {
313 if ((linenum & 1) == 0) {
314 EXPECT_EQ("this is a successful test", line);
316 EXPECT_EQ("another line", line);
321 // stderr should only contain the lines containing "another line"
322 std::vector<StringPiece> stderrLines;
323 split('\n', stderrStr, stderrLines);
324 EXPECT_EQ(numCopies + 1, stderrLines.size());
325 // Strip off the trailing empty line
326 if (!stderrLines.empty()) {
327 EXPECT_EQ("", stderrLines.back());
328 stderrLines.pop_back();
330 for (const auto& line : stderrLines) {
331 EXPECT_EQ("another line", line);
338 bool readToString(int fd, std::string& buf, size_t maxSize) {
339 size_t bytesRead = 0;
342 char* dest = &buf.front();
343 size_t remaining = maxSize;
347 n = ::read(fd, dest, remaining);
349 if (errno == EINTR) {
352 if (errno == EAGAIN) {
355 PCHECK("read failed");
363 buf.resize(dest - buf.data());
369 TEST(CommunicateSubprocessTest, Chatty) {
371 const int lineCount = 1000;
376 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
377 std::vector<std::string> cmd {
381 "s/a test/a successful test/",
384 Subprocess proc(cmd, options);
386 auto writeCallback = [&] (int pfd, int cfd) -> bool {
387 EXPECT_EQ(0, cfd); // child stdin
388 EXPECT_EQ(rcount, wcount); // chatty, one read for every write
390 auto msg = folly::to<std::string>("a test ", wcount, "\n");
392 // Not entirely kosher, we should handle partial writes, but this is
393 // fine for writes <= PIPE_BUF
394 EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
397 proc.enableNotifications(0, false);
399 return (wcount == lineCount);
402 bool eofSeen = false;
404 auto readCallback = [&] (int pfd, int cfd) -> bool {
409 EXPECT_TRUE(readToString(pfd, lineBuf, 1));
410 EXPECT_EQ(0, lineBuf.size());
414 EXPECT_FALSE(eofSeen);
416 std::string expected;
418 if (rcount < lineCount) {
419 expected = folly::to<std::string>("a successful test ", rcount++, "\n");
422 EXPECT_EQ(wcount, rcount);
424 // Not entirely kosher, we should handle partial reads, but this is
425 // fine for reads <= PIPE_BUF
426 bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
428 // EOF only expected after we finished reading
429 EXPECT_EQ(lineCount, rcount);
433 EXPECT_EQ(expected, lineBuf);
435 if (wcount != lineCount) { // still more to write...
436 proc.enableNotifications(0, true);
442 proc.communicate(readCallback, writeCallback);
444 EXPECT_EQ(lineCount, wcount);
445 EXPECT_EQ(lineCount, rcount);
446 EXPECT_TRUE(eofSeen);
448 EXPECT_EQ(0, proc.wait().exitStatus());
452 TEST(CommunicateSubprocessTest, TakeOwnershipOfPipes) {
453 std::vector<Subprocess::ChildPipe> pipes;
456 "echo $'oh\\nmy\\ncat' | wc -l &", Subprocess::pipeStdout()
458 pipes = proc.takeOwnershipOfPipes();
461 EXPECT_EQ(1, pipes.size());
462 EXPECT_EQ(1, pipes[0].childFd);
465 EXPECT_EQ(2, readFull(pipes[0].pipe.fd(), buf, 10));
467 EXPECT_EQ("3\n", std::string(buf));