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