f17f3a51da37dda83886694e0777058542bb0c50
[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/String.h"
30 #include "folly/gen/Base.h"
31 #include "folly/gen/File.h"
32 #include "folly/gen/String.h"
33 #include "folly/experimental/io/FsUtil.h"
34
35 using namespace folly;
36
37 TEST(SimpleSubprocessTest, ExitsSuccessfully) {
38   Subprocess proc(std::vector<std::string>{ "/bin/true" });
39   EXPECT_EQ(0, proc.wait().exitStatus());
40 }
41
42 TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
43   Subprocess proc(std::vector<std::string>{ "/bin/true" });
44   proc.waitChecked();
45 }
46
47 TEST(SimpleSubprocessTest, ExitsWithError) {
48   Subprocess proc(std::vector<std::string>{ "/bin/false" });
49   EXPECT_EQ(1, proc.wait().exitStatus());
50 }
51
52 TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
53   Subprocess proc(std::vector<std::string>{ "/bin/false" });
54   EXPECT_THROW(proc.waitChecked(), CalledProcessError);
55 }
56
57 #define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
58   do { \
59     try { \
60       Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
61       ADD_FAILURE() << "expected an error when running " << (cmd); \
62     } catch (const SubprocessSpawnError& ex) { \
63       EXPECT_EQ((err), ex.errnoValue()); \
64       if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
65         ADD_FAILURE() << "failed to find \"" << (errMsg) << \
66           "\" in exception: \"" << ex.what() << "\""; \
67       } \
68     } \
69   } while (0)
70
71 TEST(SimpleSubprocessTest, ExecFails) {
72   EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
73                      "/no/such/file");
74   EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
75                      "/etc/passwd");
76   EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
77                      "/etc/passwd/not/a/file");
78 }
79
80 TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
81   Subprocess proc("true");
82   EXPECT_EQ(0, proc.wait().exitStatus());
83 }
84
85 TEST(SimpleSubprocessTest, ShellExitsWithError) {
86   Subprocess proc("false");
87   EXPECT_EQ(1, proc.wait().exitStatus());
88 }
89
90 namespace {
91 boost::container::flat_set<int> getOpenFds() {
92   auto pid = getpid();
93   auto dirname = to<std::string>("/proc/", pid, "/fd");
94
95   boost::container::flat_set<int> fds;
96   for (fs::directory_iterator it(dirname);
97        it != fs::directory_iterator();
98        ++it) {
99     int fd = to<int>(it->path().filename().native());
100     fds.insert(fd);
101   }
102   return fds;
103 }
104
105 template<class Runnable>
106 void checkFdLeak(const Runnable& r) {
107   // Get the currently open fds.  Check that they are the same both before and
108   // after calling the specified function.  We read the open fds from /proc.
109   // (If we wanted to work even on systems that don't have /proc, we could
110   // perhaps create and immediately close a socket both before and after
111   // running the function, and make sure we got the same fd number both times.)
112   auto fdsBefore = getOpenFds();
113   r();
114   auto fdsAfter = getOpenFds();
115   EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
116 }
117 }
118
119 // Make sure Subprocess doesn't leak any file descriptors
120 TEST(SimpleSubprocessTest, FdLeakTest) {
121   // Normal execution
122   checkFdLeak([] {
123     Subprocess proc("true");
124     EXPECT_EQ(0, proc.wait().exitStatus());
125   });
126   // Normal execution with pipes
127   checkFdLeak([] {
128     Subprocess proc("echo foo; echo bar >&2",
129                     Subprocess::pipeStdout() | Subprocess::pipeStderr());
130     auto p = proc.communicate();
131     EXPECT_EQ("foo\n", p.first);
132     EXPECT_EQ("bar\n", p.second);
133     proc.waitChecked();
134   });
135
136   // Test where the exec call fails()
137   checkFdLeak([] {
138     EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
139   });
140   // Test where the exec call fails() with pipes
141   checkFdLeak([] {
142     try {
143       Subprocess proc(std::vector<std::string>({"/no/such/file"}),
144                       Subprocess::pipeStdout().stderr(Subprocess::PIPE));
145       ADD_FAILURE() << "expected an error when running /no/such/file";
146     } catch (const SubprocessSpawnError& ex) {
147       EXPECT_EQ(ENOENT, ex.errnoValue());
148     }
149   });
150 }
151
152 TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
153   // Find out where we are.
154   static constexpr size_t pathLength = 2048;
155   char buf[pathLength + 1];
156   int r = readlink("/proc/self/exe", buf, pathLength);
157   CHECK_ERR(r);
158   buf[r] = '\0';
159
160   fs::path helper(buf);
161   helper.remove_filename();
162   helper /= "subprocess_test_parent_death_helper";
163
164   fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
165
166   std::vector<std::string> args {helper.string(), tempFile.string()};
167   Subprocess proc(args);
168   // The helper gets killed by its child, see details in
169   // SubprocessTestParentDeathHelper.cpp
170   ASSERT_EQ(SIGKILL, proc.wait().killSignal());
171
172   // Now wait for the file to be created, see details in
173   // SubprocessTestParentDeathHelper.cpp
174   while (!fs::exists(tempFile)) {
175     usleep(20000);  // 20ms
176   }
177
178   fs::remove(tempFile);
179 }
180
181 TEST(PopenSubprocessTest, PopenRead) {
182   Subprocess proc("ls /", Subprocess::pipeStdout());
183   int found = 0;
184   gen::byLine(File(proc.stdout())) |
185     [&] (StringPiece line) {
186       if (line == "etc" || line == "bin" || line == "usr") {
187         ++found;
188       }
189     };
190   EXPECT_EQ(3, found);
191   proc.waitChecked();
192 }
193
194 TEST(CommunicateSubprocessTest, SimpleRead) {
195   Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
196                   Subprocess::pipeStdout());
197   auto p = proc.communicate();
198   EXPECT_EQ("foo bar", p.first);
199   proc.waitChecked();
200 }
201
202 TEST(CommunicateSubprocessTest, BigWrite) {
203   const int numLines = 1 << 20;
204   std::string line("hello\n");
205   std::string data;
206   data.reserve(numLines * line.size());
207   for (int i = 0; i < numLines; ++i) {
208     data.append(line);
209   }
210
211   Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
212   auto p = proc.communicate(data);
213   EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
214   proc.waitChecked();
215 }
216
217 TEST(CommunicateSubprocessTest, Duplex) {
218   // Take 10MB of data and pass them through a filter.
219   // One line, as tr is line-buffered
220   const int bytes = 10 << 20;
221   std::string line(bytes, 'x');
222
223   Subprocess proc("tr a-z A-Z",
224                   Subprocess::pipeStdin() | Subprocess::pipeStdout());
225   auto p = proc.communicate(line);
226   EXPECT_EQ(bytes, p.first.size());
227   EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
228   proc.waitChecked();
229 }
230
231 TEST(CommunicateSubprocessTest, Duplex2) {
232   checkFdLeak([] {
233     // Pipe 200,000 lines through sed
234     const size_t numCopies = 100000;
235     auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
236     IOBufQueue input;
237     for (int n = 0; n < numCopies; ++n) {
238       input.append(iobuf->clone());
239     }
240
241     std::vector<std::string> cmd({
242       "sed", "-u",
243       "-e", "s/a test/a successful test/",
244       "-e", "/^another line/w/dev/stderr",
245     });
246     auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
247     Subprocess proc(cmd, options);
248     auto out = proc.communicateIOBuf(std::move(input));
249     proc.waitChecked();
250
251     // Convert stdout and stderr to strings so we can call split() on them.
252     fbstring stdoutStr;
253     if (out.first.front()) {
254       stdoutStr = out.first.move()->moveToFbString();
255     }
256     fbstring stderrStr;
257     if (out.second.front()) {
258       stderrStr = out.second.move()->moveToFbString();
259     }
260
261     // stdout should be a copy of stdin, with "a test" replaced by
262     // "a successful test"
263     std::vector<StringPiece> stdoutLines;
264     split('\n', stdoutStr, stdoutLines);
265     EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
266     // Strip off the trailing empty line
267     if (!stdoutLines.empty()) {
268       EXPECT_EQ("", stdoutLines.back());
269       stdoutLines.pop_back();
270     }
271     size_t linenum = 0;
272     for (const auto& line : stdoutLines) {
273       if ((linenum & 1) == 0) {
274         EXPECT_EQ("this is a successful test", line);
275       } else {
276         EXPECT_EQ("another line", line);
277       }
278       ++linenum;
279     }
280
281     // stderr should only contain the lines containing "another line"
282     std::vector<StringPiece> stderrLines;
283     split('\n', stderrStr, stderrLines);
284     EXPECT_EQ(numCopies + 1, stderrLines.size());
285     // Strip off the trailing empty line
286     if (!stderrLines.empty()) {
287       EXPECT_EQ("", stderrLines.back());
288       stderrLines.pop_back();
289     }
290     for (const auto& line : stderrLines) {
291       EXPECT_EQ("another line", line);
292     }
293   });
294 }