Support linux namespace clone flags
[folly.git] / folly / test / SubprocessTest.cpp
1 /*
2  * Copyright 2017 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 <sys/types.h>
20
21 #include <boost/container/flat_set.hpp>
22 #include <glog/logging.h>
23
24 #include <folly/Exception.h>
25 #include <folly/FileUtil.h>
26 #include <folly/Format.h>
27 #include <folly/String.h>
28 #include <folly/experimental/TestUtil.h>
29 #include <folly/experimental/io/FsUtil.h>
30 #include <folly/gen/Base.h>
31 #include <folly/gen/File.h>
32 #include <folly/gen/String.h>
33 #include <folly/portability/GTest.h>
34 #include <folly/portability/Unistd.h>
35
36 FOLLY_GCC_DISABLE_WARNING("-Wdeprecated-declarations")
37
38 using namespace folly;
39
40 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
41   Subprocess proc(std::vector<std::string>{ "/bin/true" });
42   EXPECT_EQ(0, proc.wait().exitStatus());
43 }
44
45 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
46   Subprocess proc(std::vector<std::string>{ "/bin/true" });
47   proc.waitChecked();
48 }
49
50 TEST(SimpleSubprocessTest, CloneFlagsWithVfork) {
51   Subprocess proc(
52       std::vector<std::string>{"/bin/true"},
53       Subprocess::Options().useCloneWithFlags(SIGCHLD | CLONE_VFORK));
54   EXPECT_EQ(0, proc.wait().exitStatus());
55 }
56
57 TEST(SimpleSubprocessTest, CloneFlagsWithFork) {
58   Subprocess proc(
59       std::vector<std::string>{"/bin/true"},
60       Subprocess::Options().useCloneWithFlags(SIGCHLD));
61   EXPECT_EQ(0, proc.wait().exitStatus());
62 }
63
64 TEST(SimpleSubprocessTest, CloneFlagsSubprocessCtorExitsAfterExec) {
65   Subprocess proc(
66       std::vector<std::string>{"/bin/sleep", "3600"},
67       Subprocess::Options().useCloneWithFlags(SIGCHLD));
68   checkUnixError(::kill(proc.pid(), SIGKILL), "kill");
69   auto retCode = proc.wait();
70   EXPECT_TRUE(retCode.killed());
71 }
72
73 TEST(SimpleSubprocessTest, ExitsWithError) {
74   Subprocess proc(std::vector<std::string>{ "/bin/false" });
75   EXPECT_EQ(1, proc.wait().exitStatus());
76 }
77
78 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
79   Subprocess proc(std::vector<std::string>{ "/bin/false" });
80   EXPECT_THROW(proc.waitChecked(), CalledProcessError);
81 }
82
83 TEST(SimpleSubprocessTest, DefaultConstructibleProcessReturnCode) {
84   ProcessReturnCode retcode;
85   EXPECT_TRUE(retcode.notStarted());
86 }
87
88 TEST(SimpleSubprocessTest, MoveSubprocess) {
89   Subprocess old_proc(std::vector<std::string>{ "/bin/true" });
90   EXPECT_TRUE(old_proc.returnCode().running());
91   auto new_proc = std::move(old_proc);
92   EXPECT_TRUE(old_proc.returnCode().notStarted());
93   EXPECT_TRUE(new_proc.returnCode().running());
94   EXPECT_EQ(0, new_proc.wait().exitStatus());
95   // Now old_proc is destroyed, but we don't crash.
96 }
97
98 TEST(SimpleSubprocessTest, DefaultConstructor) {
99   Subprocess proc;
100   EXPECT_TRUE(proc.returnCode().notStarted());
101
102   {
103     auto p1 = Subprocess(std::vector<std::string>{"/bin/true"});
104     proc = std::move(p1);
105   }
106
107   EXPECT_TRUE(proc.returnCode().running());
108   EXPECT_EQ(0, proc.wait().exitStatus());
109 }
110
111 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
112   do { \
113     try { \
114       Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
115       ADD_FAILURE() << "expected an error when running " << (cmd); \
116     } catch (const SubprocessSpawnError& ex) { \
117       EXPECT_EQ((err), ex.errnoValue()); \
118       if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
119         ADD_FAILURE() << "failed to find \"" << (errMsg) << \
120           "\" in exception: \"" << ex.what() << "\""; \
121       } \
122     } \
123   } while (0)
124
125 TEST(SimpleSubprocessTest, ExecFails) {
126   EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
127                      "/no/such/file");
128   EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
129                      "/etc/passwd");
130   EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
131                      "/etc/passwd/not/a/file");
132 }
133
134 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
135   Subprocess proc("true");
136   EXPECT_EQ(0, proc.wait().exitStatus());
137 }
138
139 TEST(SimpleSubprocessTest, ShellExitsWithError) {
140   Subprocess proc("false");
141   EXPECT_EQ(1, proc.wait().exitStatus());
142 }
143
144 TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
145   // The filesystem root normally lacks a 'true' binary
146   EXPECT_EQ(0, chdir("/"));
147   EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
148   // The child can fix that by moving to /bin before exec().
149   Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
150   EXPECT_EQ(0, proc.wait().exitStatus());
151 }
152
153 TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
154   try {
155     Subprocess proc(
156       std::vector<std::string>{"/bin/true"},
157       Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
158     );
159     ADD_FAILURE() << "expected to fail when changing the child's directory";
160   } catch (const SubprocessSpawnError& ex) {
161     EXPECT_EQ(ENOENT, ex.errnoValue());
162     const std::string expectedError =
163       "error preparing to execute /bin/true: No such file or directory";
164     if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
165       ADD_FAILURE() << "failed to find \"" << expectedError <<
166         "\" in exception: \"" << ex.what() << "\"";
167     }
168   }
169 }
170
171 namespace {
172 boost::container::flat_set<int> getOpenFds() {
173   auto pid = getpid();
174   auto dirname = to<std::string>("/proc/", pid, "/fd");
175
176   boost::container::flat_set<int> fds;
177   for (fs::directory_iterator it(dirname);
178        it != fs::directory_iterator();
179        ++it) {
180     int fd = to<int>(it->path().filename().native());
181     fds.insert(fd);
182   }
183   return fds;
184 }
185
186 template<class Runnable>
187 void checkFdLeak(const Runnable& r) {
188   // Get the currently open fds.  Check that they are the same both before and
189   // after calling the specified function.  We read the open fds from /proc.
190   // (If we wanted to work even on systems that don't have /proc, we could
191   // perhaps create and immediately close a socket both before and after
192   // running the function, and make sure we got the same fd number both times.)
193   auto fdsBefore = getOpenFds();
194   r();
195   auto fdsAfter = getOpenFds();
196   EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
197 }
198 }
199
200 // Make sure Subprocess doesn't leak any file descriptors
201 TEST(SimpleSubprocessTest, FdLeakTest) {
202   // Normal execution
203   checkFdLeak([] {
204     Subprocess proc("true");
205     EXPECT_EQ(0, proc.wait().exitStatus());
206   });
207   // Normal execution with pipes
208   checkFdLeak([] {
209     Subprocess proc("echo foo; echo bar >&2",
210                     Subprocess::pipeStdout() | Subprocess::pipeStderr());
211     auto p = proc.communicate();
212     EXPECT_EQ("foo\n", p.first);
213     EXPECT_EQ("bar\n", p.second);
214     proc.waitChecked();
215   });
216
217   // Test where the exec call fails()
218   checkFdLeak([] {
219     EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
220   });
221   // Test where the exec call fails() with pipes
222   checkFdLeak([] {
223     try {
224       Subprocess proc(std::vector<std::string>({"/no/such/file"}),
225                       Subprocess::pipeStdout().stderrFd(Subprocess::PIPE));
226       ADD_FAILURE() << "expected an error when running /no/such/file";
227     } catch (const SubprocessSpawnError& ex) {
228       EXPECT_EQ(ENOENT, ex.errnoValue());
229     }
230   });
231 }
232
233 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
234   // Find out where we are.
235   const auto basename = "subprocess_test_parent_death_helper";
236   auto helper = fs::executable_path();
237   helper.remove_filename() /= basename;
238   if (!fs::exists(helper)) {
239     helper = helper.parent_path().parent_path() / basename / basename;
240   }
241
242   fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
243
244   std::vector<std::string> args {helper.string(), tempFile.string()};
245   Subprocess proc(args);
246   // The helper gets killed by its child, see details in
247   // SubprocessTestParentDeathHelper.cpp
248   ASSERT_EQ(SIGKILL, proc.wait().killSignal());
249
250   // Now wait for the file to be created, see details in
251   // SubprocessTestParentDeathHelper.cpp
252   while (!fs::exists(tempFile)) {
253     usleep(20000);  // 20ms
254   }
255
256   fs::remove(tempFile);
257 }
258
259 TEST(PopenSubprocessTest, PopenRead) {
260   Subprocess proc("ls /", Subprocess::pipeStdout());
261   int found = 0;
262   gen::byLine(File(proc.stdoutFd())) |
263     [&] (StringPiece line) {
264       if (line == "etc" || line == "bin" || line == "usr") {
265         ++found;
266       }
267     };
268   EXPECT_EQ(3, found);
269   proc.waitChecked();
270 }
271
272 // DANGER: This class runs after fork in a child processes. Be fast, the
273 // parent thread is waiting, but remember that other parent threads are
274 // running and may mutate your state.  Avoid mutating any data belonging to
275 // the parent.  Avoid interacting with non-POD data that originated in the
276 // parent.  Avoid any libraries that may internally reference non-POD data.
277 // Especially beware parent mutexes -- for example, glog's LOG() uses one.
278 struct WriteFileAfterFork
279     : public Subprocess::DangerousPostForkPreExecCallback {
280   explicit WriteFileAfterFork(std::string filename)
281     : filename_(std::move(filename)) {}
282   virtual ~WriteFileAfterFork() {}
283   int operator()() override {
284     return writeFile(std::string("ok"), filename_.c_str()) ? 0 : errno;
285   }
286   const std::string filename_;
287 };
288
289 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackSuccess) {
290   test::ChangeToTempDir td;
291   // Trigger a file write from the child.
292   WriteFileAfterFork write_cob("good_file");
293   Subprocess proc(
294     std::vector<std::string>{"/bin/echo"},
295     Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
296   );
297   // The file gets written immediately.
298   std::string s;
299   EXPECT_TRUE(readFile(write_cob.filename_.c_str(), s));
300   EXPECT_EQ("ok", s);
301   proc.waitChecked();
302 }
303
304 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackError) {
305   test::ChangeToTempDir td;
306   // The child will try to write to a file, whose directory does not exist.
307   WriteFileAfterFork write_cob("bad/file");
308   EXPECT_THROW(
309     Subprocess proc(
310       std::vector<std::string>{"/bin/echo"},
311       Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
312     ),
313     SubprocessSpawnError
314   );
315   EXPECT_FALSE(fs::exists(write_cob.filename_));
316 }
317
318 TEST(CommunicateSubprocessTest, SimpleRead) {
319   Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
320                   Subprocess::pipeStdout());
321   auto p = proc.communicate();
322   EXPECT_EQ("foo bar", p.first);
323   proc.waitChecked();
324 }
325
326 TEST(CommunicateSubprocessTest, BigWrite) {
327   const int numLines = 1 << 20;
328   std::string line("hello\n");
329   std::string data;
330   data.reserve(numLines * line.size());
331   for (int i = 0; i < numLines; ++i) {
332     data.append(line);
333   }
334
335   Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
336   auto p = proc.communicate(data);
337   EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
338   proc.waitChecked();
339 }
340
341 TEST(CommunicateSubprocessTest, Duplex) {
342   // Take 10MB of data and pass them through a filter.
343   // One line, as tr is line-buffered
344   const int bytes = 10 << 20;
345   std::string line(bytes, 'x');
346
347   Subprocess proc("tr a-z A-Z",
348                   Subprocess::pipeStdin() | Subprocess::pipeStdout());
349   auto p = proc.communicate(line);
350   EXPECT_EQ(bytes, p.first.size());
351   EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
352   proc.waitChecked();
353 }
354
355 TEST(CommunicateSubprocessTest, ProcessGroupLeader) {
356   const auto testIsLeader = "test $(cut -d ' ' -f 5 /proc/$$/stat) = $$";
357   Subprocess nonLeader(testIsLeader);
358   EXPECT_THROW(nonLeader.waitChecked(), CalledProcessError);
359   Subprocess leader(testIsLeader, Subprocess::Options().processGroupLeader());
360   leader.waitChecked();
361 }
362
363 TEST(CommunicateSubprocessTest, Duplex2) {
364   checkFdLeak([] {
365     // Pipe 200,000 lines through sed
366     const size_t numCopies = 100000;
367     auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
368     IOBufQueue input;
369     for (size_t n = 0; n < numCopies; ++n) {
370       input.append(iobuf->clone());
371     }
372
373     std::vector<std::string> cmd({
374       "sed", "-u",
375       "-e", "s/a test/a successful test/",
376       "-e", "/^another line/w/dev/stderr",
377     });
378     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
379     Subprocess proc(cmd, options);
380     auto out = proc.communicateIOBuf(std::move(input));
381     proc.waitChecked();
382
383     // Convert stdout and stderr to strings so we can call split() on them.
384     fbstring stdoutStr;
385     if (out.first.front()) {
386       stdoutStr = out.first.move()->moveToFbString();
387     }
388     fbstring stderrStr;
389     if (out.second.front()) {
390       stderrStr = out.second.move()->moveToFbString();
391     }
392
393     // stdout should be a copy of stdin, with "a test" replaced by
394     // "a successful test"
395     std::vector<StringPiece> stdoutLines;
396     split('\n', stdoutStr, stdoutLines);
397     EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
398     // Strip off the trailing empty line
399     if (!stdoutLines.empty()) {
400       EXPECT_EQ("", stdoutLines.back());
401       stdoutLines.pop_back();
402     }
403     size_t linenum = 0;
404     for (const auto& line : stdoutLines) {
405       if ((linenum & 1) == 0) {
406         EXPECT_EQ("this is a successful test", line);
407       } else {
408         EXPECT_EQ("another line", line);
409       }
410       ++linenum;
411     }
412
413     // stderr should only contain the lines containing "another line"
414     std::vector<StringPiece> stderrLines;
415     split('\n', stderrStr, stderrLines);
416     EXPECT_EQ(numCopies + 1, stderrLines.size());
417     // Strip off the trailing empty line
418     if (!stderrLines.empty()) {
419       EXPECT_EQ("", stderrLines.back());
420       stderrLines.pop_back();
421     }
422     for (const auto& line : stderrLines) {
423       EXPECT_EQ("another line", line);
424     }
425   });
426 }
427
428 namespace {
429
430 bool readToString(int fd, std::string& buf, size_t maxSize) {
431   buf.resize(maxSize);
432   char* dest = &buf.front();
433   size_t remaining = maxSize;
434
435   ssize_t n = -1;
436   while (remaining) {
437     n = ::read(fd, dest, remaining);
438     if (n == -1) {
439       if (errno == EINTR) {
440         continue;
441       }
442       if (errno == EAGAIN) {
443         break;
444       }
445       PCHECK("read failed");
446     } else if (n == 0) {
447       break;
448     }
449     dest += n;
450     remaining -= n;
451   }
452
453   buf.resize(dest - buf.data());
454   return (n == 0);
455 }
456
457 }  // namespace
458
459 TEST(CommunicateSubprocessTest, Chatty) {
460   checkFdLeak([] {
461     const int lineCount = 1000;
462
463     int wcount = 0;
464     int rcount = 0;
465
466     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
467     std::vector<std::string> cmd {
468       "sed",
469       "-u",
470       "-e",
471       "s/a test/a successful test/",
472     };
473
474     Subprocess proc(cmd, options);
475
476     auto writeCallback = [&] (int pfd, int cfd) -> bool {
477       EXPECT_EQ(0, cfd);  // child stdin
478       EXPECT_EQ(rcount, wcount);  // chatty, one read for every write
479
480       auto msg = folly::to<std::string>("a test ", wcount, "\n");
481
482       // Not entirely kosher, we should handle partial writes, but this is
483       // fine for writes <= PIPE_BUF
484       EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
485
486       ++wcount;
487       proc.enableNotifications(0, false);
488
489       return (wcount == lineCount);
490     };
491
492     bool eofSeen = false;
493
494     auto readCallback = [&] (int pfd, int cfd) -> bool {
495       std::string lineBuf;
496
497       if (cfd != 1) {
498         EXPECT_EQ(2, cfd);
499         EXPECT_TRUE(readToString(pfd, lineBuf, 1));
500         EXPECT_EQ(0, lineBuf.size());
501         return true;
502       }
503
504       EXPECT_FALSE(eofSeen);
505
506       std::string expected;
507
508       if (rcount < lineCount) {
509         expected = folly::to<std::string>("a successful test ", rcount++, "\n");
510       }
511
512       EXPECT_EQ(wcount, rcount);
513
514       // Not entirely kosher, we should handle partial reads, but this is
515       // fine for reads <= PIPE_BUF
516       bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
517       if (atEof) {
518         // EOF only expected after we finished reading
519         EXPECT_EQ(lineCount, rcount);
520         eofSeen = true;
521       }
522
523       EXPECT_EQ(expected, lineBuf);
524
525       if (wcount != lineCount) {  // still more to write...
526         proc.enableNotifications(0, true);
527       }
528
529       return eofSeen;
530     };
531
532     proc.communicate(readCallback, writeCallback);
533
534     EXPECT_EQ(lineCount, wcount);
535     EXPECT_EQ(lineCount, rcount);
536     EXPECT_TRUE(eofSeen);
537
538     EXPECT_EQ(0, proc.wait().exitStatus());
539   });
540 }
541
542 TEST(CommunicateSubprocessTest, TakeOwnershipOfPipes) {
543   std::vector<Subprocess::ChildPipe> pipes;
544   {
545     Subprocess proc(
546       "echo $'oh\\nmy\\ncat' | wc -l &", Subprocess::pipeStdout()
547     );
548     pipes = proc.takeOwnershipOfPipes();
549     proc.waitChecked();
550   }
551   EXPECT_EQ(1, pipes.size());
552   EXPECT_EQ(1, pipes[0].childFd);
553
554   char buf[10];
555   EXPECT_EQ(2, readFull(pipes[0].pipe.fd(), buf, 10));
556   buf[2] = 0;
557   EXPECT_EQ("3\n", std::string(buf));
558 }