2 * Copyright 2014 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/io/FsUtil.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 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
61 Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
62 ADD_FAILURE() << "expected an error when running " << (cmd); \
63 } catch (const SubprocessSpawnError& ex) { \
64 EXPECT_EQ((err), ex.errnoValue()); \
65 if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
66 ADD_FAILURE() << "failed to find \"" << (errMsg) << \
67 "\" in exception: \"" << ex.what() << "\""; \
72 TEST(SimpleSubprocessTest, ExecFails) {
73 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
75 EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
77 EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
78 "/etc/passwd/not/a/file");
81 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
82 Subprocess proc("true");
83 EXPECT_EQ(0, proc.wait().exitStatus());
86 TEST(SimpleSubprocessTest, ShellExitsWithError) {
87 Subprocess proc("false");
88 EXPECT_EQ(1, proc.wait().exitStatus());
91 TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
92 // The filesystem root normally lacks a 'true' binary
93 EXPECT_EQ(0, chdir("/"));
94 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
95 // The child can fix that by moving to /bin before exec().
96 Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
97 EXPECT_EQ(0, proc.wait().exitStatus());
100 TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
103 std::vector<std::string>{"/bin/true"},
104 Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
106 ADD_FAILURE() << "expected to fail when changing the child's directory";
107 } catch (const SubprocessSpawnError& ex) {
108 EXPECT_EQ(ENOENT, ex.errnoValue());
109 const std::string expectedError =
110 "error preparing to execute /bin/true: No such file or directory";
111 if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
112 ADD_FAILURE() << "failed to find \"" << expectedError <<
113 "\" in exception: \"" << ex.what() << "\"";
119 boost::container::flat_set<int> getOpenFds() {
121 auto dirname = to<std::string>("/proc/", pid, "/fd");
123 boost::container::flat_set<int> fds;
124 for (fs::directory_iterator it(dirname);
125 it != fs::directory_iterator();
127 int fd = to<int>(it->path().filename().native());
133 template<class Runnable>
134 void checkFdLeak(const Runnable& r) {
135 // Get the currently open fds. Check that they are the same both before and
136 // after calling the specified function. We read the open fds from /proc.
137 // (If we wanted to work even on systems that don't have /proc, we could
138 // perhaps create and immediately close a socket both before and after
139 // running the function, and make sure we got the same fd number both times.)
140 auto fdsBefore = getOpenFds();
142 auto fdsAfter = getOpenFds();
143 EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
147 // Make sure Subprocess doesn't leak any file descriptors
148 TEST(SimpleSubprocessTest, FdLeakTest) {
151 Subprocess proc("true");
152 EXPECT_EQ(0, proc.wait().exitStatus());
154 // Normal execution with pipes
156 Subprocess proc("echo foo; echo bar >&2",
157 Subprocess::pipeStdout() | Subprocess::pipeStderr());
158 auto p = proc.communicate();
159 EXPECT_EQ("foo\n", p.first);
160 EXPECT_EQ("bar\n", p.second);
164 // Test where the exec call fails()
166 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
168 // Test where the exec call fails() with pipes
171 Subprocess proc(std::vector<std::string>({"/no/such/file"}),
172 Subprocess::pipeStdout().stderr(Subprocess::PIPE));
173 ADD_FAILURE() << "expected an error when running /no/such/file";
174 } catch (const SubprocessSpawnError& ex) {
175 EXPECT_EQ(ENOENT, ex.errnoValue());
180 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
181 // Find out where we are.
182 static constexpr size_t pathLength = 2048;
183 char buf[pathLength + 1];
184 int r = readlink("/proc/self/exe", buf, pathLength);
188 fs::path helper(buf);
189 helper.remove_filename();
190 helper /= "subprocess_test_parent_death_helper";
192 fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
194 std::vector<std::string> args {helper.string(), tempFile.string()};
195 Subprocess proc(args);
196 // The helper gets killed by its child, see details in
197 // SubprocessTestParentDeathHelper.cpp
198 ASSERT_EQ(SIGKILL, proc.wait().killSignal());
200 // Now wait for the file to be created, see details in
201 // SubprocessTestParentDeathHelper.cpp
202 while (!fs::exists(tempFile)) {
203 usleep(20000); // 20ms
206 fs::remove(tempFile);
209 TEST(PopenSubprocessTest, PopenRead) {
210 Subprocess proc("ls /", Subprocess::pipeStdout());
212 gen::byLine(File(proc.stdout())) |
213 [&] (StringPiece line) {
214 if (line == "etc" || line == "bin" || line == "usr") {
222 TEST(CommunicateSubprocessTest, SimpleRead) {
223 Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
224 Subprocess::pipeStdout());
225 auto p = proc.communicate();
226 EXPECT_EQ("foo bar", p.first);
230 TEST(CommunicateSubprocessTest, BigWrite) {
231 const int numLines = 1 << 20;
232 std::string line("hello\n");
234 data.reserve(numLines * line.size());
235 for (int i = 0; i < numLines; ++i) {
239 Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
240 auto p = proc.communicate(data);
241 EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
245 TEST(CommunicateSubprocessTest, Duplex) {
246 // Take 10MB of data and pass them through a filter.
247 // One line, as tr is line-buffered
248 const int bytes = 10 << 20;
249 std::string line(bytes, 'x');
251 Subprocess proc("tr a-z A-Z",
252 Subprocess::pipeStdin() | Subprocess::pipeStdout());
253 auto p = proc.communicate(line);
254 EXPECT_EQ(bytes, p.first.size());
255 EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
259 TEST(CommunicateSubprocessTest, Duplex2) {
261 // Pipe 200,000 lines through sed
262 const size_t numCopies = 100000;
263 auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
265 for (int n = 0; n < numCopies; ++n) {
266 input.append(iobuf->clone());
269 std::vector<std::string> cmd({
271 "-e", "s/a test/a successful test/",
272 "-e", "/^another line/w/dev/stderr",
274 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
275 Subprocess proc(cmd, options);
276 auto out = proc.communicateIOBuf(std::move(input));
279 // Convert stdout and stderr to strings so we can call split() on them.
281 if (out.first.front()) {
282 stdoutStr = out.first.move()->moveToFbString();
285 if (out.second.front()) {
286 stderrStr = out.second.move()->moveToFbString();
289 // stdout should be a copy of stdin, with "a test" replaced by
290 // "a successful test"
291 std::vector<StringPiece> stdoutLines;
292 split('\n', stdoutStr, stdoutLines);
293 EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
294 // Strip off the trailing empty line
295 if (!stdoutLines.empty()) {
296 EXPECT_EQ("", stdoutLines.back());
297 stdoutLines.pop_back();
300 for (const auto& line : stdoutLines) {
301 if ((linenum & 1) == 0) {
302 EXPECT_EQ("this is a successful test", line);
304 EXPECT_EQ("another line", line);
309 // stderr should only contain the lines containing "another line"
310 std::vector<StringPiece> stderrLines;
311 split('\n', stderrStr, stderrLines);
312 EXPECT_EQ(numCopies + 1, stderrLines.size());
313 // Strip off the trailing empty line
314 if (!stderrLines.empty()) {
315 EXPECT_EQ("", stderrLines.back());
316 stderrLines.pop_back();
318 for (const auto& line : stderrLines) {
319 EXPECT_EQ("another line", line);
326 bool readToString(int fd, std::string& buf, size_t maxSize) {
327 size_t bytesRead = 0;
330 char* dest = &buf.front();
331 size_t remaining = maxSize;
335 n = ::read(fd, dest, remaining);
337 if (errno == EINTR) {
340 if (errno == EAGAIN) {
343 PCHECK("read failed");
351 buf.resize(dest - buf.data());
357 TEST(CommunicateSubprocessTest, Chatty) {
359 const int lineCount = 1000;
364 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
365 std::vector<std::string> cmd {
369 "s/a test/a successful test/",
372 Subprocess proc(cmd, options);
374 auto writeCallback = [&] (int pfd, int cfd) -> bool {
375 EXPECT_EQ(0, cfd); // child stdin
376 EXPECT_EQ(rcount, wcount); // chatty, one read for every write
378 auto msg = folly::to<std::string>("a test ", wcount, "\n");
380 // Not entirely kosher, we should handle partial writes, but this is
381 // fine for writes <= PIPE_BUF
382 EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
385 proc.enableNotifications(0, false);
387 return (wcount == lineCount);
390 bool eofSeen = false;
392 auto readCallback = [&] (int pfd, int cfd) -> bool {
397 EXPECT_TRUE(readToString(pfd, lineBuf, 1));
398 EXPECT_EQ(0, lineBuf.size());
402 EXPECT_FALSE(eofSeen);
404 std::string expected;
406 if (rcount < lineCount) {
407 expected = folly::to<std::string>("a successful test ", rcount++, "\n");
410 EXPECT_EQ(wcount, rcount);
412 // Not entirely kosher, we should handle partial reads, but this is
413 // fine for reads <= PIPE_BUF
414 bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
416 // EOF only expected after we finished reading
417 EXPECT_EQ(lineCount, rcount);
421 EXPECT_EQ(expected, lineBuf);
423 if (wcount != lineCount) { // still more to write...
424 proc.enableNotifications(0, true);
430 proc.communicate(readCallback, writeCallback);
432 EXPECT_EQ(lineCount, wcount);
433 EXPECT_EQ(lineCount, rcount);
434 EXPECT_TRUE(eofSeen);
436 EXPECT_EQ(0, proc.wait().exitStatus());