add a default Subprocess constructor
[folly.git] / folly / test / SubprocessTest.cpp
1 /*
2  * Copyright 2016 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/TestUtil.h>
35 #include <folly/experimental/io/FsUtil.h>
36
37 using namespace folly;
38
39 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
40   Subprocess proc(std::vector<std::string>{ "/bin/true" });
41   EXPECT_EQ(0, proc.wait().exitStatus());
42 }
43
44 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
45   Subprocess proc(std::vector<std::string>{ "/bin/true" });
46   proc.waitChecked();
47 }
48
49 TEST(SimpleSubprocessTest, ExitsWithError) {
50   Subprocess proc(std::vector<std::string>{ "/bin/false" });
51   EXPECT_EQ(1, proc.wait().exitStatus());
52 }
53
54 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
55   Subprocess proc(std::vector<std::string>{ "/bin/false" });
56   EXPECT_THROW(proc.waitChecked(), CalledProcessError);
57 }
58
59 TEST(SimpleSubprocessTest, DefaultConstructibleProcessReturnCode) {
60   ProcessReturnCode retcode;
61   EXPECT_TRUE(retcode.notStarted());
62 }
63
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.
72 }
73
74 TEST(SimpleSubprocessTest, DefaultConstructor) {
75   Subprocess proc;
76   EXPECT_TRUE(proc.returnCode().notStarted());
77
78   {
79     auto p1 = Subprocess(std::vector<std::string>{"/bin/true"});
80     proc = std::move(p1);
81   }
82
83   EXPECT_TRUE(proc.returnCode().running());
84   EXPECT_EQ(0, proc.wait().exitStatus());
85 }
86
87 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
88   do { \
89     try { \
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() << "\""; \
97       } \
98     } \
99   } while (0)
100
101 TEST(SimpleSubprocessTest, ExecFails) {
102   EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
103                      "/no/such/file");
104   EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
105                      "/etc/passwd");
106   EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
107                      "/etc/passwd/not/a/file");
108 }
109
110 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
111   Subprocess proc("true");
112   EXPECT_EQ(0, proc.wait().exitStatus());
113 }
114
115 TEST(SimpleSubprocessTest, ShellExitsWithError) {
116   Subprocess proc("false");
117   EXPECT_EQ(1, proc.wait().exitStatus());
118 }
119
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());
127 }
128
129 TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
130   try {
131     Subprocess proc(
132       std::vector<std::string>{"/bin/true"},
133       Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
134     );
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() << "\"";
143     }
144   }
145 }
146
147 namespace {
148 boost::container::flat_set<int> getOpenFds() {
149   auto pid = getpid();
150   auto dirname = to<std::string>("/proc/", pid, "/fd");
151
152   boost::container::flat_set<int> fds;
153   for (fs::directory_iterator it(dirname);
154        it != fs::directory_iterator();
155        ++it) {
156     int fd = to<int>(it->path().filename().native());
157     fds.insert(fd);
158   }
159   return fds;
160 }
161
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();
170   r();
171   auto fdsAfter = getOpenFds();
172   EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
173 }
174 }
175
176 // Make sure Subprocess doesn't leak any file descriptors
177 TEST(SimpleSubprocessTest, FdLeakTest) {
178   // Normal execution
179   checkFdLeak([] {
180     Subprocess proc("true");
181     EXPECT_EQ(0, proc.wait().exitStatus());
182   });
183   // Normal execution with pipes
184   checkFdLeak([] {
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);
190     proc.waitChecked();
191   });
192
193   // Test where the exec call fails()
194   checkFdLeak([] {
195     EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
196   });
197   // Test where the exec call fails() with pipes
198   checkFdLeak([] {
199     try {
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());
205     }
206   });
207 }
208
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;
216   }
217
218   fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
219
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());
225
226   // Now wait for the file to be created, see details in
227   // SubprocessTestParentDeathHelper.cpp
228   while (!fs::exists(tempFile)) {
229     usleep(20000);  // 20ms
230   }
231
232   fs::remove(tempFile);
233 }
234
235 TEST(PopenSubprocessTest, PopenRead) {
236   Subprocess proc("ls /", Subprocess::pipeStdout());
237   int found = 0;
238   gen::byLine(File(proc.stdout())) |
239     [&] (StringPiece line) {
240       if (line == "etc" || line == "bin" || line == "usr") {
241         ++found;
242       }
243     };
244   EXPECT_EQ(3, found);
245   proc.waitChecked();
246 }
247
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;
261   }
262   const std::string filename_;
263 };
264
265 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackSuccess) {
266   test::ChangeToTempDir td;
267   // Trigger a file write from the child.
268   WriteFileAfterFork write_cob("good_file");
269   Subprocess proc(
270     std::vector<std::string>{"/bin/echo"},
271     Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
272   );
273   // The file gets written immediately.
274   std::string s;
275   EXPECT_TRUE(readFile(write_cob.filename_.c_str(), s));
276   EXPECT_EQ("ok", s);
277   proc.waitChecked();
278 }
279
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");
284   EXPECT_THROW(
285     Subprocess proc(
286       std::vector<std::string>{"/bin/echo"},
287       Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
288     ),
289     SubprocessSpawnError
290   );
291   EXPECT_FALSE(fs::exists(write_cob.filename_));
292 }
293
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);
299   proc.waitChecked();
300 }
301
302 TEST(CommunicateSubprocessTest, BigWrite) {
303   const int numLines = 1 << 20;
304   std::string line("hello\n");
305   std::string data;
306   data.reserve(numLines * line.size());
307   for (int i = 0; i < numLines; ++i) {
308     data.append(line);
309   }
310
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);
314   proc.waitChecked();
315 }
316
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');
322
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'));
328   proc.waitChecked();
329 }
330
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();
337 }
338
339 TEST(CommunicateSubprocessTest, Duplex2) {
340   checkFdLeak([] {
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");
344     IOBufQueue input;
345     for (size_t n = 0; n < numCopies; ++n) {
346       input.append(iobuf->clone());
347     }
348
349     std::vector<std::string> cmd({
350       "sed", "-u",
351       "-e", "s/a test/a successful test/",
352       "-e", "/^another line/w/dev/stderr",
353     });
354     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
355     Subprocess proc(cmd, options);
356     auto out = proc.communicateIOBuf(std::move(input));
357     proc.waitChecked();
358
359     // Convert stdout and stderr to strings so we can call split() on them.
360     fbstring stdoutStr;
361     if (out.first.front()) {
362       stdoutStr = out.first.move()->moveToFbString();
363     }
364     fbstring stderrStr;
365     if (out.second.front()) {
366       stderrStr = out.second.move()->moveToFbString();
367     }
368
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();
378     }
379     size_t linenum = 0;
380     for (const auto& line : stdoutLines) {
381       if ((linenum & 1) == 0) {
382         EXPECT_EQ("this is a successful test", line);
383       } else {
384         EXPECT_EQ("another line", line);
385       }
386       ++linenum;
387     }
388
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();
397     }
398     for (const auto& line : stderrLines) {
399       EXPECT_EQ("another line", line);
400     }
401   });
402 }
403
404 namespace {
405
406 bool readToString(int fd, std::string& buf, size_t maxSize) {
407   buf.resize(maxSize);
408   char* dest = &buf.front();
409   size_t remaining = maxSize;
410
411   ssize_t n = -1;
412   while (remaining) {
413     n = ::read(fd, dest, remaining);
414     if (n == -1) {
415       if (errno == EINTR) {
416         continue;
417       }
418       if (errno == EAGAIN) {
419         break;
420       }
421       PCHECK("read failed");
422     } else if (n == 0) {
423       break;
424     }
425     dest += n;
426     remaining -= n;
427   }
428
429   buf.resize(dest - buf.data());
430   return (n == 0);
431 }
432
433 }  // namespace
434
435 TEST(CommunicateSubprocessTest, Chatty) {
436   checkFdLeak([] {
437     const int lineCount = 1000;
438
439     int wcount = 0;
440     int rcount = 0;
441
442     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
443     std::vector<std::string> cmd {
444       "sed",
445       "-u",
446       "-e",
447       "s/a test/a successful test/",
448     };
449
450     Subprocess proc(cmd, options);
451
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
455
456       auto msg = folly::to<std::string>("a test ", wcount, "\n");
457
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()));
461
462       ++wcount;
463       proc.enableNotifications(0, false);
464
465       return (wcount == lineCount);
466     };
467
468     bool eofSeen = false;
469
470     auto readCallback = [&] (int pfd, int cfd) -> bool {
471       std::string lineBuf;
472
473       if (cfd != 1) {
474         EXPECT_EQ(2, cfd);
475         EXPECT_TRUE(readToString(pfd, lineBuf, 1));
476         EXPECT_EQ(0, lineBuf.size());
477         return true;
478       }
479
480       EXPECT_FALSE(eofSeen);
481
482       std::string expected;
483
484       if (rcount < lineCount) {
485         expected = folly::to<std::string>("a successful test ", rcount++, "\n");
486       }
487
488       EXPECT_EQ(wcount, rcount);
489
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);
493       if (atEof) {
494         // EOF only expected after we finished reading
495         EXPECT_EQ(lineCount, rcount);
496         eofSeen = true;
497       }
498
499       EXPECT_EQ(expected, lineBuf);
500
501       if (wcount != lineCount) {  // still more to write...
502         proc.enableNotifications(0, true);
503       }
504
505       return eofSeen;
506     };
507
508     proc.communicate(readCallback, writeCallback);
509
510     EXPECT_EQ(lineCount, wcount);
511     EXPECT_EQ(lineCount, rcount);
512     EXPECT_TRUE(eofSeen);
513
514     EXPECT_EQ(0, proc.wait().exitStatus());
515   });
516 }
517
518 TEST(CommunicateSubprocessTest, TakeOwnershipOfPipes) {
519   std::vector<Subprocess::ChildPipe> pipes;
520   {
521     Subprocess proc(
522       "echo $'oh\\nmy\\ncat' | wc -l &", Subprocess::pipeStdout()
523     );
524     pipes = proc.takeOwnershipOfPipes();
525     proc.waitChecked();
526   }
527   EXPECT_EQ(1, pipes.size());
528   EXPECT_EQ(1, pipes[0].childFd);
529
530   char buf[10];
531   EXPECT_EQ(2, readFull(pipes[0].pipe.fd(), buf, 10));
532   buf[2] = 0;
533   EXPECT_EQ("3\n", std::string(buf));
534 }