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());
92 boost::container::flat_set<int> getOpenFds() {
94 auto dirname = to<std::string>("/proc/", pid, "/fd");
96 boost::container::flat_set<int> fds;
97 for (fs::directory_iterator it(dirname);
98 it != fs::directory_iterator();
100 int fd = to<int>(it->path().filename().native());
106 template<class Runnable>
107 void checkFdLeak(const Runnable& r) {
108 // Get the currently open fds. Check that they are the same both before and
109 // after calling the specified function. We read the open fds from /proc.
110 // (If we wanted to work even on systems that don't have /proc, we could
111 // perhaps create and immediately close a socket both before and after
112 // running the function, and make sure we got the same fd number both times.)
113 auto fdsBefore = getOpenFds();
115 auto fdsAfter = getOpenFds();
116 EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
120 // Make sure Subprocess doesn't leak any file descriptors
121 TEST(SimpleSubprocessTest, FdLeakTest) {
124 Subprocess proc("true");
125 EXPECT_EQ(0, proc.wait().exitStatus());
127 // Normal execution with pipes
129 Subprocess proc("echo foo; echo bar >&2",
130 Subprocess::pipeStdout() | Subprocess::pipeStderr());
131 auto p = proc.communicate();
132 EXPECT_EQ("foo\n", p.first);
133 EXPECT_EQ("bar\n", p.second);
137 // Test where the exec call fails()
139 EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
141 // Test where the exec call fails() with pipes
144 Subprocess proc(std::vector<std::string>({"/no/such/file"}),
145 Subprocess::pipeStdout().stderr(Subprocess::PIPE));
146 ADD_FAILURE() << "expected an error when running /no/such/file";
147 } catch (const SubprocessSpawnError& ex) {
148 EXPECT_EQ(ENOENT, ex.errnoValue());
153 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
154 // Find out where we are.
155 static constexpr size_t pathLength = 2048;
156 char buf[pathLength + 1];
157 int r = readlink("/proc/self/exe", buf, pathLength);
161 fs::path helper(buf);
162 helper.remove_filename();
163 helper /= "subprocess_test_parent_death_helper";
165 fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
167 std::vector<std::string> args {helper.string(), tempFile.string()};
168 Subprocess proc(args);
169 // The helper gets killed by its child, see details in
170 // SubprocessTestParentDeathHelper.cpp
171 ASSERT_EQ(SIGKILL, proc.wait().killSignal());
173 // Now wait for the file to be created, see details in
174 // SubprocessTestParentDeathHelper.cpp
175 while (!fs::exists(tempFile)) {
176 usleep(20000); // 20ms
179 fs::remove(tempFile);
182 TEST(PopenSubprocessTest, PopenRead) {
183 Subprocess proc("ls /", Subprocess::pipeStdout());
185 gen::byLine(File(proc.stdout())) |
186 [&] (StringPiece line) {
187 if (line == "etc" || line == "bin" || line == "usr") {
195 TEST(CommunicateSubprocessTest, SimpleRead) {
196 Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
197 Subprocess::pipeStdout());
198 auto p = proc.communicate();
199 EXPECT_EQ("foo bar", p.first);
203 TEST(CommunicateSubprocessTest, BigWrite) {
204 const int numLines = 1 << 20;
205 std::string line("hello\n");
207 data.reserve(numLines * line.size());
208 for (int i = 0; i < numLines; ++i) {
212 Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
213 auto p = proc.communicate(data);
214 EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
218 TEST(CommunicateSubprocessTest, Duplex) {
219 // Take 10MB of data and pass them through a filter.
220 // One line, as tr is line-buffered
221 const int bytes = 10 << 20;
222 std::string line(bytes, 'x');
224 Subprocess proc("tr a-z A-Z",
225 Subprocess::pipeStdin() | Subprocess::pipeStdout());
226 auto p = proc.communicate(line);
227 EXPECT_EQ(bytes, p.first.size());
228 EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
232 TEST(CommunicateSubprocessTest, Duplex2) {
234 // Pipe 200,000 lines through sed
235 const size_t numCopies = 100000;
236 auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
238 for (int n = 0; n < numCopies; ++n) {
239 input.append(iobuf->clone());
242 std::vector<std::string> cmd({
244 "-e", "s/a test/a successful test/",
245 "-e", "/^another line/w/dev/stderr",
247 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
248 Subprocess proc(cmd, options);
249 auto out = proc.communicateIOBuf(std::move(input));
252 // Convert stdout and stderr to strings so we can call split() on them.
254 if (out.first.front()) {
255 stdoutStr = out.first.move()->moveToFbString();
258 if (out.second.front()) {
259 stderrStr = out.second.move()->moveToFbString();
262 // stdout should be a copy of stdin, with "a test" replaced by
263 // "a successful test"
264 std::vector<StringPiece> stdoutLines;
265 split('\n', stdoutStr, stdoutLines);
266 EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
267 // Strip off the trailing empty line
268 if (!stdoutLines.empty()) {
269 EXPECT_EQ("", stdoutLines.back());
270 stdoutLines.pop_back();
273 for (const auto& line : stdoutLines) {
274 if ((linenum & 1) == 0) {
275 EXPECT_EQ("this is a successful test", line);
277 EXPECT_EQ("another line", line);
282 // stderr should only contain the lines containing "another line"
283 std::vector<StringPiece> stderrLines;
284 split('\n', stderrStr, stderrLines);
285 EXPECT_EQ(numCopies + 1, stderrLines.size());
286 // Strip off the trailing empty line
287 if (!stderrLines.empty()) {
288 EXPECT_EQ("", stderrLines.back());
289 stderrLines.pop_back();
291 for (const auto& line : stderrLines) {
292 EXPECT_EQ("another line", line);
299 bool readToString(int fd, std::string& buf, size_t maxSize) {
300 size_t bytesRead = 0;
303 char* dest = &buf.front();
304 size_t remaining = maxSize;
308 n = ::read(fd, dest, remaining);
310 if (errno == EINTR) {
313 if (errno == EAGAIN) {
316 PCHECK("read failed");
324 buf.resize(dest - buf.data());
330 TEST(CommunicateSubprocessTest, Chatty) {
332 const int lineCount = 1000;
337 auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
338 std::vector<std::string> cmd {
342 "s/a test/a successful test/",
345 Subprocess proc(cmd, options);
347 auto writeCallback = [&] (int pfd, int cfd) -> bool {
348 EXPECT_EQ(0, cfd); // child stdin
349 EXPECT_EQ(rcount, wcount); // chatty, one read for every write
351 auto msg = folly::to<std::string>("a test ", wcount, "\n");
353 // Not entirely kosher, we should handle partial writes, but this is
354 // fine for writes <= PIPE_BUF
355 EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
358 proc.enableNotifications(0, false);
360 return (wcount == lineCount);
363 auto readCallback = [&] (int pfd, int cfd) -> bool {
364 EXPECT_EQ(1, cfd); // child stdout
365 EXPECT_EQ(wcount, rcount + 1);
368 folly::to<std::string>("a successful test ", rcount, "\n");
372 // Not entirely kosher, we should handle partial reads, but this is
373 // fine for reads <= PIPE_BUF
374 bool r = readToString(pfd, lineBuf, expected.size() + 1);
376 EXPECT_EQ((rcount == lineCount), r); // EOF iff at lineCount
377 EXPECT_EQ(expected, lineBuf);
380 if (rcount != lineCount) {
381 proc.enableNotifications(0, true);
384 return (rcount == lineCount);
387 proc.communicate(readCallback, writeCallback);
389 EXPECT_EQ(lineCount, wcount);
390 EXPECT_EQ(lineCount, rcount);
392 EXPECT_EQ(0, proc.wait().exitStatus());