d9763ae63ecf19316c3164891d8a39057d3aa35a
[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(
210         "echo foo; echo bar >&2",
211         Subprocess::Options().pipeStdout().pipeStderr());
212     auto p = proc.communicate();
213     EXPECT_EQ("foo\n", p.first);
214     EXPECT_EQ("bar\n", p.second);
215     proc.waitChecked();
216   });
217
218   // Test where the exec call fails()
219   checkFdLeak([] {
220     EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
221   });
222   // Test where the exec call fails() with pipes
223   checkFdLeak([] {
224     try {
225       Subprocess proc(std::vector<std::string>({"/no/such/file"}),
226                       Subprocess::pipeStdout().stderrFd(Subprocess::PIPE));
227       ADD_FAILURE() << "expected an error when running /no/such/file";
228     } catch (const SubprocessSpawnError& ex) {
229       EXPECT_EQ(ENOENT, ex.errnoValue());
230     }
231   });
232 }
233
234 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
235   // Find out where we are.
236   const auto basename = "subprocess_test_parent_death_helper";
237   auto helper = fs::executable_path();
238   helper.remove_filename() /= basename;
239   if (!fs::exists(helper)) {
240     helper = helper.parent_path().parent_path() / basename / basename;
241   }
242
243   fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
244
245   std::vector<std::string> args {helper.string(), tempFile.string()};
246   Subprocess proc(args);
247   // The helper gets killed by its child, see details in
248   // SubprocessTestParentDeathHelper.cpp
249   ASSERT_EQ(SIGKILL, proc.wait().killSignal());
250
251   // Now wait for the file to be created, see details in
252   // SubprocessTestParentDeathHelper.cpp
253   while (!fs::exists(tempFile)) {
254     usleep(20000);  // 20ms
255   }
256
257   fs::remove(tempFile);
258 }
259
260 TEST(PopenSubprocessTest, PopenRead) {
261   Subprocess proc("ls /", Subprocess::pipeStdout());
262   int found = 0;
263   gen::byLine(File(proc.stdoutFd())) |
264     [&] (StringPiece line) {
265       if (line == "etc" || line == "bin" || line == "usr") {
266         ++found;
267       }
268     };
269   EXPECT_EQ(3, found);
270   proc.waitChecked();
271 }
272
273 // DANGER: This class runs after fork in a child processes. Be fast, the
274 // parent thread is waiting, but remember that other parent threads are
275 // running and may mutate your state.  Avoid mutating any data belonging to
276 // the parent.  Avoid interacting with non-POD data that originated in the
277 // parent.  Avoid any libraries that may internally reference non-POD data.
278 // Especially beware parent mutexes -- for example, glog's LOG() uses one.
279 struct WriteFileAfterFork
280     : public Subprocess::DangerousPostForkPreExecCallback {
281   explicit WriteFileAfterFork(std::string filename)
282     : filename_(std::move(filename)) {}
283   virtual ~WriteFileAfterFork() {}
284   int operator()() override {
285     return writeFile(std::string("ok"), filename_.c_str()) ? 0 : errno;
286   }
287   const std::string filename_;
288 };
289
290 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackSuccess) {
291   test::ChangeToTempDir td;
292   // Trigger a file write from the child.
293   WriteFileAfterFork write_cob("good_file");
294   Subprocess proc(
295     std::vector<std::string>{"/bin/echo"},
296     Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
297   );
298   // The file gets written immediately.
299   std::string s;
300   EXPECT_TRUE(readFile(write_cob.filename_.c_str(), s));
301   EXPECT_EQ("ok", s);
302   proc.waitChecked();
303 }
304
305 TEST(AfterForkCallbackSubprocessTest, TestAfterForkCallbackError) {
306   test::ChangeToTempDir td;
307   // The child will try to write to a file, whose directory does not exist.
308   WriteFileAfterFork write_cob("bad/file");
309   EXPECT_THROW(
310     Subprocess proc(
311       std::vector<std::string>{"/bin/echo"},
312       Subprocess::Options().dangerousPostForkPreExecCallback(&write_cob)
313     ),
314     SubprocessSpawnError
315   );
316   EXPECT_FALSE(fs::exists(write_cob.filename_));
317 }
318
319 TEST(CommunicateSubprocessTest, SimpleRead) {
320   Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
321                   Subprocess::pipeStdout());
322   auto p = proc.communicate();
323   EXPECT_EQ("foo bar", p.first);
324   proc.waitChecked();
325 }
326
327 TEST(CommunicateSubprocessTest, BigWrite) {
328   const int numLines = 1 << 20;
329   std::string line("hello\n");
330   std::string data;
331   data.reserve(numLines * line.size());
332   for (int i = 0; i < numLines; ++i) {
333     data.append(line);
334   }
335
336   Subprocess proc("wc -l", Subprocess::Options().pipeStdin().pipeStdout());
337   auto p = proc.communicate(data);
338   EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
339   proc.waitChecked();
340 }
341
342 TEST(CommunicateSubprocessTest, Duplex) {
343   // Take 10MB of data and pass them through a filter.
344   // One line, as tr is line-buffered
345   const int bytes = 10 << 20;
346   std::string line(bytes, 'x');
347
348   Subprocess proc("tr a-z A-Z", Subprocess::Options().pipeStdin().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::Options().pipeStdout());
547     pipes = proc.takeOwnershipOfPipes();
548     proc.waitChecked();
549   }
550   EXPECT_EQ(1, pipes.size());
551   EXPECT_EQ(1, pipes[0].childFd);
552
553   char buf[10];
554   EXPECT_EQ(2, readFull(pipes[0].pipe.fd(), buf, 10));
555   buf[2] = 0;
556   EXPECT_EQ("3\n", std::string(buf));
557 }