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