mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-01-19 14:53:43 +01:00
a4f929696490 Merge bitcoin-core/libmultiprocess#224: doc: fix typos f4344ae87da0 Merge bitcoin-core/libmultiprocess#222: test, ci: Fix threadsanitizer errors in mptest 1434642b3804 doc: fix typos 73d22ba2e930 test: Fix tsan race in thread busy test b74e1bba014d ci: Use tsan-instrumented cap'n proto in sanitizers job c332774409ad test: Fix failing exception check in new thread busy test ca3c05d56709 test: Use KJ_LOG instead of std::cout for logging 7eb1da120ab6 ci: Use tsan-instrumented libcxx in sanitizers job 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 47d79db8a552 Merge bitcoin-core/libmultiprocess#201: bug: fix mptest hang, ProxyClient<Thread> deadlock in disconnect handler f15ae9c9b9fb Merge bitcoin-core/libmultiprocess#211: Add .gitignore 4a269b21b8c8 bug: fix ProxyClient<Thread> deadlock if disconnected as IPC call is returning 85df96482c49 Use try_emplace in SetThread instead of threads.find ca9b380ea91a Use std::optional in ConnThreads to allow shortening locks 9b0799113557 doc: describe ThreadContext struct and synchronization requirements d60db601ed9b proxy-io.h: add Waiter::m_mutex thread safety annotations 4e365b019a9f ci: Use -Wthread-safety not -Wthread-safety-analysis 15d7bafbb001 Add .gitignore fe1cd8c76131 Merge bitcoin-core/libmultiprocess#208: ci: Test minimum cmake version in olddeps job b713a0b7bfbc Merge bitcoin-core/libmultiprocess#207: ci: output CMake version in CI script 0f580397c913 ci: Test minimum cmake version in olddeps job d603dcc0eef0 ci: output CMake version in CI script git-subtree-dir: src/ipc/libmultiprocess git-subtree-split: a4f92969649018ca70f949a09148bccfeaecd99a
173 lines
9.5 KiB
C++
173 lines
9.5 KiB
C++
// Copyright (c) The Bitcoin Core developers
|
|
// Distributed under the MIT software license, see the accompanying
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
#ifndef MP_PROXY_TYPE_CONTEXT_H
|
|
#define MP_PROXY_TYPE_CONTEXT_H
|
|
|
|
#include <mp/proxy-io.h>
|
|
#include <mp/util.h>
|
|
|
|
namespace mp {
|
|
template <typename Output>
|
|
void CustomBuildField(TypeList<>,
|
|
Priority<1>,
|
|
ClientInvokeContext& invoke_context,
|
|
Output&& output,
|
|
typename std::enable_if<std::is_same<decltype(output.get()), Context::Builder>::value>::type* enable = nullptr)
|
|
{
|
|
auto& connection = invoke_context.connection;
|
|
auto& thread_context = invoke_context.thread_context;
|
|
|
|
// Create local Thread::Server object corresponding to the current thread
|
|
// and pass a Thread::Client reference to it in the Context.callbackThread
|
|
// field so the function being called can make callbacks to this thread.
|
|
// Also store the Thread::Client reference in the callback_threads map so
|
|
// future calls over this connection can reuse it.
|
|
auto [callback_thread, _]{SetThread(
|
|
GuardedRef{thread_context.waiter->m_mutex, thread_context.callback_threads}, &connection,
|
|
[&] { return connection.m_threads.add(kj::heap<ProxyServer<Thread>>(thread_context, std::thread{})); })};
|
|
|
|
// Call remote ThreadMap.makeThread function so server will create a
|
|
// dedicated worker thread to run function calls from this thread. Store the
|
|
// Thread::Client reference it returns in the request_threads map.
|
|
auto make_request_thread{[&]{
|
|
// This code will only run if an IPC client call is being made for the
|
|
// first time on this thread. After the first call, subsequent calls
|
|
// will use the existing request thread. This code will also never run at
|
|
// all if the current thread is a request thread created for a different
|
|
// IPC client, because in that case PassField code (below) will have set
|
|
// request_thread to point to the calling thread.
|
|
auto request = connection.m_thread_map.makeThreadRequest();
|
|
request.setName(thread_context.thread_name);
|
|
return request.send().getResult(); // Nonblocking due to capnp request pipelining.
|
|
}};
|
|
auto [request_thread, _1]{SetThread(
|
|
GuardedRef{thread_context.waiter->m_mutex, thread_context.request_threads},
|
|
&connection, make_request_thread)};
|
|
|
|
auto context = output.init();
|
|
context.setThread(request_thread->second->m_client);
|
|
context.setCallbackThread(callback_thread->second->m_client);
|
|
}
|
|
|
|
//! PassField override for mp.Context arguments. Return asynchronously and call
|
|
//! function on other thread found in context.
|
|
template <typename Accessor, typename ServerContext, typename Fn, typename... Args>
|
|
auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn& fn, Args&&... args) ->
|
|
typename std::enable_if<
|
|
std::is_same<decltype(Accessor::get(server_context.call_context.getParams())), Context::Reader>::value,
|
|
kj::Promise<typename ServerContext::CallContext>>::type
|
|
{
|
|
const auto& params = server_context.call_context.getParams();
|
|
Context::Reader context_arg = Accessor::get(params);
|
|
auto future = kj::newPromiseAndFulfiller<typename ServerContext::CallContext>();
|
|
auto& server = server_context.proxy_server;
|
|
int req = server_context.req;
|
|
auto invoke = [fulfiller = kj::mv(future.fulfiller),
|
|
call_context = kj::mv(server_context.call_context), &server, req, fn, args...]() mutable {
|
|
const auto& params = call_context.getParams();
|
|
Context::Reader context_arg = Accessor::get(params);
|
|
ServerContext server_context{server, call_context, req};
|
|
{
|
|
// Before invoking the function, store a reference to the
|
|
// callbackThread provided by the client in the
|
|
// thread_local.request_threads map. This way, if this
|
|
// server thread needs to execute any RPCs that call back to
|
|
// the client, they will happen on the same client thread
|
|
// that is waiting for this function, just like what would
|
|
// happen if this were a normal function call made on the
|
|
// local stack.
|
|
//
|
|
// If the request_threads map already has an entry for this
|
|
// connection, it will be left unchanged, and it indicates
|
|
// that the current thread is an RPC client thread which is
|
|
// in the middle of an RPC call, and the current RPC call is
|
|
// a nested call from the remote thread handling that RPC
|
|
// call. In this case, the callbackThread value should point
|
|
// to the same thread already in the map, so there is no
|
|
// need to update the map.
|
|
auto& thread_context = g_thread_context;
|
|
auto& request_threads = thread_context.request_threads;
|
|
ConnThread request_thread;
|
|
bool inserted;
|
|
server.m_context.loop->sync([&] {
|
|
std::tie(request_thread, inserted) = SetThread(
|
|
GuardedRef{thread_context.waiter->m_mutex, request_threads}, server.m_context.connection,
|
|
[&] { return context_arg.getCallbackThread(); });
|
|
});
|
|
|
|
// If an entry was inserted into the request_threads map,
|
|
// remove it after calling fn.invoke. If an entry was not
|
|
// inserted, one already existed, meaning this must be a
|
|
// recursive call (IPC call calling back to the caller which
|
|
// makes another IPC call), so avoid modifying the map.
|
|
const bool erase_thread{inserted};
|
|
KJ_DEFER(if (erase_thread) {
|
|
// Erase the request_threads entry on the event loop
|
|
// thread with loop->sync(), so if the connection is
|
|
// broken there is not a race between this thread and
|
|
// the disconnect handler trying to destroy the thread
|
|
// client object.
|
|
server.m_context.loop->sync([&] {
|
|
// Look up the thread again without using existing
|
|
// iterator since entry may no longer be there after
|
|
// a disconnect. Destroy node after releasing
|
|
// Waiter::m_mutex, so the ProxyClient<Thread>
|
|
// destructor is able to use EventLoop::mutex
|
|
// without violating lock order.
|
|
ConnThreads::node_type removed;
|
|
{
|
|
Lock lock(thread_context.waiter->m_mutex);
|
|
removed = request_threads.extract(server.m_context.connection);
|
|
}
|
|
});
|
|
});
|
|
fn.invoke(server_context, args...);
|
|
}
|
|
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
|
|
server.m_context.loop->sync([&] {
|
|
auto fulfiller_dispose = kj::mv(fulfiller);
|
|
fulfiller_dispose->fulfill(kj::mv(call_context));
|
|
});
|
|
}))
|
|
{
|
|
server.m_context.loop->sync([&]() {
|
|
auto fulfiller_dispose = kj::mv(fulfiller);
|
|
fulfiller_dispose->reject(kj::mv(*exception));
|
|
});
|
|
}
|
|
};
|
|
|
|
// Lookup Thread object specified by the client. The specified thread should
|
|
// be a local Thread::Server object, but it needs to be looked up
|
|
// asynchronously with getLocalServer().
|
|
auto thread_client = context_arg.getThread();
|
|
return server.m_context.connection->m_threads.getLocalServer(thread_client)
|
|
.then([&server, invoke = kj::mv(invoke), req](const kj::Maybe<Thread::Server&>& perhaps) mutable {
|
|
// Assuming the thread object is found, pass it a pointer to the
|
|
// `invoke` lambda above which will invoke the function on that
|
|
// thread.
|
|
KJ_IF_MAYBE (thread_server, perhaps) {
|
|
const auto& thread = static_cast<ProxyServer<Thread>&>(*thread_server);
|
|
MP_LOG(*server.m_context.loop, Log::Debug)
|
|
<< "IPC server post request #" << req << " {" << thread.m_thread_context.thread_name << "}";
|
|
if (!thread.m_thread_context.waiter->post(std::move(invoke))) {
|
|
MP_LOG(*server.m_context.loop, Log::Error)
|
|
<< "IPC server error request #" << req
|
|
<< " {" << thread.m_thread_context.thread_name << "}" << ", thread busy";
|
|
throw std::runtime_error("thread busy");
|
|
}
|
|
} else {
|
|
MP_LOG(*server.m_context.loop, Log::Error)
|
|
<< "IPC server error request #" << req << ", missing thread to execute request";
|
|
throw std::runtime_error("invalid thread handle");
|
|
}
|
|
})
|
|
// Wait for the invocation to finish before returning to the caller.
|
|
.then([invoke_wait = kj::mv(future.promise)]() mutable { return kj::mv(invoke_wait); });
|
|
}
|
|
} // namespace mp
|
|
|
|
#endif // MP_PROXY_TYPE_CONTEXT_H
|