Bitcoin Core 30.99.0
P2P Digital Currency
protocol.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <interfaces/init.h>
6#include <ipc/capnp/context.h>
7#include <ipc/capnp/init.capnp.h>
8#include <ipc/capnp/init.capnp.proxy.h>
10#include <ipc/exception.h>
11#include <ipc/protocol.h>
12#include <kj/async.h>
13#include <logging.h>
14#include <mp/proxy-io.h>
15#include <mp/proxy-types.h>
16#include <mp/util.h>
17#include <util/threadnames.h>
18
19#include <cassert>
20#include <cerrno>
21#include <future>
22#include <memory>
23#include <mutex>
24#include <optional>
25#include <string>
26#include <sys/socket.h>
27#include <system_error>
28#include <thread>
29
30namespace ipc {
31namespace capnp {
32namespace {
33
34BCLog::Level ConvertIPCLogLevel(mp::Log level)
35{
36 switch (level) {
43 } // no default case, so the compiler can warn about missing cases
44
45 // Be conservative and assume that if MP ever adds a new log level, it
46 // should only be shown at our most verbose level.
48}
49
50mp::Log GetRequestedIPCLogLevel()
51{
54
55 // Info, Warning, and Error are logged unconditionally
56 return mp::Log::Info;
57}
58
59void IpcLogFn(mp::LogMessage message)
60{
61 LogPrintLevel(BCLog::IPC, ConvertIPCLogLevel(message.level), "%s\n", message.message);
62 if (message.level == mp::Log::Raise) throw Exception(message.message);
63}
64
65class CapnpProtocol : public Protocol
66{
67public:
68 ~CapnpProtocol() noexcept(true)
69 {
70 m_loop_ref.reset();
71 if (m_loop_thread.joinable()) m_loop_thread.join();
72 assert(!m_loop);
73 };
74 std::unique_ptr<interfaces::Init> connect(int fd, const char* exe_name) override
75 {
76 startLoop(exe_name);
77 return mp::ConnectStream<messages::Init>(*m_loop, fd);
78 }
79 void listen(int listen_fd, const char* exe_name, interfaces::Init& init) override
80 {
81 startLoop(exe_name);
82 if (::listen(listen_fd, /*backlog=*/5) != 0) {
83 throw std::system_error(errno, std::system_category());
84 }
85 mp::ListenConnections<messages::Init>(*m_loop, listen_fd, init);
86 }
87 void serve(int fd, const char* exe_name, interfaces::Init& init, const std::function<void()>& ready_fn = {}) override
88 {
89 assert(!m_loop);
91 mp::LogOptions opts = {
92 .log_fn = IpcLogFn,
93 .log_level = GetRequestedIPCLogLevel()
94 };
95 m_loop.emplace(exe_name, std::move(opts), &m_context);
96 if (ready_fn) ready_fn();
97 mp::ServeStream<messages::Init>(*m_loop, fd, init);
98 m_parent_connection = &m_loop->m_incoming_connections.back();
99 m_loop->loop();
100 m_loop.reset();
101 }
102 void disconnectIncoming() override
103 {
104 if (!m_loop) return;
105 // Delete incoming connections, except the connection to a parent
106 // process (if there is one), since a parent process should be able to
107 // monitor and control this process, even during shutdown.
108 m_loop->sync([&] {
109 m_loop->m_incoming_connections.remove_if([this](mp::Connection& c) { return &c != m_parent_connection; });
110 });
111 }
112 void addCleanup(std::type_index type, void* iface, std::function<void()> cleanup) override
113 {
114 mp::ProxyTypeRegister::types().at(type)(iface).cleanup_fns.emplace_back(std::move(cleanup));
115 }
116 Context& context() override { return m_context; }
117 void startLoop(const char* exe_name)
118 {
119 if (m_loop) return;
120 std::promise<void> promise;
121 m_loop_thread = std::thread([&] {
122 util::ThreadRename("capnp-loop");
123 mp::LogOptions opts = {
124 .log_fn = IpcLogFn,
125 .log_level = GetRequestedIPCLogLevel()
126 };
127 m_loop.emplace(exe_name, std::move(opts), &m_context);
128 m_loop_ref.emplace(*m_loop);
129 promise.set_value();
130 m_loop->loop();
131 m_loop.reset();
132 });
133 promise.get_future().wait();
134 }
135 Context m_context;
136 std::thread m_loop_thread;
138 std::optional<mp::EventLoop> m_loop;
142 std::optional<mp::EventLoopRef> m_loop_ref;
145};
146} // namespace
147
148std::unique_ptr<Protocol> MakeCapnpProtocol() { return std::make_unique<CapnpProtocol>(); }
149} // namespace capnp
150} // namespace ipc
Initial interface created when a process is first started, and used to give and get access to other i...
Definition: init.h:31
Object holding network & rpc state associated with either an incoming server connection,...
Definition: proxy-io.h:377
std::thread m_loop_thread
Definition: protocol.cpp:136
mp::Connection * m_parent_connection
Connection to parent, if this is a child process spawned by a parent process.
Definition: protocol.cpp:144
std::optional< mp::EventLoop > m_loop
EventLoop object which manages I/O events for all connections.
Definition: protocol.cpp:138
std::optional< mp::EventLoopRef > m_loop_ref
Reference to the same EventLoop.
Definition: protocol.cpp:142
Context m_context
Definition: protocol.cpp:135
#define LogPrintLevel(category, level,...)
Definition: logging.h:372
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:328
Level
Definition: logging.h:99
@ IPC
Definition: logging.h:89
std::unique_ptr< Protocol > MakeCapnpProtocol()
Definition: protocol.cpp:148
Definition: ipc.h:12
std::string ThreadName(const char *exe_name)
Format current thread name as "{exe_name}-{$pid}/{thread_name}-{$tid}".
Definition: util.cpp:52
thread_local ThreadContext g_thread_context
Definition: proxy.cpp:41
Log
Log flags. Update stringify function if changed!
Definition: proxy-io.h:102
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:55
Log level
The severity level of this message.
Definition: proxy-io.h:119
std::string message
Message to be logged.
Definition: proxy-io.h:116
LogFn log_fn
External logging callback.
Definition: proxy-io.h:127
static Types & types()
Definition: proxy-types.h:747
std::string thread_name
Identifying string for debug.
Definition: proxy-io.h:623
assert(!tx.IsCoinBase())