Fix -Wsign-compare
[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, Duplex2) {
260   checkFdLeak([] {
261     // Pipe 200,000 lines through sed
262     const size_t numCopies = 100000;
263     auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
264     IOBufQueue input;
265     for (size_t n = 0; n < numCopies; ++n) {
266       input.append(iobuf->clone());
267     }
268
269     std::vector<std::string> cmd({
270       "sed", "-u",
271       "-e", "s/a test/a successful test/",
272       "-e", "/^another line/w/dev/stderr",
273     });
274     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
275     Subprocess proc(cmd, options);
276     auto out = proc.communicateIOBuf(std::move(input));
277     proc.waitChecked();
278
279     // Convert stdout and stderr to strings so we can call split() on them.
280     fbstring stdoutStr;
281     if (out.first.front()) {
282       stdoutStr = out.first.move()->moveToFbString();
283     }
284     fbstring stderrStr;
285     if (out.second.front()) {
286       stderrStr = out.second.move()->moveToFbString();
287     }
288
289     // stdout should be a copy of stdin, with "a test" replaced by
290     // "a successful test"
291     std::vector<StringPiece> stdoutLines;
292     split('\n', stdoutStr, stdoutLines);
293     EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
294     // Strip off the trailing empty line
295     if (!stdoutLines.empty()) {
296       EXPECT_EQ("", stdoutLines.back());
297       stdoutLines.pop_back();
298     }
299     size_t linenum = 0;
300     for (const auto& line : stdoutLines) {
301       if ((linenum & 1) == 0) {
302         EXPECT_EQ("this is a successful test", line);
303       } else {
304         EXPECT_EQ("another line", line);
305       }
306       ++linenum;
307     }
308
309     // stderr should only contain the lines containing "another line"
310     std::vector<StringPiece> stderrLines;
311     split('\n', stderrStr, stderrLines);
312     EXPECT_EQ(numCopies + 1, stderrLines.size());
313     // Strip off the trailing empty line
314     if (!stderrLines.empty()) {
315       EXPECT_EQ("", stderrLines.back());
316       stderrLines.pop_back();
317     }
318     for (const auto& line : stderrLines) {
319       EXPECT_EQ("another line", line);
320     }
321   });
322 }
323
324 namespace {
325
326 bool readToString(int fd, std::string& buf, size_t maxSize) {
327   size_t bytesRead = 0;
328
329   buf.resize(maxSize);
330   char* dest = &buf.front();
331   size_t remaining = maxSize;
332
333   ssize_t n = -1;
334   while (remaining) {
335     n = ::read(fd, dest, remaining);
336     if (n == -1) {
337       if (errno == EINTR) {
338         continue;
339       }
340       if (errno == EAGAIN) {
341         break;
342       }
343       PCHECK("read failed");
344     } else if (n == 0) {
345       break;
346     }
347     dest += n;
348     remaining -= n;
349   }
350
351   buf.resize(dest - buf.data());
352   return (n == 0);
353 }
354
355 }  // namespace
356
357 TEST(CommunicateSubprocessTest, Chatty) {
358   checkFdLeak([] {
359     const int lineCount = 1000;
360
361     int wcount = 0;
362     int rcount = 0;
363
364     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
365     std::vector<std::string> cmd {
366       "sed",
367       "-u",
368       "-e",
369       "s/a test/a successful test/",
370     };
371
372     Subprocess proc(cmd, options);
373
374     auto writeCallback = [&] (int pfd, int cfd) -> bool {
375       EXPECT_EQ(0, cfd);  // child stdin
376       EXPECT_EQ(rcount, wcount);  // chatty, one read for every write
377
378       auto msg = folly::to<std::string>("a test ", wcount, "\n");
379
380       // Not entirely kosher, we should handle partial writes, but this is
381       // fine for writes <= PIPE_BUF
382       EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
383
384       ++wcount;
385       proc.enableNotifications(0, false);
386
387       return (wcount == lineCount);
388     };
389
390     bool eofSeen = false;
391
392     auto readCallback = [&] (int pfd, int cfd) -> bool {
393       std::string lineBuf;
394
395       if (cfd != 1) {
396         EXPECT_EQ(2, cfd);
397         EXPECT_TRUE(readToString(pfd, lineBuf, 1));
398         EXPECT_EQ(0, lineBuf.size());
399         return true;
400       }
401
402       EXPECT_FALSE(eofSeen);
403
404       std::string expected;
405
406       if (rcount < lineCount) {
407         expected = folly::to<std::string>("a successful test ", rcount++, "\n");
408       }
409
410       EXPECT_EQ(wcount, rcount);
411
412       // Not entirely kosher, we should handle partial reads, but this is
413       // fine for reads <= PIPE_BUF
414       bool atEof = readToString(pfd, lineBuf, expected.size() + 1);
415       if (atEof) {
416         // EOF only expected after we finished reading
417         EXPECT_EQ(lineCount, rcount);
418         eofSeen = true;
419       }
420
421       EXPECT_EQ(expected, lineBuf);
422
423       if (wcount != lineCount) {  // still more to write...
424         proc.enableNotifications(0, true);
425       }
426
427       return eofSeen;
428     };
429
430     proc.communicate(readCallback, writeCallback);
431
432     EXPECT_EQ(lineCount, wcount);
433     EXPECT_EQ(lineCount, rcount);
434     EXPECT_TRUE(eofSeen);
435
436     EXPECT_EQ(0, proc.wait().exitStatus());
437   });
438 }