Fully clean up before each round of benchmarks in RangeFindBenchmark.cpp
[folly.git] / folly / test / SubprocessTest.cpp
1 /*
2  * Copyright 2015 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 TEST(CommunicateSubprocessTest, SimpleRead) {
236   Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
237                   Subprocess::pipeStdout());
238   auto p = proc.communicate();
239   EXPECT_EQ("foo bar", p.first);
240   proc.waitChecked();
241 }
242
243 TEST(CommunicateSubprocessTest, BigWrite) {
244   const int numLines = 1 << 20;
245   std::string line("hello\n");
246   std::string data;
247   data.reserve(numLines * line.size());
248   for (int i = 0; i < numLines; ++i) {
249     data.append(line);
250   }
251
252   Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
253   auto p = proc.communicate(data);
254   EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
255   proc.waitChecked();
256 }
257
258 TEST(CommunicateSubprocessTest, Duplex) {
259   // Take 10MB of data and pass them through a filter.
260   // One line, as tr is line-buffered
261   const int bytes = 10 << 20;
262   std::string line(bytes, 'x');
263
264   Subprocess proc("tr a-z A-Z",
265                   Subprocess::pipeStdin() | Subprocess::pipeStdout());
266   auto p = proc.communicate(line);
267   EXPECT_EQ(bytes, p.first.size());
268   EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
269   proc.waitChecked();
270 }
271
272 TEST(CommunicateSubprocessTest, ProcessGroupLeader) {
273   const auto testIsLeader = "test $(cut -d ' ' -f 5 /proc/$$/stat) = $$";
274   Subprocess nonLeader(testIsLeader);
275   EXPECT_THROW(nonLeader.waitChecked(), CalledProcessError);
276   Subprocess leader(testIsLeader, Subprocess::Options().processGroupLeader());
277   leader.waitChecked();
278 }
279
280 TEST(CommunicateSubprocessTest, Duplex2) {
281   checkFdLeak([] {
282     // Pipe 200,000 lines through sed
283     const size_t numCopies = 100000;
284     auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
285     IOBufQueue input;
286     for (size_t n = 0; n < numCopies; ++n) {
287       input.append(iobuf->clone());
288     }
289
290     std::vector<std::string> cmd({
291       "sed", "-u",
292       "-e", "s/a test/a successful test/",
293       "-e", "/^another line/w/dev/stderr",
294     });
295     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
296     Subprocess proc(cmd, options);
297     auto out = proc.communicateIOBuf(std::move(input));
298     proc.waitChecked();
299
300     // Convert stdout and stderr to strings so we can call split() on them.
301     fbstring stdoutStr;
302     if (out.first.front()) {
303       stdoutStr = out.first.move()->moveToFbString();
304     }
305     fbstring stderrStr;
306     if (out.second.front()) {
307       stderrStr = out.second.move()->moveToFbString();
308     }
309
310     // stdout should be a copy of stdin, with "a test" replaced by
311     // "a successful test"
312     std::vector<StringPiece> stdoutLines;
313     split('\n', stdoutStr, stdoutLines);
314     EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
315     // Strip off the trailing empty line
316     if (!stdoutLines.empty()) {
317       EXPECT_EQ("", stdoutLines.back());
318       stdoutLines.pop_back();
319     }
320     size_t linenum = 0;
321     for (const auto& line : stdoutLines) {
322       if ((linenum & 1) == 0) {
323         EXPECT_EQ("this is a successful test", line);
324       } else {
325         EXPECT_EQ("another line", line);
326       }
327       ++linenum;
328     }
329
330     // stderr should only contain the lines containing "another line"
331     std::vector<StringPiece> stderrLines;
332     split('\n', stderrStr, stderrLines);
333     EXPECT_EQ(numCopies + 1, stderrLines.size());
334     // Strip off the trailing empty line
335     if (!stderrLines.empty()) {
336       EXPECT_EQ("", stderrLines.back());
337       stderrLines.pop_back();
338     }
339     for (const auto& line : stderrLines) {
340       EXPECT_EQ("another line", line);
341     }
342   });
343 }
344
345 namespace {
346
347 bool readToString(int fd, std::string& buf, size_t maxSize) {
348   size_t bytesRead = 0;
349
350   buf.resize(maxSize);
351   char* dest = &buf.front();
352   size_t remaining = maxSize;
353
354   ssize_t n = -1;
355   while (remaining) {
356     n = ::read(fd, dest, remaining);
357     if (n == -1) {
358       if (errno == EINTR) {
359         continue;
360       }
361       if (errno == EAGAIN) {
362         break;
363       }
364       PCHECK("read failed");
365     } else if (n == 0) {
366       break;
367     }
368     dest += n;
369     remaining -= n;
370   }
371
372   buf.resize(dest - buf.data());
373   return (n == 0);
374 }
375
376 }  // namespace
377
378 TEST(CommunicateSubprocessTest, Chatty) {
379   checkFdLeak([] {
380     const int lineCount = 1000;
381
382     int wcount = 0;
383     int rcount = 0;
384
385     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
386     std::vector<std::string> cmd {
387       "sed",
388       "-u",
389       "-e",
390       "s/a test/a successful test/",
391     };
392
393     Subprocess proc(cmd, options);
394
395     auto writeCallback = [&] (int pfd, int cfd) -> bool {
396       EXPECT_EQ(0, cfd);  // child stdin
397       EXPECT_EQ(rcount, wcount);  // chatty, one read for every write
398
399       auto msg = folly::to<std::string>("a test ", wcount, "\n");
400
401       // Not entirely kosher, we should handle partial writes, but this is
402       // fine for writes <= PIPE_BUF
403       EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
404
405       ++wcount;
406       proc.enableNotifications(0, false);
407
408       return (wcount == lineCount);
409     };
410
411     bool eofSeen = false;
412
413     auto readCallback = [&] (int pfd, int cfd) -> bool {
414       std::string lineBuf;
415
416       if (cfd != 1) {
417         EXPECT_EQ(2, cfd);
418         EXPECT_TRUE(readToString(pfd, lineBuf, 1));
419         EXPECT_EQ(0, lineBuf.size());
420         return true;
421       }
422
423       EXPECT_FALSE(eofSeen);
424
425       std::string expected;
426
427       if (rcount < lineCount) {
428         expected = folly::to<std::string>("a successful test ", rcount++, "\n");
429       }
430
431       EXPECT_EQ(wcount, rcount);
432
433       // Not entirely kosher, we should handle partial reads, but this is
434       // fine for reads <= PIPE_BUF
435       bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
436       if (atEof) {
437         // EOF only expected after we finished reading
438         EXPECT_EQ(lineCount, rcount);
439         eofSeen = true;
440       }
441
442       EXPECT_EQ(expected, lineBuf);
443
444       if (wcount != lineCount) {  // still more to write...
445         proc.enableNotifications(0, true);
446       }
447
448       return eofSeen;
449     };
450
451     proc.communicate(readCallback, writeCallback);
452
453     EXPECT_EQ(lineCount, wcount);
454     EXPECT_EQ(lineCount, rcount);
455     EXPECT_TRUE(eofSeen);
456
457     EXPECT_EQ(0, proc.wait().exitStatus());
458   });
459 }
460
461 TEST(CommunicateSubprocessTest, TakeOwnershipOfPipes) {
462   std::vector<Subprocess::ChildPipe> pipes;
463   {
464     Subprocess proc(
465       "echo $'oh\\nmy\\ncat' | wc -l &", Subprocess::pipeStdout()
466     );
467     pipes = proc.takeOwnershipOfPipes();
468     proc.waitChecked();
469   }
470   EXPECT_EQ(1, pipes.size());
471   EXPECT_EQ(1, pipes[0].childFd);
472
473   char buf[10];
474   EXPECT_EQ(2, readFull(pipes[0].pipe.fd(), buf, 10));
475   buf[2] = 0;
476   EXPECT_EQ("3\n", std::string(buf));
477 }