libe3 0.6.1
C++ library for E3AP RAN vendor integration
Loading...
Searching...
No Matches
e3_interface.cpp
Go to the documentation of this file.
1/**
2 * @file e3_interface.cpp
3 * @brief E3Interface implementation
4 *
5 * Ported from the original C implementation's e3_agent.c
6 *
7 * SPDX-FileCopyrightText: Copyright (c) 2026 Northeastern University
8 * SPDX-License-Identifier: Apache-2.0
9 */
10
12#include "libe3/logger.hpp"
13#include "libe3/latrec.h"
14#include <algorithm>
15#include <cctype>
16#include <cerrno>
17#include <chrono>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <signal.h>
22#include <string>
23
24#ifdef __linux__
25#include <pthread.h>
26#include <sched.h>
27#include <sys/resource.h>
28#include <sys/syscall.h>
29#include <unistd.h>
30#endif
31
32namespace libe3 {
33
34namespace {
35constexpr const char* LOG_TAG = "E3Iface";
36
37// How often subscriptions whose time has run out are looked for. On the RAN,
38// dispatch already skips an expired subscription, so this only bounds how late
39// its SM is stopped and the status handler told.
40constexpr auto EXPIRY_SWEEP_INTERVAL = std::chrono::milliseconds(250);
41
42/// The dApp that sent @p pdu, or 0 for a PDU that names none (a setup request,
43/// or a type a dApp does not send).
44uint32_t dapp_id_of(const Pdu& pdu) {
45 if (const auto* m = std::get_if<SubscriptionRequest>(&pdu.choice)) return m->dapp_identifier;
46 if (const auto* m = std::get_if<SubscriptionDelete>(&pdu.choice)) return m->dapp_identifier;
47 if (const auto* m = std::get_if<DAppControlAction>(&pdu.choice)) return m->dapp_identifier;
48 if (const auto* m = std::get_if<DAppReport>(&pdu.choice)) return m->dapp_identifier;
49 if (const auto* m = std::get_if<ReleaseMessage>(&pdu.choice)) return m->dapp_identifier;
50 if (const auto* m = std::get_if<ControlResponse>(&pdu.choice)) return m->dapp_identifier;
51 return 0;
52}
53
54/// The dApp that an outbound @p pdu is for, or 0 for a PDU that names none.
55uint32_t target_dapp_of(const Pdu& pdu) {
56 if (const auto* m = std::get_if<SubscriptionResponse>(&pdu.choice)) return m->dapp_identifier;
57 if (const auto* m = std::get_if<IndicationMessage>(&pdu.choice)) return m->dapp_identifier;
58 if (const auto* m = std::get_if<XAppControlAction>(&pdu.choice)) return m->dapp_identifier;
59 if (const auto* m = std::get_if<ReleaseMessage>(&pdu.choice)) return m->dapp_identifier;
60 if (const auto* m = std::get_if<ControlResponse>(&pdu.choice)) return m->dapp_identifier;
61 return 0;
62}
63
64/**
65 * @brief Build the default log-file path for a given role/identifier.
66 *
67 * Produces `/tmp/e3_<role>[_<sanitized-id>]_<euid>.log`. The id is sanitized
68 * to `[A-Za-z0-9._-]` (other bytes become '_') and omitted when empty. The
69 * effective uid is appended so the file is always owned by the opener,
70 * sidestepping `fs.protected_regular` denials in sticky /tmp.
71 */
72std::string default_log_path(E3Role role, const std::string& id) {
73 std::string san;
74 san.reserve(id.size());
75 for (char c : id) {
76 san.push_back((std::isalnum(static_cast<unsigned char>(c)) ||
77 c == '.' || c == '_' || c == '-')
78 ? c
79 : '_');
80 }
81 std::string path = "/tmp/e3_";
82 path += (role == E3Role::DAPP) ? "dapp" : "agent";
83 if (!san.empty()) {
84 path += '_';
85 path += san;
86 }
87#ifdef __linux__
88 path += '_';
89 path += std::to_string(static_cast<unsigned long>(geteuid()));
90#endif
91 path += ".log";
92 return path;
93}
94
95/**
96 * @brief Apply CPU-affinity and niceness to the calling thread, then open its
97 * latrec ring.
98 *
99 * Invoked at the very start of each I/O thread so that the settings take
100 * effect before any real work begins.
101 *
102 * @param affinity Logical CPU core to pin to, or -1 to skip pinning.
103 * @param niceness Nice value in [-20, 19], or 0 to skip.
104 * @param role latrec ring name for this thread (see LATREC_ROLE_* below).
105 */
106void apply_thread_config(int affinity, int niceness, const char* role) noexcept {
107#ifdef __linux__
108 if (affinity >= 0) {
109 cpu_set_t cpuset;
110 CPU_ZERO(&cpuset);
111 CPU_SET(static_cast<size_t>(affinity), &cpuset);
112 // Non-fatal, but say so: a silent miss looks identical to a working pin.
113 int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
114 if (rc != 0) {
115 E3_LOG_WARN(LOG_TAG) << "Failed to pin " << role << " thread to core "
116 << affinity << ": " << std::strerror(rc)
117 << " (thread left unpinned)";
118 } else {
119 E3_LOG_INFO(LOG_TAG) << "Pinned " << role << " thread to core " << affinity;
120 }
121 }
122 if (niceness != 0) {
123 // Use the kernel TID so only this thread's scheduling priority changes.
124 // syscall(SYS_gettid) returns the kernel thread ID as a long; cast it
125 // to pid_t first, then to the id_t expected by setpriority(PRIO_PROCESS).
126 auto tid = static_cast<id_t>(static_cast<pid_t>(syscall(SYS_gettid)));
127 // Non-fatal: negative values require CAP_SYS_NICE.
128 if (setpriority(PRIO_PROCESS, tid, niceness) == -1) {
129 E3_LOG_WARN(LOG_TAG) << "Failed to set niceness " << niceness << " on "
130 << role << " thread: " << std::strerror(errno);
131 }
132 }
133#else
134 (void)affinity;
135 (void)niceness;
136#endif
137 // Open this thread's latrec ring up front: the stamp path never opens one,
138 // and doing it after pinning faults the mapping on the local NUMA node.
139 latrec_tls_open_as(role);
140}
141
142/* latrec ring names for the threads libe3 starts; an unnamed ring falls back to
143 * the program name, which is the same for all of them. They also select the
144 * per-role LATREC_ENTRIES_LOG2_<ROLE> sizing override. The RAN and dApp roles
145 * run in separate processes, so the two sides reuse one name per function. */
146constexpr const char* LATREC_ROLE_OUTBOUND = "libe3.outbound";
147constexpr const char* LATREC_ROLE_INBOUND = "libe3.inbound";
148constexpr const char* LATREC_ROLE_REPORT = "libe3.report";
149constexpr const char* LATREC_ROLE_SETUP = "libe3.setup";
150#ifdef LIBE3_ENABLE_LATREC
151constexpr const char* LATREC_ROLE_CONTEXT = "libe3.context";
152#endif
153
154// Byte limits of E3-Name and E3-Version in e3ap-1.0.0.asn1.
155constexpr size_t MAX_NAME_BYTES = 64;
156constexpr size_t MAX_VERSION_BYTES = 32;
157
158// Largest periodicity e3ap-1.0.0.asn1 carries, in microseconds.
159constexpr uint32_t MAX_PERIODICITY_US = 60000000;
160
161// OCTET STRING (SIZE (1..n)) refuses an empty string, so a name the config
162// left unset goes out as a placeholder on every encoding.
163std::string name_or_unknown(const std::string& name) {
164 return name.empty() ? "unknown" : name;
165}
166
167// Over ASN.1 an out-of-range string fails the setup encode, which aborts a RAN
168// answering its first dApp. Refuse the config up front instead.
169bool wire_text_fits(const char* field, const std::string& value, size_t max_bytes,
170 bool may_be_empty) {
171 if (value.size() > max_bytes || (value.empty() && !may_be_empty)) {
172 E3_LOG_ERROR(LOG_TAG) << "Config " << field << " is " << value.size()
173 << " bytes; ASN.1 allows "
174 << (may_be_empty ? 0 : 1) << ".." << max_bytes;
175 return false;
176 }
177 return true;
178}
179} // anonymous namespace
180
182 // Monotonic over the ASN.1 E3-MessageID (1..4294967295) range, skipping 0
183 // (the grammar's lower bound is 1). A 32-bit counter does not wrap within
184 // any realistic run, so an id identifies a request uniquely rather than
185 // only across the in-flight window.
186 const uint64_t n = next_message_id_.fetch_add(1, std::memory_order_relaxed);
187 return static_cast<uint32_t>(n % 0xFFFFFFFFull) + 1;
188}
189
190void E3Interface::remember_subscription_op(
191 uint32_t request_id, uint32_t ran_function_id, bool is_delete,
192 std::optional<uint32_t> subscription_time_s) {
193 std::lock_guard<std::mutex> lk(pending_subscriptions_mutex_);
194 pending_subscriptions_[request_id] =
195 PendingSubscriptionOp{ran_function_id, is_delete, subscription_time_s};
196}
197
198void E3Interface::forget_subscription_op(uint32_t request_id) {
199 std::lock_guard<std::mutex> lk(pending_subscriptions_mutex_);
200 pending_subscriptions_.erase(request_id);
201}
202
203uint32_t E3Interface::sanitize_request_message_id(uint32_t request_id) {
204 // E3-MessageID is 1..4294967295: every non-zero id can be echoed, a peer
205 // that counts across message types (Aerial) passes 1000 within seconds.
206 if (request_id != 0) {
207 return request_id;
208 }
209 return generate_message_id();
210}
211
213 : config_(config)
214{
215 // Suppress shared log-file writes when logging is disabled. This lets
216 // multiple E3Interface instances (e.g. a RAN-role and a dApp-role one in
217 // the same process — integration tests, the latency benchmark, or
218 // production multi-peer dApps) coexist without racing on the same file.
219 if (config.log_level > 0) {
220 std::string log_path = config.log_path;
221 if (log_path.empty()) {
222 const std::string& id = (config.role == E3Role::DAPP)
223 ? config.dapp_name
224 : config.ran_identifier;
225 log_path = default_log_path(config.role, id);
226 }
227 Logger::instance().set_log_file(log_path);
228 }
229 Logger::instance().set_level(config.log_level);
230 E3_LOG_INFO(LOG_TAG) << "E3Interface created (role=" << role_to_string(config.role) << ")";
231}
232
234 stop();
235 E3_LOG_INFO(LOG_TAG) << "E3Interface destroyed";
236}
237
239 if (state_.load() != AgentState::UNINITIALIZED) {
240 E3_LOG_WARN(LOG_TAG) << "Interface already initialized";
241 return ErrorCode::ALREADY_INITIALIZED;
242 }
243
244 E3_LOG_INFO(LOG_TAG) << "Initializing E3Interface";
245
246 // Create encoder
247 encoder_ = create_encoder(config_.encoding);
248 if (!encoder_) {
249 E3_LOG_ERROR(LOG_TAG) << "Failed to create encoder";
250 return ErrorCode::INTERNAL_ERROR;
251 }
252
253 if (config_.encoding == EncodingFormat::ASN1) {
254 const bool fits =
255 wire_text_fits("e3ap_version", config_.e3ap_version, MAX_VERSION_BYTES, false) &&
256 (config_.role == E3Role::RAN
257 ? wire_text_fits("ran_identifier", config_.ran_identifier, MAX_NAME_BYTES, true)
258 : wire_text_fits("dapp_name", config_.dapp_name, MAX_NAME_BYTES, false) &&
259 wire_text_fits("dapp_version", config_.dapp_version, MAX_VERSION_BYTES, false) &&
260 wire_text_fits("vendor", config_.vendor, MAX_NAME_BYTES, true));
261 if (!fits) {
262 return ErrorCode::INVALID_PARAM;
263 }
264 }
265
266 // Allocate role-specific state. Exactly one is non-null.
267 if (config_.role == E3Role::RAN) {
268 subscription_manager_ = std::make_unique<SubscriptionManager>();
269 subscription_manager_->set_sm_lifecycle_callback(
270 [this](uint32_t ran_function_id, bool should_start) {
271 on_sm_lifecycle_change(ran_function_id, should_start);
272 }
273 );
274 } else {
275 dapp_state_ = std::make_unique<DAppSubscriptionState>();
276 }
277
278 // Create response queue
279 response_queue_ = std::make_unique<LockFreeQueue<Pdu>>();
280
281 // Create dApp-report queue (RAN side drains it via the report worker)
282 report_queue_ = std::make_unique<LockFreeQueue<DAppReport>>(1024);
283
284 ErrorCode conn_rc = create_connector_from_config();
285 if (conn_rc != ErrorCode::SUCCESS) {
286 return conn_rc;
287 }
288
289 state_.store(AgentState::INITIALIZED);
290 E3_LOG_INFO(LOG_TAG) << "E3Interface initialized successfully";
291
292 return ErrorCode::SUCCESS;
293}
294
295ErrorCode E3Interface::create_connector_from_config() {
296 connector_ = create_connector(
297 config_.link_layer,
298 config_.transport_layer,
299 config_.setup_endpoint,
300 config_.subscriber_endpoint,
301 config_.publisher_endpoint,
302 config_.setup_port,
303 config_.subscriber_port,
304 config_.publisher_port,
305 config_.io_threads,
306 config_.role,
307 PosixOptions{config_.socket_buffer_bytes, config_.sctp_delayed_sack,
308 config_.allowed_peers, config_.maximum_associations}
309 );
310
311 if (!connector_) {
312 E3_LOG_ERROR(LOG_TAG) << "Failed to create connector";
313 return ErrorCode::INTERNAL_ERROR;
314 }
315 return ErrorCode::SUCCESS;
316}
317
319 std::lock_guard<std::mutex> lifecycle(lifecycle_mu_);
320 {
321 std::lock_guard<std::mutex> lk(reconnect_mu_);
322 user_stopped_ = false;
323 reconnect_pending_ = false;
324 }
325 const ErrorCode rc = start_locked();
326 if (rc == ErrorCode::SUCCESS && config_.role == E3Role::DAPP &&
327 config_.reconnect_interval_ms > 0 && !reconnect_thread_) {
328 reconnect_thread_ = std::make_unique<std::thread>(&E3Interface::reconnect_loop, this);
329 }
330 return rc;
331}
332
333ErrorCode E3Interface::start_locked() {
335 if (!state_.compare_exchange_strong(expected, AgentState::CONNECTING)) {
336 E3_LOG_ERROR(LOG_TAG) << "Cannot start from state: "
337 << agent_state_to_string(expected);
338 return ErrorCode::STATE_ERROR;
339 }
340
341 E3_LOG_INFO(LOG_TAG) << "Starting E3Interface (role=" << role_to_string(config_.role) << ")";
342 should_stop_.store(false);
343
344 // A restart after stop(): the connector was disposed and its shutdown flag
345 // is set, and stop() shut the queues down.
346 if (started_before_) {
347 ErrorCode conn_rc = create_connector_from_config();
348 if (conn_rc != ErrorCode::SUCCESS) {
349 state_.store(AgentState::ERROR);
350 return conn_rc;
351 }
352 response_queue_->rearm();
353 report_queue_->rearm();
354 }
355 started_before_ = true;
356 if (dapp_state_) {
357 dapp_state_->clear_session();
358 std::lock_guard<std::mutex> lk(pending_subscriptions_mutex_);
359 pending_subscriptions_.clear();
360 }
361 ran_gone_.store(false);
362 release_sent_.store(false);
363 {
364 std::lock_guard<std::mutex> lk(setup_complete_mu_);
365 setup_complete_ = false;
366 setup_succeeded_ = false;
367 }
368
369 // Set up the setup channel. RAN binds; dApp connects.
370 ErrorCode conn_result = (config_.role == E3Role::RAN)
371 ? connector_->setup_initial_connection()
372 : connector_->setup_initial_connection_client();
373 if (conn_result != ErrorCode::SUCCESS) {
374 E3_LOG_ERROR(LOG_TAG) << "Failed to setup initial connection: "
375 << error_code_to_string(conn_result);
376 state_.store(AgentState::ERROR);
377 return conn_result;
378 }
379
380 state_.store(AgentState::CONNECTED);
381
382 // Start threads. RAN runs setup+inbound+outbound plus a report worker; dApp
383 // runs setup+inbound+outbound (dApps host no SMs and receive no reports).
384 if (config_.role == E3Role::RAN) {
385 setup_thread_ = std::make_unique<std::thread>(&E3Interface::setup_loop_ran, this);
386 inbound_thread_ = std::make_unique<std::thread>(&E3Interface::inbound_loop_ran, this);
387 outbound_thread_ = std::make_unique<std::thread>(&E3Interface::outbound_loop_ran, this);
388 // RAN receives dApp reports; drain them off the inbound thread.
389 report_worker_thread_ = std::make_unique<std::thread>(&E3Interface::report_worker_loop, this);
390 } else {
391 setup_thread_ = std::make_unique<std::thread>(&E3Interface::setup_loop_dapp, this);
392 inbound_thread_ = std::make_unique<std::thread>(&E3Interface::inbound_loop_dapp, this);
393 outbound_thread_ = std::make_unique<std::thread>(&E3Interface::outbound_loop_dapp, this);
394 }
395 expiry_thread_ = std::make_unique<std::thread>(&E3Interface::subscription_expiry_loop, this);
396
397#ifdef LIBE3_ENABLE_LATREC
398 context_thread_ = std::make_unique<std::thread>(&E3Interface::context_monitor_loop, this);
399#endif
400
401 state_.store(AgentState::RUNNING);
402 E3_LOG_INFO(LOG_TAG) << "E3Interface started successfully";
403
404 return ErrorCode::SUCCESS;
405}
406
408 // The reconnect thread goes first. It takes the lifecycle lock to restart, so
409 // it is joined before this takes the lock, and it does not restart once
410 // user_stopped_ is set.
411 {
412 std::lock_guard<std::mutex> lk(reconnect_mu_);
413 user_stopped_ = true;
414 }
415 reconnect_cv_.notify_all();
416 if (reconnect_thread_ && reconnect_thread_->joinable()) {
417 reconnect_thread_->join();
418 }
419 reconnect_thread_.reset();
420
421 std::lock_guard<std::mutex> lifecycle(lifecycle_mu_);
422 stop_locked();
423}
424
425void E3Interface::stop_locked() {
426 if (state_.load() == AgentState::UNINITIALIZED ||
427 state_.load() == AgentState::STOPPING) {
428 return;
429 }
430
431 E3_LOG_INFO(LOG_TAG) << "Stopping E3Interface";
432 state_.store(AgentState::STOPPING);
433 should_stop_.store(true);
434
435 // Wake up response queue
436 if (response_queue_) {
437 response_queue_->shutdown();
438 }
439
440 // Wake up the report queue so the report worker's blocking pop returns.
441 if (report_queue_) {
442 report_queue_->shutdown();
443 }
444
445 {
446 std::lock_guard<std::mutex> lk(expiry_mu_);
447 expiry_cv_.notify_all();
448 }
449
450 // Interrupt blocking socket operations
451 if (connector_) {
452 connector_->shutdown();
453 }
454
455 // Join threads
456 if (setup_thread_ && setup_thread_->joinable()) {
457 setup_thread_->join();
458 }
459 if (inbound_thread_ && inbound_thread_->joinable()) {
460 inbound_thread_->join();
461 }
462 if (outbound_thread_ && outbound_thread_->joinable()) {
463 outbound_thread_->join();
464 }
465 if (report_worker_thread_ && report_worker_thread_->joinable()) {
466 report_worker_thread_->join();
467 }
468 if (expiry_thread_ && expiry_thread_->joinable()) {
469 expiry_thread_->join();
470 }
471#ifdef LIBE3_ENABLE_LATREC
472 if (context_thread_ && context_thread_->joinable()) {
473 context_thread_->join();
474 }
475#endif
476
477 // Wake up anyone blocked in wait_for_setup so they don't hang.
478 {
479 std::lock_guard<std::mutex> lk(setup_complete_mu_);
480 setup_complete_ = true;
481 }
482 setup_complete_cv_.notify_all();
483
484 // Clean up SM registry — only the RAN role owns SMs. Doing this
485 // unconditionally would wipe a sibling RAN-role E3Interface's registered
486 // SMs in a two-roles-in-one-process scenario (integration tests, the
487 // latency benchmark, multi-peer dApps colocated with a RAN). The dApp
488 // role never registers an SM, so there's nothing to clear.
489 if (config_.role == E3Role::RAN) {
490 SmRegistry::instance().clear();
491 }
492
493 // Dispose connector
494 if (connector_) {
495 connector_->dispose();
496 }
497
498 state_.store(AgentState::INITIALIZED);
499 E3_LOG_INFO(LOG_TAG) << "E3Interface stopped";
500}
501
503 if (!response_queue_) {
504 return ErrorCode::NOT_INITIALIZED;
505 }
506 // Per-thread ring: open the producer thread's outbound ring so the L0 stamp
507 // below is recorded (idempotent; no-op with tracing off).
508 latrec_tls_open_as(LATREC_ROLE_OUTBOUND);
509 // enqueue_seq identifies this PDU across the latrec stage records. An emit
510 // path that already stamped LATREC_EMIT_ENTER allocated it there, so
511 // that record and these share one key; everything else allocates here.
512 if (pdu.enqueue_seq == 0)
514 const uint64_t seq = pdu.enqueue_seq;
515 latrec_tstamp(seq, LATREC_ENQUEUE, 0, static_cast<uint64_t>(pdu.type));
516 const ErrorCode rc = response_queue_->push(std::move(pdu));
517 if (rc != ErrorCode::SUCCESS) {
518 // NOT_INITIALIZED means shutdown() had already been called on this
519 // queue (e.g. a registered SM's own producer thread, not one of
520 // E3Interface's own, still emitting in the window between
521 // response_queue_->shutdown() and that thread being joined via
522 // SmRegistry::clear() in stop()) -- distinct from the queue actually
523 // being full.
524 const uint64_t reason = (rc == ErrorCode::NOT_INITIALIZED)
526 latrec_tstamp(seq, LATREC_DROP, 0, reason);
527 }
528 return rc;
529}
530
531std::vector<uint32_t> E3Interface::get_available_ran_functions() const {
532 return SmRegistry::instance().get_available_ran_functions();
533}
534
535ErrorCode E3Interface::register_sm(std::unique_ptr<ServiceModel> sm) {
536 if (!sm) {
537 return ErrorCode::INVALID_PARAM;
538 }
539 const uint32_t ran_function_id = sm->ran_function_id();
540 sm->set_subscribers_provider([this, ran_function_id]() {
541 if (!subscription_manager_) {
542 return std::vector<uint32_t>{};
543 }
544 return subscription_manager_->get_subscribed_dapps(ran_function_id);
545 });
546 sm->set_outbound_emitter([this, ran_function_id](Pdu&& pdu) {
547 if (pdu.message_id == 0) {
548 pdu.message_id = generate_message_id();
549 }
550 // Mirrors E3Agent::send_indication / e3_service_model_emit_indication:
551 // this is an emit path, so it stamps EMIT_ENTER itself rather than
552 // leaving it to queue_outbound, which only allocates enqueue_seq for a
553 // Pdu that arrives with none (its own comment says as much -- this was
554 // "everything else", the one emit path that hadn't followed it). A
555 // Service Model that has opened its own ring and called
556 // latrec_ctx_set() before this point -- the documented pattern every
557 // producer follows -- gets a real join to the outbound leg; one that
558 // hasn't gets an EMIT_ENTER with aux 0, same as an unset context
559 // anywhere else.
560 pdu.enqueue_seq = latrec_seq_next();
561 latrec_tstamp(pdu.enqueue_seq, LATREC_EMIT_ENTER, latrec_ctx(), ran_function_id);
562 return queue_outbound(std::move(pdu));
563 });
564 sm->set_control_responder([this](uint32_t dapp_id, uint32_t request_id, const ControlResult& result) {
565 return respond_to_control(dapp_id, request_id, result);
566 });
567 return SmRegistry::instance().register_sm(std::move(sm));
568}
569
571 if (dapp_status_changed_handler_) {
572 dapp_status_changed_handler_();
573 }
574}
575
576// =========================================================================
577// Thread Entry Points
578// =========================================================================
579
580void E3Interface::setup_loop_ran() {
581 // This thread takes no affinity/niceness config, so open its ring here.
582 latrec_tls_open_as(LATREC_ROLE_SETUP);
583 E3_LOG_INFO(LOG_TAG) << "Setup loop (RAN) started";
584
585 auto available_ran_functions = SmRegistry::instance().get_available_ran_functions();
586
587 while (!should_stop_.load()) {
588 std::vector<uint8_t> buffer;
589 int ret = connector_->recv_setup_request(buffer);
590
591 if (ret <= 0) {
592 if (should_stop_.load()) break;
593 continue;
594 }
595
596 E3_LOG_INFO(LOG_TAG) << "Setup request received: " << ret << " bytes";
597
598 // Decode the setup request. On any failure the REQ/REP exchange
599 // must still be completed (see send_negative_setup_reply) or the
600 // setup channel wedges for every subsequent dApp.
601 auto decode_result = encoder_->decode(buffer.data(), static_cast<size_t>(ret));
602 if (!decode_result) {
603 E3_LOG_WARN(LOG_TAG) << "Undecodable setup message (" << ret
604 << " bytes, wrong encoding or garbage); rejecting";
605 send_negative_setup_reply(0);
606 continue;
607 }
608
609 Pdu& pdu = *decode_result;
610 if (pdu.type != PduType::SETUP_REQUEST) {
611 E3_LOG_WARN(LOG_TAG) << "Unexpected PDU type in setup: "
612 << pdu_type_to_string(pdu.type) << "; rejecting";
613 send_negative_setup_reply(pdu.message_id);
614 continue;
615 }
616
617 auto* request = std::get_if<SetupRequest>(&pdu.choice);
618 if (!request) {
619 E3_LOG_WARN(LOG_TAG) << "Failed to get SetupRequest from PDU; rejecting";
620 send_negative_setup_reply(pdu.message_id);
621 continue;
622 }
623
624 handle_setup_request(*request, pdu.message_id);
625 }
626
627 E3_LOG_INFO(LOG_TAG) << "Setup loop (RAN) stopped";
628}
629
630void E3Interface::inbound_loop_ran() {
631 apply_thread_config(config_.io_thread_affinity, config_.io_thread_niceness, LATREC_ROLE_INBOUND);
632 E3_LOG_INFO(LOG_TAG) << "Inbound loop (RAN) started";
633
634 ErrorCode result = connector_->setup_inbound_connection();
635 if (result != ErrorCode::SUCCESS) {
636 E3_LOG_ERROR(LOG_TAG) << "Failed to setup inbound connection";
637 return;
638 }
639
640 std::vector<uint8_t> buffer;
641
642 while (!should_stop_.load()) {
643 int ret = connector_->receive(buffer);
644
645 // After the receive, which delivers what a peer sent before it closed.
646 remove_dapps_of_closed_peers();
647
648 if (ret <= 0) {
649 if (should_stop_.load()) break;
650 continue;
651 }
652
653 // seq comes from the process-wide counter, so an inbound message never
654 // shares a key with an outbound one.
655 const uint64_t seq = latrec_seq_next();
656 latrec_tstamp(seq, LATREC_RECV, static_cast<uint64_t>(ret), 0);
657
658 auto decode_result = encoder_->decode(buffer.data(), static_cast<size_t>(ret));
659 if (!decode_result) {
660 E3_LOG_ERROR(LOG_TAG) << "Failed to decode PDU in subscriber";
662 continue;
663 }
664
665 Pdu& pdu = *decode_result;
666 latrec_tstamp(seq, LATREC_DECODE_E3AP_DONE, pdu.message_id, static_cast<uint64_t>(pdu.type));
667
668 // Before the dispatch, so a report that the queue then drops still counts.
669 if (const uint32_t sender = dapp_id_of(pdu); sender != 0) {
670 if (!admit_dapp_message(connector_->last_peer_token(), sender)) {
671 E3_LOG_WARN(LOG_TAG) << "Dropping " << pdu_type_to_string(pdu.type)
672 << " that names dApp " << sender
673 << ", which belongs to another connection";
675 continue;
676 }
677 subscription_manager_->touch_dapp(sender);
678 }
679
680 switch (pdu.type) {
681 case PduType::SUBSCRIPTION_REQUEST: {
682 auto* request = std::get_if<SubscriptionRequest>(&pdu.choice);
683 if (request) {
684 handle_subscription_request(*request, pdu.message_id);
685 }
686 break;
687 }
688
689 case PduType::SUBSCRIPTION_DELETE: {
690 auto* del = std::get_if<SubscriptionDelete>(&pdu.choice);
691 if (del) {
692 handle_subscription_delete(*del, pdu.message_id);
693 }
694 break;
695 }
696
697 case PduType::DAPP_CONTROL_ACTION: {
698 auto* action = std::get_if<DAppControlAction>(&pdu.choice);
699 if (action) {
700 handle_control_action(*action, pdu.message_id, seq);
701 }
702 break;
703 }
704
705 case PduType::DAPP_REPORT: {
706 auto* report = std::get_if<DAppReport>(&pdu.choice);
707 if (report) {
708 if (report_queue_) {
709 // Hand off to the report worker so downstream work
710 // never blocks the inbound read path. The queue logs
711 // on overflow; surface it here as an error too.
712 report->recv_seq = seq;
713 // Timestamped before the push, not after: the worker
714 // is already blocked on pop(), so it can drain, run
715 // the handler and stamp REPORT_DONE inside the window
716 // between the push returning and this thread issuing
717 // its own stamp. Stamping afterwards puts the queue
718 // entry after the queue exit whenever that happens.
719 const uint64_t t_queued = latrec_tnow();
720 const ErrorCode report_rc = report_queue_->push(std::move(*report));
721 if (report_rc != ErrorCode::SUCCESS) {
722 E3_LOG_ERROR(LOG_TAG) << "Report queue full — dropping dApp report";
723 // See queue_outbound: NOT_INITIALIZED means
724 // shutdown() already ran, not that this queue was
725 // actually full.
726 const uint64_t reason = (report_rc == ErrorCode::NOT_INITIALIZED)
728 latrec_tstamp(seq, LATREC_DROP, 0, reason);
729 } else {
730 latrec_tstamp_at(seq, LATREC_REPORT_QUEUED, 0, 0, t_queued);
731 }
732 }
733 }
734 break;
735 }
736
737 case PduType::RELEASE_MESSAGE: {
738 auto* release = std::get_if<ReleaseMessage>(&pdu.choice);
739 if (release) {
740 handle_release_message(*release);
741 }
742 break;
743 }
744
745 case PduType::CONTROL_RESPONSE: {
746 auto* response = std::get_if<ControlResponse>(&pdu.choice);
747 if (response) {
748 handle_control_response_from_dapp(*response);
749 }
750 break;
751 }
752
753 default:
754 E3_LOG_WARN(LOG_TAG) << "Received unexpected PDU type: "
755 << pdu_type_to_string(pdu.type);
757 break;
758 }
759 }
760
761 E3_LOG_INFO(LOG_TAG) << "Inbound loop (RAN) stopped";
762}
763
764void E3Interface::outbound_loop_ran() {
765 apply_thread_config(config_.io_thread_affinity, config_.io_thread_niceness, LATREC_ROLE_OUTBOUND);
766 E3_LOG_INFO(LOG_TAG) << "Outbound loop (RAN) started";
767
768 // Ignore SIGPIPE to handle closed connections gracefully
769 signal(SIGPIPE, SIG_IGN);
770
771 // Set up the outbound (PUB) socket. Try immediately; retry with backoff
772 // only on failure. Putting an unconditional sleep before the first
773 // attempt introduces a multi-second startup latency that breaks
774 // integration tests and any colocated RAN/dApp pair.
775 ErrorCode result = connector_->setup_outbound_connection();
776 while (result != ErrorCode::SUCCESS && !should_stop_.load()) {
777 E3_LOG_WARN(LOG_TAG) << "Outbound connection setup failed ("
778 << error_code_to_string(result) << "), retrying in 1s";
779 std::this_thread::sleep_for(std::chrono::seconds(1));
780 if (should_stop_.load()) return;
781 result = connector_->setup_outbound_connection();
782 }
783
784 if (result != ErrorCode::SUCCESS) {
785 E3_LOG_ERROR(LOG_TAG) << "Failed to setup outbound connection";
786 return;
787 }
788 E3_LOG_INFO(LOG_TAG) << "Outbound connection established";
789
790 while (!should_stop_.load()) {
791 // Pop from queue (blocking)
792 auto pdu_opt = response_queue_->pop(std::chrono::milliseconds(10));
793
794 if (!pdu_opt) {
795 continue;
796 }
797 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_DEQUEUE, 0, static_cast<uint64_t>(pdu_opt->type));
798
799 // Encode and send
800 auto encode_result = encoder_->encode(*pdu_opt);
801 if (!encode_result) {
802 E3_LOG_ERROR(LOG_TAG) << "Failed to encode PDU for sending";
803 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_DROP, 0, LATREC_DROP_ENCODE);
804 continue;
805 }
806 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_ENCODE_E3AP_DONE, encode_result->buffer.size(), 0);
807
808 latrec_ctx_set(pdu_opt->enqueue_seq); // for the connector's LC stamps
809 // To the connection of the dApp the PDU is for. A dApp that is not bound to one (the
810 // connector cannot tell its peers apart, or the connection is gone) gets the broadcast,
811 // and each dApp filters by its own identifier.
812 const uint32_t target = target_dapp_of(*pdu_opt);
813 const uint64_t peer = target != 0 ? connection_of(target) : 0;
814 const PduClass kind = pdu_opt->type == PduType::INDICATION_MESSAGE
815 ? PduClass::INDICATION : PduClass::PROCEDURE;
816 ErrorCode send_result = connector_->send_to(peer, encode_result->buffer, kind);
817 if (send_result != ErrorCode::SUCCESS) {
818 E3_LOG_ERROR(LOG_TAG) << "Failed to send PDU";
819 // CANCELLED means the connector's shutdown() had already run,
820 // distinct from a genuine transport failure.
821 const uint64_t reason = (send_result == ErrorCode::CANCELLED)
823 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_DROP, 0, reason);
824 } else {
825 E3_LOG_DEBUG(LOG_TAG) << "Sent PDU: " << pdu_type_to_string(pdu_opt->type);
826 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_SEND_DONE, pdu_opt->message_id, 0);
827 }
828 }
829
830 E3_LOG_INFO(LOG_TAG) << "Outbound loop (RAN) stopped";
831}
832
833void E3Interface::report_worker_loop() {
834 apply_thread_config(config_.io_thread_affinity, config_.io_thread_niceness, LATREC_ROLE_REPORT);
835 E3_LOG_INFO(LOG_TAG) << "Report worker loop started";
836
837 while (!should_stop_.load()) {
838 // Blocking pop with the queue's adaptive spin-wait, mirroring
839 // outbound_loop_ran's use of response_queue_.
840 auto report_opt = report_queue_->pop(std::chrono::milliseconds(10));
841 if (report_opt) {
842 handle_dapp_report(*report_opt);
843 latrec_tstamp(report_opt->recv_seq, LATREC_REPORT_DONE, 0, 0);
844 }
845 }
846
847 // Drain anything left after shutdown was signalled.
848 while (auto report_opt = report_queue_->try_pop()) {
849 handle_dapp_report(*report_opt);
850 }
851
852 E3_LOG_INFO(LOG_TAG) << "Report worker loop stopped";
853}
854
855void E3Interface::subscription_expiry_loop() {
856 E3_LOG_INFO(LOG_TAG) << "Subscription expiry loop started";
857 std::unique_lock<std::mutex> lk(expiry_mu_);
858 while (!should_stop_.load()) {
859 expiry_cv_.wait_for(lk, EXPIRY_SWEEP_INTERVAL);
860 if (should_stop_.load()) {
861 break;
862 }
863 lk.unlock();
864 if (subscription_manager_) {
865 if (!subscription_manager_->expire_subscriptions().empty()) {
866 notify_dapp_status_changed();
867 }
868 remove_idle_dapps();
869 } else if (dapp_state_) {
870 for (uint32_t ran_function_id :
871 dapp_state_->expire_subscriptions(std::chrono::steady_clock::now())) {
872 E3_LOG_INFO(LOG_TAG) << "Subscription to RAN function " << ran_function_id
873 << " ran out of time";
874 }
875 }
876 lk.lock();
877 }
878}
879
880#ifdef LIBE3_ENABLE_LATREC
881void E3Interface::context_monitor_loop() {
882 latrec_tls_open_as(LATREC_ROLE_CONTEXT);
883
884#ifdef __linux__
885 long prev_nivcsw = 0;
886 {
887 struct rusage ru {};
888 if (getrusage(RUSAGE_SELF, &ru) == 0) {
889 prev_nivcsw = ru.ru_nivcsw;
890 }
891 }
892#endif
893
894 while (!should_stop_.load()) {
895 std::this_thread::sleep_for(std::chrono::seconds(1));
896 if (should_stop_.load()) {
897 break;
898 }
899
900 uint64_t nivcsw_delta = 0;
901 uint64_t cur_freq_khz = 0;
902#ifdef __linux__
903 struct rusage ru {};
904 if (getrusage(RUSAGE_SELF, &ru) == 0) {
905 nivcsw_delta = static_cast<uint64_t>(ru.ru_nivcsw - prev_nivcsw);
906 prev_nivcsw = ru.ru_nivcsw;
907 }
908
909 // Best-effort: absent under most VMs/containers and some CI runners,
910 // in which case this stays 0 rather than failing the sample.
911 const int cpu = sched_getcpu();
912 if (cpu >= 0) {
913 char path[128];
914 std::snprintf(path, sizeof(path),
915 "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", cpu);
916 if (FILE* f = std::fopen(path, "r")) {
917 long khz = 0;
918 if (std::fscanf(f, "%ld", &khz) == 1) {
919 cur_freq_khz = static_cast<uint64_t>(khz);
920 }
921 std::fclose(f);
922 }
923 }
924#endif
925 // seq = 0: a 1 Hz slow-lane record carries no per-message key.
926 latrec_tstamp(0, LATREC_CONTEXT, nivcsw_delta, cur_freq_khz);
927 }
928}
929#endif // LIBE3_ENABLE_LATREC
930
931// =========================================================================
932// Refusals
933// =========================================================================
934
935namespace {
936
937/// The reason a peer gave with a negative answer, for a log line: " (cause: detail)", or nothing.
938template <typename Response>
939std::string reason_suffix(const Response& resp) {
940 if (resp.response_code != ResponseCode::NEGATIVE || (!resp.cause && !resp.detail)) return {};
941 std::string out = " (";
942 if (resp.cause) out += cause_to_string(*resp.cause);
943 if (resp.cause && resp.detail) out += ": ";
944 if (resp.detail) out += *resp.detail;
945 return out + ")";
946}
947
948/// Why a request is refused: the code and the text a RAN sends with a negative answer.
949struct Refusal {
950 Cause cause;
951 std::string detail;
952};
953
954/// Key of a control that waits for an answer: the dApp that sent it and its message id.
955uint64_t pending_key(uint32_t dapp_id, uint32_t request_id) {
956 return (static_cast<uint64_t>(dapp_id) << 32) | request_id;
957}
958
959bool contains(const std::vector<uint32_t>& ids, uint32_t id) {
960 return std::find(ids.begin(), ids.end(), id) != ids.end();
961}
962
963/// What a subscription asks for against what the RAN function advertises in its setup
964/// response. The same three questions Aerial's and OCUDU's agents ask: is the function
965/// served, is anything asked for, is every identifier one the function offers.
966/// Unknown identifiers are refused for controls as well as telemetry, because a RAN
967/// function may have controls (OCUDU refuses any control, Aerial ignores the list).
968std::optional<Refusal> refusal_for_subscription(const SubscriptionRequest& request) {
969 ServiceModel* sm = SmRegistry::instance().get_by_ran_function(request.ran_function_identifier);
970 if (sm == nullptr) {
971 return Refusal{Cause::UNSUPPORTED_RAN_FUNCTION,
972 "RAN function " + std::to_string(request.ran_function_identifier)
973 + " is not served"};
974 }
975 if (request.telemetry_identifier_list.empty() && request.control_identifier_list.empty()) {
976 return Refusal{Cause::INVALID_REQUEST,
977 "a subscription names at least one telemetry or control identifier"};
978 }
979 const std::vector<uint32_t> telemetry = sm->telemetry_ids();
980 for (uint32_t id : request.telemetry_identifier_list) {
981 if (!contains(telemetry, id)) {
982 return Refusal{Cause::UNSUPPORTED_IDENTIFIER,
983 "unknown telemetry identifier " + std::to_string(id)};
984 }
985 }
986 const std::vector<uint32_t> controls = sm->control_ids();
987 for (uint32_t id : request.control_identifier_list) {
988 if (!contains(controls, id)) {
989 return Refusal{Cause::UNSUPPORTED_IDENTIFIER,
990 "unknown control identifier " + std::to_string(id)};
991 }
992 }
993 return std::nullopt;
994}
995
996} // namespace
997
998// =========================================================================
999// Message Handlers
1000// =========================================================================
1001
1002void E3Interface::handle_setup_request(const SetupRequest& request, uint32_t request_message_id) {
1003 request_message_id = sanitize_request_message_id(request_message_id);
1004 latrec_tstamp(request_message_id, LATREC_SETUP_BEGIN, 0, 0);
1005 E3_LOG_INFO(LOG_TAG) << "Handling setup request from dApp '" << request.dapp_name
1006 << "' (version=" << request.dapp_version
1007 << ", vendor=" << request.vendor
1008 << ", e3ap_version=" << request.e3ap_protocol_version << ")";
1009
1010 ResponseCode response_code = ResponseCode::NEGATIVE;
1011 uint32_t assigned_dapp_id = 0;
1012 std::optional<Cause> refusal_cause;
1013 std::optional<std::string> refusal_detail;
1014
1015 // Register the dApp
1016 auto [result, dapp_id] = subscription_manager_->register_dapp();
1017 assigned_dapp_id = dapp_id;
1018
1019 if (result == ErrorCode::SUCCESS) {
1020 response_code = ResponseCode::POSITIVE;
1021 // The connection that sent the request is the dApp's, from now on.
1022 bind_dapp_to_connection(assigned_dapp_id, connector_->last_setup_peer_token());
1023 E3_LOG_INFO(LOG_TAG) << "dApp '" << request.dapp_name << "' registered with assigned ID " << assigned_dapp_id;
1024 notify_dapp_status_changed();
1025 } else {
1026 E3_LOG_ERROR(LOG_TAG) << "Failed to register dApp '" << request.dapp_name << "': " << error_code_to_string(result);
1027 refusal_cause = Cause::RESOURCE_EXHAUSTED;
1028 refusal_detail = "no free dApp identifier";
1029 }
1030
1031 // Create and send response
1032 // Get available RAN functions and convert to RanFunctionDef list
1033 auto available_ran_function_ids = SmRegistry::instance().get_available_ran_functions();
1034 E3_LOG_DEBUG(LOG_TAG) << "Available RAN function ids count: " << available_ran_function_ids.size();
1035 std::vector<RanFunctionDef> ran_function_list;
1036 for (auto id : available_ran_function_ids) {
1037 RanFunctionDef func;
1038 func.ran_function_identifier = id;
1039 ServiceModel* sm = SmRegistry::instance().get_by_ran_function(id);
1040 if (sm) {
1041 func.telemetry_identifier_list = sm->telemetry_ids();
1042 func.control_identifier_list = sm->control_ids();
1043 func.ran_function_data = sm->ran_function_data();
1044 }
1045 // ranFunctionData is mandatory SIZE(1..262144) per entry (limited to 1..32768), and the value
1046 // is recomputed on every SetupRequest, so registration cannot vouch for
1047 // what we get here. An entry that cannot be encoded would fail the whole
1048 // response -- every other RAN function with it -- so omit it instead:
1049 // ranFunctionList itself is OPTIONAL, which is how E3AP spells "nothing
1050 // to advertise".
1051 if (func.ran_function_data.empty()
1052 || func.ran_function_data.size() > MAX_PROTOCOL_DATA_SIZE) {
1053 E3_LOG_ERROR(LOG_TAG) << "Omitting RAN function " << id
1054 << " from the setup response: "
1055 << func.ran_function_data.size()
1056 << " bytes of ran_function_data (need 1.."
1057 << MAX_PROTOCOL_DATA_SIZE << ")";
1058 continue;
1059 }
1060 if (func.telemetry_identifier_list.size() > MAX_IDENTIFIER_LIST_SIZE
1061 || func.control_identifier_list.size() > MAX_IDENTIFIER_LIST_SIZE) {
1062 E3_LOG_ERROR(LOG_TAG) << "Omitting RAN function " << id
1063 << " from the setup response: more than "
1064 << MAX_IDENTIFIER_LIST_SIZE << " telemetry or control ids";
1065 continue;
1066 }
1067 if (ran_function_list.size() >= MAX_RAN_FUNCTIONS) {
1068 E3_LOG_ERROR(LOG_TAG) << "Omitting RAN function " << id
1069 << " from the setup response: it lists at most "
1071 continue;
1072 }
1073 ran_function_list.push_back(func);
1074 }
1075 E3_LOG_DEBUG(LOG_TAG) << "Constructed ran_function_list size: " << ran_function_list.size();
1076 for (const auto &rf : ran_function_list) {
1077 E3_LOG_DEBUG(LOG_TAG) << " RAN function id=" << rf.ran_function_identifier
1078 << ", telemetry_count=" << rf.telemetry_identifier_list.size()
1079 << ", control_count=" << rf.control_identifier_list.size()
1080 << ", ran_function_data_len=" << rf.ran_function_data.size();
1081 }
1082
1083 auto encode_result = encoder_->encode_setup_response(
1084 generate_message_id(),
1085 request_message_id,
1086 response_code,
1087 config_.e3ap_version,
1088 // A failed registration assigns no id; engaging the optional with 0
1089 // would violate E3-DAppID (1..65535) at encode.
1090 response_code == ResponseCode::POSITIVE
1091 ? std::optional<uint32_t>(assigned_dapp_id)
1092 : std::nullopt,
1093 name_or_unknown(config_.ran_identifier),
1094 ran_function_list,
1095 refusal_cause,
1096 refusal_detail
1097 );
1098
1099 if (!encode_result) {
1100 // The peer-controlled inputs are sanitized above, so a failure here
1101 // is an internal encoder or configuration bug.
1102 E3_LOG_ERROR(LOG_TAG) << "Failed to encode setup response for request id "
1103 << request_message_id << "; aborting";
1104 std::abort();
1105 }
1106
1107 ErrorCode send_result = connector_->send_response(encode_result->buffer);
1108 if (send_result != ErrorCode::SUCCESS) {
1109 E3_LOG_ERROR(LOG_TAG) << "Failed to send setup response for request id " << request_message_id
1110 << "; error=" << error_code_to_string(send_result);
1111 } else {
1112 E3_LOG_INFO(LOG_TAG) << "Sent setup response for request id " << request_message_id;
1113 }
1114 latrec_tstamp(request_message_id, LATREC_SETUP_DONE, 0,
1115 send_result == ErrorCode::SUCCESS ? 1 : 0);
1116}
1117
1118void E3Interface::send_negative_setup_reply(uint32_t request_id) {
1119 // A bare negative SetupResponse omits every OPTIONAL field
1120 // (ranFunctionList included), so with the fixed, mutually known
1121 // encoding it always encodes. The mandatory fields have to satisfy
1122 // their schema constraints, though: requestId is E3-MessageID
1123 // INTEGER (1..4294967295) — an id that cannot be echoed (0, from
1124 // undecodable bytes) is replaced with a freshly generated one — and ranIdentifier is
1125 // SIZE (1..64), hence the placeholder when the config left it empty.
1126 uint32_t message_id = generate_message_id();
1127 request_id = sanitize_request_message_id(request_id);
1128 auto encode_result = encoder_->encode_setup_response(
1129 message_id,
1130 request_id,
1131 ResponseCode::NEGATIVE,
1132 config_.e3ap_version,
1133 std::nullopt, // no dApp identifier assigned
1134 name_or_unknown(config_.ran_identifier),
1135 std::nullopt, // no RAN functions advertised
1136 Cause::PROTOCOL_ERROR,
1137 std::string("not a decodable setup request")
1138 );
1139
1140 if (!encode_result) {
1141 E3_LOG_ERROR(LOG_TAG) << "Failed to encode negative setup response for request id "
1142 << request_id << "; setup channel may be left unusable";
1143 return;
1144 }
1145
1146 ErrorCode send_result = connector_->send_response(encode_result->buffer);
1147 if (send_result != ErrorCode::SUCCESS) {
1148 E3_LOG_WARN(LOG_TAG) << "Failed to send negative setup response for request id "
1149 << request_id << "; error=" << error_code_to_string(send_result);
1150 }
1151 latrec_tstamp(request_id, LATREC_SETUP_DONE, 0, 0 /* rejected */);
1152}
1153
1154void E3Interface::handle_subscription_request(const SubscriptionRequest& request, uint32_t request_message_id) {
1155 latrec_tstamp(request_message_id, LATREC_SUB_BEGIN, 0, 0);
1156 E3_LOG_INFO(LOG_TAG) << "Handling subscription request from dApp " << request.dapp_identifier
1157 << " for RAN function " << request.ran_function_identifier;
1158
1159 ResponseCode response_code = ResponseCode::NEGATIVE;
1160 uint32_t subscription_id = 1;
1161 std::optional<Refusal> refusal;
1162 // What the RAN holds when the request repeats a subscription it already has.
1163 std::optional<SubscriptionDetails> held;
1164 bool repeated = false;
1165
1166 // Check if dApp is registered
1167 if (!subscription_manager_->is_dapp_registered(request.dapp_identifier)) {
1168 E3_LOG_ERROR(LOG_TAG) << "dApp " << request.dapp_identifier << " not registered";
1169 refusal = Refusal{Cause::SETUP_REQUIRED, "complete setup before subscribing"};
1170 } else if ((refusal = refusal_for_subscription(request))) {
1171 E3_LOG_WARN(LOG_TAG) << "Refusing subscription of dApp " << request.dapp_identifier
1172 << " to RAN function " << request.ran_function_identifier << ": "
1173 << cause_to_string(refusal->cause) << " (" << refusal->detail << ")";
1174 } else {
1175 uint32_t period = request.periodicity.value_or(0);
1176 // Seconds, absent or 0 = no limit.
1177 const uint32_t subscription_time = request.subscription_time.value_or(0);
1178 auto [result, sub_id] = subscription_manager_->add_subscription(
1179 request.dapp_identifier,
1180 request.ran_function_identifier,
1181 request.telemetry_identifier_list,
1182 request.control_identifier_list,
1183 period,
1184 subscription_time
1185 );
1186 subscription_id = sub_id;
1187
1188 if (result == ErrorCode::SUCCESS || result == ErrorCode::SUBSCRIPTION_EXISTS) {
1189 response_code = ResponseCode::POSITIVE;
1190 E3_LOG_INFO(LOG_TAG) << "Subscription added: dApp " << request.dapp_identifier
1191 << " -> RAN function " << request.ran_function_identifier
1192 << " (subscription_id=" << subscription_id << ")";
1193 if (result == ErrorCode::SUCCESS) {
1194 notify_dapp_status_changed();
1195 } else {
1196 repeated = true;
1197 held = subscription_manager_->get_subscription_details(
1198 request.dapp_identifier, request.ran_function_identifier);
1199 }
1200 } else {
1201 E3_LOG_ERROR(LOG_TAG) << "Failed to add subscription: "
1202 << error_code_to_string(result);
1203 refusal = Refusal{result == ErrorCode::INTERNAL_ERROR ? Cause::RESOURCE_EXHAUSTED
1204 : Cause::UNSPECIFIED,
1205 result == ErrorCode::INTERNAL_ERROR
1206 ? std::string("no free subscription identifier")
1207 : std::string(error_code_to_string(result))};
1208 }
1209 }
1210
1211 // Create and queue response
1212 Pdu response_pdu(PduType::SUBSCRIPTION_RESPONSE);
1213 SubscriptionResponse resp;
1214 response_pdu.message_id = generate_message_id();
1215 resp.request_id = request_message_id;
1216 resp.dapp_identifier = request.dapp_identifier;
1217 resp.response_code = response_code;
1218 if (response_code == ResponseCode::POSITIVE) {
1219 resp.subscription_id = subscription_id;
1220 resp.ran_function_identifier = request.ran_function_identifier;
1221 if (!repeated) {
1222 resp.telemetry_identifier_list = request.telemetry_identifier_list;
1223 resp.control_identifier_list = request.control_identifier_list;
1224 } else if (held) {
1225 // A repeat keeps the subscription it repeats, so say what that holds.
1226 resp.telemetry_identifier_list = held->telemetry_ids;
1227 resp.control_identifier_list = held->control_ids;
1228 }
1229 // Only the SM knows the interval it keeps, so the response has one when it says so.
1230 if (!repeated || held) {
1231 const uint32_t requested = held ? held->periodicity_us
1232 : request.periodicity.value_or(0);
1233 ServiceModel* sm = SmRegistry::instance().get_by_ran_function(
1234 request.ran_function_identifier);
1235 const auto granted = sm ? sm->granted_periodicity(requested) : std::nullopt;
1236 if (granted && *granted != 0 && *granted <= MAX_PERIODICITY_US) resp.periodicity = *granted;
1237 }
1238 } else if (refusal) {
1239 resp.cause = refusal->cause;
1240 resp.detail = refusal->detail;
1241 }
1242 response_pdu.choice = resp;
1243
1244 latrec_tstamp(request_message_id, LATREC_SUB_DONE, 0,
1245 response_code == ResponseCode::POSITIVE ? 1 : 0);
1246 queue_outbound(std::move(response_pdu));
1247}
1248
1249void E3Interface::handle_subscription_delete(const SubscriptionDelete& del, uint32_t request_message_id) {
1250 E3_LOG_INFO(LOG_TAG) << "Handling subscription delete from dApp " << del.dapp_identifier
1251 << " for subscription " << del.subscription_id;
1252
1253 ResponseCode response_code = ResponseCode::NEGATIVE;
1254 std::optional<Cause> refusal_cause;
1255
1256 ErrorCode result = subscription_manager_->remove_subscription_by_id(
1257 del.dapp_identifier,
1258 del.subscription_id
1259 );
1260
1261 if (result == ErrorCode::SUCCESS) {
1262 response_code = ResponseCode::POSITIVE;
1263 E3_LOG_INFO(LOG_TAG) << "Subscription " << del.subscription_id << " removed for dApp " << del.dapp_identifier;
1264 notify_dapp_status_changed();
1265 } else {
1266 E3_LOG_ERROR(LOG_TAG) << "Failed to remove subscription: "
1267 << error_code_to_string(result);
1268 refusal_cause = result == ErrorCode::DAPP_NOT_REGISTERED ? Cause::SETUP_REQUIRED
1269 : Cause::NOT_FOUND;
1270 }
1271
1272 // Create and queue response
1273 Pdu response_pdu(PduType::SUBSCRIPTION_RESPONSE);
1274 SubscriptionResponse resp;
1275 response_pdu.message_id = generate_message_id();
1276 resp.request_id = request_message_id;
1277 resp.dapp_identifier = del.dapp_identifier;
1278 resp.response_code = response_code;
1279 if (response_code == ResponseCode::POSITIVE) {
1280 resp.subscription_id = del.subscription_id;
1281 } else {
1282 resp.cause = refusal_cause;
1283 resp.detail = refusal_cause == Cause::SETUP_REQUIRED
1284 ? "complete setup before deleting a subscription"
1285 : "the subscription does not exist or has ended";
1286 }
1287 response_pdu.choice = resp;
1288
1289 queue_outbound(std::move(response_pdu));
1290}
1291
1292void E3Interface::refuse_control(const DAppControlAction& action, uint32_t request_message_id,
1293 Cause cause, std::string detail) {
1294 E3_LOG_WARN(LOG_TAG) << "Refusing control of dApp " << action.dapp_identifier
1295 << " for RAN function " << action.ran_function_identifier << ": "
1296 << cause_to_string(cause) << " (" << detail << ")";
1297 Pdu pdu(PduType::CONTROL_RESPONSE);
1298 ControlResponse resp;
1299 resp.request_id = sanitize_request_message_id(request_message_id);
1300 resp.dapp_identifier = action.dapp_identifier;
1301 resp.ran_function_identifier = action.ran_function_identifier;
1302 resp.control_identifier = action.control_identifier;
1303 resp.response_code = ResponseCode::NEGATIVE;
1304 resp.cause = cause;
1305 resp.detail = std::move(detail);
1306 pdu.message_id = generate_message_id();
1307 pdu.choice = std::move(resp);
1308 queue_outbound(std::move(pdu));
1309}
1310
1311void E3Interface::handle_control_action(const DAppControlAction& action, uint32_t request_message_id,
1312 uint64_t latrec_seq) {
1313 E3_LOG_INFO(LOG_TAG) << "Handling control action from dApp " << action.dapp_identifier
1314 << " for RAN function " << action.ran_function_identifier
1315 << " control " << action.control_identifier
1316 << " (" << action.action_data.size() << " bytes)";
1317
1318 // The RAN answers a control it cannot hand to a Service Model with a negative
1319 // ControlResponse, whether the dApp asked for an answer or not, so a mistake of
1320 // the dApp does not pass unseen. A Service Model answers for what it takes, and
1321 // only when asked.
1322 if (!subscription_manager_->is_dapp_registered(action.dapp_identifier)) {
1323 refuse_control(action, request_message_id, Cause::SETUP_REQUIRED,
1324 "complete setup before sending a control");
1325 return;
1326 }
1327 ServiceModel* sm = SmRegistry::instance().get_by_ran_function(action.ran_function_identifier);
1328 if (sm == nullptr) {
1329 refuse_control(action, request_message_id, Cause::UNSUPPORTED_RAN_FUNCTION,
1330 "RAN function " + std::to_string(action.ran_function_identifier) + " is not served");
1331 return;
1332 }
1333 {
1334 const std::vector<uint32_t> controls = sm->control_ids();
1335 if (!contains(controls, action.control_identifier)) {
1336 refuse_control(action, request_message_id, Cause::UNSUPPORTED_IDENTIFIER,
1337 "unknown control identifier " + std::to_string(action.control_identifier));
1338 return;
1339 }
1340 }
1341 if (!sm->is_running()) {
1342 refuse_control(action, request_message_id, Cause::NOT_FOUND, "no subscription to this RAN function");
1343 return;
1344 }
1345
1346 // Remember a control that asked for an answer before the SM sees it: it may answer
1347 // from another thread before handle_control_action returns.
1348 const uint64_t key = pending_key(action.dapp_identifier, request_message_id);
1349 if (action.request_ack) {
1350 std::unique_lock<std::mutex> lk(pending_controls_mu_);
1351 if (pending_controls_.size() >= MAX_PENDING_CONTROLS && pending_controls_.count(key) == 0) {
1352 lk.unlock();
1353 refuse_control(action, request_message_id, Cause::RESOURCE_EXHAUSTED,
1354 "too many controls wait for an answer");
1355 return;
1356 }
1357 pending_controls_[key] = PendingControl{action.ran_function_identifier, action.control_identifier};
1358 }
1359
1360 // The SM's own DECODE_E3SM_BEGIN/DONE already marks the library-to-SM
1361 // boundary, keyed on the SM's own inflight counter -- that pair needs
1362 // no bridge. What has none is whatever the SM emits in response
1363 // (typically a ControlResponse): its EMIT_ENTER has nothing to read unless
1364 // this inbound leg's key is published first, the same bridge
1365 // handle_indication and handle_xapp_control_action publish on the
1366 // dApp role.
1367 latrec_ctx_set(latrec_seq);
1368 ErrorCode result = sm->handle_control_action(request_message_id, action);
1369 if (result != ErrorCode::SUCCESS) {
1370 E3_LOG_ERROR(LOG_TAG) << "SM failed to process control action: "
1371 << error_code_to_string(result);
1372 if (action.request_ack) {
1373 bool unanswered = false;
1374 {
1375 std::lock_guard<std::mutex> lk(pending_controls_mu_);
1376 unanswered = pending_controls_.erase(key) != 0;
1377 }
1378 if (unanswered) {
1379 refuse_control(action, request_message_id, Cause::UNSPECIFIED,
1380 "the service model could not take the control");
1381 }
1382 }
1383 return;
1384 }
1385 E3_LOG_INFO(LOG_TAG) << "Control action processed by SM";
1386}
1387
1389 const ControlResult& result) {
1390 if (result.outcome.size() > MAX_CONTROL_OUTCOME_SIZE) {
1391 return ErrorCode::INVALID_PARAM;
1392 }
1393 PendingControl pending;
1394 {
1395 std::lock_guard<std::mutex> lk(pending_controls_mu_);
1396 auto it = pending_controls_.find(pending_key(dapp_id, request_id));
1397 if (it == pending_controls_.end()) {
1398 return ErrorCode::NOT_FOUND;
1399 }
1400 pending = it->second;
1401 pending_controls_.erase(it);
1402 }
1404 ControlResponse resp;
1405 resp.request_id = sanitize_request_message_id(request_id);
1406 resp.dapp_identifier = dapp_id;
1407 resp.ran_function_identifier = pending.ran_function_id;
1408 resp.control_identifier = pending.control_id;
1409 resp.response_code = result.response_code;
1410 resp.cause = result.cause;
1411 resp.detail = result.detail;
1412 if (!result.outcome.empty()) resp.control_outcome = result.outcome;
1414 pdu.choice = std::move(resp);
1415 // An emit path, like the SM's outbound emitter: it stamps EMIT_ENTER itself.
1417 latrec_tstamp(pdu.enqueue_seq, LATREC_EMIT_ENTER, latrec_ctx(), pending.ran_function_id);
1418 return queue_outbound(std::move(pdu));
1419}
1420
1421void E3Interface::handle_dapp_report(const DAppReport& report) {
1422 E3_LOG_INFO(LOG_TAG) << "Handling dApp report from dApp " << report.dapp_identifier
1423 << " for RAN function " << report.ran_function_identifier;
1424
1425 // Forward to callback if set
1426 if (dapp_report_handler_) {
1427 dapp_report_handler_(report);
1428 }
1429}
1430
1431void E3Interface::handle_release_message(const ReleaseMessage& release) {
1432 E3_LOG_INFO(LOG_TAG) << "Handling release message from dApp " << release.dapp_identifier;
1433
1434 handle_dapp_disconnection(release.dapp_identifier);
1435}
1436
1437void E3Interface::handle_dapp_disconnection(uint32_t dapp_id) {
1438 E3_LOG_INFO(LOG_TAG) << "Handling dApp disconnection: " << dapp_id;
1439
1440 // Nobody is left to answer to.
1441 {
1442 std::lock_guard<std::mutex> lk(pending_controls_mu_);
1443 for (auto it = pending_controls_.begin(); it != pending_controls_.end();) {
1444 it = (it->first >> 32) == dapp_id ? pending_controls_.erase(it) : std::next(it);
1445 }
1446 }
1447
1448 // Get subscriptions before unregistering
1449 auto subscriptions = subscription_manager_->get_dapp_subscriptions(dapp_id);
1450
1451 // Unregister dApp (this will also clean up subscriptions)
1452 ErrorCode result = subscription_manager_->unregister_dapp(dapp_id);
1453
1454 if (result == ErrorCode::SUCCESS) {
1455 E3_LOG_INFO(LOG_TAG) << "dApp " << dapp_id << " unregistered, "
1456 << subscriptions.size() << " subscriptions removed";
1457 notify_dapp_status_changed();
1458 } else {
1459 E3_LOG_ERROR(LOG_TAG) << "Failed to unregister dApp " << dapp_id << ": "
1460 << error_code_to_string(result);
1461 }
1462}
1463
1464void E3Interface::bind_dapp_to_connection(uint32_t dapp_id, uint64_t peer) {
1465 if (peer == 0) {
1466 return; // a connector that cannot tell its peers apart
1467 }
1468 const auto generation = subscription_manager_->dapp_generation(dapp_id);
1469 if (!generation) {
1470 return;
1471 }
1472 std::lock_guard<std::mutex> lock(bindings_mu_);
1473 if (auto owner = peer_bindings_.owner.find(dapp_id); owner != peer_bindings_.owner.end()) {
1474 // The id was handed out again: the record is of the registration before.
1475 if (auto old = peer_bindings_.by_peer.find(owner->second.first); old != peer_bindings_.by_peer.end()) {
1476 old->second.erase(dapp_id);
1477 }
1478 }
1479 peer_bindings_.owner[dapp_id] = {peer, *generation};
1480 peer_bindings_.by_peer[peer][dapp_id] = *generation;
1481}
1482
1483uint64_t E3Interface::connection_of(uint32_t dapp_id) {
1484 std::lock_guard<std::mutex> lock(bindings_mu_);
1485 auto owner = peer_bindings_.owner.find(dapp_id);
1486 return owner == peer_bindings_.owner.end() ? 0 : owner->second.first;
1487}
1488
1489bool E3Interface::admit_dapp_message(uint64_t peer, uint32_t dapp_id) {
1490 if (peer == 0) {
1491 return true; // a connector that cannot tell its peers apart
1492 }
1493 const auto generation = subscription_manager_->dapp_generation(dapp_id);
1494 if (!generation) {
1495 return true; // not registered: the handler refuses it, as for any unknown id
1496 }
1497 std::lock_guard<std::mutex> lock(bindings_mu_);
1498 auto owner = peer_bindings_.owner.find(dapp_id);
1499 if (owner == peer_bindings_.owner.end() || owner->second.second != *generation) {
1500 return true; // not bound to a connection: nothing to compare with
1501 }
1502 return owner->second.first == peer;
1503}
1504
1505void E3Interface::remove_dapps_of_closed_peers() {
1506 std::vector<std::pair<uint32_t, uint64_t>> gone; // dApp id, generation
1507 for (uint64_t peer : connector_->take_closed_peers()) {
1508 std::lock_guard<std::mutex> lock(bindings_mu_);
1509 auto bound = peer_bindings_.by_peer.find(peer);
1510 if (bound == peer_bindings_.by_peer.end()) {
1511 continue; // no dApp was bound to it
1512 }
1513 for (const auto& [dapp_id, generation] : bound->second) {
1514 auto owner = peer_bindings_.owner.find(dapp_id);
1515 if (owner != peer_bindings_.owner.end() && owner->second.first == peer) {
1516 peer_bindings_.owner.erase(owner);
1517 }
1518 gone.emplace_back(dapp_id, generation);
1519 }
1520 peer_bindings_.by_peer.erase(bound);
1521 }
1522 for (const auto& [dapp_id, generation] : gone) {
1523 if (subscription_manager_->dapp_generation(dapp_id) != generation) {
1524 continue; // released, removed as idle, or the id is someone else's now
1525 }
1526 E3_LOG_INFO(LOG_TAG) << "Connection of dApp " << dapp_id << " closed without a release";
1527 handle_dapp_disconnection(dapp_id);
1528 }
1529}
1530
1531void E3Interface::request_reconnect() {
1532 if (config_.role != E3Role::DAPP || config_.reconnect_interval_ms == 0) {
1533 return;
1534 }
1535 {
1536 std::lock_guard<std::mutex> lk(reconnect_mu_);
1537 if (user_stopped_) {
1538 return;
1539 }
1540 reconnect_pending_ = true;
1541 }
1542 reconnect_cv_.notify_all();
1543}
1544
1545void E3Interface::reconnect_loop() {
1546 const std::chrono::milliseconds interval(config_.reconnect_interval_ms);
1547 std::unique_lock<std::mutex> lk(reconnect_mu_);
1548 for (;;) {
1549 reconnect_cv_.wait(lk, [this] { return user_stopped_ || reconnect_pending_; });
1550 if (user_stopped_) {
1551 return;
1552 }
1553 reconnect_pending_ = false;
1554
1555 // The pause is the retry interval too: a restart that fails asks again.
1556 if (reconnect_cv_.wait_for(lk, interval, [this] { return user_stopped_; })) {
1557 return;
1558 }
1559 lk.unlock();
1560 restart_session();
1561 lk.lock();
1562 }
1563}
1564
1565void E3Interface::restart_session() {
1566 std::lock_guard<std::mutex> lifecycle(lifecycle_mu_);
1567 {
1568 std::lock_guard<std::mutex> lk(reconnect_mu_);
1569 if (user_stopped_) {
1570 return;
1571 }
1572 }
1573 E3_LOG_INFO(LOG_TAG) << "Registering with the RAN again";
1574 stop_locked();
1575 const ErrorCode rc = start_locked();
1576 if (rc != ErrorCode::SUCCESS) {
1577 E3_LOG_WARN(LOG_TAG) << "Could not reach the RAN: " << error_code_to_string(rc);
1578 request_reconnect();
1579 }
1580}
1581
1582void E3Interface::remove_idle_dapps() {
1583 if (config_.dapp_idle_timeout_s == 0) {
1584 return;
1585 }
1586 const std::chrono::seconds idle_for(config_.dapp_idle_timeout_s);
1587 for (uint32_t dapp_id : subscription_manager_->idle_dapps(idle_for)) {
1588 E3_LOG_INFO(LOG_TAG) << "dApp " << dapp_id << " sent nothing for "
1589 << config_.dapp_idle_timeout_s << " s, releasing it";
1590
1591 // The release goes first. Freeing the id lets the next setup take it, and
1592 // a dApp filters a release by its own id, so it must name the old owner.
1593 Pdu pdu(PduType::RELEASE_MESSAGE);
1594 ReleaseMessage release;
1595 release.dapp_identifier = dapp_id;
1596 pdu.choice = release;
1597 pdu.message_id = generate_message_id();
1598 queue_outbound(std::move(pdu));
1599
1600 handle_dapp_disconnection(dapp_id);
1601 }
1602}
1603
1604// =========================================================================
1605// SM Lifecycle Management
1606// =========================================================================
1607
1608// ===========================================================================
1609// dApp-role thread bodies
1610// ===========================================================================
1611
1612void E3Interface::setup_loop_dapp() {
1613 // As in setup_loop_ran: this thread takes no affinity/niceness config, so
1614 // its ring is opened here. It enqueues the setup response, which the dApp
1615 // session ring picks up.
1616 latrec_tls_open_as(LATREC_ROLE_SETUP);
1617 E3_LOG_INFO(LOG_TAG) << "Setup loop (dApp) started";
1618
1619 // Encode the SetupRequest from config_'s dApp identification fields.
1620 auto enc = encoder_->encode_setup_request(
1621 generate_message_id(),
1622 config_.e3ap_version,
1623 config_.dapp_name,
1624 config_.dapp_version,
1625 name_or_unknown(config_.vendor)
1626 );
1627 if (!enc) {
1628 E3_LOG_ERROR(LOG_TAG) << "Failed to encode SetupRequest";
1629 std::lock_guard<std::mutex> lk(setup_complete_mu_);
1630 setup_complete_ = true;
1631 setup_succeeded_ = false;
1632 setup_complete_cv_.notify_all();
1633 return;
1634 }
1635
1636 // Lazy-pirate REQ: send, wait for reply with timeout, retry on no reply.
1637 constexpr int MAX_RETRIES = 5;
1638 int retries = 0;
1639 bool got_response = false;
1640 while (!should_stop_.load() && retries < MAX_RETRIES) {
1641 ErrorCode rc = connector_->send_setup_request_client(enc->buffer);
1642 if (rc != ErrorCode::SUCCESS) {
1643 E3_LOG_ERROR(LOG_TAG) << "send_setup_request_client failed: "
1644 << error_code_to_string(rc);
1645 ++retries;
1646 std::this_thread::sleep_for(std::chrono::seconds(1));
1647 continue;
1648 }
1649
1650 // Try a few times to receive (connector recv has its own short timeout).
1651 for (int attempt = 0; attempt < 4 && !should_stop_.load(); ++attempt) {
1652 std::vector<uint8_t> resp_buf;
1653 int n = connector_->recv_setup_response_client(resp_buf);
1654 if (n > 0) {
1655 auto decoded = encoder_->decode(resp_buf.data(), static_cast<size_t>(n));
1656 if (!decoded) {
1657 E3_LOG_ERROR(LOG_TAG) << "Failed to decode SetupResponse. If the RAN is a libe3 built before "
1658 "0.6, it speaks the old POSIX layout (three connections, "
1659 "unframed messages) and has to be upgraded together with the dApp.";
1660 break;
1661 }
1662 if (decoded->type != PduType::SETUP_RESPONSE) {
1663 E3_LOG_ERROR(LOG_TAG) << "Unexpected PDU on setup channel: "
1664 << pdu_type_to_string(decoded->type);
1665 break;
1666 }
1667 auto* resp = std::get_if<SetupResponse>(&decoded->choice);
1668 if (resp) {
1669 handle_setup_response(*resp);
1670 got_response = true;
1671 }
1672 break;
1673 }
1674 if (n < 0) {
1675 E3_LOG_ERROR(LOG_TAG) << "recv_setup_response_client error";
1676 break;
1677 }
1678 }
1679 if (got_response) break;
1680 ++retries;
1681 }
1682
1683 {
1684 std::lock_guard<std::mutex> lk(setup_complete_mu_);
1685 setup_complete_ = true;
1686 setup_succeeded_ = got_response;
1687 }
1688 setup_complete_cv_.notify_all();
1689
1690 E3_LOG_INFO(LOG_TAG) << "Setup loop (dApp) finished, success="
1691 << (got_response ? "yes" : "no");
1692
1693 // Nothing answered, or the RAN refused: try again, as for a RAN that left.
1694 if (!should_stop_.load() && !dapp_id().has_value()) {
1695 request_reconnect();
1696 }
1697}
1698
1699void E3Interface::inbound_loop_dapp() {
1700 apply_thread_config(config_.io_thread_affinity, config_.io_thread_niceness, LATREC_ROLE_INBOUND);
1701 E3_LOG_INFO(LOG_TAG) << "Inbound loop (dApp) started";
1702
1703 ErrorCode result = connector_->setup_inbound_connection_client();
1704 if (result != ErrorCode::SUCCESS) {
1705 E3_LOG_ERROR(LOG_TAG) << "Failed to setup inbound (dApp) connection: "
1706 << error_code_to_string(result);
1707 // A RAN that left before this thread connected is gone like any other.
1708 if (!should_stop_.load()) on_ran_gone(DisconnectReason::CONNECTION_LOST);
1709 return;
1710 }
1711
1712 std::vector<uint8_t> buffer;
1713 while (!should_stop_.load()) {
1714 int ret = connector_->receive(buffer);
1715 if (ret <= 0) {
1716 if (should_stop_.load()) break;
1717 if (ret < 0) {
1718 // 0 is a timeout; a negative is a closed peer or a failed link.
1719 on_ran_gone(DisconnectReason::CONNECTION_LOST);
1720 break;
1721 }
1722 continue;
1723 }
1724 const uint64_t seq = latrec_seq_next();
1725 latrec_tstamp(seq, LATREC_RECV, static_cast<uint64_t>(ret), 0);
1726 auto decoded = encoder_->decode(buffer.data(), static_cast<size_t>(ret));
1727 if (!decoded) {
1728 E3_LOG_ERROR(LOG_TAG) << "Failed to decode PDU in dApp inbound";
1730 continue;
1731 }
1732 Pdu& pdu = *decoded;
1733 latrec_tstamp(seq, LATREC_DECODE_E3AP_DONE, pdu.message_id, static_cast<uint64_t>(pdu.type));
1734 switch (pdu.type) {
1735 case PduType::SUBSCRIPTION_RESPONSE: {
1736 auto* r = std::get_if<SubscriptionResponse>(&pdu.choice);
1737 if (r) handle_subscription_response(*r);
1738 break;
1739 }
1740 case PduType::INDICATION_MESSAGE: {
1741 auto* m = std::get_if<IndicationMessage>(&pdu.choice);
1742 if (m) handle_indication(*m, seq);
1743 break;
1744 }
1745 case PduType::XAPP_CONTROL_ACTION: {
1746 auto* a = std::get_if<XAppControlAction>(&pdu.choice);
1747 if (a) {
1748 a->message_id = pdu.message_id;
1749 handle_xapp_control_action(*a, seq);
1750 }
1751 break;
1752 }
1753 case PduType::MESSAGE_ACK: { // DEPRECATED TO BE REMOVED
1754 auto* a = std::get_if<MessageAck>(&pdu.choice);
1755 if (a) handle_message_ack(*a);
1756 break;
1757 }
1758 case PduType::CONTROL_RESPONSE: {
1759 auto* r = std::get_if<ControlResponse>(&pdu.choice);
1760 if (r) handle_control_response_from_ran(*r, seq);
1761 break;
1762 }
1763 case PduType::RELEASE_MESSAGE: {
1764 auto* r = std::get_if<ReleaseMessage>(&pdu.choice);
1765 if (r) handle_release_from_ran(*r);
1766 break;
1767 }
1768 default:
1769 E3_LOG_WARN(LOG_TAG) << "dApp received unexpected PDU type: "
1770 << pdu_type_to_string(pdu.type);
1772 break;
1773 }
1774 }
1775
1776 E3_LOG_INFO(LOG_TAG) << "Inbound loop (dApp) stopped";
1777}
1778
1779void E3Interface::outbound_loop_dapp() {
1780 apply_thread_config(config_.io_thread_affinity, config_.io_thread_niceness, LATREC_ROLE_OUTBOUND);
1781 E3_LOG_INFO(LOG_TAG) << "Outbound loop (dApp) started";
1782
1783 signal(SIGPIPE, SIG_IGN);
1784
1785 ErrorCode result = connector_->setup_outbound_connection_client();
1786 if (result != ErrorCode::SUCCESS) {
1787 E3_LOG_ERROR(LOG_TAG) << "Failed to setup outbound (dApp) connection: "
1788 << error_code_to_string(result);
1789 if (!should_stop_.load()) on_ran_gone(DisconnectReason::CONNECTION_LOST);
1790 return;
1791 }
1792
1793 while (!should_stop_.load()) {
1794 auto pdu_opt = response_queue_->pop(std::chrono::milliseconds(10));
1795 if (!pdu_opt) continue;
1796 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_DEQUEUE, 0, static_cast<uint64_t>(pdu_opt->type));
1797
1798 auto enc = encoder_->encode(*pdu_opt);
1799 if (!enc) {
1800 E3_LOG_ERROR(LOG_TAG) << "Failed to encode dApp outbound PDU";
1801 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_DROP, 0, LATREC_DROP_ENCODE);
1802 continue;
1803 }
1804 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_ENCODE_E3AP_DONE, enc->buffer.size(), 0);
1805 latrec_ctx_set(pdu_opt->enqueue_seq); // for the connector's LC stamps
1806 ErrorCode rc = connector_->send(enc->buffer);
1807 if (rc != ErrorCode::SUCCESS) {
1808 E3_LOG_ERROR(LOG_TAG) << "Failed to send dApp outbound PDU";
1809 const uint64_t reason = (rc == ErrorCode::CANCELLED)
1811 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_DROP, 0, reason);
1812 } else {
1813 E3_LOG_DEBUG(LOG_TAG) << "Sent dApp outbound PDU: "
1814 << pdu_type_to_string(pdu_opt->type);
1815 latrec_tstamp(pdu_opt->enqueue_seq, LATREC_SEND_DONE, pdu_opt->message_id, 0);
1816 }
1817 }
1818
1819 E3_LOG_INFO(LOG_TAG) << "Outbound loop (dApp) stopped";
1820}
1821
1822// ===========================================================================
1823// dApp-role message handlers
1824// ===========================================================================
1825
1826void E3Interface::on_ran_gone(DisconnectReason reason) {
1827 if (!dapp_state_ || ran_gone_.exchange(true)) return;
1828 E3_LOG_WARN(LOG_TAG) << "RAN is gone ("
1829 << (reason == DisconnectReason::RELEASED_BY_RAN
1830 ? "released by RAN" : "connection lost") << ")";
1831 dapp_state_->clear_session();
1832 {
1833 std::lock_guard<std::mutex> lk(pending_subscriptions_mutex_);
1834 pending_subscriptions_.clear();
1835 }
1836 {
1837 std::lock_guard<std::mutex> lk(setup_complete_mu_);
1838 setup_succeeded_ = false;
1839 }
1840 // The application asked for this end when it released, so it needs no event.
1841 if (release_sent_.load()) return;
1842 if (disconnect_handler_) {
1843 disconnect_handler_(reason);
1844 }
1845 request_reconnect();
1846}
1847
1848void E3Interface::handle_release_from_ran(const ReleaseMessage& release) {
1849 // The RAN's PUB reaches every dApp, so a release for another dApp is not ours.
1850 {
1851 std::lock_guard<std::mutex> lk(dapp_state_->mu);
1852 if (!dapp_state_->assigned_dapp_id.has_value() ||
1853 *dapp_state_->assigned_dapp_id != release.dapp_identifier) {
1854 return;
1855 }
1856 }
1857 E3_LOG_INFO(LOG_TAG) << "RAN released dApp " << release.dapp_identifier;
1858 on_ran_gone(DisconnectReason::RELEASED_BY_RAN);
1859}
1860
1861void E3Interface::handle_setup_response(const SetupResponse& resp) {
1862 E3_LOG_INFO(LOG_TAG) << "Handling SetupResponse rc="
1863 << response_code_to_string(resp.response_code) << reason_suffix(resp);
1864 if (dapp_state_ && resp.response_code == ResponseCode::POSITIVE) {
1865 uint32_t dapp_id = resp.dapp_identifier.value_or(0);
1866 dapp_state_->record_setup_response(dapp_id, resp.ran_function_list);
1867 }
1868 if (setup_response_handler_) {
1869 setup_response_handler_(resp);
1870 }
1871}
1872
1873void E3Interface::handle_subscription_response(const SubscriptionResponse& resp) {
1874 latrec_tstamp(resp.request_id, LATREC_SUB_BEGIN, 0, 0);
1875 if (dapp_state_) {
1876 std::lock_guard<std::mutex> lk(dapp_state_->mu);
1877 if (!dapp_state_->assigned_dapp_id.has_value() ||
1878 *dapp_state_->assigned_dapp_id != resp.dapp_identifier) {
1879 return; // not for us
1880 }
1881 }
1882 E3_LOG_INFO(LOG_TAG) << "Handling SubscriptionResponse for request "
1883 << resp.request_id << " rc="
1884 << response_code_to_string(resp.response_code) << reason_suffix(resp);
1885 // Attribute the response to the request that caused it. The RAN function id
1886 // is optional on the wire, so it comes from the pending-op record keyed by
1887 // the id we sent.
1888 std::optional<PendingSubscriptionOp> pending;
1889 {
1890 std::lock_guard<std::mutex> lk(pending_subscriptions_mutex_);
1891 auto it = pending_subscriptions_.find(resp.request_id);
1892 if (it != pending_subscriptions_.end()) {
1893 pending = it->second;
1894 pending_subscriptions_.erase(it);
1895 }
1896 }
1897 if (dapp_state_ && pending && resp.response_code == ResponseCode::POSITIVE) {
1898 // Not under dapp_state_->mu: these helpers take it themselves.
1899 if (pending->is_delete) {
1900 dapp_state_->remove_subscription_by_rf(pending->ran_function_id);
1901 E3_LOG_INFO(LOG_TAG) << "Subscription to RAN function "
1902 << pending->ran_function_id << " released";
1903 } else if (resp.subscription_id.has_value()) {
1904 // The RAN started its clock before it sent this response, so a clock
1905 // started now ends later than the RAN's. A dApp that renews the
1906 // moment its own deadline passes then always reaches the RAN after
1907 // the old subscription is gone.
1908 std::optional<std::chrono::steady_clock::time_point> expires_at;
1909 if (pending->subscription_time_s && *pending->subscription_time_s > 0) {
1910 expires_at = std::chrono::steady_clock::now() +
1911 std::chrono::seconds(*pending->subscription_time_s);
1912 }
1913 dapp_state_->record_subscription(pending->ran_function_id,
1914 *resp.subscription_id,
1915 expires_at);
1916 E3_LOG_INFO(LOG_TAG) << "Subscription " << *resp.subscription_id
1917 << " granted for RAN function "
1918 << pending->ran_function_id;
1919 }
1920 }
1921 if (subscription_response_handler_) {
1922 subscription_response_handler_(resp);
1923 }
1924}
1925
1926void E3Interface::handle_indication(const IndicationMessage& msg, uint64_t latrec_seq) {
1927 // ZMQ PUB broadcasts to every connected SUB, so a dApp instance will
1928 // receive indications addressed to other dApps connected to the same RAN.
1929 // Filter: an indication is only for us if its dApp identifier matches
1930 // the one the RAN assigned us during setup.
1931 if (dapp_state_) {
1932 std::lock_guard<std::mutex> lk(dapp_state_->mu);
1933 if (!dapp_state_->assigned_dapp_id.has_value() ||
1934 *dapp_state_->assigned_dapp_id != msg.dapp_identifier) {
1936 return; // not for us
1937 }
1938 }
1939 latrec_tstamp(latrec_seq, LATREC_DELIVER_BEGIN, 0, 0);
1940 // The application's own stages key on this: it is handed the message, not
1941 // the seq, so publish it the way the outbound direction already does for
1942 // EMIT_ENTER. Without this a dApp's A9..A12 can only be paired with this
1943 // leg positionally, on the strength of sharing a thread.
1944 latrec_ctx_set(latrec_seq);
1945 if (indication_handler_) {
1946 indication_handler_(msg);
1947 }
1948 latrec_tstamp(latrec_seq, LATREC_DELIVER_DONE, 0, 0);
1949}
1950
1951void E3Interface::handle_xapp_control_action(const XAppControlAction& action,
1952 uint64_t latrec_seq) {
1953 if (dapp_state_) {
1954 std::lock_guard<std::mutex> lk(dapp_state_->mu);
1955 if (!dapp_state_->assigned_dapp_id.has_value() ||
1956 *dapp_state_->assigned_dapp_id != action.dapp_identifier) {
1958 return;
1959 }
1960 }
1961 // aux carries the loop's sequenceId. The ring's own seq stays the inbound
1962 // counter (the ctx_set bridge below depends on it), so this is what lets a
1963 // reader join this dApp-side leg to the RAN's BRIDGE_IN/OUT records for the
1964 // same procedure -- the two rings share no counter, only this id.
1965 latrec_tstamp(latrec_seq, LATREC_DELIVER_BEGIN, action.sequence_id, 0);
1966 latrec_ctx_set(latrec_seq);
1967 if (xapp_control_handler_) {
1968 xapp_control_handler_(action);
1969 } else if (action.request_ack) {
1970 // The control asked for an answer and nothing here acts on it. The control
1971 // names no control identifier, so use the first the RAN function advertises.
1972 uint32_t control_id = 1;
1973 for (const auto& fn : remote_ran_functions()) {
1974 if (fn.ran_function_identifier == action.ran_function_identifier &&
1975 !fn.control_identifier_list.empty()) {
1976 control_id = fn.control_identifier_list.front();
1977 }
1978 }
1979 ControlResult refused;
1980 refused.response_code = ResponseCode::NEGATIVE;
1981 refused.cause = Cause::UNSUPPORTED_RAN_FUNCTION;
1982 refused.detail = "this dApp does not act on xApp controls";
1983 queue_control_response(action.message_id, action.ran_function_identifier, control_id, refused);
1984 }
1985 latrec_tstamp(latrec_seq, LATREC_DELIVER_DONE, action.sequence_id, 0);
1986}
1987
1988// DEPRECATED TO BE REMOVED. libe3 sends no MessageAck; another RAN may, and the
1989// handler hears it. It names no dApp, so on a link that broadcasts every dApp hears it.
1990void E3Interface::handle_message_ack(const MessageAck& ack) {
1991 if (ack.response_code == ResponseCode::NEGATIVE) {
1992 E3_LOG_WARN(LOG_TAG) << "MessageAck for request " << ack.request_id << " is negative"
1993 << reason_suffix(ack);
1994 }
1995 latrec_tstamp(ack.request_id, LATREC_ACK_RECV,
1996 static_cast<uint64_t>(ack.response_code), 0);
1997 if (message_ack_handler_) {
1998 message_ack_handler_(ack);
1999 }
2000}
2001
2002void E3Interface::handle_control_response_from_ran(const ControlResponse& resp, uint64_t latrec_seq) {
2003 // A ControlResponse names its dApp, so on a link that broadcasts a dApp reads
2004 // only the ones that are its own.
2005 if (dapp_state_) {
2006 std::lock_guard<std::mutex> lk(dapp_state_->mu);
2007 if (!dapp_state_->assigned_dapp_id.has_value() ||
2008 *dapp_state_->assigned_dapp_id != resp.dapp_identifier) {
2010 return;
2011 }
2012 }
2013 if (resp.response_code == ResponseCode::NEGATIVE) {
2014 E3_LOG_WARN(LOG_TAG) << "ControlResponse for request " << resp.request_id << " is negative"
2015 << reason_suffix(resp);
2016 }
2017 // Closes the acknowledgment tail. Keyed on the answered control's id,
2018 // matching the LATREC_ACK_SENT the RAN-side Service Model stamps, so the
2019 // leg joins on a libe3 build the way it already did on backends that
2020 // stamped this themselves.
2021 latrec_tstamp(resp.request_id, LATREC_ACK_RECV,
2022 static_cast<uint64_t>(resp.response_code), 0);
2023 if (control_response_handler_) {
2024 control_response_handler_(resp);
2025 }
2026}
2027
2028void E3Interface::handle_control_response_from_dapp(const ControlResponse& resp) {
2029 if (!subscription_manager_->is_dapp_registered(resp.dapp_identifier)) {
2030 E3_LOG_WARN(LOG_TAG) << "Dropping ControlResponse of unregistered dApp " << resp.dapp_identifier;
2031 return;
2032 }
2033 if (resp.response_code == ResponseCode::NEGATIVE) {
2034 E3_LOG_WARN(LOG_TAG) << "ControlResponse of dApp " << resp.dapp_identifier << " for request "
2035 << resp.request_id << " is negative" << reason_suffix(resp);
2036 }
2037 if (control_response_handler_) {
2038 control_response_handler_(resp);
2039 }
2040}
2041
2042// ===========================================================================
2043// dApp-role accessors and outbound helpers
2044// ===========================================================================
2045
2046std::optional<uint32_t> E3Interface::dapp_id() const noexcept {
2047 if (!dapp_state_) return std::nullopt;
2048 std::lock_guard<std::mutex> lk(dapp_state_->mu);
2049 return dapp_state_->assigned_dapp_id;
2050}
2051
2052std::vector<uint32_t> E3Interface::active_subscription_ids() const {
2053 if (!dapp_state_) return {};
2054 return dapp_state_->active_subscriptions();
2055}
2056
2057std::vector<uint32_t> E3Interface::subscribed_ran_functions() const {
2058 if (!dapp_state_) return {};
2059 return dapp_state_->subscribed_ran_functions();
2060}
2061
2062std::vector<RanFunctionDef> E3Interface::remote_ran_functions() const {
2063 if (!dapp_state_) return {};
2064 std::lock_guard<std::mutex> lk(dapp_state_->mu);
2065 return dapp_state_->remote_ran_functions;
2066}
2067
2069 uint32_t ran_function_id,
2070 std::vector<uint32_t> telemetry_ids,
2071 std::vector<uint32_t> control_ids,
2072 std::optional<uint32_t> sub_time,
2073 std::optional<uint32_t> periodicity,
2074 uint32_t* out_request_id
2075) {
2076 if (!dapp_state_) return ErrorCode::STATE_ERROR;
2077 auto id = dapp_id();
2078 if (!id) return ErrorCode::NOT_INITIALIZED;
2079
2082 req.dapp_identifier = *id;
2083 req.ran_function_identifier = ran_function_id;
2084 req.telemetry_identifier_list = std::move(telemetry_ids);
2085 req.control_identifier_list = std::move(control_ids);
2086 req.subscription_time = sub_time;
2087 req.periodicity = periodicity;
2088 pdu.choice = std::move(req);
2089 const uint32_t mid = generate_message_id();
2090 pdu.message_id = mid;
2091 // Recorded before the send, not after: the response can only be attributed
2092 // to a RAN function through this entry, and the inbound thread may see it
2093 // before this call returns.
2094 remember_subscription_op(mid, ran_function_id, /*is_delete=*/false, sub_time);
2095 ErrorCode rc = queue_outbound(std::move(pdu));
2096 if (rc != ErrorCode::SUCCESS) {
2097 forget_subscription_op(mid);
2098 return rc;
2099 }
2100 if (out_request_id) {
2101 *out_request_id = mid;
2102 }
2103 return rc;
2104}
2105
2107 if (!dapp_state_) return ErrorCode::STATE_ERROR;
2108 auto id = dapp_id();
2109 if (!id) return ErrorCode::NOT_INITIALIZED;
2110 auto sub_id = dapp_state_->subscription_id_for(ran_function_id);
2111 if (!sub_id) return ErrorCode::SUBSCRIPTION_NOT_FOUND;
2112
2115 del.dapp_identifier = *id;
2116 del.subscription_id = *sub_id;
2117 pdu.choice = del;
2118 const uint32_t mid = generate_message_id();
2119 pdu.message_id = mid;
2120 // The RAN answers a delete with a SubscriptionResponse too, so both
2121 // directions land in handle_subscription_response and are told apart here.
2122 remember_subscription_op(mid, ran_function_id, /*is_delete=*/true);
2123 ErrorCode rc = queue_outbound(std::move(pdu));
2124 if (rc != ErrorCode::SUCCESS) {
2125 forget_subscription_op(mid);
2126 }
2127 return rc;
2128}
2129
2131 uint32_t ran_function_id,
2132 uint32_t control_id,
2133 std::vector<uint8_t> action_data,
2134 uint32_t sequence_id,
2135 uint32_t* out_message_id,
2136 bool request_ack
2137) {
2138 if (!dapp_state_) return ErrorCode::STATE_ERROR;
2139 auto id = dapp_id();
2140 if (!id) return ErrorCode::NOT_INITIALIZED;
2141
2144 a.dapp_identifier = *id;
2145 a.ran_function_identifier = ran_function_id;
2146 a.control_identifier = control_id;
2147 a.sequence_id = sequence_id;
2148 a.request_ack = request_ack;
2149 a.action_data = std::move(action_data);
2150 pdu.choice = std::move(a);
2151 const uint32_t mid = generate_message_id();
2152 pdu.message_id = mid;
2153 // Mirrors E3Agent::send_indication: this is an emit path, so it stamps
2154 // EMIT_ENTER itself rather than leaving it to queue_outbound, which only
2155 // allocates enqueue_seq for a Pdu that arrives with none.
2157 latrec_tstamp(pdu.enqueue_seq, LATREC_EMIT_ENTER, latrec_ctx(), ran_function_id);
2158 ErrorCode rc = queue_outbound(std::move(pdu));
2159 if (rc == ErrorCode::SUCCESS && out_message_id) {
2160 *out_message_id = mid;
2161 }
2162 return rc;
2163}
2164
2166 uint32_t request_id,
2167 uint32_t ran_function_id,
2168 uint32_t control_id,
2169 const ControlResult& result
2170) {
2171 if (!dapp_state_) return ErrorCode::STATE_ERROR;
2172 auto id = dapp_id();
2173 if (!id) return ErrorCode::NOT_INITIALIZED;
2174 if (result.outcome.size() > MAX_CONTROL_OUTCOME_SIZE) return ErrorCode::INVALID_PARAM;
2175
2177 ControlResponse resp;
2178 resp.request_id = sanitize_request_message_id(request_id);
2179 resp.dapp_identifier = *id;
2180 resp.ran_function_identifier = ran_function_id;
2181 resp.control_identifier = control_id;
2182 resp.response_code = result.response_code;
2183 resp.cause = result.cause;
2184 resp.detail = result.detail;
2185 if (!result.outcome.empty()) resp.control_outcome = result.outcome;
2186 pdu.choice = std::move(resp);
2189 latrec_tstamp(pdu.enqueue_seq, LATREC_EMIT_ENTER, latrec_ctx(), ran_function_id);
2190 return queue_outbound(std::move(pdu));
2191}
2192
2194 uint32_t ran_function_id,
2195 std::vector<uint8_t> report_data,
2196 uint32_t sequence_id,
2197 uint32_t* out_message_id
2198) {
2199 // E3-SequenceID is 1..4294967295 and mandatory on a report: with 0 every
2200 // encode fails, so refuse it here where the caller sees it.
2201 if (sequence_id == 0) {
2202 E3_LOG_ERROR(LOG_TAG) << "dApp report refused: sequence_id must be non-zero (E3-SequenceID is 1..4294967295)";
2203 return ErrorCode::INVALID_PARAM;
2204 }
2205
2206 if (!dapp_state_) return ErrorCode::STATE_ERROR;
2207 auto id = dapp_id();
2208 if (!id) return ErrorCode::NOT_INITIALIZED;
2209
2211 DAppReport r;
2212 r.dapp_identifier = *id;
2213 r.ran_function_identifier = ran_function_id;
2214 r.sequence_id = sequence_id;
2215 r.report_data = std::move(report_data);
2216 pdu.choice = std::move(r);
2217 const uint32_t mid = generate_message_id();
2218 pdu.message_id = mid;
2219 ErrorCode rc = queue_outbound(std::move(pdu));
2220 if (rc == ErrorCode::SUCCESS && out_message_id) {
2221 *out_message_id = mid;
2222 }
2223 return rc;
2224}
2225
2227 if (!dapp_state_) return ErrorCode::STATE_ERROR;
2228 auto id = dapp_id();
2229 if (!id) return ErrorCode::NOT_INITIALIZED;
2230
2232 ReleaseMessage rel;
2233 rel.dapp_identifier = *id;
2234 pdu.choice = rel;
2236 release_sent_.store(true);
2237 ErrorCode rc = queue_outbound(std::move(pdu));
2238 if (rc != ErrorCode::SUCCESS) release_sent_.store(false);
2239 return rc;
2240}
2241
2242ErrorCode E3Interface::wait_for_setup(std::chrono::milliseconds timeout) {
2243 if (config_.role != E3Role::DAPP) return ErrorCode::INVALID_PARAM;
2244 std::unique_lock<std::mutex> lk(setup_complete_mu_);
2245 if (!setup_complete_cv_.wait_for(lk, timeout, [this]() { return setup_complete_; })) {
2246 return ErrorCode::TIMEOUT;
2247 }
2248 return setup_succeeded_ ? ErrorCode::SUCCESS : ErrorCode::CONNECTION_FAILED;
2249}
2250
2251void E3Interface::on_sm_lifecycle_change(uint32_t ran_function_id, bool should_start) {
2252 if (should_start) {
2253 ErrorCode result = SmRegistry::instance().start_sm(ran_function_id);
2254 if (result != ErrorCode::SUCCESS) {
2255 E3_LOG_ERROR(LOG_TAG) << "Failed to start SM for RAN function "
2256 << ran_function_id << ": " << error_code_to_string(result);
2257 }
2258 } else {
2259 ErrorCode result = SmRegistry::instance().stop_sm(ran_function_id);
2260 if (result != ErrorCode::SUCCESS) {
2261 E3_LOG_WARN(LOG_TAG) << "Failed to stop SM for RAN function "
2262 << ran_function_id << ": " << error_code_to_string(result);
2263 }
2264 }
2265}
2266
2267} // namespace libe3
ErrorCode queue_dapp_report(uint32_t ran_function_id, std::vector< uint8_t > report_data, uint32_t sequence_id, uint32_t *out_message_id=nullptr)
void notify_dapp_status_changed()
Tell the status handler that a dApp connected, subscribed, unsubscribed or left.
ErrorCode init()
Initialize the interface.
std::vector< uint32_t > subscribed_ran_functions() const
ErrorCode respond_to_control(uint32_t dapp_id, uint32_t request_id, const ControlResult &result)
ErrorCode queue_control_response(uint32_t request_id, uint32_t ran_function_id, uint32_t control_id, const ControlResult &result)
ErrorCode queue_outbound(Pdu pdu)
Queue a PDU for outbound transmission.
ErrorCode queue_subscription_delete(uint32_t ran_function_id)
~E3Interface()
Destructor - ensures clean shutdown.
ErrorCode queue_subscription_request(uint32_t ran_function_id, std::vector< uint32_t > telemetry_ids, std::vector< uint32_t > control_ids, std::optional< uint32_t > sub_time=std::nullopt, std::optional< uint32_t > periodicity=std::nullopt, uint32_t *out_request_id=nullptr)
Queue a SubscriptionRequest for the outbound loop to send.
std::vector< uint32_t > get_available_ran_functions() const
Get available RAN functions.
uint32_t generate_message_id()
Generate the next message ID, monotonic within 1..4294967295.
ErrorCode start()
Start the interface processing loops.
ErrorCode wait_for_setup(std::chrono::milliseconds timeout)
ErrorCode queue_release_message()
E3Interface(const E3Config &config)
Construct with configuration.
void stop()
Stop the interface.
std::vector< uint32_t > active_subscription_ids() const
ErrorCode queue_dapp_control_action(uint32_t ran_function_id, uint32_t control_id, std::vector< uint8_t > action_data, uint32_t sequence_id=0, uint32_t *out_message_id=nullptr, bool request_ack=false)
std::vector< RanFunctionDef > remote_ran_functions() const
std::optional< uint32_t > dapp_id() const noexcept
uint32_t sanitize_request_message_id(uint32_t request_id)
Return a request id that can be echoed into a response.
ErrorCode register_sm(std::unique_ptr< ServiceModel > sm)
Register a Service Model.
static Logger & instance()
Get the singleton logger instance.
Definition logger.hpp:60
void set_level(LogLevel level) noexcept
Set the log level.
Definition logger.hpp:68
static SmRegistry & instance()
Get the singleton instance.
E3Interface - Internal protocol coordination layer.
Lock-free per-thread latency stamp recorder (header-only, C99).
static void latrec_tstamp(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2)
Definition latrec.h:720
static uint64_t latrec_tnow(void)
Definition latrec.h:713
static void latrec_ctx_set(uint64_t seq)
Definition latrec.h:742
static void latrec_tstamp_at(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2, uint64_t t_ns)
Definition latrec.h:702
static uint64_t latrec_ctx(void)
Definition latrec.h:751
@ LATREC_DROP_SHUTDOWN
Definition latrec.h:394
@ LATREC_DROP_FILTERED
Definition latrec.h:386
@ LATREC_DROP_DECODE
Definition latrec.h:382
@ LATREC_DROP_ENCODE
Definition latrec.h:380
@ LATREC_DROP_REPORT_QUEUE
Definition latrec.h:383
@ LATREC_DROP_QUEUE_PUSH
Definition latrec.h:379
@ LATREC_DROP_SEND
Definition latrec.h:381
@ LATREC_DROP_NO_HANDLER
Definition latrec.h:384
@ LATREC_SUB_BEGIN
Definition latrec.h:253
@ LATREC_EMIT_ENTER
Definition latrec.h:199
@ LATREC_DEQUEUE
Definition latrec.h:208
@ LATREC_ACK_RECV
Definition latrec.h:302
@ LATREC_SETUP_BEGIN
Definition latrec.h:246
@ LATREC_CONTEXT
Definition latrec.h:348
@ LATREC_ENCODE_E3AP_DONE
Definition latrec.h:210
@ LATREC_RECV
Definition latrec.h:218
@ LATREC_DECODE_E3AP_DONE
Definition latrec.h:219
@ LATREC_REPORT_QUEUED
Definition latrec.h:229
@ LATREC_DELIVER_BEGIN
Definition latrec.h:221
@ LATREC_SETUP_DONE
Definition latrec.h:248
@ LATREC_SEND_DONE
Definition latrec.h:211
@ LATREC_SUB_DONE
Definition latrec.h:254
@ LATREC_REPORT_DONE
Definition latrec.h:231
@ LATREC_ENQUEUE
Definition latrec.h:206
@ LATREC_DELIVER_DONE
Definition latrec.h:227
@ LATREC_DROP
Definition latrec.h:237
uint64_t latrec_seq_next(void)
Definition latrec.c:164
latrec_t * latrec_tls_open_as(const char *role)
Definition latrec.c:122
Logging facility for libe3.
#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
std::unique_ptr< E3Connector > create_connector(E3LinkLayer link_layer, 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=2, E3Role role=E3Role::RAN, const PosixOptions &posix=PosixOptions{})
Factory function to create appropriate connector.
ErrorCode
Error codes returned by libe3 operations Use shared error-code list (see libe3/error_codes....
Definition types.hpp:177
const char * cause_to_string(Cause cause) noexcept
Convert Cause to the name E3AP gives it in JSON and in logs.
Definition types.hpp:751
AgentState
Agent state machine states.
Definition types.hpp:162
@ CONNECTING
Connection in progress.
Definition types.hpp:165
@ UNINITIALIZED
Agent not yet initialized.
Definition types.hpp:163
@ INITIALIZED
Agent initialized but not connected.
Definition types.hpp:164
@ STOPPING
Shutdown in progress.
Definition types.hpp:168
std::unique_ptr< E3Encoder > create_encoder(EncodingFormat format)
Factory function to create appropriate encoder.
E3Role
Role this E3 endpoint plays in the protocol.
Definition types.hpp:77
@ RAN
RAN function (binds sockets; today's only behaviour).
Definition types.hpp:78
@ DAPP
dApp (connects to a RAN agent)
Definition types.hpp:79
ResponseCode
E3AP response codes.
Definition types.hpp:103
constexpr size_t MAX_PROTOCOL_DATA_SIZE
Largest protocolData of an indication, in bytes.
Definition types.hpp:200
const char * pdu_type_to_string(PduType type) noexcept
Convert PduType to string representation.
Definition types.hpp:701
@ SUBSCRIPTION_DELETE
Definition types.hpp:148
@ SUBSCRIPTION_REQUEST
Definition types.hpp:147
@ DAPP_CONTROL_ACTION
Definition types.hpp:151
const char * agent_state_to_string(AgentState state) noexcept
Convert AgentState to string representation.
Definition types.hpp:832
@ ASN1
ASN.1 PER encoding (standard O-RAN format).
Definition types.hpp:54
const char * role_to_string(E3Role role) noexcept
Convert E3Role to string representation.
Definition types.hpp:851
PduClass
What a PDU is for, so that a link that has streams can pick one.
const char * response_code_to_string(ResponseCode code) noexcept
Convert ResponseCode to string representation.
Definition types.hpp:738
constexpr size_t MAX_RAN_FUNCTIONS
ranFunctionList SIZE (0..64)
Definition types.hpp:206
Cause
Why a RAN refused a request (E3-Cause).
Definition types.hpp:115
constexpr size_t MAX_CONTROL_OUTCOME_SIZE
Largest controlOutcome of a control response, in bytes.
Definition types.hpp:205
const char * error_code_to_string(ErrorCode code) noexcept
Convert ErrorCode to string representation.
Definition types.hpp:800
constexpr size_t MAX_IDENTIFIER_LIST_SIZE
telemetry and control lists SIZE (0..256)
Definition types.hpp:207
E3AP Control Response structure.
Definition types.hpp:366
uint32_t request_id
Message id of the control this answers.
Definition types.hpp:367
uint32_t control_identifier
Control the answer is about.
Definition types.hpp:370
std::optional< Cause > cause
Why the control was refused (negative only).
Definition types.hpp:372
ResponseCode response_code
Response code (positive/negative).
Definition types.hpp:371
uint32_t ran_function_identifier
RAN function of the control.
Definition types.hpp:369
uint32_t dapp_identifier
dApp the control belongs to
Definition types.hpp:368
std::optional< std::string > detail
Definition types.hpp:373
std::optional< std::vector< uint8_t > > control_outcome
Definition types.hpp:376
What a Service Model answers to a control (see ServiceModel::respond_to_control).
Definition types.hpp:382
ResponseCode response_code
Whether the control was applied.
Definition types.hpp:383
std::optional< std::string > detail
UTF-8 text for the cause, up to MAX_DETAIL_SIZE bytes.
Definition types.hpp:385
std::optional< Cause > cause
Why not (negative only).
Definition types.hpp:384
std::vector< uint8_t > outcome
Opaque service-model content; empty for none.
Definition types.hpp:386
E3AP dApp Control Action structure.
Definition types.hpp:332
uint32_t ran_function_identifier
RAN function the control is for.
Definition types.hpp:334
std::vector< uint8_t > action_data
Definition types.hpp:336
uint32_t dapp_identifier
dApp that sends the control
Definition types.hpp:333
uint32_t control_identifier
Control identifier.
Definition types.hpp:335
E3AP dApp Report structure.
Definition types.hpp:392
uint32_t dapp_identifier
dApp that sends the report
Definition types.hpp:393
uint32_t sequence_id
Definition types.hpp:398
std::vector< uint8_t > report_data
Definition types.hpp:395
uint32_t ran_function_identifier
RAN function the report is for.
Definition types.hpp:394
Configuration for E3Agent.
Definition types.hpp:506
int log_level
Logging verbosity: 0=none, 1=error, 2=warn, 3=info, 4=debug, 5=trace.
Definition types.hpp:655
Generic E3AP PDU structure.
Definition types.hpp:448
uint64_t enqueue_seq
Set by queue_outbound; keys the [latrec] L-stage records.
Definition types.hpp:452
PduType type
Which alternative of choice is set.
Definition types.hpp:449
PduChoice choice
The message itself.
Definition types.hpp:450
uint32_t message_id
Unique message identifier.
Definition types.hpp:451
Socket and admission options of the POSIX link.
E3AP Release Message structure.
Definition types.hpp:423
uint32_t dapp_identifier
dApp identifier
Definition types.hpp:424
E3AP Subscription Delete structure.
Definition types.hpp:299
uint32_t dapp_identifier
dApp identifier
Definition types.hpp:300
uint32_t subscription_id
Subscription ID to delete.
Definition types.hpp:301
E3AP Subscription Request structure.
Definition types.hpp:287
std::optional< uint32_t > periodicity
Microseconds between indications, 0 = every event (ASN.1: 0 to 60000000).
Definition types.hpp:293
std::optional< uint32_t > subscription_time
How long to keep the subscription (0-86400 sec).
Definition types.hpp:292
uint32_t ran_function_identifier
RAN function to subscribe to.
Definition types.hpp:289
std::vector< uint32_t > control_identifier_list
List of control identifiers.
Definition types.hpp:291
std::vector< uint32_t > telemetry_identifier_list
List of telemetry identifiers.
Definition types.hpp:290
uint32_t dapp_identifier
dApp identifier
Definition types.hpp:288