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