27#include <sys/resource.h>
28#include <sys/syscall.h>
35constexpr const char* LOG_TAG =
"E3Iface";
40constexpr auto EXPIRY_SWEEP_INTERVAL = std::chrono::milliseconds(250);
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;
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;
72std::string default_log_path(
E3Role role,
const std::string&
id) {
74 san.reserve(
id.size());
76 san.push_back((std::isalnum(
static_cast<unsigned char>(c)) ||
77 c ==
'.' || c ==
'_' || c ==
'-')
81 std::string path =
"/tmp/e3_";
89 path += std::to_string(
static_cast<unsigned long>(geteuid()));
106void apply_thread_config(
int affinity,
int niceness,
const char* role)
noexcept {
111 CPU_SET(
static_cast<size_t>(affinity), &cpuset);
113 int rc = pthread_setaffinity_np(pthread_self(),
sizeof(cpu_set_t), &cpuset);
115 E3_LOG_WARN(LOG_TAG) <<
"Failed to pin " << role <<
" thread to core "
116 << affinity <<
": " << std::strerror(rc)
117 <<
" (thread left unpinned)";
119 E3_LOG_INFO(LOG_TAG) <<
"Pinned " << role <<
" thread to core " << affinity;
126 auto tid =
static_cast<id_t
>(
static_cast<pid_t
>(syscall(SYS_gettid)));
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);
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";
155constexpr size_t MAX_NAME_BYTES = 64;
156constexpr size_t MAX_VERSION_BYTES = 32;
159constexpr uint32_t MAX_PERIODICITY_US = 60000000;
163std::string name_or_unknown(
const std::string& name) {
164 return name.empty() ?
"unknown" : name;
169bool wire_text_fits(
const char* field,
const std::string& value,
size_t max_bytes,
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;
186 const uint64_t n = next_message_id_.fetch_add(1, std::memory_order_relaxed);
187 return static_cast<uint32_t
>(n % 0xFFFFFFFFull) + 1;
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};
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);
206 if (request_id != 0) {
220 std::string log_path = config.log_path;
221 if (log_path.empty()) {
222 const std::string& id = (config.role == E3Role::DAPP)
224 : config.ran_identifier;
225 log_path = default_log_path(config.role, id);
240 E3_LOG_WARN(LOG_TAG) <<
"Interface already initialized";
241 return ErrorCode::ALREADY_INITIALIZED;
244 E3_LOG_INFO(LOG_TAG) <<
"Initializing E3Interface";
250 return ErrorCode::INTERNAL_ERROR;
255 wire_text_fits(
"e3ap_version", config_.e3ap_version, MAX_VERSION_BYTES,
false) &&
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));
262 return ErrorCode::INVALID_PARAM;
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);
275 dapp_state_ = std::make_unique<DAppSubscriptionState>();
279 response_queue_ = std::make_unique<LockFreeQueue<Pdu>>();
282 report_queue_ = std::make_unique<LockFreeQueue<DAppReport>>(1024);
284 ErrorCode conn_rc = create_connector_from_config();
285 if (conn_rc != ErrorCode::SUCCESS) {
290 E3_LOG_INFO(LOG_TAG) <<
"E3Interface initialized successfully";
292 return ErrorCode::SUCCESS;
295ErrorCode E3Interface::create_connector_from_config() {
298 config_.transport_layer,
299 config_.setup_endpoint,
300 config_.subscriber_endpoint,
301 config_.publisher_endpoint,
303 config_.subscriber_port,
304 config_.publisher_port,
307 PosixOptions{config_.socket_buffer_bytes, config_.sctp_delayed_sack,
308 config_.allowed_peers, config_.maximum_associations}
313 return ErrorCode::INTERNAL_ERROR;
315 return ErrorCode::SUCCESS;
319 std::lock_guard<std::mutex> lifecycle(lifecycle_mu_);
321 std::lock_guard<std::mutex> lk(reconnect_mu_);
322 user_stopped_ =
false;
323 reconnect_pending_ =
false;
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);
338 return ErrorCode::STATE_ERROR;
341 E3_LOG_INFO(LOG_TAG) <<
"Starting E3Interface (role=" << role_to_string(config_.role) <<
")";
342 should_stop_.store(
false);
346 if (started_before_) {
347 ErrorCode conn_rc = create_connector_from_config();
348 if (conn_rc != ErrorCode::SUCCESS) {
349 state_.store(AgentState::ERROR);
352 response_queue_->rearm();
353 report_queue_->rearm();
355 started_before_ =
true;
357 dapp_state_->clear_session();
358 std::lock_guard<std::mutex> lk(pending_subscriptions_mutex_);
359 pending_subscriptions_.clear();
361 ran_gone_.store(
false);
362 release_sent_.store(
false);
364 std::lock_guard<std::mutex> lk(setup_complete_mu_);
365 setup_complete_ =
false;
366 setup_succeeded_ =
false;
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: "
376 state_.store(AgentState::ERROR);
380 state_.store(AgentState::CONNECTED);
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);
389 report_worker_thread_ = std::make_unique<std::thread>(&E3Interface::report_worker_loop,
this);
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);
395 expiry_thread_ = std::make_unique<std::thread>(&E3Interface::subscription_expiry_loop,
this);
397#ifdef LIBE3_ENABLE_LATREC
398 context_thread_ = std::make_unique<std::thread>(&E3Interface::context_monitor_loop,
this);
401 state_.store(AgentState::RUNNING);
402 E3_LOG_INFO(LOG_TAG) <<
"E3Interface started successfully";
404 return ErrorCode::SUCCESS;
412 std::lock_guard<std::mutex> lk(reconnect_mu_);
413 user_stopped_ =
true;
415 reconnect_cv_.notify_all();
416 if (reconnect_thread_ && reconnect_thread_->joinable()) {
417 reconnect_thread_->join();
419 reconnect_thread_.reset();
421 std::lock_guard<std::mutex> lifecycle(lifecycle_mu_);
425void E3Interface::stop_locked() {
432 state_.store(AgentState::STOPPING);
433 should_stop_.store(
true);
436 if (response_queue_) {
437 response_queue_->shutdown();
442 report_queue_->shutdown();
446 std::lock_guard<std::mutex> lk(expiry_mu_);
447 expiry_cv_.notify_all();
452 connector_->shutdown();
456 if (setup_thread_ && setup_thread_->joinable()) {
457 setup_thread_->join();
459 if (inbound_thread_ && inbound_thread_->joinable()) {
460 inbound_thread_->join();
462 if (outbound_thread_ && outbound_thread_->joinable()) {
463 outbound_thread_->join();
465 if (report_worker_thread_ && report_worker_thread_->joinable()) {
466 report_worker_thread_->join();
468 if (expiry_thread_ && expiry_thread_->joinable()) {
469 expiry_thread_->join();
471#ifdef LIBE3_ENABLE_LATREC
472 if (context_thread_ && context_thread_->joinable()) {
473 context_thread_->join();
479 std::lock_guard<std::mutex> lk(setup_complete_mu_);
480 setup_complete_ =
true;
482 setup_complete_cv_.notify_all();
489 if (config_.role == E3Role::RAN) {
490 SmRegistry::instance().clear();
495 connector_->dispose();
498 state_.store(AgentState::INITIALIZED);
503 if (!response_queue_) {
504 return ErrorCode::NOT_INITIALIZED;
516 const ErrorCode rc = response_queue_->push(std::move(pdu));
517 if (rc != ErrorCode::SUCCESS) {
524 const uint64_t reason = (rc == ErrorCode::NOT_INITIALIZED)
537 return ErrorCode::INVALID_PARAM;
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>{};
544 return subscription_manager_->get_subscribed_dapps(ran_function_id);
546 sm->set_outbound_emitter([
this, ran_function_id](
Pdu&& pdu) {
547 if (pdu.message_id == 0) {
564 sm->set_control_responder([
this](uint32_t
dapp_id, uint32_t request_id,
const ControlResult& result) {
571 if (dapp_status_changed_handler_) {
572 dapp_status_changed_handler_();
580void E3Interface::setup_loop_ran() {
583 E3_LOG_INFO(LOG_TAG) <<
"Setup loop (RAN) started";
587 while (!should_stop_.load()) {
588 std::vector<uint8_t> buffer;
589 int ret = connector_->recv_setup_request(buffer);
592 if (should_stop_.load())
break;
596 E3_LOG_INFO(LOG_TAG) <<
"Setup request received: " << ret <<
" bytes";
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);
609 Pdu& pdu = *decode_result;
610 if (pdu.type != PduType::SETUP_REQUEST) {
611 E3_LOG_WARN(LOG_TAG) <<
"Unexpected PDU type in setup: "
613 send_negative_setup_reply(pdu.message_id);
617 auto* request = std::get_if<SetupRequest>(&pdu.choice);
619 E3_LOG_WARN(LOG_TAG) <<
"Failed to get SetupRequest from PDU; rejecting";
620 send_negative_setup_reply(pdu.message_id);
624 handle_setup_request(*request, pdu.message_id);
627 E3_LOG_INFO(LOG_TAG) <<
"Setup loop (RAN) stopped";
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";
634 ErrorCode result = connector_->setup_inbound_connection();
635 if (result != ErrorCode::SUCCESS) {
636 E3_LOG_ERROR(LOG_TAG) <<
"Failed to setup inbound connection";
640 std::vector<uint8_t> buffer;
642 while (!should_stop_.load()) {
643 int ret = connector_->receive(buffer);
646 remove_dapps_of_closed_peers();
649 if (should_stop_.load())
break;
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";
665 Pdu& pdu = *decode_result;
669 if (
const uint32_t sender = dapp_id_of(pdu); sender != 0) {
670 if (!admit_dapp_message(connector_->last_peer_token(), sender)) {
672 <<
" that names dApp " << sender
673 <<
", which belongs to another connection";
677 subscription_manager_->touch_dapp(sender);
681 case PduType::SUBSCRIPTION_REQUEST: {
682 auto* request = std::get_if<SubscriptionRequest>(&pdu.choice);
684 handle_subscription_request(*request, pdu.message_id);
689 case PduType::SUBSCRIPTION_DELETE: {
690 auto* del = std::get_if<SubscriptionDelete>(&pdu.choice);
692 handle_subscription_delete(*del, pdu.message_id);
697 case PduType::DAPP_CONTROL_ACTION: {
698 auto* action = std::get_if<DAppControlAction>(&pdu.choice);
700 handle_control_action(*action, pdu.message_id, seq);
705 case PduType::DAPP_REPORT: {
706 auto* report = std::get_if<DAppReport>(&pdu.choice);
712 report->recv_seq = seq;
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";
726 const uint64_t reason = (report_rc == ErrorCode::NOT_INITIALIZED)
737 case PduType::RELEASE_MESSAGE: {
738 auto* release = std::get_if<ReleaseMessage>(&pdu.choice);
740 handle_release_message(*release);
745 case PduType::CONTROL_RESPONSE: {
746 auto* response = std::get_if<ControlResponse>(&pdu.choice);
748 handle_control_response_from_dapp(*response);
754 E3_LOG_WARN(LOG_TAG) <<
"Received unexpected PDU type: "
761 E3_LOG_INFO(LOG_TAG) <<
"Inbound loop (RAN) stopped";
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";
769 signal(SIGPIPE, SIG_IGN);
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 ("
779 std::this_thread::sleep_for(std::chrono::seconds(1));
780 if (should_stop_.load())
return;
781 result = connector_->setup_outbound_connection();
784 if (result != ErrorCode::SUCCESS) {
785 E3_LOG_ERROR(LOG_TAG) <<
"Failed to setup outbound connection";
788 E3_LOG_INFO(LOG_TAG) <<
"Outbound connection established";
790 while (!should_stop_.load()) {
792 auto pdu_opt = response_queue_->pop(std::chrono::milliseconds(10));
800 auto encode_result = encoder_->encode(*pdu_opt);
801 if (!encode_result) {
802 E3_LOG_ERROR(LOG_TAG) <<
"Failed to encode PDU for sending";
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) {
821 const uint64_t reason = (send_result == ErrorCode::CANCELLED)
830 E3_LOG_INFO(LOG_TAG) <<
"Outbound loop (RAN) stopped";
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";
837 while (!should_stop_.load()) {
840 auto report_opt = report_queue_->pop(std::chrono::milliseconds(10));
842 handle_dapp_report(*report_opt);
848 while (
auto report_opt = report_queue_->try_pop()) {
849 handle_dapp_report(*report_opt);
852 E3_LOG_INFO(LOG_TAG) <<
"Report worker loop stopped";
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()) {
864 if (subscription_manager_) {
865 if (!subscription_manager_->expire_subscriptions().empty()) {
866 notify_dapp_status_changed();
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";
880#ifdef LIBE3_ENABLE_LATREC
881void E3Interface::context_monitor_loop() {
885 long prev_nivcsw = 0;
888 if (getrusage(RUSAGE_SELF, &ru) == 0) {
889 prev_nivcsw = ru.ru_nivcsw;
894 while (!should_stop_.load()) {
895 std::this_thread::sleep_for(std::chrono::seconds(1));
896 if (should_stop_.load()) {
900 uint64_t nivcsw_delta = 0;
901 uint64_t cur_freq_khz = 0;
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;
911 const int cpu = sched_getcpu();
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")) {
918 if (std::fscanf(f,
"%ld", &khz) == 1) {
919 cur_freq_khz =
static_cast<uint64_t
>(khz);
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 =
" (";
943 if (resp.cause && resp.detail) out +=
": ";
944 if (resp.detail) out += *resp.detail;
955uint64_t pending_key(uint32_t dapp_id, uint32_t request_id) {
956 return (
static_cast<uint64_t
>(dapp_id) << 32) | request_id;
959bool contains(
const std::vector<uint32_t>& ids, uint32_t
id) {
960 return std::find(ids.begin(), ids.end(),
id) != ids.end();
968std::optional<Refusal> refusal_for_subscription(
const SubscriptionRequest& request) {
969 ServiceModel* sm = SmRegistry::instance().get_by_ran_function(request.ran_function_identifier);
971 return Refusal{Cause::UNSUPPORTED_RAN_FUNCTION,
972 "RAN function " + std::to_string(request.ran_function_identifier)
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"};
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)};
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)};
1002void E3Interface::handle_setup_request(
const SetupRequest& request, uint32_t request_message_id) {
1003 request_message_id = sanitize_request_message_id(request_message_id);
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 <<
")";
1011 uint32_t assigned_dapp_id = 0;
1012 std::optional<Cause> refusal_cause;
1013 std::optional<std::string> refusal_detail;
1016 auto [result, dapp_id] = subscription_manager_->register_dapp();
1017 assigned_dapp_id = dapp_id;
1019 if (result == ErrorCode::SUCCESS) {
1020 response_code = ResponseCode::POSITIVE;
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();
1027 refusal_cause = Cause::RESOURCE_EXHAUSTED;
1028 refusal_detail =
"no free dApp identifier";
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);
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();
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.."
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 "
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 "
1073 ran_function_list.push_back(func);
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();
1083 auto encode_result = encoder_->encode_setup_response(
1084 generate_message_id(),
1087 config_.e3ap_version,
1090 response_code == ResponseCode::POSITIVE
1091 ? std::optional<uint32_t>(assigned_dapp_id)
1093 name_or_unknown(config_.ran_identifier),
1099 if (!encode_result) {
1102 E3_LOG_ERROR(LOG_TAG) <<
"Failed to encode setup response for request id "
1103 << request_message_id <<
"; aborting";
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
1112 E3_LOG_INFO(LOG_TAG) <<
"Sent setup response for request id " << request_message_id;
1115 send_result == ErrorCode::SUCCESS ? 1 : 0);
1118void E3Interface::send_negative_setup_reply(uint32_t request_id) {
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(
1131 ResponseCode::NEGATIVE,
1132 config_.e3ap_version,
1134 name_or_unknown(config_.ran_identifier),
1136 Cause::PROTOCOL_ERROR,
1137 std::string(
"not a decodable setup request")
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";
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 "
1154void E3Interface::handle_subscription_request(
const SubscriptionRequest& request, uint32_t request_message_id) {
1156 E3_LOG_INFO(LOG_TAG) <<
"Handling subscription request from dApp " << request.dapp_identifier
1157 <<
" for RAN function " << request.ran_function_identifier;
1160 uint32_t subscription_id = 1;
1161 std::optional<Refusal> refusal;
1163 std::optional<SubscriptionDetails> held;
1164 bool repeated =
false;
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 <<
": "
1175 uint32_t period = request.periodicity.value_or(0);
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,
1186 subscription_id = sub_id;
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();
1197 held = subscription_manager_->get_subscription_details(
1198 request.dapp_identifier, request.ran_function_identifier);
1201 E3_LOG_ERROR(LOG_TAG) <<
"Failed to add subscription: "
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")
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;
1222 resp.telemetry_identifier_list = request.telemetry_identifier_list;
1223 resp.control_identifier_list = request.control_identifier_list;
1226 resp.telemetry_identifier_list = held->telemetry_ids;
1227 resp.control_identifier_list = held->control_ids;
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;
1238 }
else if (refusal) {
1239 resp.cause = refusal->cause;
1240 resp.detail = refusal->detail;
1242 response_pdu.choice = resp;
1245 response_code == ResponseCode::POSITIVE ? 1 : 0);
1246 queue_outbound(std::move(response_pdu));
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;
1254 std::optional<Cause> refusal_cause;
1256 ErrorCode result = subscription_manager_->remove_subscription_by_id(
1257 del.dapp_identifier,
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();
1266 E3_LOG_ERROR(LOG_TAG) <<
"Failed to remove subscription: "
1268 refusal_cause = result == ErrorCode::DAPP_NOT_REGISTERED ? Cause::SETUP_REQUIRED
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;
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";
1287 response_pdu.choice = resp;
1289 queue_outbound(std::move(response_pdu));
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 <<
": "
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;
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));
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)";
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");
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");
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));
1341 if (!sm->is_running()) {
1342 refuse_control(action, request_message_id, Cause::NOT_FOUND,
"no subscription to this RAN function");
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) {
1353 refuse_control(action, request_message_id, Cause::RESOURCE_EXHAUSTED,
1354 "too many controls wait for an answer");
1357 pending_controls_[key] = PendingControl{action.ran_function_identifier, action.control_identifier};
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: "
1372 if (action.request_ack) {
1373 bool unanswered =
false;
1375 std::lock_guard<std::mutex> lk(pending_controls_mu_);
1376 unanswered = pending_controls_.erase(key) != 0;
1379 refuse_control(action, request_message_id, Cause::UNSPECIFIED,
1380 "the service model could not take the control");
1385 E3_LOG_INFO(LOG_TAG) <<
"Control action processed by SM";
1391 return ErrorCode::INVALID_PARAM;
1393 PendingControl pending;
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;
1400 pending = it->second;
1401 pending_controls_.erase(it);
1414 pdu.
choice = std::move(resp);
1421void E3Interface::handle_dapp_report(
const DAppReport& report) {
1426 if (dapp_report_handler_) {
1427 dapp_report_handler_(report);
1431void E3Interface::handle_release_message(
const ReleaseMessage& release) {
1432 E3_LOG_INFO(LOG_TAG) <<
"Handling release message from dApp " << release.dapp_identifier;
1434 handle_dapp_disconnection(release.dapp_identifier);
1437void E3Interface::handle_dapp_disconnection(uint32_t dapp_id) {
1438 E3_LOG_INFO(LOG_TAG) <<
"Handling dApp disconnection: " << dapp_id;
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);
1449 auto subscriptions = subscription_manager_->get_dapp_subscriptions(dapp_id);
1452 ErrorCode result = subscription_manager_->unregister_dapp(dapp_id);
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();
1459 E3_LOG_ERROR(LOG_TAG) <<
"Failed to unregister dApp " << dapp_id <<
": "
1464void E3Interface::bind_dapp_to_connection(uint32_t dapp_id, uint64_t peer) {
1468 const auto generation = subscription_manager_->dapp_generation(dapp_id);
1472 std::lock_guard<std::mutex> lock(bindings_mu_);
1473 if (
auto owner = peer_bindings_.owner.find(dapp_id); owner != peer_bindings_.owner.end()) {
1475 if (
auto old = peer_bindings_.by_peer.find(owner->second.first); old != peer_bindings_.by_peer.end()) {
1476 old->second.erase(dapp_id);
1479 peer_bindings_.owner[dapp_id] = {peer, *generation};
1480 peer_bindings_.by_peer[peer][dapp_id] = *generation;
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;
1489bool E3Interface::admit_dapp_message(uint64_t peer, uint32_t dapp_id) {
1493 const auto generation = subscription_manager_->dapp_generation(dapp_id);
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) {
1502 return owner->second.first == peer;
1505void E3Interface::remove_dapps_of_closed_peers() {
1506 std::vector<std::pair<uint32_t, uint64_t>> gone;
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()) {
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);
1518 gone.emplace_back(dapp_id, generation);
1520 peer_bindings_.by_peer.erase(bound);
1522 for (
const auto& [dapp_id, generation] : gone) {
1523 if (subscription_manager_->dapp_generation(dapp_id) != generation) {
1526 E3_LOG_INFO(LOG_TAG) <<
"Connection of dApp " << dapp_id <<
" closed without a release";
1527 handle_dapp_disconnection(dapp_id);
1531void E3Interface::request_reconnect() {
1532 if (config_.role != E3Role::DAPP || config_.reconnect_interval_ms == 0) {
1536 std::lock_guard<std::mutex> lk(reconnect_mu_);
1537 if (user_stopped_) {
1540 reconnect_pending_ =
true;
1542 reconnect_cv_.notify_all();
1545void E3Interface::reconnect_loop() {
1546 const std::chrono::milliseconds interval(config_.reconnect_interval_ms);
1547 std::unique_lock<std::mutex> lk(reconnect_mu_);
1549 reconnect_cv_.wait(lk, [
this] {
return user_stopped_ || reconnect_pending_; });
1550 if (user_stopped_) {
1553 reconnect_pending_ =
false;
1556 if (reconnect_cv_.wait_for(lk, interval, [
this] { return user_stopped_; })) {
1565void E3Interface::restart_session() {
1566 std::lock_guard<std::mutex> lifecycle(lifecycle_mu_);
1568 std::lock_guard<std::mutex> lk(reconnect_mu_);
1569 if (user_stopped_) {
1573 E3_LOG_INFO(LOG_TAG) <<
"Registering with the RAN again";
1576 if (rc != ErrorCode::SUCCESS) {
1578 request_reconnect();
1582void E3Interface::remove_idle_dapps() {
1583 if (config_.dapp_idle_timeout_s == 0) {
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";
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));
1600 handle_dapp_disconnection(dapp_id);
1612void E3Interface::setup_loop_dapp() {
1617 E3_LOG_INFO(LOG_TAG) <<
"Setup loop (dApp) started";
1620 auto enc = encoder_->encode_setup_request(
1621 generate_message_id(),
1622 config_.e3ap_version,
1624 config_.dapp_version,
1625 name_or_unknown(config_.vendor)
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();
1637 constexpr int MAX_RETRIES = 5;
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: "
1646 std::this_thread::sleep_for(std::chrono::seconds(1));
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);
1655 auto decoded = encoder_->decode(resp_buf.data(),
static_cast<size_t>(n));
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.";
1662 if (decoded->type != PduType::SETUP_RESPONSE) {
1663 E3_LOG_ERROR(LOG_TAG) <<
"Unexpected PDU on setup channel: "
1667 auto* resp = std::get_if<SetupResponse>(&decoded->choice);
1669 handle_setup_response(*resp);
1670 got_response =
true;
1675 E3_LOG_ERROR(LOG_TAG) <<
"recv_setup_response_client error";
1679 if (got_response)
break;
1684 std::lock_guard<std::mutex> lk(setup_complete_mu_);
1685 setup_complete_ =
true;
1686 setup_succeeded_ = got_response;
1688 setup_complete_cv_.notify_all();
1690 E3_LOG_INFO(LOG_TAG) <<
"Setup loop (dApp) finished, success="
1691 << (got_response ?
"yes" :
"no");
1694 if (!should_stop_.load() && !dapp_id().has_value()) {
1695 request_reconnect();
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";
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: "
1708 if (!should_stop_.load()) on_ran_gone(DisconnectReason::CONNECTION_LOST);
1712 std::vector<uint8_t> buffer;
1713 while (!should_stop_.load()) {
1714 int ret = connector_->receive(buffer);
1716 if (should_stop_.load())
break;
1719 on_ran_gone(DisconnectReason::CONNECTION_LOST);
1726 auto decoded = encoder_->decode(buffer.data(),
static_cast<size_t>(ret));
1728 E3_LOG_ERROR(LOG_TAG) <<
"Failed to decode PDU in dApp inbound";
1732 Pdu& pdu = *decoded;
1735 case PduType::SUBSCRIPTION_RESPONSE: {
1736 auto* r = std::get_if<SubscriptionResponse>(&pdu.choice);
1737 if (r) handle_subscription_response(*r);
1740 case PduType::INDICATION_MESSAGE: {
1741 auto* m = std::get_if<IndicationMessage>(&pdu.choice);
1742 if (m) handle_indication(*m, seq);
1745 case PduType::XAPP_CONTROL_ACTION: {
1746 auto* a = std::get_if<XAppControlAction>(&pdu.choice);
1748 a->message_id = pdu.message_id;
1749 handle_xapp_control_action(*a, seq);
1753 case PduType::MESSAGE_ACK: {
1754 auto* a = std::get_if<MessageAck>(&pdu.choice);
1755 if (a) handle_message_ack(*a);
1758 case PduType::CONTROL_RESPONSE: {
1759 auto* r = std::get_if<ControlResponse>(&pdu.choice);
1760 if (r) handle_control_response_from_ran(*r, seq);
1763 case PduType::RELEASE_MESSAGE: {
1764 auto* r = std::get_if<ReleaseMessage>(&pdu.choice);
1765 if (r) handle_release_from_ran(*r);
1769 E3_LOG_WARN(LOG_TAG) <<
"dApp received unexpected PDU type: "
1776 E3_LOG_INFO(LOG_TAG) <<
"Inbound loop (dApp) stopped";
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";
1783 signal(SIGPIPE, SIG_IGN);
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: "
1789 if (!should_stop_.load()) on_ran_gone(DisconnectReason::CONNECTION_LOST);
1793 while (!should_stop_.load()) {
1794 auto pdu_opt = response_queue_->pop(std::chrono::milliseconds(10));
1795 if (!pdu_opt)
continue;
1798 auto enc = encoder_->encode(*pdu_opt);
1800 E3_LOG_ERROR(LOG_TAG) <<
"Failed to encode dApp outbound PDU";
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)
1819 E3_LOG_INFO(LOG_TAG) <<
"Outbound loop (dApp) stopped";
1826void E3Interface::on_ran_gone(DisconnectReason reason) {
1827 if (!dapp_state_ || ran_gone_.exchange(
true))
return;
1829 << (reason == DisconnectReason::RELEASED_BY_RAN
1830 ?
"released by RAN" :
"connection lost") <<
")";
1831 dapp_state_->clear_session();
1833 std::lock_guard<std::mutex> lk(pending_subscriptions_mutex_);
1834 pending_subscriptions_.clear();
1837 std::lock_guard<std::mutex> lk(setup_complete_mu_);
1838 setup_succeeded_ =
false;
1841 if (release_sent_.load())
return;
1842 if (disconnect_handler_) {
1843 disconnect_handler_(reason);
1845 request_reconnect();
1848void E3Interface::handle_release_from_ran(
const ReleaseMessage& release) {
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) {
1857 E3_LOG_INFO(LOG_TAG) <<
"RAN released dApp " << release.dapp_identifier;
1858 on_ran_gone(DisconnectReason::RELEASED_BY_RAN);
1861void E3Interface::handle_setup_response(
const SetupResponse& resp) {
1862 E3_LOG_INFO(LOG_TAG) <<
"Handling SetupResponse rc="
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);
1868 if (setup_response_handler_) {
1869 setup_response_handler_(resp);
1873void E3Interface::handle_subscription_response(
const SubscriptionResponse& resp) {
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) {
1882 E3_LOG_INFO(LOG_TAG) <<
"Handling SubscriptionResponse for request "
1883 << resp.request_id <<
" rc="
1888 std::optional<PendingSubscriptionOp> pending;
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);
1897 if (dapp_state_ && pending && resp.response_code == ResponseCode::POSITIVE) {
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()) {
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);
1913 dapp_state_->record_subscription(pending->ran_function_id,
1914 *resp.subscription_id,
1916 E3_LOG_INFO(LOG_TAG) <<
"Subscription " << *resp.subscription_id
1917 <<
" granted for RAN function "
1918 << pending->ran_function_id;
1921 if (subscription_response_handler_) {
1922 subscription_response_handler_(resp);
1926void E3Interface::handle_indication(
const IndicationMessage& msg, uint64_t latrec_seq) {
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) {
1945 if (indication_handler_) {
1946 indication_handler_(msg);
1951void E3Interface::handle_xapp_control_action(
const XAppControlAction& action,
1952 uint64_t latrec_seq) {
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) {
1967 if (xapp_control_handler_) {
1968 xapp_control_handler_(action);
1969 }
else if (action.request_ack) {
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();
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);
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);
1996 static_cast<uint64_t
>(ack.response_code), 0);
1997 if (message_ack_handler_) {
1998 message_ack_handler_(ack);
2002void E3Interface::handle_control_response_from_ran(
const ControlResponse& resp, uint64_t latrec_seq) {
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) {
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);
2022 static_cast<uint64_t
>(resp.response_code), 0);
2023 if (control_response_handler_) {
2024 control_response_handler_(resp);
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;
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);
2037 if (control_response_handler_) {
2038 control_response_handler_(resp);
2047 if (!dapp_state_)
return std::nullopt;
2048 std::lock_guard<std::mutex> lk(dapp_state_->mu);
2049 return dapp_state_->assigned_dapp_id;
2053 if (!dapp_state_)
return {};
2054 return dapp_state_->active_subscriptions();
2058 if (!dapp_state_)
return {};
2059 return dapp_state_->subscribed_ran_functions();
2063 if (!dapp_state_)
return {};
2064 std::lock_guard<std::mutex> lk(dapp_state_->mu);
2065 return dapp_state_->remote_ran_functions;
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
2076 if (!dapp_state_)
return ErrorCode::STATE_ERROR;
2078 if (!
id)
return ErrorCode::NOT_INITIALIZED;
2088 pdu.
choice = std::move(req);
2094 remember_subscription_op(mid, ran_function_id,
false, sub_time);
2096 if (rc != ErrorCode::SUCCESS) {
2097 forget_subscription_op(mid);
2100 if (out_request_id) {
2101 *out_request_id = mid;
2107 if (!dapp_state_)
return ErrorCode::STATE_ERROR;
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;
2122 remember_subscription_op(mid, ran_function_id,
true);
2124 if (rc != ErrorCode::SUCCESS) {
2125 forget_subscription_op(mid);
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,
2138 if (!dapp_state_)
return ErrorCode::STATE_ERROR;
2140 if (!
id)
return ErrorCode::NOT_INITIALIZED;
2150 pdu.
choice = std::move(a);
2159 if (rc == ErrorCode::SUCCESS && out_message_id) {
2160 *out_message_id = mid;
2166 uint32_t request_id,
2167 uint32_t ran_function_id,
2168 uint32_t control_id,
2171 if (!dapp_state_)
return ErrorCode::STATE_ERROR;
2173 if (!
id)
return ErrorCode::NOT_INITIALIZED;
2186 pdu.
choice = std::move(resp);
2194 uint32_t ran_function_id,
2195 std::vector<uint8_t> report_data,
2196 uint32_t sequence_id,
2197 uint32_t* out_message_id
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;
2206 if (!dapp_state_)
return ErrorCode::STATE_ERROR;
2208 if (!
id)
return ErrorCode::NOT_INITIALIZED;
2216 pdu.
choice = std::move(r);
2220 if (rc == ErrorCode::SUCCESS && out_message_id) {
2221 *out_message_id = mid;
2227 if (!dapp_state_)
return ErrorCode::STATE_ERROR;
2229 if (!
id)
return ErrorCode::NOT_INITIALIZED;
2236 release_sent_.store(
true);
2238 if (rc != ErrorCode::SUCCESS) release_sent_.store(
false);
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;
2248 return setup_succeeded_ ? ErrorCode::SUCCESS : ErrorCode::CONNECTION_FAILED;
2251void E3Interface::on_sm_lifecycle_change(uint32_t ran_function_id,
bool should_start) {
2254 if (result != ErrorCode::SUCCESS) {
2255 E3_LOG_ERROR(LOG_TAG) <<
"Failed to start SM for RAN function "
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 "
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.
void set_level(LogLevel level) noexcept
Set the log level.
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)
static uint64_t latrec_tnow(void)
static void latrec_ctx_set(uint64_t seq)
static void latrec_tstamp_at(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2, uint64_t t_ns)
static uint64_t latrec_ctx(void)
@ LATREC_DROP_REPORT_QUEUE
@ LATREC_ENCODE_E3AP_DONE
@ LATREC_DECODE_E3AP_DONE
uint64_t latrec_seq_next(void)
latrec_t * latrec_tls_open_as(const char *role)
Logging facility for libe3.
#define E3_LOG_WARN(component)
#define E3_LOG_DEBUG(component)
#define E3_LOG_INFO(component)
#define E3_LOG_ERROR(component)
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....
const char * cause_to_string(Cause cause) noexcept
Convert Cause to the name E3AP gives it in JSON and in logs.
AgentState
Agent state machine states.
@ CONNECTING
Connection in progress.
@ UNINITIALIZED
Agent not yet initialized.
@ INITIALIZED
Agent initialized but not connected.
@ STOPPING
Shutdown in progress.
std::unique_ptr< E3Encoder > create_encoder(EncodingFormat format)
Factory function to create appropriate encoder.
E3Role
Role this E3 endpoint plays in the protocol.
@ RAN
RAN function (binds sockets; today's only behaviour).
@ DAPP
dApp (connects to a RAN agent)
ResponseCode
E3AP response codes.
constexpr size_t MAX_PROTOCOL_DATA_SIZE
Largest protocolData of an indication, in bytes.
const char * pdu_type_to_string(PduType type) noexcept
Convert PduType to string representation.
const char * agent_state_to_string(AgentState state) noexcept
Convert AgentState to string representation.
@ ASN1
ASN.1 PER encoding (standard O-RAN format).
const char * role_to_string(E3Role role) noexcept
Convert E3Role to string representation.
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.
constexpr size_t MAX_RAN_FUNCTIONS
ranFunctionList SIZE (0..64)
Cause
Why a RAN refused a request (E3-Cause).
constexpr size_t MAX_CONTROL_OUTCOME_SIZE
Largest controlOutcome of a control response, in bytes.
const char * error_code_to_string(ErrorCode code) noexcept
Convert ErrorCode to string representation.
constexpr size_t MAX_IDENTIFIER_LIST_SIZE
telemetry and control lists SIZE (0..256)
E3AP Control Response structure.
uint32_t request_id
Message id of the control this answers.
uint32_t control_identifier
Control the answer is about.
std::optional< Cause > cause
Why the control was refused (negative only).
ResponseCode response_code
Response code (positive/negative).
uint32_t ran_function_identifier
RAN function of the control.
uint32_t dapp_identifier
dApp the control belongs to
std::optional< std::string > detail
std::optional< std::vector< uint8_t > > control_outcome
What a Service Model answers to a control (see ServiceModel::respond_to_control).
ResponseCode response_code
Whether the control was applied.
std::optional< std::string > detail
UTF-8 text for the cause, up to MAX_DETAIL_SIZE bytes.
std::optional< Cause > cause
Why not (negative only).
std::vector< uint8_t > outcome
Opaque service-model content; empty for none.
E3AP dApp Control Action structure.
uint32_t ran_function_identifier
RAN function the control is for.
std::vector< uint8_t > action_data
uint32_t dapp_identifier
dApp that sends the control
uint32_t control_identifier
Control identifier.
E3AP dApp Report structure.
uint32_t dapp_identifier
dApp that sends the report
std::vector< uint8_t > report_data
uint32_t ran_function_identifier
RAN function the report is for.
Configuration for E3Agent.
int log_level
Logging verbosity: 0=none, 1=error, 2=warn, 3=info, 4=debug, 5=trace.
Generic E3AP PDU structure.
uint64_t enqueue_seq
Set by queue_outbound; keys the [latrec] L-stage records.
PduType type
Which alternative of choice is set.
PduChoice choice
The message itself.
uint32_t message_id
Unique message identifier.
Socket and admission options of the POSIX link.
E3AP Release Message structure.
uint32_t dapp_identifier
dApp identifier
E3AP Subscription Delete structure.
uint32_t dapp_identifier
dApp identifier
uint32_t subscription_id
Subscription ID to delete.
E3AP Subscription Request structure.
std::optional< uint32_t > periodicity
Microseconds between indications, 0 = every event (ASN.1: 0 to 60000000).
std::optional< uint32_t > subscription_time
How long to keep the subscription (0-86400 sec).
uint32_t ran_function_identifier
RAN function to subscribe to.
std::vector< uint32_t > control_identifier_list
List of control identifiers.
std::vector< uint32_t > telemetry_identifier_list
List of telemetry identifiers.
uint32_t dapp_identifier
dApp identifier