Skip to content

Commit 3f74b5a

Browse files
committed
Squashed 'src/ipc/libmultiprocess/' changes from 47d79db8a552..ec86e4336e98
ec86e4336e98 Merge bitcoin-core/libmultiprocess#220: Add log levels and advertise them to users via logging callback 515ce93ad349 Logging: Pass LogData struct to logging callback 213574ccc43d Logging: reclassify remaining log messages e4de0412b430 Logging: Break out expensive log messages and classify them as Trace 408874a78fdc Logging: Use new logging macros 67b092d835cd Logging: Disable logging if messsage level is less than the requested level d0a1ba7ebf21 Logging: add log levels to mirror Core's 463a8296d188 Logging: Disable moving or copying Logger 83a2e10c0b03 Logging: Add an EventLoop constructor to allow for user-specified log options 58cf47a7fc8c Merge bitcoin-core/libmultiprocess#221: test default PassField impl handles output parameters db03a663f514 Merge bitcoin-core/libmultiprocess#214: Fix crash on simultaneous IPC calls using the same thread afcc40b0f1e8 Merge bitcoin-core/libmultiprocess#213: util+doc: Clearer errors when attempting to run examples + polished docs 6db669628387 test In|Out parameter 29cf2ada75ea test default PassField impl handles output parameters 1238170f68e8 test: simultaneous IPC calls using same thread eb069ab75d83 Fix crash on simultaneous IPC calls using the same thread ec03a9639ab5 doc: Precision and typos 2b4348193551 doc: Where possible, remove links to ryanofsky/bitcoin/ 286fe469c9c9 util: Add helpful error message when failing to execute file git-subtree-dir: src/ipc/libmultiprocess git-subtree-split: ec86e4336e986a02b08ab12f7eea9f74551c5bef
1 parent 535fa0a commit 3f74b5a

File tree

13 files changed

+219
-71
lines changed

13 files changed

+219
-71
lines changed

doc/design.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
Given an interface description of an object with one or more methods, libmultiprocess generates:
44

5-
* A C++ `ProxyClient` class with an implementation of each interface method that sends a request over a socket, waits for a response, and returns the result.
6-
* A C++ `ProxyServer` class that listens for requests over a socket and calls a wrapped C++ object implementing the same interface to actually execute the requests.
5+
* A C++ `ProxyClient` class template specialization with an implementation of each interface method that sends a request over a socket, waits for a response, and returns the result.
6+
* A C++ `ProxyServer` class template specialization that listens for requests over a socket and calls a wrapped C++ object implementing the same interface to actually execute the requests.
77

88
The function call ⇆ request translation supports input and output arguments, standard types like `unique_ptr`, `vector`, `map`, and `optional`, and bidirectional calls between processes through interface pointer and `std::function` arguments.
99

@@ -15,21 +15,21 @@ Libmultiprocess acts as a pure wrapper or layer over the underlying protocol. Cl
1515

1616
### Internals
1717

18-
The `ProxyClient` and `ProxyServer` generated classes are not directly exposed to the user, as described in [usage.md](usage.md). Instead, they wrap c++ interfaces and appear to the user as pointers to an interface. They are first instantiated when calling `ConnectStream` and `ServeStream` respectively for creating the `InitInterface`. These methods establish connections through sockets, internally creating `Connection` objects wrapping a `capnp::RpcSystem` configured for client and server mode respectively.
18+
The `ProxyClient` and `ProxyServer` generated classes are not directly exposed to the user, as described in [usage.md](usage.md). Instead, they wrap C++ interfaces and appear to the user as pointers to an interface. They are first instantiated when calling `ConnectStream` and `ServeStream` respectively for creating the `InitInterface`. These methods establish connections through sockets, internally creating `Connection` objects wrapping a `capnp::RpcSystem` configured for client and server mode respectively.
1919

2020
The `InitInterface` interface will typically have methods which return other interfaces, giving the connecting process the ability to call other functions in the serving process. Interfaces can also have methods accepting other interfaces as parameters, giving serving processes the ability to call back and invoke functions in connecting processes. Creating new interfaces does not create new connections, and typically many interface objects will share the same connection.
2121

2222
Both `ConnectStream` and `ServeStream` also require an instantiation of the `EventLoop`. The `EventLoop` owns pending requests, notifies on request dispatch, allows clients from multiple threads to make synchronous calls, and handles some cleanup routines on exit. It must be run in a separate thread so it is always active and can process incoming requests from local clients and remote connections.
2323

2424
When a generated method on the `ProxyClient` is called, it calls `clientInvoke` with the capnp-translated types. `clientInvoke` creates a self-executing promise (`kj::TaskSet`) that drives the execution of the request and gives ownership of it to the `EventLoop`. `clientInvoke` blocks until a response is received, or until there is a call from the server that needs to run on the same client thread, using a `Waiter` object.
2525

26-
On the server side, the `capnp::RpcSystem` receives the capnp request and invokes the corresponding c++ method through the corresponding `ProxyServer` and the heavily templated `serverInvoke` triggering a `ServerCall`. Its return values from the actual c++ methods are copied into capnp responses by `ServerRet` and exceptions are caught and copied by `ServerExcept`. The two are connected through `ServerField`. The main method driving execution of a request is `PassField`, which is invoked through `ServerField`. Instantiated interfaces, or capabilities in capnp speak, are tracked and owned by the server's `capnp::RpcSystem`.
26+
On the server side, the `capnp::RpcSystem` receives the capnp request and invokes the corresponding C++ method through the corresponding `ProxyServer` and the heavily templated `serverInvoke` triggering a `ServerCall`. The return values from the actual C++ methods are copied into capnp responses by `ServerRet` and exceptions are caught and copied by `ServerExcept`. The two are connected through `ServerField`. The main method driving execution of a request is `PassField`, which is invoked through `ServerField`. Instantiated interfaces, or capabilities in capnp speak, are tracked and owned by the server's `capnp::RpcSystem`.
2727

2828
## Interface descriptions
2929

3030
As explained in the [usage](usage.md) document, interface descriptions need to be consumed both by the _libmultiprocess_ code generator, and by C++ code that calls and implements the interfaces. The C++ code only needs to know about C++ arguments and return types, while the code generator only needs to know about capnp arguments and return types, but both need to know class and method names, so the corresponding `.h` and `.capnp` source files contain some of the same information, and have to be kept in sync manually when methods or parameters change. Despite the redundancy, reconciling the interface definitions is designed to be _straightforward_ and _safe_. _Straightforward_ because there is no need to write manual serialization code or use awkward intermediate types like [`UniValue`](https://github.com/bitcoin/bitcoin/blob/master/src/univalue/include/univalue.h) instead of native types. _Safe_ because if there are any inconsistencies between API and data definitions (even minor ones like using a narrow int data type for a wider int API input), there are errors at build time instead of errors or bugs at runtime.
3131

32-
In the future, it would be possible to combine API and data definitions together using [C++ attributes](https://en.cppreference.com/w/cpp/language/attributes). To do this we would add attributes to the API definition files, and then generate the data definitions from the API definitions and attributes. I didn't take this approach mostly because it would be extra work, but also because until c++ standardizes reflection, this would require either hooking into compiler APIs like https://github.com/RosettaCommons/binder, or parsing c++ code manually like http://www.swig.org/.
32+
In the future, it would be possible to combine API and data definitions together using [C++ attributes](https://en.cppreference.com/w/cpp/language/attributes). To do this we would add attributes to the API definition files, and then generate the data definitions from the API definitions and attributes. I didn't take this approach mostly because it would be extra work, but also because until C++ standardizes reflection, this would require either hooking into compiler APIs like https://github.com/RosettaCommons/binder, or parsing C++ code manually like http://www.swig.org/.
3333

3434
## What is `kj`?
3535

@@ -39,6 +39,6 @@ basis in this library to construct the event-loop necessary to service IPC reque
3939

4040
## Future directions
4141

42-
_libmultiprocess_ uses the [Cap'n Proto](https://capnproto.org) interface description language and protocol, but it could be extended or changed to use a different IDL/protocol like [gRPC](https://grpc.io). The nice thing about _Cap'n Proto_ compared to _gRPC_ and most other lower level protocols is that it allows interface pointers (_Services_ in gRPC parlance) to be passed as method arguments and return values, so object references and bidirectional requests work out of the box. Supporting a lower-level protocol would require writing adding maps and tracking code to proxy objects.
42+
_libmultiprocess_ uses the [Cap'n Proto](https://capnproto.org) interface description language and protocol, but it could be extended or changed to use a different IDL/protocol like [gRPC](https://grpc.io). The nice thing about _Cap'n Proto_ compared to _gRPC_ and most other lower level protocols is that it allows interface pointers (_Services_ in gRPC parlance) to be passed as method arguments and return values, so object references and bidirectional requests work out of the box. Supporting a lower-level protocol would require adding maps and tracking code to proxy objects.
4343

4444
_libmultiprocess_ is currently compatible with sandboxing but could add platform-specific sandboxing support or integration with a sandboxing library like [SAPI](https://github.com/google/sandboxed-api).

doc/usage.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
_libmultiprocess_ is a library and code generator that allows calling C++ class interfaces across different processes. For an interface to be available from other processes, it needs two definitions:
66

7-
- An **API definition** declaring how the interface is called. Included examples: [calculator.h](https://github.com/bitcoin-core/libmultiprocess/blob/master/example/calculator.h), [printer.h](https://github.com/bitcoin-core/libmultiprocess/blob/master/example/printer.h), [init.h](https://github.com/bitcoin-core/libmultiprocess/blob/master/example/init.h). Bitcoin examples: [node.h](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/interfaces/node.h), [wallet.h](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/interfaces/wallet.h), [echo.h](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/interfaces/echo.h), [init.h](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/interfaces/init.h).
7+
- An **API definition** declaring how the interface is called. Included examples: [calculator.h](../example/calculator.h), [printer.h](../example/printer.h), [init.h](../example/init.h). Bitcoin examples: [node.h](https://github.com/bitcoin/bitcoin/blob/master/src/interfaces/node.h), [wallet.h](https://github.com/bitcoin/bitcoin/blob/master/src/interfaces/wallet.h), [echo.h](https://github.com/bitcoin/bitcoin/blob/master/src/interfaces/echo.h), [init.h](https://github.com/bitcoin/bitcoin/blob/master/src/interfaces/init.h).
88

9-
- A **data definition** declaring how interface calls get sent across the wire. Included examples: [calculator.capnp](https://github.com/bitcoin-core/libmultiprocess/blob/master/example/calculator.capnp), [printer.capnp](https://github.com/bitcoin-core/libmultiprocess/blob/master/example/printer.capnp), [init.capnp](https://github.com/bitcoin-core/libmultiprocess/blob/master/example/init.capnp). Bitcoin examples: [node.capnp](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/ipc/capnp/node.capnp), [wallet.capnp](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/ipc/capnp/wallet.capnp), [echo.capnp](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/ipc/capnp/echo.capnp), [init.capnp](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/ipc/capnp/init.capnp).
9+
- A **data definition** declaring how interface calls get sent across the wire. Included examples: [calculator.capnp](../example/calculator.capnp), [printer.capnp](../example/printer.capnp), [init.capnp](../example/init.capnp). Bitcoin examples: [node.capnp](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/ipc/capnp/node.capnp), [wallet.capnp](https://github.com/ryanofsky/bitcoin/blob/ipc-export/src/ipc/capnp/wallet.capnp), [echo.capnp](https://github.com/bitcoin/bitcoin/blob/master/src/ipc/capnp/echo.capnp), [init.capnp](https://github.com/bitcoin/bitcoin/blob/master/src/ipc/capnp/init.capnp).
1010

1111
The `*.capnp` data definition files are consumed by the _libmultiprocess_ code generator and each `X.capnp` file generates `X.capnp.c++`, `X.capnp.h`, `X.capnp.proxy-client.c++`, `X.capnp.proxy-server.c++`, `X.capnp.proxy-types.c++`, `X.capnp.proxy-types.h`, and `X.capnp.proxy.h` output files. The generated files include `mp::ProxyClient<Interface>` and `mp::ProxyServer<Interface>` class specializations for all the interfaces in the `.capnp` files. These allow methods on C++ objects in one process to be called from other processes over IPC sockets.
1212

example/calculator.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <charconv>
1010
#include <cstring>
1111
#include <fstream>
12+
#include <functional>
1213
#include <iostream>
1314
#include <kj/async.h>
1415
#include <kj/common.h>
@@ -37,6 +38,7 @@ class InitImpl : public Init
3738
}
3839
};
3940

41+
// Exercises deprecated log callback signature
4042
static void LogPrint(bool raise, const std::string& message)
4143
{
4244
if (raise) throw std::runtime_error(message);

example/example.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,10 @@ static auto Spawn(mp::EventLoop& loop, const std::string& process_argv0, const s
3535
return std::make_tuple(mp::ConnectStream<InitInterface>(loop, fd), pid);
3636
}
3737

38-
static void LogPrint(bool raise, const std::string& message)
38+
static void LogPrint(mp::LogMessage log_data)
3939
{
40-
if (raise) throw std::runtime_error(message);
41-
std::ofstream("debug.log", std::ios_base::app) << message << std::endl;
40+
if (log_data.level == mp::Log::Raise) throw std::runtime_error(log_data.message);
41+
std::ofstream("debug.log", std::ios_base::app) << log_data.message << std::endl;
4242
}
4343

4444
int main(int argc, char** argv)

example/printer.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@ class InitImpl : public Init
3232
std::unique_ptr<Printer> makePrinter() override { return std::make_unique<PrinterImpl>(); }
3333
};
3434

35-
static void LogPrint(bool raise, const std::string& message)
35+
static void LogPrint(mp::LogMessage log_data)
3636
{
37-
if (raise) throw std::runtime_error(message);
38-
std::ofstream("debug.log", std::ios_base::app) << message << std::endl;
37+
if (log_data.level == mp::Log::Raise) throw std::runtime_error(log_data.message);
38+
std::ofstream("debug.log", std::ios_base::app) << log_data.message << std::endl;
3939
}
4040

4141
int main(int argc, char** argv)

include/mp/proxy-io.h

Lines changed: 75 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -98,22 +98,59 @@ class LoggingErrorHandler : public kj::TaskSet::ErrorHandler
9898
EventLoop& m_loop;
9999
};
100100

101-
using LogFn = std::function<void(bool raise, std::string message)>;
101+
enum class Log {
102+
Trace = 0,
103+
Debug,
104+
Info,
105+
Warning,
106+
Error,
107+
Raise,
108+
};
109+
110+
struct LogMessage {
111+
112+
//! Message to be logged
113+
std::string message;
114+
115+
//! The severity level of this message
116+
Log level;
117+
};
118+
119+
using LogFn = std::function<void(LogMessage)>;
120+
121+
struct LogOptions {
122+
123+
//! External logging callback.
124+
LogFn log_fn;
125+
126+
//! Maximum number of characters to use when representing
127+
//! request and response structs as strings.
128+
size_t max_chars{200};
129+
130+
//! Messages with a severity level less than log_level will not be
131+
//! reported.
132+
Log log_level{Log::Trace};
133+
};
102134

103135
class Logger
104136
{
105137
public:
106-
Logger(bool raise, LogFn& fn) : m_raise(raise), m_fn(fn) {}
107-
Logger(Logger&& logger) : m_raise(logger.m_raise), m_fn(logger.m_fn), m_buffer(std::move(logger.m_buffer)) {}
138+
Logger(const LogOptions& options, Log log_level) : m_options(options), m_log_level(log_level) {}
139+
140+
Logger(Logger&&) = delete;
141+
Logger& operator=(Logger&&) = delete;
142+
Logger(const Logger&) = delete;
143+
Logger& operator=(const Logger&) = delete;
144+
108145
~Logger() noexcept(false)
109146
{
110-
if (m_fn) m_fn(m_raise, m_buffer.str());
147+
if (enabled()) m_options.log_fn({std::move(m_buffer).str(), m_log_level});
111148
}
112149

113150
template <typename T>
114151
friend Logger& operator<<(Logger& logger, T&& value)
115152
{
116-
if (logger.m_fn) logger.m_buffer << std::forward<T>(value);
153+
if (logger.enabled()) logger.m_buffer << std::forward<T>(value);
117154
return logger;
118155
}
119156

@@ -123,20 +160,25 @@ class Logger
123160
return logger << std::forward<T>(value);
124161
}
125162

126-
bool m_raise;
127-
LogFn& m_fn;
163+
explicit operator bool() const
164+
{
165+
return enabled();
166+
}
167+
168+
private:
169+
bool enabled() const
170+
{
171+
return m_options.log_fn && m_log_level >= m_options.log_level;
172+
}
173+
174+
const LogOptions& m_options;
175+
Log m_log_level;
128176
std::ostringstream m_buffer;
129177
};
130178

131-
struct LogOptions {
179+
#define MP_LOGPLAIN(loop, ...) if (mp::Logger logger{(loop).m_log_opts, __VA_ARGS__}; logger) logger
132180

133-
//! External logging callback.
134-
LogFn log_fn;
135-
136-
//! Maximum number of characters to use when representing
137-
//! request and response structs as strings.
138-
size_t max_chars{200};
139-
};
181+
#define MP_LOG(loop, ...) MP_LOGPLAIN(loop, __VA_ARGS__) << "{" << LongThreadName((loop).m_exe_name) << "} "
140182

141183
std::string LongThreadName(const char* exe_name);
142184

@@ -168,8 +210,19 @@ std::string LongThreadName(const char* exe_name);
168210
class EventLoop
169211
{
170212
public:
171-
//! Construct event loop object.
172-
EventLoop(const char* exe_name, LogFn log_fn, void* context = nullptr);
213+
//! Construct event loop object with default logging options.
214+
EventLoop(const char* exe_name, LogFn log_fn, void* context = nullptr)
215+
: EventLoop(exe_name, LogOptions{std::move(log_fn)}, context){}
216+
217+
//! Construct event loop object with specified logging options.
218+
EventLoop(const char* exe_name, LogOptions log_opts, void* context = nullptr);
219+
220+
//! Backwards-compatible constructor for previous (deprecated) logging callback signature
221+
EventLoop(const char* exe_name, std::function<void(bool, std::string)> old_callback, void* context = nullptr)
222+
: EventLoop(exe_name,
223+
LogFn{[old_callback = std::move(old_callback)](LogMessage log_data) {old_callback(log_data.level == Log::Raise, std::move(log_data.message));}},
224+
context){}
225+
173226
~EventLoop();
174227

175228
//! Run event loop. Does not return until shutdown. This should only be
@@ -210,15 +263,6 @@ class EventLoop
210263
//! Check if loop should exit.
211264
bool done() const MP_REQUIRES(m_mutex);
212265

213-
Logger log()
214-
{
215-
Logger logger(false, m_log_opts.log_fn);
216-
logger << "{" << LongThreadName(m_exe_name) << "} ";
217-
return logger;
218-
}
219-
Logger logPlain() { return {false, m_log_opts.log_fn}; }
220-
Logger raise() { return {true, m_log_opts.log_fn}; }
221-
222266
//! Process name included in thread names so combined debug output from
223267
//! multiple processes is easier to understand.
224268
const char* m_exe_name;
@@ -281,12 +325,13 @@ struct Waiter
281325
Waiter() = default;
282326

283327
template <typename Fn>
284-
void post(Fn&& fn)
328+
bool post(Fn&& fn)
285329
{
286330
const Lock lock(m_mutex);
287-
assert(!m_fn);
331+
if (m_fn) return false;
288332
m_fn = std::forward<Fn>(fn);
289333
m_cv.notify_all();
334+
return true;
290335
}
291336

292337
template <class Predicate>
@@ -642,7 +687,7 @@ std::unique_ptr<ProxyClient<InitInterface>> ConnectStream(EventLoop& loop, int f
642687
init_client = connection->m_rpc_system->bootstrap(ServerVatId().vat_id).castAs<InitInterface>();
643688
Connection* connection_ptr = connection.get();
644689
connection->onDisconnect([&loop, connection_ptr] {
645-
loop.log() << "IPC client: unexpected network disconnect.";
690+
MP_LOG(loop, Log::Warning) << "IPC client: unexpected network disconnect.";
646691
delete connection_ptr;
647692
});
648693
});
@@ -665,7 +710,7 @@ void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init
665710
});
666711
auto it = loop.m_incoming_connections.begin();
667712
it->onDisconnect([&loop, it] {
668-
loop.log() << "IPC server: socket disconnected.";
713+
MP_LOG(loop, Log::Info) << "IPC server: socket disconnected.";
669714
loop.m_incoming_connections.erase(it);
670715
});
671716
}

0 commit comments

Comments
 (0)