Bitcoin Core 31.99.0
P2P Digital Currency
protocol.cpp
Go to the documentation of this file.
1// Copyright (c) 2021-present 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 <mp/proxy-io.h>
14#include <mp/proxy-types.h>
15#include <mp/util.h>
16#include <util/log.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
34mp::Log GetRequestedIPCLogLevel()
35{
38
39 // Info, Warning, and Error are logged unconditionally
40 return mp::Log::Info;
41}
42
43void IpcLogFn(mp::LogMessage message)
44{
45 switch (message.level) {
46 case mp::Log::Trace:
47 LogTrace(BCLog::IPC, "%s", message.message);
48 return;
49 case mp::Log::Debug:
50 LogDebug(BCLog::IPC, "%s", message.message);
51 return;
52 case mp::Log::Info:
53 LogInfo("ipc: %s", message.message);
54 return;
56 LogWarning("ipc: %s", message.message);
57 return;
58 case mp::Log::Error:
59 LogError("ipc: %s", message.message);
60 return;
61 case mp::Log::Raise:
62 LogError("ipc: %s", message.message);
63 throw Exception(message.message);
64 } // no default case, so the compiler can warn about missing cases
65
66 // Be conservative and assume that if MP ever adds a new log level, it
67 // should only be shown at our most verbose level.
68 LogTrace(BCLog::IPC, "%s", message.message);
69}
70
71class CapnpProtocol : public Protocol
72{
73public:
74 CapnpProtocol(const char* exe_name) : m_exe_name{exe_name} {}
75 ~CapnpProtocol() noexcept(true)
76 {
77 m_loop_ref.reset();
78 if (m_loop_thread.joinable()) m_loop_thread.join();
79 assert(!m_loop);
80 };
81 std::unique_ptr<interfaces::Init> connect(mp::Stream stream) override
82 {
83 startLoop();
84 return mp::ConnectStream<messages::Init>(*m_loop, std::move(stream));
85 }
86 void listen(mp::SocketId listen_fd, interfaces::Init& init) override
87 {
88 startLoop();
89 if (::listen(listen_fd, /*backlog=*/5) != 0) {
90 throw std::system_error(errno, std::system_category());
91 }
92 mp::ListenConnections<messages::Init>(*m_loop, listen_fd, init);
93 }
94 void serve(interfaces::Init& init, const std::function<mp::Stream()>& make_stream) override
95 {
96 assert(!m_loop);
98 mp::LogOptions opts = {
99 .log_fn = IpcLogFn,
100 .log_level = GetRequestedIPCLogLevel()
101 };
102 m_loop.emplace(m_exe_name, std::move(opts), &m_context);
103 mp::ServeStream<messages::Init>(*m_loop, make_stream(), init);
104 m_parent_connection = &m_loop->m_incoming_connections.back();
105 m_loop->loop();
106 m_loop.reset();
107 }
108 void disconnectIncoming() override
109 {
110 if (!m_loop) return;
111 // Delete incoming connections, except the connection to a parent
112 // process (if there is one), since a parent process should be able to
113 // monitor and control this process, even during shutdown.
114 m_loop->sync([&] {
115 m_loop->m_incoming_connections.remove_if([this](mp::Connection& c) { return &c != m_parent_connection; });
116 });
117 }
118 mp::Stream makeStream(mp::SocketId socket) override
119 {
120 startLoop();
121 return mp::MakeStream(*m_loop, socket);
122 }
123 void addCleanup(std::type_index type, void* iface, std::function<void()> cleanup) override
124 {
125 mp::ProxyTypeRegister::types().at(type)(iface).cleanup_fns.emplace_back(std::move(cleanup));
126 }
127 Context& context() override { return m_context; }
128 void startLoop()
129 {
130 if (m_loop) return;
131 std::promise<void> promise;
133 util::ThreadRename("capnp-loop");
134 mp::LogOptions opts = {
135 .log_fn = IpcLogFn,
136 .log_level = GetRequestedIPCLogLevel()
137 };
138 m_loop.emplace(m_exe_name, std::move(opts), &m_context);
139 m_loop_ref.emplace(*m_loop);
140 promise.set_value();
141 m_loop->loop();
142 m_loop.reset();
143 });
144 promise.get_future().wait();
145 }
146 const char* m_exe_name;
147 Context m_context;
149 std::optional<mp::EventLoop> m_loop;
153 std::optional<mp::EventLoopRef> m_loop_ref;
157};
158} // namespace
159
160std::unique_ptr<Protocol> MakeCapnpProtocol(const char* exe_name) { return std::make_unique<CapnpProtocol>(exe_name); }
161} // namespace capnp
162} // namespace ipc
Initial interface created when a process is first started, and used to give and get access to other i...
Definition: init.h:32
Object holding network & rpc state associated with either an incoming server connection,...
Definition: proxy-io.h:436
std::thread m_loop_thread
Definition: protocol.cpp:156
const char * m_exe_name
Definition: protocol.cpp:146
mp::Connection * m_parent_connection
Connection to parent, if this is a child process spawned by a parent process.
Definition: protocol.cpp:155
std::optional< mp::EventLoop > m_loop
EventLoop object which manages I/O events for all connections.
Definition: protocol.cpp:149
std::optional< mp::EventLoopRef > m_loop_ref
Reference to the same EventLoop.
Definition: protocol.cpp:153
Context m_context
Definition: protocol.cpp:147
std::thread thread
Thread variable should be after other struct members so the thread does not start until the other mem...
#define LogWarning(...)
Definition: log.h:126
#define LogInfo(...)
Definition: log.h:125
#define LogError(...)
Definition: log.h:127
#define LogTrace(category,...)
Definition: log.h:144
#define LogDebug(category,...)
Definition: log.h:143
@ IPC
Definition: categories.h:38
Definition: basic.cpp:8
std::unique_ptr< Protocol > MakeCapnpProtocol(const char *exe_name)
Definition: protocol.cpp:160
Definition: ipc.h:13
SocketId Stream
Definition: util.h:30
ThreadContext & CurrentThread()
Definition: util.h:57
std::string ThreadName(const char *exe_name)
Format current thread name as "{exe_name}-{$pid}/{thread_name}-{$tid}".
Definition: util.cpp:64
Stream MakeStream(EventLoop &, SocketId socket)
Definition: util.h:31
int SocketId
Definition: util.h:27
Log
Log flags. Update stringify function if changed!
Definition: proxy-io.h:130
bool ShouldDebugLog(Category category)
Return whether messages with specified category should be debug logged.
Definition: logging.cpp:619
bool ShouldTraceLog(Category category)
Return whether messages with specified category should be trace logged.
Definition: logging.cpp:624
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:147
std::string message
Message to be logged.
Definition: proxy-io.h:144
LogFn log_fn
External logging callback.
Definition: proxy-io.h:155
static Types & types()
Definition: proxy-types.h:854
std::string thread_name
Identifying string for debug.
Definition: proxy-io.h:708
assert(!tx.IsCoinBase())