Skip to content

Commit e9bbbc8

Browse files
committed
Switch to new subprocess lib in type 0 plugins, mk. 2
Apparently fixes all buffer-related crashes, but there's a few minor bugs left. CC #143
1 parent 68f4655 commit e9bbbc8

4 files changed

Lines changed: 151 additions & 135 deletions

File tree

‎include/linuxdeploy/plugin/base_impl.h‎

Lines changed: 3 additions & 133 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include "linuxdeploy/core/log.h"
1515
#include "linuxdeploy/util/util.h"
1616
#include "linuxdeploy/subprocess/process.h"
17+
#include "linuxdeploy/plugin/plugin_process_handler.h"
1718

1819
#pragma once
1920

@@ -135,139 +136,8 @@ namespace linuxdeploy {
135136

136137
template<int API_LEVEL>
137138
int PluginBase<API_LEVEL>::run(const boost::filesystem::path& appDirPath) {
138-
const auto pluginPath = path();
139-
const std::initializer_list<std::string> args = {pluginPath.string(), "--appdir", appDirPath.string()};
140-
141-
auto log = ldLog();
142-
log << "Running process:";
143-
for (const auto& arg : args) {
144-
log << "" << arg;
145-
}
146-
log << std::endl;
147-
148-
subprocess::subprocess_env_map_t environmentVariables{};
149-
150-
if (this->pluginType() == PLUGIN_TYPE::INPUT_TYPE) {
151-
// add $LINUXDEPLOY, which points to the current binary
152-
// we do not need to pass $APPIMAGE or alike, since while linuxdeploy is running, the path in the
153-
// temporary mountpoint of its AppImage will be valid anyway
154-
environmentVariables["LINUXDEPLOY"] = linuxdeploy::util::getOwnExecutablePath();
155-
}
156-
157-
subprocess::process process(args, environmentVariables);
158-
159-
std::vector<pollfd> pfds(2);
160-
auto* opfd = &pfds[0];
161-
auto* epfd = &pfds[1];
162-
163-
opfd->fd = process.stdout_fd();
164-
opfd->events = POLLIN;
165-
166-
epfd->fd = process.stderr_fd();
167-
epfd->events = POLLIN;
168-
169-
for (const auto& fd : {process.stdout_fd(), process.stderr_fd()}) {
170-
auto flags = fcntl(fd, F_GETFL, 0);
171-
flags |= O_NONBLOCK;
172-
fcntl(fd, F_SETFL, flags);
173-
}
174-
175-
auto printOutput = [&pfds, opfd, epfd, this, &process]() {
176-
poll(pfds.data(), pfds.size(), -1);
177-
178-
auto printUntilLastLine = [this](std::vector<char>& buf, size_t& bufSize, const std::string& streamType) {
179-
std::ostringstream oss;
180-
181-
while (true) {
182-
const auto firstLineFeed = std::find(buf.begin(), buf.end(), '\n');
183-
const auto firstCarriageReturn = std::find(buf.begin(), buf.end(), '\r');
184-
185-
if (firstLineFeed == buf.end() && firstCarriageReturn == buf.end())
186-
break;
187-
188-
const auto endOfLine = std::min(firstLineFeed, firstCarriageReturn);
189-
190-
std::string line(buf.begin(), endOfLine+1);
191-
192-
oss << "[" << d->name << "/" << streamType << "] " << line;
193-
194-
bufSize -= std::distance(buf.begin(), endOfLine+1);
195-
buf.erase(buf.begin(), endOfLine+1);
196-
}
197-
198-
auto messages = oss.str();
199-
if (!messages.empty())
200-
ldLog() << messages;
201-
};
202-
203-
std::vector<char> stdoutBuf(16 * 1024);
204-
std::vector<char> stderrBuf(16 * 1024);
205-
size_t currentStdoutBufSize = 0;
206-
size_t currentStderrBufSize = 0;
207-
208-
if ((opfd->revents & POLLIN) != 0) {
209-
if (currentStdoutBufSize >= stdoutBuf.size())
210-
throw std::runtime_error("Buffer overflow");
211-
212-
while (true) {
213-
auto bytesRead = read(
214-
process.stdout_fd(),
215-
reinterpret_cast<void*>(stdoutBuf.data() + currentStdoutBufSize),
216-
static_cast<size_t>(stdoutBuf.size() - currentStdoutBufSize)
217-
);
218-
219-
if (bytesRead == 0)
220-
break;
221-
222-
currentStdoutBufSize += bytesRead;
223-
224-
printUntilLastLine(stdoutBuf, currentStdoutBufSize, "stdout");
225-
}
226-
}
227-
228-
std::this_thread::sleep_for(std::chrono::milliseconds(50));
229-
230-
if ((epfd->revents & POLLIN) != 0) {
231-
if (currentStderrBufSize >= stderrBuf.size())
232-
throw std::runtime_error("Buffer overflow");
233-
234-
while (true) {
235-
auto bytesRead = read(
236-
process.stderr_fd(),
237-
reinterpret_cast<void*>(stderrBuf.data() + currentStderrBufSize),
238-
static_cast<size_t>(stderrBuf.size() - currentStderrBufSize)
239-
);
240-
241-
if (bytesRead == 0)
242-
break;
243-
244-
currentStderrBufSize += bytesRead;
245-
246-
printUntilLastLine(stderrBuf, currentStderrBufSize, "stderr");
247-
}
248-
}
249-
250-
std::this_thread::sleep_for(std::chrono::milliseconds(50));
251-
252-
return true;
253-
};
254-
255-
do {
256-
if (!printOutput()) {
257-
ldLog() << LD_ERROR << "Failed to communicate with process" << std::endl;
258-
process.kill();
259-
return -1;
260-
}
261-
} while (process.is_running());
262-
263-
if (!printOutput()) {
264-
ldLog() << LD_ERROR << "Failed to communicate with process" << std::endl;
265-
process.kill();
266-
return -1;
267-
}
268-
269-
const auto retcode = process.close();
270-
return retcode;
139+
plugin_process_handler handler(d->name, path());
140+
return handler.run(appDirPath);
271141
}
272142
}
273143
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#pragma once
2+
3+
// library headers
4+
#include <boost/filesystem/path.hpp>
5+
6+
namespace linuxdeploy {
7+
namespace plugin {
8+
class plugin_process_handler {
9+
private:
10+
std::string name_;
11+
boost::filesystem::path path_;
12+
13+
public:
14+
plugin_process_handler(std::string name, boost::filesystem::path path);
15+
16+
int run(const boost::filesystem::path& appDir) const;
17+
};
18+
}
19+
}

‎src/plugin/CMakeLists.txt‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,20 @@
1-
file(GLOB PLUGIN_HEADERS ${PROJECT_SOURCE_DIR}/include/linuxdeploy/plugin/*.h)
1+
set(headers_dir ${PROJECT_SOURCE_DIR}/include/linuxdeploy/plugin/)
22

3-
add_library(linuxdeploy_plugin STATIC plugin_type0.cpp plugin.cpp ${PLUGIN_HEADERS})
3+
set(headers
4+
${headers_dir}/plugin.h
5+
${headers_dir}/base.h
6+
${headers_dir}/base_impl.h
7+
${headers_dir}/exceptions.h
8+
${headers_dir}/plugin_process_handler.h
9+
)
10+
11+
add_library(linuxdeploy_plugin STATIC
12+
plugin.cpp
13+
plugin_type0.cpp
14+
plugin_process_handler.cpp
15+
${headers}
16+
)
417
target_link_libraries(linuxdeploy_plugin PUBLIC linuxdeploy_core ${BOOST_LIBS} linuxdeploy_subprocess)
18+
19+
unset(headers)
20+
unset(headers_dir)
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// system headers
2+
#include <tuple>
3+
#include <thread>
4+
5+
// local headers
6+
#include <linuxdeploy/plugin/plugin_process_handler.h>
7+
#include <linuxdeploy/subprocess/process.h>
8+
#include <linuxdeploy/util/util.h>
9+
#include <linuxdeploy/core/log.h>
10+
#include <linuxdeploy/subprocess/pipe_reader.h>
11+
12+
namespace bf = boost::filesystem;
13+
14+
namespace linuxdeploy {
15+
namespace plugin {
16+
using namespace core::log;
17+
18+
plugin_process_handler::plugin_process_handler(std::string name, bf::path path) : name_(std::move(name)), path_(std::move(path)) {}
19+
20+
int plugin_process_handler::run(const bf::path& appDir) const {
21+
// prepare arguments and environment variables
22+
const std::initializer_list<std::string> args = {path_.string(), "--appdir", appDir.string()};
23+
24+
subprocess::subprocess_env_map_t environmentVariables{};
25+
26+
// add $LINUXDEPLOY, which points to the current binary
27+
// we do not need to pass $APPIMAGE or alike, since while linuxdeploy is running, the path in the
28+
// temporary mountpoint of its AppImage will be valid anyway
29+
environmentVariables["LINUXDEPLOY"] = linuxdeploy::util::getOwnExecutablePath();
30+
31+
linuxdeploy::subprocess::process proc{args, environmentVariables};
32+
33+
// we want to insert a custom log prefix whenever a CR or LF is written into either buffer
34+
// like in subprocess's check_output, we use pipe readers to read from the subprocess's stdout/stderr pipes
35+
// however, we just dump everything we receive directly in the log, using our ĺogging framework
36+
// we store an ldLog instance per stream so we can just send all data into those, which allows us to get away
37+
// with relatively small buffers (we don't have to cache complete lines or alike)
38+
// parameter order: pipe reader, log type (used in prefix), ldLog instance, first message
39+
std::array<std::tuple<pipe_reader, std::string, ldLog, bool>, 2> pipes_to_be_logged{
40+
std::make_tuple(pipe_reader(proc.stdout_fd()), "stdout", ldLog{}, true),
41+
std::make_tuple(pipe_reader(proc.stderr_fd()), "stderr", ldLog{}, true),
42+
};
43+
44+
for (;;) {
45+
for (auto& tuple : pipes_to_be_logged) {
46+
// make code in this loop more readable
47+
auto& reader = std::get<0>(tuple);
48+
const auto& stream_name = std::get<1>(tuple);
49+
auto& log = std::get<2>(tuple);
50+
auto& is_first_message = std::get<3>(tuple);
51+
52+
const auto log_prefix = "[" + name_ + "/" + stream_name + "] ";
53+
54+
// since we have our own ldLog instance for every pipe, we can get away with this rather small read buffer
55+
subprocess::subprocess_result_buffer_t intermediate_buffer(4096);
56+
57+
// (try to) read from pipe
58+
const auto bytes_read = reader.read(intermediate_buffer);
59+
60+
// no action required in case we have not read anything from the pipe
61+
if (bytes_read > 0) {
62+
// special handling for the first message
63+
if (is_first_message) {
64+
log << log_prefix;
65+
is_first_message = false;
66+
}
67+
68+
// we just trim the buffer to the bytes we read (makes the code below easier)
69+
intermediate_buffer.resize(bytes_read);
70+
71+
// all we have to do now is to look for CR or LF, send everything up to that location into the ldLog instance,
72+
// write our prefix and then repeat
73+
for (auto it = intermediate_buffer.begin(); it != intermediate_buffer.end(); ++it) {
74+
const auto next_lf = std::find(it, intermediate_buffer.end(), '\n');
75+
const auto next_cr = std::find(it, intermediate_buffer.end(), '\r');
76+
77+
// we don't care which one goes first -- we pick the closest one, write everything up to it into our ldLog,
78+
// then print our prefix and repeat that until there's nothing left in our buffer
79+
auto next_control_char = std::min({next_lf, next_cr});
80+
81+
if (next_control_char == intermediate_buffer.end()) {
82+
break;
83+
}
84+
85+
// need to make sure we include the control char in the write
86+
log.write(
87+
intermediate_buffer.data() + std::distance(intermediate_buffer.begin(), it),
88+
std::distance(it, next_control_char) + 1
89+
);
90+
91+
log << log_prefix;
92+
93+
it = next_control_char;
94+
}
95+
}
96+
}
97+
98+
// do-while might be a little more elegant, but we can save this one unnecessary sleep, so...
99+
if (proc.is_running()) {
100+
// reduce load on CPU
101+
std::this_thread::sleep_for(std::chrono::milliseconds(50));
102+
} else {
103+
break;
104+
}
105+
}
106+
107+
return proc.close();
108+
}
109+
110+
}
111+
}

0 commit comments

Comments
 (0)