[util] add RunCommandParseJSON

This commit is contained in:
Sjors Provoost
2020-01-30 12:07:57 +01:00
parent c17f54ee53
commit 31cf68a3ad
4 changed files with 149 additions and 0 deletions

View File

@@ -6,6 +6,10 @@
#include <sync.h>
#include <util/system.h>
#ifdef HAVE_BOOST_PROCESS
#include <boost/process.hpp>
#endif // HAVE_BOOST_PROCESS
#include <chainparamsbase.h>
#include <util/strencodings.h>
#include <util/string.h>
@@ -1161,6 +1165,43 @@ void runCommand(const std::string& strCommand)
}
#endif
#ifdef HAVE_BOOST_PROCESS
UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
{
namespace bp = boost::process;
UniValue result_json;
bp::opstream stdin_stream;
bp::ipstream stdout_stream;
bp::ipstream stderr_stream;
if (str_command.empty()) return UniValue::VNULL;
bp::child c(
str_command,
bp::std_out > stdout_stream,
bp::std_err > stderr_stream,
bp::std_in < stdin_stream
);
if (!str_std_in.empty()) {
stdin_stream << str_std_in << std::endl;
}
stdin_stream.pipe().close();
std::string result;
std::string error;
std::getline(stdout_stream, result);
std::getline(stderr_stream, error);
c.wait();
const int n_error = c.exit_code();
if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
return result_json;
}
#endif // HAVE_BOOST_PROCESS
void SetupEnvironment()
{
#ifdef HAVE_MALLOPT_ARENA_MAX

View File

@@ -37,6 +37,8 @@
#include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted
class UniValue;
// Application startup time (used for uptime calculation)
int64_t GetStartupTime();
@@ -96,6 +98,16 @@ std::string ShellEscape(const std::string& arg);
#if HAVE_SYSTEM
void runCommand(const std::string& strCommand);
#endif
#ifdef HAVE_BOOST_PROCESS
/**
* Execute a command which returns JSON, and parse the result.
*
* @param str_command The command to execute, including any arguments
* @param str_std_in string to pass to stdin
* @return parsed JSON
*/
UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in="");
#endif // HAVE_BOOST_PROCESS
/**
* Most paths passed as configuration arguments are treated as relative to