getVia() and waitVia()
[folly.git] / folly / test / SubprocessTest.cpp
1 /*
2  * Copyright 2014 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/io/FsUtil.h>
35
36 using namespace folly;
37
38 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
39   Subprocess proc(std::vector<std::string>{ "/bin/true" });
40   EXPECT_EQ(0, proc.wait().exitStatus());
41 }
42
43 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
44   Subprocess proc(std::vector<std::string>{ "/bin/true" });
45   proc.waitChecked();
46 }
47
48 TEST(SimpleSubprocessTest, ExitsWithError) {
49   Subprocess proc(std::vector<std::string>{ "/bin/false" });
50   EXPECT_EQ(1, proc.wait().exitStatus());
51 }
52
53 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
54   Subprocess proc(std::vector<std::string>{ "/bin/false" });
55   EXPECT_THROW(proc.waitChecked(), CalledProcessError);
56 }
57
58 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
59   do { \
60     try { \
61       Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
62       ADD_FAILURE() << "expected an error when running " << (cmd); \
63     } catch (const SubprocessSpawnError& ex) { \
64       EXPECT_EQ((err), ex.errnoValue()); \
65       if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
66         ADD_FAILURE() << "failed to find \"" << (errMsg) << \
67           "\" in exception: \"" << ex.what() << "\""; \
68       } \
69     } \
70   } while (0)
71
72 TEST(SimpleSubprocessTest, ExecFails) {
73   EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
74                      "/no/such/file");
75   EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
76                      "/etc/passwd");
77   EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
78                      "/etc/passwd/not/a/file");
79 }
80
81 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
82   Subprocess proc("true");
83   EXPECT_EQ(0, proc.wait().exitStatus());
84 }
85
86 TEST(SimpleSubprocessTest, ShellExitsWithError) {
87   Subprocess proc("false");
88   EXPECT_EQ(1, proc.wait().exitStatus());
89 }
90
91 TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
92   // The filesystem root normally lacks a 'true' binary
93   EXPECT_EQ(0, chdir("/"));
94   EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
95   // The child can fix that by moving to /bin before exec().
96   Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
97   EXPECT_EQ(0, proc.wait().exitStatus());
98 }
99
100 TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
101   try {
102     Subprocess proc(
103       std::vector<std::string>{"/bin/true"},
104       Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
105     );
106     ADD_FAILURE() << "expected to fail when changing the child's directory";
107   } catch (const SubprocessSpawnError& ex) {
108     EXPECT_EQ(ENOENT, ex.errnoValue());
109     const std::string expectedError =
110       "error preparing to execute /bin/true: No such file or directory";
111     if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
112       ADD_FAILURE() << "failed to find \"" << expectedError <<
113         "\" in exception: \"" << ex.what() << "\"";
114     }
115   }
116 }
117
118 namespace {
119 boost::container::flat_set<int> getOpenFds() {
120   auto pid = getpid();
121   auto dirname = to<std::string>("/proc/", pid, "/fd");
122
123   boost::container::flat_set<int> fds;
124   for (fs::directory_iterator it(dirname);
125        it != fs::directory_iterator();
126        ++it) {
127     int fd = to<int>(it->path().filename().native());
128     fds.insert(fd);
129   }
130   return fds;
131 }
132
133 template<class Runnable>
134 void checkFdLeak(const Runnable& r) {
135   // Get the currently open fds.  Check that they are the same both before and
136   // after calling the specified function.  We read the open fds from /proc.
137   // (If we wanted to work even on systems that don't have /proc, we could
138   // perhaps create and immediately close a socket both before and after
139   // running the function, and make sure we got the same fd number both times.)
140   auto fdsBefore = getOpenFds();
141   r();
142   auto fdsAfter = getOpenFds();
143   EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
144 }
145 }
146
147 // Make sure Subprocess doesn't leak any file descriptors
148 TEST(SimpleSubprocessTest, FdLeakTest) {
149   // Normal execution
150   checkFdLeak([] {
151     Subprocess proc("true");
152     EXPECT_EQ(0, proc.wait().exitStatus());
153   });
154   // Normal execution with pipes
155   checkFdLeak([] {
156     Subprocess proc("echo foo; echo bar >&2",
157                     Subprocess::pipeStdout() | Subprocess::pipeStderr());
158     auto p = proc.communicate();
159     EXPECT_EQ("foo\n", p.first);
160     EXPECT_EQ("bar\n", p.second);
161     proc.waitChecked();
162   });
163
164   // Test where the exec call fails()
165   checkFdLeak([] {
166     EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
167   });
168   // Test where the exec call fails() with pipes
169   checkFdLeak([] {
170     try {
171       Subprocess proc(std::vector<std::string>({"/no/such/file"}),
172                       Subprocess::pipeStdout().stderr(Subprocess::PIPE));
173       ADD_FAILURE() << "expected an error when running /no/such/file";
174     } catch (const SubprocessSpawnError& ex) {
175       EXPECT_EQ(ENOENT, ex.errnoValue());
176     }
177   });
178 }
179
180 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
181   // Find out where we are.
182   static constexpr size_t pathLength = 2048;
183   char buf[pathLength + 1];
184   int r = readlink("/proc/self/exe", buf, pathLength);
185   CHECK_ERR(r);
186   buf[r] = '\0';
187
188   fs::path helper(buf);
189   helper.remove_filename();
190   helper /= "subprocess_test_parent_death_helper";
191
192   fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
193
194   std::vector<std::string> args {helper.string(), tempFile.string()};
195   Subprocess proc(args);
196   // The helper gets killed by its child, see details in
197   // SubprocessTestParentDeathHelper.cpp
198   ASSERT_EQ(SIGKILL, proc.wait().killSignal());
199
200   // Now wait for the file to be created, see details in
201   // SubprocessTestParentDeathHelper.cpp
202   while (!fs::exists(tempFile)) {
203     usleep(20000);  // 20ms
204   }
205
206   fs::remove(tempFile);
207 }
208
209 TEST(PopenSubprocessTest, PopenRead) {
210   Subprocess proc("ls /", Subprocess::pipeStdout());
211   int found = 0;
212   gen::byLine(File(proc.stdout())) |
213     [&] (StringPiece line) {
214       if (line == "etc" || line == "bin" || line == "usr") {
215         ++found;
216       }
217     };
218   EXPECT_EQ(3, found);
219   proc.waitChecked();
220 }
221
222 TEST(CommunicateSubprocessTest, SimpleRead) {
223   Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
224                   Subprocess::pipeStdout());
225   auto p = proc.communicate();
226   EXPECT_EQ("foo bar", p.first);
227   proc.waitChecked();
228 }
229
230 TEST(CommunicateSubprocessTest, BigWrite) {
231   const int numLines = 1 << 20;
232   std::string line("hello\n");
233   std::string data;
234   data.reserve(numLines * line.size());
235   for (int i = 0; i < numLines; ++i) {
236     data.append(line);
237   }
238
239   Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
240   auto p = proc.communicate(data);
241   EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
242   proc.waitChecked();
243 }
244
245 TEST(CommunicateSubprocessTest, Duplex) {
246   // Take 10MB of data and pass them through a filter.
247   // One line, as tr is line-buffered
248   const int bytes = 10 << 20;
249   std::string line(bytes, 'x');
250
251   Subprocess proc("tr a-z A-Z",
252                   Subprocess::pipeStdin() | Subprocess::pipeStdout());
253   auto p = proc.communicate(line);
254   EXPECT_EQ(bytes, p.first.size());
255   EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
256   proc.waitChecked();
257 }
258
259 TEST(CommunicateSubprocessTest, ProcessGroupLeader) {
260   const auto testIsLeader = "test $(cut -d ' ' -f 5 /proc/$$/stat) = $$";
261   Subprocess nonLeader(testIsLeader);
262   EXPECT_THROW(nonLeader.waitChecked(), CalledProcessError);
263   Subprocess leader(testIsLeader, Subprocess::Options().processGroupLeader());
264   leader.waitChecked();
265 }
266
267 TEST(CommunicateSubprocessTest, Duplex2) {
268   checkFdLeak([] {
269     // Pipe 200,000 lines through sed
270     const size_t numCopies = 100000;
271     auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
272     IOBufQueue input;
273     for (size_t n = 0; n < numCopies; ++n) {
274       input.append(iobuf->clone());
275     }
276
277     std::vector<std::string> cmd({
278       "sed", "-u",
279       "-e", "s/a test/a successful test/",
280       "-e", "/^another line/w/dev/stderr",
281     });
282     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
283     Subprocess proc(cmd, options);
284     auto out = proc.communicateIOBuf(std::move(input));
285     proc.waitChecked();
286
287     // Convert stdout and stderr to strings so we can call split() on them.
288     fbstring stdoutStr;
289     if (out.first.front()) {
290       stdoutStr = out.first.move()->moveToFbString();
291     }
292     fbstring stderrStr;
293     if (out.second.front()) {
294       stderrStr = out.second.move()->moveToFbString();
295     }
296
297     // stdout should be a copy of stdin, with "a test" replaced by
298     // "a successful test"
299     std::vector<StringPiece> stdoutLines;
300     split('\n', stdoutStr, stdoutLines);
301     EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
302     // Strip off the trailing empty line
303     if (!stdoutLines.empty()) {
304       EXPECT_EQ("", stdoutLines.back());
305       stdoutLines.pop_back();
306     }
307     size_t linenum = 0;
308     for (const auto& line : stdoutLines) {
309       if ((linenum & 1) == 0) {
310         EXPECT_EQ("this is a successful test", line);
311       } else {
312         EXPECT_EQ("another line", line);
313       }
314       ++linenum;
315     }
316
317     // stderr should only contain the lines containing "another line"
318     std::vector<StringPiece> stderrLines;
319     split('\n', stderrStr, stderrLines);
320     EXPECT_EQ(numCopies + 1, stderrLines.size());
321     // Strip off the trailing empty line
322     if (!stderrLines.empty()) {
323       EXPECT_EQ("", stderrLines.back());
324       stderrLines.pop_back();
325     }
326     for (const auto& line : stderrLines) {
327       EXPECT_EQ("another line", line);
328     }
329   });
330 }
331
332 namespace {
333
334 bool readToString(int fd, std::string& buf, size_t maxSize) {
335   size_t bytesRead = 0;
336
337   buf.resize(maxSize);
338   char* dest = &buf.front();
339   size_t remaining = maxSize;
340
341   ssize_t n = -1;
342   while (remaining) {
343     n = ::read(fd, dest, remaining);
344     if (n == -1) {
345       if (errno == EINTR) {
346         continue;
347       }
348       if (errno == EAGAIN) {
349         break;
350       }
351       PCHECK("read failed");
352     } else if (n == 0) {
353       break;
354     }
355     dest += n;
356     remaining -= n;
357   }
358
359   buf.resize(dest - buf.data());
360   return (n == 0);
361 }
362
363 }  // namespace
364
365 TEST(CommunicateSubprocessTest, Chatty) {
366   checkFdLeak([] {
367     const int lineCount = 1000;
368
369     int wcount = 0;
370     int rcount = 0;
371
372     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
373     std::vector<std::string> cmd {
374       "sed",
375       "-u",
376       "-e",
377       "s/a test/a successful test/",
378     };
379
380     Subprocess proc(cmd, options);
381
382     auto writeCallback = [&] (int pfd, int cfd) -> bool {
383       EXPECT_EQ(0, cfd);  // child stdin
384       EXPECT_EQ(rcount, wcount);  // chatty, one read for every write
385
386       auto msg = folly::to<std::string>("a test ", wcount, "\n");
387
388       // Not entirely kosher, we should handle partial writes, but this is
389       // fine for writes <= PIPE_BUF
390       EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
391
392       ++wcount;
393       proc.enableNotifications(0, false);
394
395       return (wcount == lineCount);
396     };
397
398     bool eofSeen = false;
399
400     auto readCallback = [&] (int pfd, int cfd) -> bool {
401       std::string lineBuf;
402
403       if (cfd != 1) {
404         EXPECT_EQ(2, cfd);
405         EXPECT_TRUE(readToString(pfd, lineBuf, 1));
406         EXPECT_EQ(0, lineBuf.size());
407         return true;
408       }
409
410       EXPECT_FALSE(eofSeen);
411
412       std::string expected;
413
414       if (rcount < lineCount) {
415         expected = folly::to<std::string>("a successful test ", rcount++, "\n");
416       }
417
418       EXPECT_EQ(wcount, rcount);
419
420       // Not entirely kosher, we should handle partial reads, but this is
421       // fine for reads <= PIPE_BUF
422       bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
423       if (atEof) {
424         // EOF only expected after we finished reading
425         EXPECT_EQ(lineCount, rcount);
426         eofSeen = true;
427       }
428
429       EXPECT_EQ(expected, lineBuf);
430
431       if (wcount != lineCount) {  // still more to write...
432         proc.enableNotifications(0, true);
433       }
434
435       return eofSeen;
436     };
437
438     proc.communicate(readCallback, writeCallback);
439
440     EXPECT_EQ(lineCount, wcount);
441     EXPECT_EQ(lineCount, rcount);
442     EXPECT_TRUE(eofSeen);
443
444     EXPECT_EQ(0, proc.wait().exitStatus());
445   });
446 }