Add ability to silence callbacks for Subprocess::communicate
[folly.git] / folly / test / SubprocessTest.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "folly/Subprocess.h"
18
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <dirent.h>
22
23 #include <boost/container/flat_set.hpp>
24 #include <glog/logging.h>
25 #include <gtest/gtest.h>
26
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"
35
36 using namespace folly;
37
38 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
39   Subprocess proc(std::vector<std::string>{ "/bin/true" });
40   EXPECT_EQ(0, proc.wait().exitStatus());
41 }
42
43 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
44   Subprocess proc(std::vector<std::string>{ "/bin/true" });
45   proc.waitChecked();
46 }
47
48 TEST(SimpleSubprocessTest, ExitsWithError) {
49   Subprocess proc(std::vector<std::string>{ "/bin/false" });
50   EXPECT_EQ(1, proc.wait().exitStatus());
51 }
52
53 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
54   Subprocess proc(std::vector<std::string>{ "/bin/false" });
55   EXPECT_THROW(proc.waitChecked(), CalledProcessError);
56 }
57
58 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
59   do { \
60     try { \
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() << "\""; \
68       } \
69     } \
70   } while (0)
71
72 TEST(SimpleSubprocessTest, ExecFails) {
73   EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
74                      "/no/such/file");
75   EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
76                      "/etc/passwd");
77   EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
78                      "/etc/passwd/not/a/file");
79 }
80
81 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
82   Subprocess proc("true");
83   EXPECT_EQ(0, proc.wait().exitStatus());
84 }
85
86 TEST(SimpleSubprocessTest, ShellExitsWithError) {
87   Subprocess proc("false");
88   EXPECT_EQ(1, proc.wait().exitStatus());
89 }
90
91 namespace {
92 boost::container::flat_set<int> getOpenFds() {
93   auto pid = getpid();
94   auto dirname = to<std::string>("/proc/", pid, "/fd");
95
96   boost::container::flat_set<int> fds;
97   for (fs::directory_iterator it(dirname);
98        it != fs::directory_iterator();
99        ++it) {
100     int fd = to<int>(it->path().filename().native());
101     fds.insert(fd);
102   }
103   return fds;
104 }
105
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();
114   r();
115   auto fdsAfter = getOpenFds();
116   EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
117 }
118 }
119
120 // Make sure Subprocess doesn't leak any file descriptors
121 TEST(SimpleSubprocessTest, FdLeakTest) {
122   // Normal execution
123   checkFdLeak([] {
124     Subprocess proc("true");
125     EXPECT_EQ(0, proc.wait().exitStatus());
126   });
127   // Normal execution with pipes
128   checkFdLeak([] {
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);
134     proc.waitChecked();
135   });
136
137   // Test where the exec call fails()
138   checkFdLeak([] {
139     EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
140   });
141   // Test where the exec call fails() with pipes
142   checkFdLeak([] {
143     try {
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());
149     }
150   });
151 }
152
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);
158   CHECK_ERR(r);
159   buf[r] = '\0';
160
161   fs::path helper(buf);
162   helper.remove_filename();
163   helper /= "subprocess_test_parent_death_helper";
164
165   fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
166
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());
172
173   // Now wait for the file to be created, see details in
174   // SubprocessTestParentDeathHelper.cpp
175   while (!fs::exists(tempFile)) {
176     usleep(20000);  // 20ms
177   }
178
179   fs::remove(tempFile);
180 }
181
182 TEST(PopenSubprocessTest, PopenRead) {
183   Subprocess proc("ls /", Subprocess::pipeStdout());
184   int found = 0;
185   gen::byLine(File(proc.stdout())) |
186     [&] (StringPiece line) {
187       if (line == "etc" || line == "bin" || line == "usr") {
188         ++found;
189       }
190     };
191   EXPECT_EQ(3, found);
192   proc.waitChecked();
193 }
194
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);
200   proc.waitChecked();
201 }
202
203 TEST(CommunicateSubprocessTest, BigWrite) {
204   const int numLines = 1 << 20;
205   std::string line("hello\n");
206   std::string data;
207   data.reserve(numLines * line.size());
208   for (int i = 0; i < numLines; ++i) {
209     data.append(line);
210   }
211
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);
215   proc.waitChecked();
216 }
217
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');
223
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'));
229   proc.waitChecked();
230 }
231
232 TEST(CommunicateSubprocessTest, Duplex2) {
233   checkFdLeak([] {
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");
237     IOBufQueue input;
238     for (int n = 0; n < numCopies; ++n) {
239       input.append(iobuf->clone());
240     }
241
242     std::vector<std::string> cmd({
243       "sed", "-u",
244       "-e", "s/a test/a successful test/",
245       "-e", "/^another line/w/dev/stderr",
246     });
247     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
248     Subprocess proc(cmd, options);
249     auto out = proc.communicateIOBuf(std::move(input));
250     proc.waitChecked();
251
252     // Convert stdout and stderr to strings so we can call split() on them.
253     fbstring stdoutStr;
254     if (out.first.front()) {
255       stdoutStr = out.first.move()->moveToFbString();
256     }
257     fbstring stderrStr;
258     if (out.second.front()) {
259       stderrStr = out.second.move()->moveToFbString();
260     }
261
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();
271     }
272     size_t linenum = 0;
273     for (const auto& line : stdoutLines) {
274       if ((linenum & 1) == 0) {
275         EXPECT_EQ("this is a successful test", line);
276       } else {
277         EXPECT_EQ("another line", line);
278       }
279       ++linenum;
280     }
281
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();
290     }
291     for (const auto& line : stderrLines) {
292       EXPECT_EQ("another line", line);
293     }
294   });
295 }
296
297 namespace {
298
299 bool readToString(int fd, std::string& buf, size_t maxSize) {
300   size_t bytesRead = 0;
301
302   buf.resize(maxSize);
303   char* dest = &buf.front();
304   size_t remaining = maxSize;
305
306   ssize_t n = -1;
307   while (remaining) {
308     n = ::read(fd, dest, remaining);
309     if (n == -1) {
310       if (errno == EINTR) {
311         continue;
312       }
313       if (errno == EAGAIN) {
314         break;
315       }
316       PCHECK("read failed");
317     } else if (n == 0) {
318       break;
319     }
320     dest += n;
321     remaining -= n;
322   }
323
324   buf.resize(dest - buf.data());
325   return (n == 0);
326 }
327
328 }  // namespace
329
330 TEST(CommunicateSubprocessTest, Chatty) {
331   checkFdLeak([] {
332     const int lineCount = 1000;
333
334     int wcount = 0;
335     int rcount = 0;
336
337     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
338     std::vector<std::string> cmd {
339       "sed",
340       "-u",
341       "-e",
342       "s/a test/a successful test/",
343     };
344
345     Subprocess proc(cmd, options);
346
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
350
351       auto msg = folly::to<std::string>("a test ", wcount, "\n");
352
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()));
356
357       ++wcount;
358       proc.enableNotifications(0, false);
359
360       return (wcount == lineCount);
361     };
362
363     auto readCallback = [&] (int pfd, int cfd) -> bool {
364       EXPECT_EQ(1, cfd);  // child stdout
365       EXPECT_EQ(wcount, rcount + 1);
366
367       auto expected =
368         folly::to<std::string>("a successful test ", rcount, "\n");
369
370       std::string lineBuf;
371
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);
375
376       EXPECT_EQ((rcount == lineCount), r);  // EOF iff at lineCount
377       EXPECT_EQ(expected, lineBuf);
378
379       ++rcount;
380       if (rcount != lineCount) {
381         proc.enableNotifications(0, true);
382       }
383
384       return (rcount == lineCount);
385     };
386
387     proc.communicate(readCallback, writeCallback);
388
389     EXPECT_EQ(lineCount, wcount);
390     EXPECT_EQ(lineCount, rcount);
391
392     EXPECT_EQ(0, proc.wait().exitStatus());
393   });
394 }