libe3 0.6.1
C++ library for E3AP RAN vendor integration
Loading...
Searching...
No Matches
zmq_connector.cpp
Go to the documentation of this file.
1/**
2 * @file zmq_connector.cpp
3 * @brief ZeroMQ connector implementation
4 *
5 *
6 * SPDX-FileCopyrightText: Copyright (c) 2026 Northeastern University
7 * SPDX-License-Identifier: Apache-2.0
8 */
9
10#include "zmq_connector.hpp"
11#include "libe3/latrec.h"
12#include "libe3/logger.hpp"
13#include <zmq.h>
14#include <cstdint>
15#include <cstring>
16#include <sys/stat.h>
17#include <unistd.h>
18#include <grp.h>
19#include <cerrno>
20#include <chrono>
21#include <thread>
22
23namespace libe3 {
24
25namespace {
26constexpr const char* LOG_TAG = "ZmqConn";
27constexpr const char* IPC_BASE_DIR = "/tmp/dapps";
28constexpr int RECV_TIMEOUT_MS = 500; // Timeout for graceful shutdown
29constexpr int PUB_CONNECT_SETTLE_MS = 200; // PUB/SUB slow-joiner settle (client outbound)
30constexpr int HEARTBEAT_IVL_MS = 1000; // dApp SUB pings an idle RAN this often
31constexpr int HEARTBEAT_TIMEOUT_MS = 3000; // ... and drops the link after this much silence
32
33// Every socket gets ZMQ_LINGER = 0: the default (-1) makes zmq_ctx_destroy
34// block until all queued messages are flushed, so a RAN with undelivered
35// indications on its PUB socket hangs forever in dispose() and the process
36// ignores SIGTERM (the signal handler runs, but stop() never returns).
37// Dropping unsent messages on teardown is the correct trade for a
38// real-time control-loop transport.
39void set_linger0(void* socket) {
40 int linger = 0;
41 zmq_setsockopt(socket, ZMQ_LINGER, &linger, sizeof(linger));
42}
43}
44
47 const std::string& setup_endpoint,
48 const std::string& inbound_endpoint,
49 const std::string& outbound_endpoint,
50 uint16_t setup_port,
51 uint16_t inbound_port,
52 uint16_t outbound_port,
53 size_t io_threads
54)
55 : transport_layer_(transport_layer)
56 , io_threads_(io_threads)
57 , setup_port_(setup_port)
58 , inbound_port_(inbound_port)
59 , outbound_port_(outbound_port)
60{
61 // For TCP, derive the endpoint strings from the port numbers. The
62 // bind/connect-direction adjustment is handled at the call sites below
63 // (RAN binds tcp://*:N; dApp connects to tcp://127.0.0.1:N). For IPC
64 // both sides use the same ipc:// string.
66 setup_endpoint_ = "tcp://*:" + std::to_string(setup_port);
67 inbound_endpoint_ = "tcp://*:" + std::to_string(inbound_port);
68 outbound_endpoint_ = "tcp://*:" + std::to_string(outbound_port);
69 } else {
73 }
74
75 E3_LOG_INFO(LOG_TAG) << "Creating ZMQ connector";
76 E3_LOG_DEBUG(LOG_TAG) << " Setup endpoint: " << setup_endpoint_;
77 E3_LOG_DEBUG(LOG_TAG) << " Inbound endpoint: " << inbound_endpoint_;
78 E3_LOG_DEBUG(LOG_TAG) << " Outbound endpoint: " << outbound_endpoint_;
79}
80
84
86 // Create ZMQ context
87 context_ = zmq_ctx_new();
88 if (!context_) {
89 E3_LOG_ERROR(LOG_TAG) << "Failed to create ZMQ context";
90 return ErrorCode::CONNECTION_FAILED;
91 }
92
93 // Set I/O threads
94 if (zmq_ctx_set(context_, ZMQ_IO_THREADS, static_cast<int>(io_threads_)) != 0) {
95 E3_LOG_ERROR(LOG_TAG) << "Failed to set ZMQ I/O threads: " << zmq_strerror(errno);
96 zmq_ctx_destroy(context_);
97 context_ = nullptr;
98 return ErrorCode::CONNECTION_FAILED;
99 }
100
101 // Create IPC directory if using IPC transport
102 if (transport_layer_ == E3TransportLayer::IPC) {
103 struct stat st{};
104 if (stat(IPC_BASE_DIR, &st) == -1) {
105 // EEXIST: another agent/test process created it between the stat
106 // and the mkdir (the directory existing is exactly what we want).
107 // The POSIX connector guards the same race the same way.
108 if (mkdir(IPC_BASE_DIR, 0777) == -1 && errno != EEXIST) {
109 E3_LOG_ERROR(LOG_TAG) << "Failed to create IPC directory: " << strerror(errno);
110 return ErrorCode::CONNECTION_FAILED;
111 }
112 E3_LOG_INFO(LOG_TAG) << "Created IPC directory: " << IPC_BASE_DIR;
113 }
114
115 // Set directory permissions
116 if (chmod(IPC_BASE_DIR, 0777) != 0) {
117 E3_LOG_WARN(LOG_TAG) << "Failed to set IPC directory permissions";
118 }
119
120 // Try to change group to "dapp"
121 struct group* grp = getgrnam("dapp");
122 if (grp) {
123 if (chown(IPC_BASE_DIR, static_cast<uid_t>(-1), grp->gr_gid) == -1) {
124 E3_LOG_WARN(LOG_TAG) << "Failed to change IPC directory group";
125 }
126 }
127 }
128
129 // Create REP socket for setup
130 setup_socket_ = zmq_socket(context_, ZMQ_REP);
131 if (!setup_socket_) {
132 E3_LOG_ERROR(LOG_TAG) << "Failed to create setup socket: " << zmq_strerror(errno);
133 return ErrorCode::CONNECTION_FAILED;
134 }
135
136 // Set receive timeout to allow graceful shutdown
137 int recv_timeout = RECV_TIMEOUT_MS;
138 zmq_setsockopt(setup_socket_, ZMQ_RCVTIMEO, &recv_timeout, sizeof(recv_timeout));
139 set_linger0(setup_socket_);
140
141 int ret = zmq_bind(setup_socket_, setup_endpoint_.c_str());
142 if (ret != 0) {
143 E3_LOG_ERROR(LOG_TAG) << "Failed to bind setup socket: " << zmq_strerror(errno);
144 return ErrorCode::CONNECTION_FAILED;
145 }
146
147 // Set IPC permissions if needed
148 if (transport_layer_ == E3TransportLayer::IPC) {
149 setup_ipc_permissions(setup_endpoint_);
150 }
151
152 E3_LOG_INFO(LOG_TAG) << "Setup socket bound to " << setup_endpoint_;
153 connected_ = true;
154
155 return ErrorCode::SUCCESS;
156}
157
158int ZmqE3Connector::recv_setup_request(std::vector<uint8_t>& buffer) {
159 if (!setup_socket_) {
160 return static_cast<int>(ErrorCode::NOT_CONNECTED);
161 }
162
163 buffer.resize(DEFAULT_BUFFER_SIZE);
164 int ret = zmq_recv(setup_socket_, buffer.data(), buffer.size(), 0);
165 if (ret < 0) {
166 if (errno == EAGAIN) {
167 // Timeout - return 0 to indicate no data (allows shutdown check)
168 return 0;
169 }
170 E3_LOG_ERROR(LOG_TAG) << "Failed to receive setup request: " << zmq_strerror(errno);
171 reset_setup_socket();
172 return static_cast<int>(ErrorCode::TRANSPORT_ERROR);
173 }
174
175 buffer.resize(static_cast<size_t>(ret));
176 E3_LOG_DEBUG(LOG_TAG) << "Received setup request: " << ret << " bytes";
177 return ret;
178}
179
180ErrorCode ZmqE3Connector::send_response(const std::vector<uint8_t>& data) {
181 if (!setup_socket_) {
182 return ErrorCode::NOT_CONNECTED;
183 }
184
185 int ret = zmq_send(setup_socket_, data.data(), data.size(), 0);
186 if (ret < 0) {
187 E3_LOG_ERROR(LOG_TAG) << "Failed to send response: " << zmq_strerror(errno);
188 reset_setup_socket();
189 return ErrorCode::TRANSPORT_ERROR;
190 }
191
192 E3_LOG_DEBUG(LOG_TAG) << "Sent response: " << data.size() << " bytes";
193 return ErrorCode::SUCCESS;
194}
195
197 if (!context_) {
198 return ErrorCode::NOT_INITIALIZED;
199 }
200
201 inbound_socket_ = zmq_socket(context_, ZMQ_SUB);
202 if (!inbound_socket_) {
203 E3_LOG_ERROR(LOG_TAG) << "Failed to create inbound socket: " << zmq_strerror(errno);
204 return ErrorCode::CONNECTION_FAILED;
205 }
206
207 // Subscribe to all messages
208 zmq_setsockopt(inbound_socket_, ZMQ_SUBSCRIBE, "", 0);
209
210 // No ZMQ_CONFLATE: multiple dApps multiplex onto this SUB; conflating would
211 // drop all but the newest message and starve all but one dApp (issue #15).
212
213 // Set receive timeout to allow graceful shutdown
214 int recv_timeout = RECV_TIMEOUT_MS;
215 zmq_setsockopt(inbound_socket_, ZMQ_RCVTIMEO, &recv_timeout, sizeof(recv_timeout));
216 set_linger0(inbound_socket_);
217
218 int ret = zmq_bind(inbound_socket_, inbound_endpoint_.c_str());
219 if (ret != 0) {
220 E3_LOG_ERROR(LOG_TAG) << "Failed to bind inbound socket: " << zmq_strerror(errno);
221 return ErrorCode::CONNECTION_FAILED;
222 }
223
224 if (transport_layer_ == E3TransportLayer::IPC) {
225 setup_ipc_permissions(inbound_endpoint_);
226 }
227
228 E3_LOG_INFO(LOG_TAG) << "Inbound socket bound to " << inbound_endpoint_;
229 return ErrorCode::SUCCESS;
230}
231
232int ZmqE3Connector::receive(std::vector<uint8_t>& buffer) {
233 if (!inbound_socket_) {
234 return static_cast<int>(ErrorCode::NOT_CONNECTED);
235 }
236
237 buffer.resize(DEFAULT_BUFFER_SIZE);
238 int ret = zmq_recv(inbound_socket_, buffer.data(), buffer.size(), 0);
239 if (ret < 0) {
240 if (errno == EAGAIN) {
241 // ZMQ reconnects silently, so a RAN that went away is only seen here.
242 if (inbound_peer_disconnected()) {
243 return static_cast<int>(ErrorCode::NOT_CONNECTED);
244 }
245 // Timeout - return 0 to indicate no data (allows shutdown check)
246 return 0;
247 }
248 if (errno == EINTR) {
249 return 0;
250 }
251 E3_LOG_ERROR(LOG_TAG) << "Failed to receive: " << zmq_strerror(errno);
252 return static_cast<int>(ErrorCode::TRANSPORT_ERROR);
253 }
254
255 buffer.resize(static_cast<size_t>(ret));
256 E3_LOG_TRACE(LOG_TAG) << "Received: " << ret << " bytes";
257 return ret;
258}
259
261 if (!context_) {
262 return ErrorCode::NOT_INITIALIZED;
263 }
264
265 outbound_socket_ = zmq_socket(context_, ZMQ_PUB);
266 if (!outbound_socket_) {
267 E3_LOG_ERROR(LOG_TAG) << "Failed to create outbound socket: " << zmq_strerror(errno);
268 return ErrorCode::CONNECTION_FAILED;
269 }
270 set_linger0(outbound_socket_);
271
272 int ret = zmq_bind(outbound_socket_, outbound_endpoint_.c_str());
273 if (ret != 0) {
274 E3_LOG_ERROR(LOG_TAG) << "Failed to bind outbound socket: " << zmq_strerror(errno);
275 return ErrorCode::CONNECTION_FAILED;
276 }
277
278 if (transport_layer_ == E3TransportLayer::IPC) {
279 setup_ipc_permissions(outbound_endpoint_);
280 }
281
282 E3_LOG_INFO(LOG_TAG) << "Outbound socket bound to " << outbound_endpoint_;
283 return ErrorCode::SUCCESS;
284}
285
286ErrorCode ZmqE3Connector::send(const std::vector<uint8_t>& data) {
287 // Checked first, same reasoning as PosixE3Connector::send(): narrows,
288 // but does not eliminate, a send racing a concurrent shutdown().
289 if (shutdown_requested_.load()) {
290 return ErrorCode::CANCELLED;
291 }
292 if (!outbound_socket_) {
293 return ErrorCode::NOT_CONNECTED;
294 }
295
296 int ret = zmq_send(outbound_socket_, data.data(), data.size(), 0);
297 if (ret < 0) {
298 E3_LOG_ERROR(LOG_TAG) << "Failed to send: " << zmq_strerror(errno);
299 return ErrorCode::TRANSPORT_ERROR;
300 }
301
302 E3_LOG_TRACE(LOG_TAG) << "Sent: " << data.size() << " bytes";
303 return ErrorCode::SUCCESS;
304}
305
306namespace {
307// Convert a bind-style endpoint ("tcp://*:9990") to a connect-style one
308// ("tcp://127.0.0.1:9990"). IPC endpoints are returned unchanged.
309std::string to_connect_endpoint(const std::string& bind_ep) {
310 const std::string prefix = "tcp://*:";
311 if (bind_ep.compare(0, prefix.size(), prefix) == 0) {
312 return "tcp://127.0.0.1:" + bind_ep.substr(prefix.size());
313 }
314 return bind_ep;
315}
316} // anonymous namespace
317
318// ===========================================================================
319// Client-side (dApp role) implementations
320//
321// The dApp ROLE inverts the bind/connect direction on all three channels:
322// - setup_endpoint : REQ connect (RAN binds REP)
323// - publisher_endpoint: SUB connect (RAN binds PUB) — this is our INBOUND
324// - subscriber_endpoint: PUB connect (RAN binds SUB) — this is our OUTBOUND
325// Socket TYPES on the inbound/outbound pair are unchanged; only the
326// bind/connect direction flips and the role of the two endpoints swaps.
327// ===========================================================================
328
330 // Create ZMQ context (same as RAN-side init)
331 context_ = zmq_ctx_new();
332 if (!context_) {
333 E3_LOG_ERROR(LOG_TAG) << "Failed to create ZMQ context";
334 return ErrorCode::CONNECTION_FAILED;
335 }
336 if (zmq_ctx_set(context_, ZMQ_IO_THREADS, static_cast<int>(io_threads_)) != 0) {
337 E3_LOG_ERROR(LOG_TAG) << "Failed to set ZMQ I/O threads: " << zmq_strerror(errno);
338 zmq_ctx_destroy(context_);
339 context_ = nullptr;
340 return ErrorCode::CONNECTION_FAILED;
341 }
342
343 // REQ socket — the dApp INITIATES setup
344 ErrorCode rc = open_setup_req_socket();
345 if (rc != ErrorCode::SUCCESS) return rc;
346 connected_ = true;
347 return ErrorCode::SUCCESS;
348}
349
350ErrorCode ZmqE3Connector::open_setup_req_socket() {
351 if (setup_socket_) {
352 zmq_close(setup_socket_);
353 setup_socket_ = nullptr;
354 }
355
356 setup_socket_ = zmq_socket(context_, ZMQ_REQ);
357 if (!setup_socket_) {
358 E3_LOG_ERROR(LOG_TAG) << "Failed to create REQ setup socket: " << zmq_strerror(errno);
359 return ErrorCode::CONNECTION_FAILED;
360 }
361
362 int recv_timeout = RECV_TIMEOUT_MS;
363 zmq_setsockopt(setup_socket_, ZMQ_RCVTIMEO, &recv_timeout, sizeof(recv_timeout));
364 set_linger0(setup_socket_); // Don't block on close if RAN never replied
365
366 const std::string setup_cep = to_connect_endpoint(setup_endpoint_);
367 int ret = zmq_connect(setup_socket_, setup_cep.c_str());
368 if (ret != 0) {
369 E3_LOG_ERROR(LOG_TAG) << "Failed to connect setup socket: " << zmq_strerror(errno);
370 return ErrorCode::CONNECTION_FAILED;
371 }
372 E3_LOG_INFO(LOG_TAG) << "Setup REQ socket connected to " << setup_cep;
373 return ErrorCode::SUCCESS;
374}
375
376ErrorCode ZmqE3Connector::send_setup_request_client(const std::vector<uint8_t>& data) {
377 if (!setup_socket_) return ErrorCode::NOT_CONNECTED;
378 // A REQ socket still awaiting a reply refuses a second send, so every attempt gets a fresh one.
379 ErrorCode rc = open_setup_req_socket();
380 if (rc != ErrorCode::SUCCESS) return rc;
381 int ret = zmq_send(setup_socket_, data.data(), data.size(), 0);
382 if (ret < 0) {
383 E3_LOG_ERROR(LOG_TAG) << "Failed to send setup request: " << zmq_strerror(errno);
384 return ErrorCode::TRANSPORT_ERROR;
385 }
386 E3_LOG_DEBUG(LOG_TAG) << "Sent SetupRequest: " << data.size() << " bytes";
387 return ErrorCode::SUCCESS;
388}
389
390int ZmqE3Connector::recv_setup_response_client(std::vector<uint8_t>& buffer) {
391 if (!setup_socket_) return static_cast<int>(ErrorCode::NOT_CONNECTED);
392 buffer.resize(DEFAULT_BUFFER_SIZE);
393 int ret = zmq_recv(setup_socket_, buffer.data(), buffer.size(), 0);
394 if (ret < 0) {
395 if (errno == EAGAIN) return 0;
396 E3_LOG_ERROR(LOG_TAG) << "Failed to receive setup response: " << zmq_strerror(errno);
397 return static_cast<int>(ErrorCode::TRANSPORT_ERROR);
398 }
399 buffer.resize(static_cast<size_t>(ret));
400 E3_LOG_DEBUG(LOG_TAG) << "Received SetupResponse: " << ret << " bytes";
401 return ret;
402}
403
404void ZmqE3Connector::open_inbound_monitor() {
405 const std::string ep = "inproc://libe3-monitor-" +
406 std::to_string(reinterpret_cast<uintptr_t>(this));
407 if (zmq_socket_monitor(inbound_socket_, ep.c_str(), ZMQ_EVENT_DISCONNECTED) != 0) {
408 E3_LOG_WARN(LOG_TAG) << "No disconnect monitor: " << zmq_strerror(errno);
409 return;
410 }
411 monitor_socket_ = zmq_socket(context_, ZMQ_PAIR);
412 if (monitor_socket_) set_linger0(monitor_socket_);
413 if (monitor_socket_ && zmq_connect(monitor_socket_, ep.c_str()) != 0) {
414 zmq_close(monitor_socket_);
415 monitor_socket_ = nullptr;
416 }
417}
418
419bool ZmqE3Connector::inbound_peer_disconnected() {
420 if (!monitor_socket_) return false;
421 bool disconnected = false;
422 // Each event is two frames: a packed uint16 event id + uint32 value, then the address.
423 for (;;) {
424 uint8_t frame[16];
425 int n = zmq_recv(monitor_socket_, frame, sizeof(frame), ZMQ_DONTWAIT);
426 if (n < 0) break;
427 uint16_t event = 0;
428 if (n >= static_cast<int>(sizeof(event))) std::memcpy(&event, frame, sizeof(event));
429 int more = 0;
430 size_t more_len = sizeof(more);
431 zmq_getsockopt(monitor_socket_, ZMQ_RCVMORE, &more, &more_len);
432 while (more) {
433 uint8_t addr[256];
434 zmq_recv(monitor_socket_, addr, sizeof(addr), 0);
435 zmq_getsockopt(monitor_socket_, ZMQ_RCVMORE, &more, &more_len);
436 }
437 if (event == ZMQ_EVENT_DISCONNECTED) disconnected = true;
438 }
439 if (disconnected) {
440 E3_LOG_WARN(LOG_TAG) << "Inbound SUB lost its peer";
441 }
442 return disconnected;
443}
444
446 if (!context_) return ErrorCode::NOT_INITIALIZED;
447
448 // dApp INBOUND = RAN's publisher_endpoint (where RAN PUB-binds)
449 inbound_socket_ = zmq_socket(context_, ZMQ_SUB);
450 if (!inbound_socket_) {
451 E3_LOG_ERROR(LOG_TAG) << "Failed to create inbound SUB socket: " << zmq_strerror(errno);
452 return ErrorCode::CONNECTION_FAILED;
453 }
454 zmq_setsockopt(inbound_socket_, ZMQ_SUBSCRIBE, "", 0);
455 // No ZMQ_CONFLATE: the RAN broadcasts per-dApp indications over one PUB and
456 // each dApp filters its own; conflating would starve all but one (issue #15).
457 int recv_timeout = RECV_TIMEOUT_MS;
458 zmq_setsockopt(inbound_socket_, ZMQ_RCVTIMEO, &recv_timeout, sizeof(recv_timeout));
459 set_linger0(inbound_socket_);
460#ifdef ZMQ_HEARTBEAT_IVL
461 // A RAN that dies without closing the connection still drops the link.
462 int hb_ivl = HEARTBEAT_IVL_MS;
463 int hb_timeout = HEARTBEAT_TIMEOUT_MS;
464 zmq_setsockopt(inbound_socket_, ZMQ_HEARTBEAT_IVL, &hb_ivl, sizeof(hb_ivl));
465 zmq_setsockopt(inbound_socket_, ZMQ_HEARTBEAT_TIMEOUT, &hb_timeout, sizeof(hb_timeout));
466#endif
467 open_inbound_monitor();
468
469 const std::string inbound_cep = to_connect_endpoint(outbound_endpoint_);
470 int ret = zmq_connect(inbound_socket_, inbound_cep.c_str());
471 if (ret != 0) {
472 E3_LOG_ERROR(LOG_TAG) << "Failed to connect inbound SUB to "
473 << inbound_cep << ": " << zmq_strerror(errno);
474 return ErrorCode::CONNECTION_FAILED;
475 }
476 E3_LOG_INFO(LOG_TAG) << "Inbound SUB socket connected to " << inbound_cep;
477 return ErrorCode::SUCCESS;
478}
479
481 if (!context_) return ErrorCode::NOT_INITIALIZED;
482
483 // dApp OUTBOUND = RAN's subscriber_endpoint (where RAN SUB-binds)
484 outbound_socket_ = zmq_socket(context_, ZMQ_PUB);
485 if (!outbound_socket_) {
486 E3_LOG_ERROR(LOG_TAG) << "Failed to create outbound PUB socket: " << zmq_strerror(errno);
487 return ErrorCode::CONNECTION_FAILED;
488 }
489 set_linger0(outbound_socket_);
490
491 const std::string outbound_cep = to_connect_endpoint(inbound_endpoint_);
492 int ret = zmq_connect(outbound_socket_, outbound_cep.c_str());
493 if (ret != 0) {
494 E3_LOG_ERROR(LOG_TAG) << "Failed to connect outbound PUB to "
495 << outbound_cep << ": " << zmq_strerror(errno);
496 return ErrorCode::CONNECTION_FAILED;
497 }
498 E3_LOG_INFO(LOG_TAG) << "Outbound PUB socket connected to " << outbound_cep;
499
500 // ZMQ PUB/SUB slow-joiner: a freshly connected PUB silently drops outgoing
501 // messages until the peer SUB's subscription has propagated to it. The
502 // dApp's first outbound message is the subscription request; without a
503 // brief settle it can be lost — reliably so for a second peer over TCP,
504 // where connection establishment is slower. Wait for the link to settle.
505 std::this_thread::sleep_for(std::chrono::milliseconds(PUB_CONNECT_SETTLE_MS));
506 return ErrorCode::SUCCESS;
507}
508
510 E3_LOG_DEBUG(LOG_TAG) << "Disposing ZMQ connector";
511
512 if (setup_socket_) {
513 zmq_close(setup_socket_);
514 setup_socket_ = nullptr;
515 }
516
517 if (monitor_socket_) {
518 zmq_close(monitor_socket_);
519 monitor_socket_ = nullptr;
520 }
521
522 if (inbound_socket_) {
523 zmq_close(inbound_socket_);
524 inbound_socket_ = nullptr;
525 }
526
527 if (outbound_socket_) {
528 zmq_close(outbound_socket_);
529 outbound_socket_ = nullptr;
530 }
531
532 if (context_) {
533 zmq_ctx_destroy(context_);
534 context_ = nullptr;
535 }
536
537 // Clean up IPC files if using IPC transport AND we own them (RAN side
538 // binds, which creates the socket files; dApp side connects, so it has
539 // nothing to unlink).
540 if (transport_layer_ == E3TransportLayer::IPC && role_ == E3Role::RAN) {
541 // Extract file paths from IPC endpoints (ipc:///path)
542 auto extract_path = [](const std::string& endpoint) -> std::string {
543 const std::string prefix = "ipc://";
544 if (endpoint.compare(0, prefix.length(), prefix) == 0) {
545 return endpoint.substr(prefix.length());
546 }
547 return "";
548 };
549
550 std::string path;
551 path = extract_path(setup_endpoint_);
552 if (!path.empty()) unlink(path.c_str());
553
554 path = extract_path(inbound_endpoint_);
555 if (!path.empty()) unlink(path.c_str());
556
557 path = extract_path(outbound_endpoint_);
558 if (!path.empty()) unlink(path.c_str());
559
560 // Deliberately do NOT rmdir(IPC_BASE_DIR): it is a shared directory
561 // (multiple agents/tests use it concurrently). Removing it here races
562 // with another agent that has already stat()'d it and is about to
563 // bind a socket inside it, making that bind fail with ENOENT. Leaving
564 // the empty directory behind is harmless.
565 }
566
567 connected_ = false;
568 E3_LOG_INFO(LOG_TAG) << "ZMQ connector disposed";
569}
570
572 // ZMQ uses ZMQ_RCVTIMEO for timeout-based shutdown.
573 // The receive loops will wake up periodically and check should_stop_.
574 shutdown_requested_.store(true);
575 E3_LOG_DEBUG(LOG_TAG) << "ZMQ connector shutdown requested";
576}
577
578void ZmqE3Connector::setup_ipc_permissions(const std::string& endpoint) {
579 // Extract file path from IPC endpoint (ipc:///path)
580 const std::string prefix = "ipc://";
581 if (endpoint.compare(0, prefix.length(), prefix) != 0) {
582 return;
583 }
584
585 std::string path = endpoint.substr(prefix.length());
586
587 if (chmod(path.c_str(), 0666) == -1) {
588 E3_LOG_WARN(LOG_TAG) << "Failed to set permissions on " << path << ": " << strerror(errno);
589 } else {
590 E3_LOG_DEBUG(LOG_TAG) << "Set permissions on " << path;
591 }
592}
593
594bool ZmqE3Connector::reset_setup_socket() {
595 E3_LOG_WARN(LOG_TAG) << "Resetting setup socket after error";
596
597 if (setup_socket_) {
598 zmq_close(setup_socket_);
599 setup_socket_ = nullptr;
600 }
601
602 if (!context_) {
603 E3_LOG_ERROR(LOG_TAG) << "Cannot reset setup socket without context";
604 return false;
605 }
606
607 setup_socket_ = zmq_socket(context_, ZMQ_REP);
608 if (!setup_socket_) {
609 E3_LOG_ERROR(LOG_TAG) << "Failed to recreate setup socket: " << zmq_strerror(errno);
610 return false;
611 }
612
613 int recv_timeout = RECV_TIMEOUT_MS;
614 zmq_setsockopt(setup_socket_, ZMQ_RCVTIMEO, &recv_timeout, sizeof(recv_timeout));
615 set_linger0(setup_socket_);
616
617 int ret = zmq_bind(setup_socket_, setup_endpoint_.c_str());
618 if (ret != 0) {
619 E3_LOG_ERROR(LOG_TAG) << "Failed to rebind setup socket: " << zmq_strerror(errno);
620 zmq_close(setup_socket_);
621 setup_socket_ = nullptr;
622 return false;
623 }
624
625 if (transport_layer_ == E3TransportLayer::IPC) {
626 setup_ipc_permissions(setup_endpoint_);
627 }
628
629 E3_LOG_INFO(LOG_TAG) << "Setup socket reset and bound to " << setup_endpoint_;
630 return true;
631}
632
633} // namespace libe3
E3Role role_
Role of this peer.
std::string inbound_endpoint_
Endpoint of the inbound channel.
std::string outbound_endpoint_
Endpoint of the outbound channel.
std::string setup_endpoint_
Endpoint of the setup channel.
const std::string & inbound_endpoint() const noexcept
Get inbound endpoint.
const std::string & setup_endpoint() const noexcept
Get setup endpoint.
const std::string & outbound_endpoint() const noexcept
Get outbound endpoint.
ErrorCode setup_outbound_connection_client() override
Connect the outbound channel (dApp role: PUB connect to the RAN's subscriber endpoint).
ErrorCode send_setup_request_client(const std::vector< uint8_t > &data) override
Send a SetupRequest on the setup channel (dApp role).
E3TransportLayer transport_layer() const noexcept override
Get the transport layer type.
ErrorCode setup_initial_connection() override
Set up the initial connection (setup channel).
ErrorCode setup_initial_connection_client() override
Connect the setup channel (dApp role: REQ connect).
void dispose() override
Clean up and release all resources.
int recv_setup_request(std::vector< uint8_t > &buffer) override
Receive a setup request.
ZmqE3Connector(E3TransportLayer transport_layer, const std::string &setup_endpoint, const std::string &inbound_endpoint, const std::string &outbound_endpoint, uint16_t setup_port, uint16_t inbound_port, uint16_t outbound_port, size_t io_threads)
int receive(std::vector< uint8_t > &buffer) override
Receive data from the inbound channel.
ErrorCode setup_inbound_connection_client() override
Connect the inbound channel (dApp role: SUB connect to the RAN's publisher endpoint).
ErrorCode setup_inbound_connection() override
Set up the inbound connection (SUB channel).
ErrorCode send_response(const std::vector< uint8_t > &data) override
Send a setup response.
ErrorCode send(const std::vector< uint8_t > &data) override
Send data on the outbound channel.
ErrorCode setup_outbound_connection() override
Set up the outbound connection (PUB channel).
int recv_setup_response_client(std::vector< uint8_t > &buffer) override
Receive a SetupResponse on the setup channel (dApp role).
void shutdown() override
Interrupt blocking operations for shutdown.
Lock-free per-thread latency stamp recorder (header-only, C99).
Logging facility for libe3.
#define E3_LOG_TRACE(component)
Definition logger.hpp:229
#define E3_LOG_WARN(component)
Definition logger.hpp:226
#define E3_LOG_DEBUG(component)
Definition logger.hpp:228
#define E3_LOG_INFO(component)
Definition logger.hpp:227
#define E3_LOG_ERROR(component)
Definition logger.hpp:225
ErrorCode
Error codes returned by libe3 operations Use shared error-code list (see libe3/error_codes....
Definition types.hpp:177
E3TransportLayer
Transport layer types (matches Python E3TransportLayer).
Definition types.hpp:85
@ IPC
Unix Domain Sockets / IPC.
Definition types.hpp:88
@ RAN
RAN function (binds sockets; today's only behaviour).
Definition types.hpp:78
constexpr size_t DEFAULT_BUFFER_SIZE
Default encode and receive buffer size, in bytes.
Definition types.hpp:208
ZeroMQ-based E3 Connector.