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