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