Removed CPU dependency
[ric-plt/e2.git] / RIC-E2-TERMINATION / sctpThread.cpp
1 // Copyright 2019 AT&T Intellectual Property
2 // Copyright 2019 Nokia
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 //  This source code is part of the near-RT RIC (RAN Intelligent Controller)
17 //  platform project (RICP).
18
19 // TODO: High-level file comment.
20
21
22
23 #include <3rdparty/oranE2/RANfunctions-List.h>
24 #include "sctpThread.h"
25 #include "BuildRunName.h"
26 #include <unistd.h>
27 //#include "3rdparty/oranE2SM/E2SM-gNB-NRT-RANfunction-Definition.h"
28 //#include "BuildXml.h"
29 //#include "pugixml/src/pugixml.hpp"
30 #include <pthread.h>
31 #include <sys/time.h>
32 #include <sys/inotify.h>
33 #include <errno.h>
34 #include <sys/stat.h>
35 #include <arpa/inet.h>
36
37 using namespace std;
38 //using namespace std::placeholders;
39 using namespace boost::filesystem;
40 using namespace prometheus;
41
42
43 //#ifdef __cplusplus
44 //extern "C"
45 //{
46 //#endif
47
48 // need to expose without the include of gcov
49 extern "C" void __gcov_flush(void);
50 #define LOG_FILE_CONFIG_MAP "CONFIG_MAP_NAME"
51 #define E2AP_PPID 70 // as per E2GAP chapter 6.1
52
53 static void catch_function(int signal) {
54     __gcov_flush();
55     exit(signal);
56 }
57
58
59 BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(my_logger, src::logger_mt)
60
61 boost::shared_ptr<sinks::synchronous_sink<sinks::text_file_backend>> boostLogger;
62 // double cpuClock = 0.0;
63 bool jsonTrace = false;
64
65 char* getinterfaceip()
66 {
67    char hostname[256];
68    char *IP;
69    struct hostent *host_entry;
70    int retVal;
71    retVal = gethostname(hostname, sizeof(hostname));
72    if ( retVal == -1 )
73        return NULL;
74    host_entry = gethostbyname(hostname);
75    if ( host_entry == NULL )
76        return NULL;
77    IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0]));
78    return IP;
79 }
80
81
82 static int enable_log_change_notify(const char* fileName)
83 {
84     int ret = -1;
85     struct stat fileInfo;
86     if ( lstat(fileName,&fileInfo) == 0 )
87     {
88         ret = register_log_change_notify(fileName);
89     }
90     return ret;
91 }
92
93
94 static int register_log_change_notify(const char *fileName)
95 {
96     pthread_attr_t cb_attr;
97     pthread_t tid;
98     pthread_attr_init(&cb_attr);
99     pthread_attr_setdetachstate(&cb_attr,PTHREAD_CREATE_DETACHED);
100     return pthread_create(&tid, &cb_attr,&monitor_loglevel_change_handler,(void *)fileName);
101 }
102
103
104 static void * monitor_loglevel_change_handler(void* arg)
105 {
106     char *fileName = (char*) arg;
107     int ifd;                   // the inotify file des
108     int wfd;                   // the watched file des
109     ssize_t n = 0;
110     char rbuf[4096];           // large read buffer as the event is var len
111     fd_set fds;
112     int res = 0;
113     char* dname=NULL;          // directory name
114     char* bname = NULL;        // basename
115     char* tok=NULL;
116     char* log_level=NULL;
117
118     dname = strdup( fileName ); // defrock the file name into dir and basename
119     if( (tok = strrchr( dname, '/' )) != NULL ) {
120         *tok = '\0';
121         bname = strdup( tok+1 );
122     }
123
124     ifd = inotify_init1( 0 ); // initialise watcher setting blocking read (no option)
125     if( ifd < 0 ) {
126         fprintf( stderr, "### ERR ### unable to initialise file watch %s\n", strerror( errno ) );
127     } else {
128         wfd = inotify_add_watch( ifd, dname, IN_MOVED_TO | IN_CLOSE_WRITE ); // we only care about close write changes
129
130         if( wfd < 0 ) {
131             fprintf( stderr, "### ERR ### unable to add watch on config file %s: %s\n", fileName, strerror( errno ) );
132         } else {
133
134             FD_ZERO (&fds);
135             FD_SET (ifd, &fds);
136             while( 1 ) {
137                 res = select (ifd + 1, &fds, NULL, NULL, NULL);
138                 if(res)
139                 {
140                     n = read( ifd, rbuf, sizeof( rbuf ) ); // read the event
141                     if( n < 0  ) {
142 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
143                         if( errno == EAGAIN ) {
144                         } else {
145                             fprintf( stderr, "### CRIT ### config listener read err: %s\n", strerror( errno ) );
146                         }
147                         continue;
148 #endif
149                     }
150
151                     //Retrieving Log Level from configmap by parsing configmap file
152                     log_level = parse_file(fileName);
153                     update_mdc_log_level_severity(log_level); //setting log level
154                     if(log_level != NULL) {
155                         mdclog_write(MDCLOG_INFO, "MDC log level updated to %s", log_level);
156                         free(log_level);
157                     }
158                 }
159             }
160             inotify_rm_watch(ifd,wfd);
161         }
162         close(ifd);
163     }
164     free(bname);
165     free(dname);
166     free(fileName);
167
168     pthread_exit(NULL);
169 }
170
171 void  update_mdc_log_level_severity(char* log_level)
172 {
173     mdclog_severity_t level = MDCLOG_ERR;
174
175     if(log_level == NULL)
176     {
177         printf("### ERR ### Invalid Log-Level Configuration in ConfigMap, Default Log-Level Applied:   %d\n",level);
178     }
179     else if(strcasecmp(log_level,"1")==0)
180     {
181         level = MDCLOG_ERR;
182     }
183     else if(strcasecmp(log_level,"2")==0)
184     {
185         level = MDCLOG_WARN;
186     }
187     else if(strcasecmp(log_level,"3")==0)
188     {
189         level = MDCLOG_INFO;
190     }
191     else if(strcasecmp(log_level,"4")==0)
192     {
193         level = MDCLOG_DEBUG;
194     }
195
196     mdclog_level_set(level);
197 }
198
199 /**
200  * @brief Remove leading and trailing spaces from s.
201  *
202  * If the string was allocated dynamically, the caller cannot
203  * overwrite the returned pointer.
204  *
205  * @param s the string we want to remove spaces.
206  * @return Returns a null-terminated substring of "s".
207  */
208 static inline char *trim(char *s)
209 {
210     char *end;
211     /* skip leading spaces */
212     while (isspace(*s)) s++;
213
214     /* all spaces */
215     if (*s == '\0') return s;
216
217     /* skip trailing spaces */
218     end = s + strlen(s) - 1;
219     while (end > s && isspace(*end)) end--;
220
221     /* write null character */
222     *(end+1) = '\0';
223
224     return s;
225 }
226
227 static char* parse_file(char* filename)
228 {
229     char *token=NULL;
230     bool found = false;
231     FILE *file = fopen ( filename, "r" );
232
233     if ( file != NULL )
234     {
235         char line [ 128 ];
236         while ( fgets ( line, sizeof(line), file ) != NULL )
237         {
238             token = strtok(line, ":");
239             token = trim(token);
240             if (strcmp(token,"log-level") == 0) {
241                 found = true;
242                 token = strtok(NULL, "\n");
243                 token = trim(token);
244                 break;
245             }
246         }
247         fclose ( file );
248      }
249      if(found)
250          return(strdup(token));
251      else
252          return(NULL);
253 }
254
255 char *read_env_param(const char*envkey)
256 {
257     if(envkey)
258     {
259         char *value = getenv(envkey);
260         if(value)
261             return strdup(value);
262     }
263     return NULL;
264 }
265
266 void dynamic_log_level_change()
267 {
268     char *logFile_Name = read_env_param(LOG_FILE_CONFIG_MAP);
269     char* log_level_init=NULL;
270     if(logFile_Name)
271     {
272         log_level_init = parse_file(logFile_Name);
273         update_mdc_log_level_severity(log_level_init); //setting log level
274         mdclog_write(MDCLOG_INFO, "MDC log level set to %s", log_level_init);
275         free(log_level_init);
276
277     }
278     enable_log_change_notify(logFile_Name);
279 }
280
281 void init_log() {
282     int log_change_monitor = 0;
283     mdclog_attr_t *attr;
284     mdclog_attr_init(&attr);
285     mdclog_attr_set_ident(attr, "E2Terminator");
286     mdclog_init(attr);
287     if(mdclog_format_initialize(log_change_monitor)!=0)
288         mdclog_write(MDCLOG_ERR, "Failed to intialize MDC log format !!!");
289     dynamic_log_level_change();
290     mdclog_attr_destroy(attr);
291 }
292 //auto start_time = std::chrono::high_resolution_clock::now();
293 //typedef std::chrono::duration<double, std::ratio<1,1>> seconds_t;
294
295 //double age() {
296 //    return seconds_t(std::chrono::high_resolution_clock::now() - start_time).count();
297 //}
298
299 // If model name in "/proc/cpuinfo" is happens to be "Common KVM processor" then
300 // approx_CPU_MHz() results in "SIGILL - Illegal Instruction" signal.
301 //
302 // double approx_CPU_MHz(unsigned sleepTime) {
303 //    using namespace std::chrono_literals;
304 //    uint32_t aux = 0;
305 //    uint64_t cycles_start = rdtscp(aux);
306 //    double time_start = age();
307 //    std::this_thread::sleep_for(sleepTime * 1ms);
308 //    uint64_t elapsed_cycles = rdtscp(aux) - cycles_start;
309 //    double elapsed_time = age() - time_start;
310 //    return elapsed_cycles / elapsed_time;
311 //}
312
313 //std::atomic<int64_t> rmrCounter{0};
314 std::atomic<int64_t> num_of_messages{0};
315 std::atomic<int64_t> num_of_XAPP_messages{0};
316 static long transactionCounter = 0;
317 pthread_mutex_t thread_lock;
318
319 int buildListeningPort(sctp_params_t &sctpParams) {
320     sctpParams.listenFD = socket(AF_INET6, SOCK_STREAM, IPPROTO_SCTP);
321     if (sctpParams.listenFD <= 0) {
322 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
323         mdclog_write(MDCLOG_ERR, "Error Opening socket, %s", strerror(errno));
324         return -1;
325 #endif
326     }
327     struct sctp_initmsg initmsg;
328     memset (&initmsg, 0, sizeof (initmsg));
329     initmsg.sinit_num_ostreams = 2;
330     initmsg.sinit_max_instreams = 2;
331     initmsg.sinit_max_attempts = 4;
332     setsockopt (sctpParams.listenFD, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof (initmsg));
333
334     struct sockaddr_in6 serverAddress {};
335     serverAddress.sin6_family = AF_INET6;
336     serverAddress.sin6_addr   = in6addr_any;
337     serverAddress.sin6_port = htons(sctpParams.sctpPort);
338     if (bind(sctpParams.listenFD, (SA *)&serverAddress, sizeof(serverAddress)) < 0 ) {
339 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
340         mdclog_write(MDCLOG_ERR, "Error binding port %d. %s", sctpParams.sctpPort, strerror(errno));
341         return -1;
342 #endif
343     }
344     if (setSocketNoBlocking(sctpParams.listenFD) == -1) {
345         //mdclog_write(MDCLOG_ERR, "Error binding. %s", strerror(errno));
346         return -1;
347     }
348     if (mdclog_level_get() >= MDCLOG_DEBUG) {
349         struct sockaddr_in6 clientAddress {};
350         socklen_t len = sizeof(clientAddress);
351         getsockname(sctpParams.listenFD, (SA *)&clientAddress, &len);
352         char buff[1024] {};
353         inet_ntop(AF_INET6, &clientAddress.sin6_addr, buff, sizeof(buff));
354         mdclog_write(MDCLOG_DEBUG, "My address: %s, port %d\n", buff, htons(clientAddress.sin6_port));
355     }
356
357     if (listen(sctpParams.listenFD, SOMAXCONN) < 0) {
358 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
359         mdclog_write(MDCLOG_ERR, "Error listening. %s\n", strerror(errno));
360         return -1;
361 #endif
362     }
363     struct epoll_event event {};
364     event.events = EPOLLIN | EPOLLET;
365     event.data.fd = sctpParams.listenFD;
366
367     // add listening port to epoll
368     if (epoll_ctl(sctpParams.epoll_fd, EPOLL_CTL_ADD, sctpParams.listenFD, &event)) {
369 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
370         printf("Failed to add descriptor to epoll\n");
371         mdclog_write(MDCLOG_ERR, "Failed to add descriptor to epoll. %s\n", strerror(errno));
372         return -1;
373 #endif
374     }
375
376     return 0;
377 }
378
379 int buildConfiguration(sctp_params_t &sctpParams) {
380     path p = (sctpParams.configFilePath + "/" + sctpParams.configFileName).c_str();
381     if (exists(p)) {
382         const int size = 2048;
383         auto fileSize = file_size(p);
384         if (fileSize > size) {
385 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
386             mdclog_write(MDCLOG_ERR, "File %s larger than %d", p.string().c_str(), size);
387             return -1;
388 #endif
389         }
390     } else {
391 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
392         mdclog_write(MDCLOG_ERR, "Configuration File %s not exists", p.string().c_str());
393         return -1;
394 #endif
395     }
396
397     ReadConfigFile conf;
398     if (conf.openConfigFile(p.string()) == -1) {
399 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
400         mdclog_write(MDCLOG_ERR, "Filed to open config file %s, %s",
401                      p.string().c_str(), strerror(errno));
402         return -1;
403 #endif
404     }
405     int rmrPort = conf.getIntValue("nano");
406     if (rmrPort == -1) {
407 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
408         mdclog_write(MDCLOG_ERR, "illegal RMR port ");
409         return -1;
410 #endif
411     }
412     sctpParams.rmrPort = (uint16_t)rmrPort;
413     snprintf(sctpParams.rmrAddress, sizeof(sctpParams.rmrAddress), "%d", (int) (sctpParams.rmrPort));
414     auto tmpStr = conf.getStringValue("volume");
415     if (tmpStr.length() == 0) {
416 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
417         mdclog_write(MDCLOG_ERR, "illegal volume.");
418         return -1;
419 #endif
420     }
421
422     char tmpLogFilespec[VOLUME_URL_SIZE];
423     tmpLogFilespec[0] = 0;
424     sctpParams.volume[0] = 0;
425     snprintf(sctpParams.volume, VOLUME_URL_SIZE, "%s", tmpStr.c_str());
426     // copy the name to temp file as well
427     snprintf(tmpLogFilespec, VOLUME_URL_SIZE, "%s", tmpStr.c_str());
428
429
430     // define the file name in the tmp directory under the volume
431     strcat(tmpLogFilespec,"/tmp/E2Term_%Y-%m-%d_%H-%M-%S.%N.tmpStr");
432
433     sctpParams.myIP = conf.getStringValue("local-ip");
434     if (sctpParams.myIP.length() == 0) {
435 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
436         mdclog_write(MDCLOG_ERR, "illegal local-ip.");
437         return -1;
438 #endif
439     }
440
441     int sctpPort = conf.getIntValue("sctp-port");
442     if (sctpPort == -1) {
443 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
444         mdclog_write(MDCLOG_ERR, "illegal SCTP port ");
445         return -1;
446 #endif
447     }
448     sctpParams.sctpPort = (uint16_t)sctpPort;
449
450     sctpParams.fqdn = conf.getStringValue("external-fqdn");
451     if (sctpParams.fqdn.length() == 0) {
452 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
453         mdclog_write(MDCLOG_ERR, "illegal external-fqdn");
454         return -1;
455 #endif
456     }
457
458     std::string pod = conf.getStringValue("pod_name");
459 #ifndef UNIT_TEST
460     if (pod.length() == 0) {
461         mdclog_write(MDCLOG_ERR, "illegal pod_name in config file");
462         return -1;
463     }
464     auto *podName = getenv(pod.c_str());
465     if (podName == nullptr) {
466         mdclog_write(MDCLOG_ERR, "illegal pod_name or environment variable not exists : %s", pod.c_str());
467         return -1;
468
469     } else {
470         sctpParams.podName.assign(podName);
471         if (sctpParams.podName.length() == 0) {
472             mdclog_write(MDCLOG_ERR, "illegal pod_name");
473             return -1;
474         }
475     }
476 #endif
477     tmpStr = conf.getStringValue("trace");
478     transform(tmpStr.begin(), tmpStr.end(), tmpStr.begin(), ::tolower);
479     if ((tmpStr.compare("start")) == 0) {
480 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
481         mdclog_write(MDCLOG_INFO, "Trace set to: start");
482         sctpParams.trace = true;
483 #endif
484     } else if ((tmpStr.compare("stop")) == 0) {
485         mdclog_write(MDCLOG_INFO, "Trace set to: stop");
486         sctpParams.trace = false;
487     } else {
488 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
489         mdclog_write(MDCLOG_ERR, "Trace was set to wrong value %s, set to stop", tmpStr.c_str());
490         sctpParams.trace = false;
491 #endif
492     }
493     jsonTrace = sctpParams.trace;
494
495     sctpParams.epollTimeOut = -1;
496
497     tmpStr = conf.getStringValue("prometheusPort");
498     if (tmpStr.length() != 0) {
499         sctpParams.prometheusPort = tmpStr;
500     }
501
502     sctpParams.ka_message_length = snprintf(sctpParams.ka_message, KA_MESSAGE_SIZE, "{\"address\": \"%s:%d\","
503                                                                                     "\"fqdn\": \"%s\","
504                                                                                     "\"pod_name\": \"%s\"}",
505                                             (const char *)sctpParams.myIP.c_str(),
506                                             sctpParams.rmrPort,
507                                             sctpParams.fqdn.c_str(),
508                                             sctpParams.podName.c_str());
509
510     if (mdclog_level_get() >= MDCLOG_INFO) {
511         mdclog_write(MDCLOG_DEBUG,"RMR Port: %s", to_string(sctpParams.rmrPort).c_str());
512         mdclog_write(MDCLOG_DEBUG,"volume: %s", sctpParams.volume);
513         mdclog_write(MDCLOG_DEBUG,"tmpLogFilespec: %s", tmpLogFilespec);
514         mdclog_write(MDCLOG_DEBUG,"my ip: %s", sctpParams.myIP.c_str());
515         mdclog_write(MDCLOG_DEBUG,"pod name: %s", sctpParams.podName.c_str());
516
517         mdclog_write(MDCLOG_INFO, "running parameters for instance : %s", sctpParams.ka_message);
518     }
519
520     // Files written to the current working directory
521     boostLogger = logging::add_file_log(
522             keywords::file_name = tmpLogFilespec, // to temp directory
523             keywords::rotation_size = 10 * 1024 * 1024,
524             keywords::time_based_rotation = sinks::file::rotation_at_time_interval(posix_time::hours(1)),
525             keywords::format = "%Message%"
526             //keywords::format = "[%TimeStamp%]: %Message%" // use each tmpStr with time stamp
527     );
528
529     // Setup a destination folder for collecting rotated (closed) files --since the same volume can use rename()
530     boostLogger->locked_backend()->set_file_collector(sinks::file::make_collector(
531             keywords::target = sctpParams.volume
532     ));
533
534     // Upon restart, scan the directory for files matching the file_name pattern
535     boostLogger->locked_backend()->scan_for_files();
536
537     // Enable auto-flushing after each tmpStr record written
538     if (mdclog_level_get() >= MDCLOG_DEBUG) {
539         boostLogger->locked_backend()->auto_flush(true);
540     }
541
542     return 0;
543 }
544
545 void startPrometheus(sctp_params_t &sctpParams) {
546     auto podName = std::getenv("POD_NAME");
547     string metric = "E2TBeta";
548     if (strstr(podName, "alpha") != NULL) {
549         metric = "E2TAlpha";
550     }
551     //Get eth0 interface IP
552     char* host = getinterfaceip();
553     string hostip = host;
554
555     sctpParams.prometheusFamily = &BuildCounter()
556             .Name(metric.c_str())
557             .Help("E2T instance metrics")
558             .Labels({{"POD_NAME", sctpParams.podName}})
559             .Register(*sctpParams.prometheusRegistry);
560
561     // Build E2T instance level metrics
562     buildE2TPrometheusCounters(sctpParams);
563
564     string prometheusPath;
565     if (hostip.empty())
566         prometheusPath = sctpParams.prometheusPort + "," + "[::]:" + sctpParams.prometheusPort;
567     else
568         prometheusPath = hostip + ":" + sctpParams.prometheusPort;
569
570     if (mdclog_level_get() >= MDCLOG_DEBUG) {
571         mdclog_write(MDCLOG_DEBUG, "Start Prometheus Pull mode on %s", prometheusPath.c_str());
572     }
573     sctpParams.prometheusExposer = new Exposer(prometheusPath, 1);
574     sctpParams.prometheusExposer->RegisterCollectable(sctpParams.prometheusRegistry);
575 }
576 #ifndef UNIT_TEST
577
578 int main(const int argc, char **argv) {
579     sctp_params_t sctpParams;
580     {
581         std::random_device device{};
582         std::mt19937 generator(device());
583         std::uniform_int_distribution<long> distribution(1, (long) 1e12);
584         transactionCounter = distribution(generator);
585     }
586
587 //    uint64_t st = 0;
588 //    uint32_t aux1 = 0;
589 //   st = rdtscp(aux1);
590
591     unsigned num_cpus = std::thread::hardware_concurrency();
592     init_log();
593     if (std::signal(SIGINT, catch_function) == SIG_ERR) {
594         mdclog_write(MDCLOG_ERR, "Error initializing SIGINT");
595         exit(1);
596     }
597     if (std::signal(SIGABRT, catch_function)== SIG_ERR) {
598         mdclog_write(MDCLOG_ERR, "Error initializing SIGABRT");
599         exit(1);
600     }
601     if (std::signal(SIGTERM, catch_function)== SIG_ERR) {
602         mdclog_write(MDCLOG_ERR, "Error initializing SIGTERM");
603         exit(1);
604     }
605
606 //    cpuClock = approx_CPU_MHz(100);
607
608 //    mdclog_write(MDCLOG_DEBUG, "CPU speed %11.11f", cpuClock);
609
610     auto result = parse(argc, argv, sctpParams);
611
612     if (buildConfiguration(sctpParams) != 0) {
613         exit(-1);
614     }
615
616     //auto registry = std::make_shared<Registry>();
617     sctpParams.prometheusRegistry = std::make_shared<Registry>();
618
619     //sctpParams.prometheusFamily = new Family<Counter>("E2T", "E2T message counter", {{"E", sctpParams.podName}});
620
621     startPrometheus(sctpParams);
622
623     // start epoll
624     sctpParams.epoll_fd = epoll_create1(0);
625     if (sctpParams.epoll_fd == -1) {
626         mdclog_write(MDCLOG_ERR, "failed to open epoll descriptor");
627         exit(-1);
628     }
629     getRmrContext(sctpParams);
630     if (sctpParams.rmrCtx == nullptr) {
631         close(sctpParams.epoll_fd);
632         exit(-1);
633     }
634
635     if (buildInotify(sctpParams) == -1) {
636         close(sctpParams.rmrListenFd);
637         rmr_close(sctpParams.rmrCtx);
638         close(sctpParams.epoll_fd);
639         exit(-1);
640     }
641
642     if (buildListeningPort(sctpParams) != 0) {
643         close(sctpParams.rmrListenFd);
644         rmr_close(sctpParams.rmrCtx);
645         close(sctpParams.epoll_fd);
646         exit(-1);
647     }
648
649     sctpParams.sctpMap = new mapWrapper();
650
651     if (pthread_mutex_init(&thread_lock, NULL) != 0) {
652         mdclog_write(MDCLOG_ERR, "failed to init thread lock");
653         exit(-1);
654     }
655     std::vector<std::thread> threads(num_cpus);
656 //    std::vector<std::thread> threads;
657
658     num_cpus = 3;
659     for (unsigned int i = 0; i < num_cpus; i++) {
660         threads[i] = std::thread(listener, &sctpParams);
661
662         cpu_set_t cpuset;
663         CPU_ZERO(&cpuset);
664         CPU_SET(i, &cpuset);
665         int rc = pthread_setaffinity_np(threads[i].native_handle(), sizeof(cpu_set_t), &cpuset);
666         if (rc != 0) {
667             mdclog_write(MDCLOG_ERR, "Error calling pthread_setaffinity_np: %d", rc);
668         }
669     }
670
671
672     //loop over term_init until first message from xApp
673     handleTermInit(sctpParams);
674
675     for (auto &t : threads) {
676         t.join();
677     }
678     pthread_mutex_destroy(&thread_lock);
679     return 0;
680 }
681 #endif
682 void handleTermInit(sctp_params_t &sctpParams) {
683     sendTermInit(sctpParams);
684     //send to e2 manager init of e2 term
685     //E2_TERM_INIT
686
687     int count = 0;
688     while (true) {
689         auto xappMessages = num_of_XAPP_messages.load(std::memory_order_acquire);
690         if (xappMessages > 0) {
691             if (mdclog_level_get() >=  MDCLOG_INFO) {
692                 mdclog_write(MDCLOG_INFO, "Got a message from some application, stop sending E2_TERM_INIT");
693             }
694             return;
695         }
696         usleep(100000);
697         count++;
698         if (count % 1000 == 0) {
699             mdclog_write(MDCLOG_ERR, "GOT No messages from any xApp");
700             sendTermInit(sctpParams);
701         }
702     }
703 }
704
705 void sendTermInit(sctp_params_t &sctpParams) {
706     rmr_mbuf_t *msg = rmr_alloc_msg(sctpParams.rmrCtx, sctpParams.ka_message_length);
707     auto count = 0;
708     while (true) {
709         msg->mtype = E2_TERM_INIT;
710         msg->state = 0;
711         rmr_bytes2payload(msg, (unsigned char *)sctpParams.ka_message, sctpParams.ka_message_length);
712         static unsigned char tx[32];
713         auto txLen = snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
714         rmr_bytes2xact(msg, tx, txLen);
715         msg = rmr_send_msg(sctpParams.rmrCtx, msg);
716         if (msg == nullptr) {
717             msg = rmr_alloc_msg(sctpParams.rmrCtx, sctpParams.ka_message_length);
718         } else if (msg->state == 0) {
719             rmr_free_msg(msg);
720             if (mdclog_level_get() >=  MDCLOG_INFO) {
721                 mdclog_write(MDCLOG_INFO, "E2_TERM_INIT successfully sent ");
722             }
723             return;
724         } else {
725             if (count % 100 == 0) {
726                 mdclog_write(MDCLOG_ERR, "Error sending E2_TERM_INIT cause : %s ", translateRmrErrorMessages(msg->state).c_str());
727             }
728             sleep(1);
729         }
730         count++;
731     }
732 }
733
734 /**
735  *
736  * @param argc
737  * @param argv
738  * @param sctpParams
739  * @return
740  */
741 cxxopts::ParseResult parse(int argc, char *argv[], sctp_params_t &sctpParams) {
742     cxxopts::Options options(argv[0], "e2 term help");
743     options.positional_help("[optional args]").show_positional_help();
744     options.allow_unrecognised_options().add_options()
745             ("p,path", "config file path", cxxopts::value<std::string>(sctpParams.configFilePath)->default_value("config"))
746             ("f,file", "config file name", cxxopts::value<std::string>(sctpParams.configFileName)->default_value("config.conf"))
747             ("h,help", "Print help");
748
749     auto result = options.parse(argc, (const char **&)argv);
750
751     if (result.count("help")) {
752         std::cout << options.help({""}) << std::endl;
753         exit(0);
754     }
755     return result;
756 }
757
758 /**
759  *
760  * @param sctpParams
761  * @return -1 failed 0 success
762  */
763 int buildInotify(sctp_params_t &sctpParams) {
764     sctpParams.inotifyFD = inotify_init1(IN_NONBLOCK);
765     if (sctpParams.inotifyFD == -1) {
766         mdclog_write(MDCLOG_ERR, "Failed to init inotify (inotify_init1) %s", strerror(errno));
767         return -1;
768     }
769
770     sctpParams.inotifyWD = inotify_add_watch(sctpParams.inotifyFD,
771                                              (const char *)sctpParams.configFilePath.c_str(),
772                                              (unsigned)IN_OPEN | (unsigned)IN_CLOSE_WRITE | (unsigned)IN_CLOSE_NOWRITE); //IN_CLOSE = (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
773     if (sctpParams.inotifyWD == -1) {
774         mdclog_write(MDCLOG_ERR, "Failed to add directory : %s to  inotify (inotify_add_watch) %s",
775                      sctpParams.configFilePath.c_str(),
776                      strerror(errno));
777         close(sctpParams.inotifyFD);
778         return -1;
779     }
780
781     struct epoll_event event{};
782     event.events = (EPOLLIN);
783     event.data.fd = sctpParams.inotifyFD;
784     // add listening RMR FD to epoll
785     if (epoll_ctl(sctpParams.epoll_fd, EPOLL_CTL_ADD, sctpParams.inotifyFD, &event)) {
786         mdclog_write(MDCLOG_ERR, "Failed to add inotify FD to epoll");
787         close(sctpParams.inotifyFD);
788         return -1;
789     }
790     return 0;
791 }
792
793 /**
794  *
795  * @param args
796  * @return
797  */
798 void listener(sctp_params_t *params) {
799     int num_of_SCTP_messages = 0;
800     auto totalTime = 0.0;
801     std::thread::id this_id = std::this_thread::get_id();
802     //save cout
803     auto pod_name = std::getenv("POD_NAME");
804     auto container_name = std::getenv("CONTAINER_NAME");
805     auto service_name = std::getenv("SERVICE_NAME");
806     auto host_name = std::getenv("HOST_NAME");
807     auto system_name = std::getenv("SYSTEM_NAME");
808     auto pid = std::to_string(getpid()).c_str();
809     streambuf *oldCout = cout.rdbuf();
810     ostringstream memCout;
811     // create new cout
812     cout.rdbuf(memCout.rdbuf());
813     cout << this_id;
814     //return to the normal cout
815     cout.rdbuf(oldCout);
816
817     char tid[32];
818     memcpy(tid, memCout.str().c_str(), memCout.str().length() < 32 ? memCout.str().length() : 31);
819     tid[memCout.str().length()] = 0;
820     mdclog_mdc_add("SYSTEM_NAME", system_name);
821     mdclog_mdc_add("HOST_NAME", host_name);
822     mdclog_mdc_add("SERVICE_NAME", service_name);
823     mdclog_mdc_add("CONTAINER_NAME", container_name);
824     mdclog_mdc_add("POD_NAME", pod_name);
825     mdclog_mdc_add("PID", pid);
826
827     if (mdclog_level_get() >= MDCLOG_DEBUG) {
828         mdclog_write(MDCLOG_DEBUG, "started thread number %s", tid);
829     }
830
831     RmrMessagesBuffer_t rmrMessageBuffer{};
832     //create and init RMR
833     rmrMessageBuffer.rmrCtx = params->rmrCtx;
834
835     auto *events = (struct epoll_event *) calloc(MAXEVENTS, sizeof(struct epoll_event));
836     struct timespec end{0, 0};
837     struct timespec start{0, 0};
838
839     rmrMessageBuffer.rcvMessage = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
840     rmrMessageBuffer.sendMessage = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
841
842     memcpy(rmrMessageBuffer.ka_message, params->ka_message, params->ka_message_length);
843     rmrMessageBuffer.ka_message_len = params->ka_message_length;
844     rmrMessageBuffer.ka_message[rmrMessageBuffer.ka_message_len] = 0;
845
846     if (mdclog_level_get() >= MDCLOG_DEBUG) {
847         mdclog_write(MDCLOG_DEBUG, "keep alive message is : %s", rmrMessageBuffer.ka_message);
848     }
849
850     ReportingMessages_t message {};
851
852 //    for (int i = 0; i < MAX_RMR_BUFF_ARRAY; i++) {
853 //        rmrMessageBuffer.rcvBufferedMessages[i] = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
854 //        rmrMessageBuffer.sendBufferedMessages[i] = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
855 //    }
856
857     while (true) {
858         if (mdclog_level_get() >= MDCLOG_DEBUG) {
859             mdclog_write(MDCLOG_DEBUG, "Start EPOLL Wait. Timeout = %d", params->epollTimeOut);
860         }
861 #ifndef UNIT_TEST
862         auto numOfEvents = epoll_wait(params->epoll_fd, events, MAXEVENTS, params->epollTimeOut);
863 #else
864         auto numOfEvents = 1;
865 #endif
866         if (numOfEvents == 0) { // time out
867 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
868             if (mdclog_level_get() >= MDCLOG_DEBUG) {
869                 mdclog_write(MDCLOG_DEBUG, "got epoll timeout");
870             }
871             continue;
872         } else if (numOfEvents < 0) {
873             if (errno == EINTR) {
874                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
875                     mdclog_write(MDCLOG_DEBUG, "got EINTR : %s", strerror(errno));
876                 }
877                 continue;
878             }
879             mdclog_write(MDCLOG_ERR, "Epoll wait failed, errno = %s", strerror(errno));
880             if(events)
881             {
882                 free(events);
883                 events = nullptr;
884             }
885             return;
886 #endif
887         }
888         for (auto i = 0; i < numOfEvents; i++) {
889             if (mdclog_level_get() >= MDCLOG_DEBUG) {
890                 mdclog_write(MDCLOG_DEBUG, "handling epoll event %d out of %d", i + 1, numOfEvents);
891             }
892             clock_gettime(CLOCK_MONOTONIC, &message.message.time);
893             start.tv_sec = message.message.time.tv_sec;
894             start.tv_nsec = message.message.time.tv_nsec;
895
896
897             if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP)) {
898                 handlepoll_error(events[i], message, rmrMessageBuffer, params);
899             } else if (events[i].events & EPOLLOUT) {
900                 handleEinprogressMessages(events[i], message, rmrMessageBuffer, params);
901             } else if (params->listenFD == events[i].data.fd) {
902                 if (mdclog_level_get() >= MDCLOG_INFO) {
903                     mdclog_write(MDCLOG_INFO, "New connection request from sctp network\n");
904                 }
905                 // new connection is requested from RAN  start build connection
906                 while (true) {
907                     struct sockaddr in_addr {};
908                     socklen_t in_len;
909                     char hostBuff[NI_MAXHOST];
910                     char portBuff[NI_MAXSERV];
911
912                     in_len = sizeof(in_addr);
913                     auto *peerInfo = (ConnectedCU_t *)calloc(1, sizeof(ConnectedCU_t));
914                     if(peerInfo == nullptr){
915                         mdclog_write(MDCLOG_ERR, "calloc failed");
916                         break;
917                     }
918                     peerInfo->sctpParams = params;
919                     peerInfo->fileDescriptor = accept(params->listenFD, &in_addr, &in_len);
920                     if (peerInfo->fileDescriptor == -1) {
921 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
922                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
923                             /* We have processed all incoming connections. */
924                             if(peerInfo)
925                                 free(peerInfo);
926                                 peerInfo = nullptr;
927                             break;
928                         } else {
929                             if(peerInfo)
930                                 free(peerInfo);
931                                 peerInfo = nullptr;
932                             mdclog_write(MDCLOG_ERR, "Accept error, errno = %s", strerror(errno));
933                             break;
934                         }
935                     }
936                     if (setSocketNoBlocking(peerInfo->fileDescriptor) == -1) {
937                         mdclog_write(MDCLOG_ERR, "setSocketNoBlocking failed to set new connection %s on port %s\n", hostBuff, portBuff);
938                         close(peerInfo->fileDescriptor);
939                         if(peerInfo)
940                             free(peerInfo);
941                             peerInfo = nullptr;
942                         break;
943 #endif
944                     }
945                     struct sctp_event_subscribe sctpevents;
946                     memset( (void *)&sctpevents, 0, sizeof(sctpevents) );
947                     sctpevents.sctp_data_io_event = 1;
948                     setsockopt(peerInfo->fileDescriptor, SOL_SCTP, SCTP_EVENTS,(const void *)&sctpevents, sizeof(sctpevents) );
949
950                     auto  ans = getnameinfo(&in_addr, in_len,
951                                             peerInfo->hostName, NI_MAXHOST,
952                                             peerInfo->portNumber, NI_MAXSERV, (unsigned )((unsigned int)NI_NUMERICHOST | (unsigned int)NI_NUMERICSERV));
953                     if (ans < 0) {
954                         mdclog_write(MDCLOG_ERR, "Failed to get info on connection request. %s\n", strerror(errno));
955                         close(peerInfo->fileDescriptor);
956                         if(peerInfo)
957                             free(peerInfo);
958                             peerInfo = nullptr;
959                         break;
960                     }
961                     if (mdclog_level_get() >= MDCLOG_DEBUG) {
962                         mdclog_write(MDCLOG_DEBUG, "Accepted connection on descriptor %d (host=%s, port=%s)\n", peerInfo->fileDescriptor, peerInfo->hostName, peerInfo->portNumber);
963                     }
964                     peerInfo->isConnected = false;
965                     peerInfo->gotSetup = false;
966                     if (addToEpoll(params->epoll_fd,
967                                    peerInfo,
968                                    (EPOLLIN | EPOLLET),
969                                    params->sctpMap, nullptr,
970                                    0) != 0) {
971                         if(peerInfo)
972                             free(peerInfo);
973                             peerInfo = nullptr;
974                         break;
975                     }
976                     break;
977                 }
978             } else if (params->rmrListenFd == events[i].data.fd) {
979                 // got message from XAPP
980                 //num_of_XAPP_messages.fetch_add(1, std::memory_order_release);
981                 num_of_messages.fetch_add(1, std::memory_order_release);
982                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
983                     mdclog_write(MDCLOG_DEBUG, "new RMR message");
984                 }
985                 if (receiveXappMessages(params->sctpMap,
986                                         rmrMessageBuffer,
987                                         message.message.time) != 0) {
988                     mdclog_write(MDCLOG_ERR, "Error handling Xapp message");
989                 }
990             } else if (params->inotifyFD == events[i].data.fd) {
991                 mdclog_write(MDCLOG_INFO, "Got event from inotify (configuration update)");
992                 handleConfigChange(params);
993             } else {
994                 /* We RMR_ERR_RETRY have data on the fd waiting to be read. Read and display it.
995                  * We must read whatever data is available completely, as we are running
996                  *  in edge-triggered mode and won't get a notification again for the same data. */
997                 num_of_messages.fetch_add(1, std::memory_order_release);
998                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
999                     mdclog_write(MDCLOG_DEBUG, "new message from SCTP, epoll flags are : %0x", events[i].events);
1000                 }
1001                 receiveDataFromSctp(&events[i],
1002                                     params->sctpMap,
1003                                     num_of_SCTP_messages,
1004                                     rmrMessageBuffer,
1005                                     message.message.time);
1006             }
1007
1008             clock_gettime(CLOCK_MONOTONIC, &end);
1009             if (mdclog_level_get() >= MDCLOG_INFO) {
1010                 totalTime += ((end.tv_sec + 1.0e-9 * end.tv_nsec) -
1011                               ((double) start.tv_sec + 1.0e-9 * start.tv_nsec));
1012             }
1013             if (mdclog_level_get() >= MDCLOG_DEBUG) {
1014                 mdclog_write(MDCLOG_DEBUG, "message handling is %ld seconds %ld nanoseconds",
1015                              end.tv_sec - start.tv_sec,
1016                              end.tv_nsec - start.tv_nsec);
1017             }
1018         }
1019 #ifdef UNIT_TEST
1020     break;
1021 #endif
1022     }
1023 }
1024
1025 /**
1026  *
1027  * @param sctpParams
1028  */
1029 void handleConfigChange(sctp_params_t *sctpParams) {
1030     char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
1031     const struct inotify_event *event;
1032     char *ptr;
1033 #ifdef UNIT_TEST
1034     struct inotify_event tmpEvent;
1035 #endif
1036     path p = (sctpParams->configFilePath + "/" + sctpParams->configFileName).c_str();
1037     auto endlessLoop = true;
1038     while (endlessLoop) {
1039 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1040         auto len = read(sctpParams->inotifyFD, buf, sizeof buf);
1041 #else
1042     auto len=10;
1043 #endif
1044         if (len == -1) {
1045 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1046             if (errno != EAGAIN) {
1047                 mdclog_write(MDCLOG_ERR, "read %s ", strerror(errno));
1048                 endlessLoop = false;
1049                 continue;
1050             }
1051             else {
1052                 endlessLoop = false;
1053                 continue;
1054             }
1055 #endif
1056         }
1057
1058         for (ptr = buf; ptr < buf + len; ptr += sizeof(struct inotify_event) + event->len) {
1059 #ifndef UNIT_TEST
1060     event = (const struct inotify_event *)ptr;
1061 #else
1062     tmpEvent.mask = (uint32_t)IN_CLOSE_WRITE;
1063     event = &tmpEvent;
1064 #endif
1065             if (event->mask & (uint32_t)IN_ISDIR) {
1066                 continue;
1067             }
1068
1069             // the directory name
1070             if (sctpParams->inotifyWD == event->wd) {
1071                 // not the directory
1072             }
1073             if (event->len) {
1074 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1075                 auto  retVal = strcmp(sctpParams->configFileName.c_str(), event->name);
1076                 if (retVal != 0) {
1077                     continue;
1078                 }
1079 #endif
1080             }
1081             // only the file we want
1082             if (event->mask & (uint32_t)IN_CLOSE_WRITE) {
1083                 if (mdclog_level_get() >= MDCLOG_INFO) {
1084                     mdclog_write(MDCLOG_INFO, "Configuration file changed");
1085                 }
1086                 if (exists(p)) {
1087                     const int size = 2048;
1088                     auto fileSize = file_size(p);
1089                     if (fileSize > size) {
1090                         mdclog_write(MDCLOG_ERR, "File %s larger than %d", p.string().c_str(), size);
1091                         return;
1092                     }
1093                 } else {
1094                     mdclog_write(MDCLOG_ERR, "Configuration File %s not exists", p.string().c_str());
1095                     return;
1096                 }
1097
1098                 ReadConfigFile conf;
1099                 if (conf.openConfigFile(p.string()) == -1) {
1100                     mdclog_write(MDCLOG_ERR, "Filed to open config file %s, %s",
1101                                  p.string().c_str(), strerror(errno));
1102                     return;
1103                 }
1104                 auto tmpStr = conf.getStringValue("trace");
1105                 if (tmpStr.length() == 0) {
1106                     mdclog_write(MDCLOG_ERR, "illegal trace. Set trace to stop");
1107                     tmpStr = "stop";
1108                 }
1109
1110                 transform(tmpStr.begin(), tmpStr.end(), tmpStr.begin(), ::tolower);
1111                 if ((tmpStr.compare("start")) == 0) {
1112                     mdclog_write(MDCLOG_INFO, "Trace set to: start");
1113                     sctpParams->trace = true;
1114                 } else if ((tmpStr.compare("stop")) == 0) {
1115                     mdclog_write(MDCLOG_INFO, "Trace set to: stop");
1116                     sctpParams->trace = false;
1117                 } else {
1118                     mdclog_write(MDCLOG_ERR, "Trace was set to wrong value %s, set to stop", tmpStr.c_str());
1119                     sctpParams->trace = false;
1120                 }
1121                 jsonTrace = sctpParams->trace;
1122
1123
1124                 endlessLoop = false;
1125             }
1126 #ifdef UNIT_TEST
1127             break;
1128 #endif
1129         }
1130     }
1131 }
1132
1133 /**
1134  *
1135  * @param event
1136  * @param message
1137  * @param rmrMessageBuffer
1138  * @param params
1139  */
1140 void handleEinprogressMessages(struct epoll_event &event,
1141                                ReportingMessages_t &message,
1142                                RmrMessagesBuffer_t &rmrMessageBuffer,
1143                                sctp_params_t *params) {
1144     auto *peerInfo = (ConnectedCU_t *)event.data.ptr;
1145     memcpy(message.message.enodbName, peerInfo->enodbName, sizeof(peerInfo->enodbName));
1146
1147     mdclog_write(MDCLOG_INFO, "file descriptor %d got EPOLLOUT", peerInfo->fileDescriptor);
1148     auto retVal = 0;
1149     socklen_t retValLen = 0;
1150     auto rc = getsockopt(peerInfo->fileDescriptor, SOL_SOCKET, SO_ERROR, &retVal, &retValLen);
1151     if (rc != 0 || retVal != 0) {
1152 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1153         if (rc != 0) {
1154             rmrMessageBuffer.sendMessage->len = snprintf((char *)rmrMessageBuffer.sendMessage->payload, 256,
1155                                                          "%s|Failed SCTP Connection, after EINPROGRESS the getsockopt%s",
1156                                                          peerInfo->enodbName, strerror(errno));
1157         } else if (retVal != 0) {
1158             rmrMessageBuffer.sendMessage->len = snprintf((char *)rmrMessageBuffer.sendMessage->payload, 256,
1159                                                          "%s|Failed SCTP Connection after EINPROGRESS, SO_ERROR",
1160                                                          peerInfo->enodbName);
1161         }
1162
1163         message.message.asndata = rmrMessageBuffer.sendMessage->payload;
1164         message.message.asnLength = rmrMessageBuffer.sendMessage->len;
1165         mdclog_write(MDCLOG_ERR, "%s", rmrMessageBuffer.sendMessage->payload);
1166         message.message.direction = 'N';
1167         if (sendRequestToXapp(message, RIC_SCTP_CONNECTION_FAILURE, rmrMessageBuffer) != 0) {
1168             mdclog_write(MDCLOG_ERR, "SCTP_CONNECTION_FAIL message failed to send to xAPP");
1169         }
1170 #endif
1171         memset(peerInfo->asnData, 0, peerInfo->asnLength);
1172         peerInfo->asnLength = 0;
1173         peerInfo->mtype = 0;
1174         return;
1175     }
1176 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1177     peerInfo->isConnected = true;
1178
1179     if (modifyToEpoll(params->epoll_fd, peerInfo, (EPOLLIN | EPOLLET), params->sctpMap, peerInfo->enodbName,
1180                       peerInfo->mtype) != 0) {
1181         mdclog_write(MDCLOG_ERR, "epoll_ctl EPOLL_CTL_MOD");
1182         return;
1183     }
1184
1185     message.message.asndata = (unsigned char *)peerInfo->asnData;
1186     message.message.asnLength = peerInfo->asnLength;
1187     message.message.messageType = peerInfo->mtype;
1188     memcpy(message.message.enodbName, peerInfo->enodbName, sizeof(peerInfo->enodbName));
1189     num_of_messages.fetch_add(1, std::memory_order_release);
1190     if (mdclog_level_get() >= MDCLOG_DEBUG) {
1191         mdclog_write(MDCLOG_DEBUG, "send the delayed SETUP/ENDC SETUP to sctp for %s",
1192                      message.message.enodbName);
1193     }
1194     if (sendSctpMsg(peerInfo, message, params->sctpMap) != 0) {
1195         if (mdclog_level_get() >= MDCLOG_DEBUG) {
1196             mdclog_write(MDCLOG_DEBUG, "Error write to SCTP  %s %d", __func__, __LINE__);
1197         }
1198         return;
1199     }
1200
1201     memset(peerInfo->asnData, 0, peerInfo->asnLength);
1202     peerInfo->asnLength = 0;
1203     peerInfo->mtype = 0;
1204 #endif
1205 }
1206
1207
1208 void handlepoll_error(struct epoll_event &event,
1209                       ReportingMessages_t &message,
1210                       RmrMessagesBuffer_t &rmrMessageBuffer,
1211                       sctp_params_t *params) {
1212     if ((event.data.fd != params->rmrListenFd) && (event.data.ptr != nullptr)) {
1213         auto *peerInfo = (ConnectedCU_t *)event.data.ptr;
1214         mdclog_write(MDCLOG_ERR, "epoll error, events %0x on fd %d, RAN NAME : %s",
1215                      event.events, peerInfo->fileDescriptor, peerInfo->enodbName);
1216 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1217         rmrMessageBuffer.sendMessage->len = snprintf((char *)rmrMessageBuffer.sendMessage->payload, 256,
1218                                                      "%s|Failed SCTP Connection",
1219                                                      peerInfo->enodbName);
1220         message.message.asndata = rmrMessageBuffer.sendMessage->payload;
1221         message.message.asnLength = rmrMessageBuffer.sendMessage->len;
1222
1223         memcpy(message.message.enodbName, peerInfo->enodbName, sizeof(peerInfo->enodbName));
1224         message.message.direction = 'N';
1225         if (sendRequestToXapp(message, RIC_SCTP_CONNECTION_FAILURE, rmrMessageBuffer) != 0) {
1226             mdclog_write(MDCLOG_ERR, "SCTP_CONNECTION_FAIL message failed to send to xAPP");
1227         }
1228 #endif
1229         close(peerInfo->fileDescriptor);
1230         //params->sctpMap->erase(peerInfo->enodbName);
1231         cleanHashEntry((ConnectedCU_t *) event.data.ptr, params->sctpMap);
1232     } else {
1233         mdclog_write(MDCLOG_ERR, "epoll error, events %0x on RMR FD", event.events);
1234     }
1235 }
1236 /**
1237  *
1238  * @param socket
1239  * @return
1240  */
1241 int setSocketNoBlocking(int socket) {
1242     auto flags = fcntl(socket, F_GETFL, 0);
1243
1244     if (flags == -1) {
1245         mdclog_write(MDCLOG_ERR, "%s, %s", __FUNCTION__, strerror(errno));
1246         return -1;
1247     }
1248
1249     flags = (unsigned) flags | (unsigned) O_NONBLOCK;
1250     if (fcntl(socket, F_SETFL, flags) == -1) {
1251         mdclog_write(MDCLOG_ERR, "%s, %s", __FUNCTION__, strerror(errno));
1252         return -1;
1253     }
1254
1255     return 0;
1256 }
1257
1258 /**
1259  *
1260  * @param val
1261  * @param m
1262  */
1263 void cleanHashEntry(ConnectedCU_t *val, Sctp_Map_t *m) {
1264     if(val != nullptr)
1265     {
1266     char *dummy;
1267     auto port = (uint16_t) strtol(val->portNumber, &dummy, 10);
1268     char searchBuff[2048]{};
1269
1270     snprintf(searchBuff, sizeof searchBuff, "host:%s:%d", val->hostName, port);
1271     if(m->find(searchBuff))
1272     {
1273     m->erase(searchBuff);
1274     }
1275
1276     if(m->find(val->enodbName))
1277     {
1278     mdclog_write(MDCLOG_DEBUG, "remove key enodbName = %s from %s at line %d", val->enodbName, __FUNCTION__, __LINE__);
1279     m->erase(val->enodbName);
1280     }
1281 #ifndef UNIT_TEST
1282     if(val) {
1283        free(val);
1284        val = nullptr;
1285     }
1286 #endif
1287     }
1288 }
1289
1290 /**
1291  *
1292  * @param fd file descriptor
1293  * @param data the asn data to send
1294  * @param len  length of the data
1295  * @param enodbName the enodbName as in the map for printing purpose
1296  * @param m map host information
1297  * @param mtype message number
1298  * @return 0 success, a negative number on fail
1299  */
1300 int sendSctpMsg(ConnectedCU_t *peerInfo, ReportingMessages_t &message, Sctp_Map_t *m) {
1301     auto loglevel = mdclog_level_get();
1302 #ifndef UNIT_TEST
1303     int fd = peerInfo->fileDescriptor;
1304     int streamId = fetchStreamId(peerInfo,message);
1305 #else
1306     int fd = FILE_DESCRIPTOR;
1307     int streamId = 0;
1308 #endif
1309     if (loglevel >= MDCLOG_DEBUG) {
1310         mdclog_write(MDCLOG_DEBUG, "Send SCTP message for CU %s, %s",
1311                      message.message.enodbName, __FUNCTION__);
1312     }
1313
1314     while (true) {
1315         if (sctp_sendmsg(fd,message.message.asndata, message.message.asnLength,(struct sockaddr *) NULL, 0, htonl(E2AP_PPID), 0,streamId,0,0) < 0) {
1316             if (errno == EINTR) {
1317                 continue;
1318             }
1319             mdclog_write(MDCLOG_ERR, "error writing to CU a message, %s ", strerror(errno));
1320 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1321             if (!peerInfo->isConnected) {
1322                 mdclog_write(MDCLOG_ERR, "connection to CU %s is still in progress.", message.message.enodbName);
1323                 return -1;
1324             }
1325 #endif
1326 #ifndef UNIT_TEST
1327             cleanHashEntry(peerInfo, m);
1328             close(fd);
1329 #endif
1330             char key[MAX_ENODB_NAME_SIZE * 2];
1331             snprintf(key, MAX_ENODB_NAME_SIZE * 2, "msg:%s|%d", message.message.enodbName,
1332                      message.message.messageType);
1333             if (loglevel >= MDCLOG_DEBUG) {
1334                 mdclog_write(MDCLOG_DEBUG, "remove key = %s from %s at line %d", key, __FUNCTION__, __LINE__);
1335             }
1336             auto tmp = m->find(key);
1337             if (tmp) {
1338                 free(tmp);
1339                 tmp = nullptr;
1340             }
1341             m->erase(key);
1342 #ifndef UNIT_TEST
1343             return -1;
1344 #endif
1345         }
1346         message.message.direction = 'D';
1347         // send report.buffer of size
1348         buildJsonMessage(message);
1349
1350         if (loglevel >= MDCLOG_DEBUG) {
1351             mdclog_write(MDCLOG_DEBUG,
1352                          "SCTP message for CU %s sent from %s",
1353                          message.message.enodbName,
1354                          __FUNCTION__);
1355         }
1356         return 0;
1357     }
1358 }
1359
1360 /**
1361  *
1362  * @param message
1363  * @param rmrMessageBuffer
1364  */
1365 void getRequestMetaData(ReportingMessages_t &message, RmrMessagesBuffer_t &rmrMessageBuffer) {
1366     message.message.asndata = rmrMessageBuffer.rcvMessage->payload;
1367     message.message.asnLength = rmrMessageBuffer.rcvMessage->len;
1368
1369     if (mdclog_level_get() >= MDCLOG_DEBUG) {
1370         mdclog_write(MDCLOG_DEBUG, "Message from Xapp RAN name = %s message length = %ld",
1371                      message.message.enodbName, (unsigned long) message.message.asnLength);
1372     }
1373 }
1374
1375
1376
1377 /**
1378  *
1379  * @param events
1380  * @param sctpMap
1381  * @param numOfMessages
1382  * @param rmrMessageBuffer
1383  * @param ts
1384  * @return
1385  */
1386 int receiveDataFromSctp(struct epoll_event *events,
1387                         Sctp_Map_t *sctpMap,
1388                         int &numOfMessages,
1389                         RmrMessagesBuffer_t &rmrMessageBuffer,
1390                         struct timespec &ts) {
1391     /* We have data on the fd waiting to be read. Read and display it.
1392  * We must read whatever data is available completely, as we are running
1393  *  in edge-triggered mode and won't get a notification again for the same data. */
1394     ReportingMessages_t message {};
1395     auto done = 0;
1396     auto loglevel = mdclog_level_get();
1397     struct sctp_sndrcvinfo sndrcvinfo;
1398     int flags;
1399     int streamId;
1400
1401     // get the identity of the interface
1402     if (events->data.ptr != nullptr){
1403     message.peerInfo = (ConnectedCU_t *)events->data.ptr;
1404     }
1405
1406     struct timespec start{0, 0};
1407     struct timespec decodeStart{0, 0};
1408     struct timespec end{0, 0};
1409
1410     E2AP_PDU_t *pdu = nullptr;
1411
1412     while (true) {
1413         if (loglevel >= MDCLOG_DEBUG) {
1414             mdclog_write(MDCLOG_DEBUG, "Start Read from SCTP %d fd", message.peerInfo->fileDescriptor);
1415             clock_gettime(CLOCK_MONOTONIC, &start);
1416         }
1417         // read the buffer directly to rmr payload
1418         message.message.asndata = rmrMessageBuffer.sendMessage->payload;
1419 #ifndef UNIT_TEST
1420         message.message.asnLength = rmrMessageBuffer.sendMessage->len =
1421                 sctp_recvmsg(message.peerInfo->fileDescriptor, rmrMessageBuffer.sendMessage->payload, RECEIVE_SCTP_BUFFER_SIZE,(struct sockaddr *) NULL, 0, &sndrcvinfo, &flags);
1422         mdclog_write(MDCLOG_DEBUG, "Start Read from SCTP fd %d stream %d ", message.peerInfo->fileDescriptor, sndrcvinfo.sinfo_stream);
1423         streamId = sndrcvinfo.sinfo_stream;
1424 #else
1425         message.message.asnLength = rmrMessageBuffer.sendMessage->len;
1426         streamId = 0;
1427 #endif
1428
1429         if (loglevel >= MDCLOG_DEBUG) {
1430             mdclog_write(MDCLOG_DEBUG, "Finish Read from SCTP %d fd message length = %ld",
1431                          message.peerInfo->fileDescriptor, message.message.asnLength);
1432         }
1433
1434         memcpy(message.message.enodbName, message.peerInfo->enodbName, sizeof(message.peerInfo->enodbName));
1435         message.message.direction = 'U';
1436         message.message.time.tv_nsec = ts.tv_nsec;
1437         message.message.time.tv_sec = ts.tv_sec;
1438
1439         if (message.message.asnLength < 0) {
1440             if (errno == EINTR) {
1441                 continue;
1442             }
1443             /* If errno == EAGAIN, that means we have read all
1444                data. So goReportingMessages_t back to the main loop. */
1445             if (errno != EAGAIN) {
1446                 mdclog_write(MDCLOG_ERR, "Read error, %s ", strerror(errno));
1447                 done = 1;
1448             } else if (loglevel >= MDCLOG_DEBUG) {
1449                 mdclog_write(MDCLOG_DEBUG, "EAGAIN - descriptor = %d", message.peerInfo->fileDescriptor);
1450             }
1451             break;
1452         } else if (message.message.asnLength == 0) {
1453             /* End of file. The remote has closed the connection. */
1454             if (loglevel >= MDCLOG_INFO) {
1455                 mdclog_write(MDCLOG_INFO, "END of File Closed connection - descriptor = %d",
1456                              message.peerInfo->fileDescriptor);
1457             }
1458             done = 1;
1459             break;
1460         }
1461
1462         if (loglevel >= MDCLOG_DEBUG) {
1463             char printBuffer[RECEIVE_SCTP_BUFFER_SIZE]{};
1464             char *tmp = printBuffer;
1465             for (size_t i = 0; i < (size_t)message.message.asnLength; ++i) {
1466                 snprintf(tmp, 3, "%02x", message.message.asndata[i]);
1467                 tmp += 2;
1468             }
1469             printBuffer[message.message.asnLength] = 0;
1470             clock_gettime(CLOCK_MONOTONIC, &end);
1471             mdclog_write(MDCLOG_DEBUG, "Before Encoding E2AP PDU for : %s, Read time is : %ld seconds, %ld nanoseconds",
1472                          message.peerInfo->enodbName, end.tv_sec - start.tv_sec, end.tv_nsec - start.tv_nsec);
1473             mdclog_write(MDCLOG_DEBUG, "PDU buffer length = %ld, data =  : %s", message.message.asnLength,
1474                          printBuffer);
1475             clock_gettime(CLOCK_MONOTONIC, &decodeStart);
1476         }
1477 #ifndef UNIT_TEST
1478         auto rval = asn_decode(nullptr, ATS_ALIGNED_BASIC_PER, &asn_DEF_E2AP_PDU, (void **) &pdu,
1479                         message.message.asndata, message.message.asnLength);
1480 #else
1481         asn_dec_rval_t rval = {RC_OK, 0};
1482         pdu = (E2AP_PDU_t*)rmrMessageBuffer.sendMessage->tp_buf;
1483 #endif
1484         if (rval.code != RC_OK) {
1485             mdclog_write(MDCLOG_ERR, "Error %d Decoding (unpack) E2AP PDU from RAN : %s", rval.code,
1486                          message.peerInfo->enodbName);
1487             if (pdu != nullptr) {
1488                 ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
1489                 pdu = nullptr;
1490             }
1491             break;
1492         }
1493
1494         if (loglevel >= MDCLOG_DEBUG) {
1495             clock_gettime(CLOCK_MONOTONIC, &end);
1496             mdclog_write(MDCLOG_DEBUG, "After Encoding E2AP PDU for : %s, Read time is : %ld seconds, %ld nanoseconds",
1497                          message.peerInfo->enodbName, end.tv_sec - decodeStart.tv_sec, end.tv_nsec - decodeStart.tv_nsec);
1498             char *printBuffer;
1499             size_t size;
1500             FILE *stream = open_memstream(&printBuffer, &size);
1501             asn_fprint(stream, &asn_DEF_E2AP_PDU, pdu);
1502             mdclog_write(MDCLOG_DEBUG, "Encoding E2AP PDU past : %s", printBuffer);
1503             clock_gettime(CLOCK_MONOTONIC, &decodeStart);
1504
1505             fclose(stream);
1506             free(printBuffer);
1507         }
1508
1509         switch (pdu->present) {
1510             case E2AP_PDU_PR_initiatingMessage: {//initiating message
1511                 asnInitiatingRequest(pdu, sctpMap,message, rmrMessageBuffer, streamId);
1512                 break;
1513             }
1514             case E2AP_PDU_PR_successfulOutcome: { //successful outcome
1515                 asnSuccessfulMsg(pdu, sctpMap, message, rmrMessageBuffer);
1516                 break;
1517             }
1518             case E2AP_PDU_PR_unsuccessfulOutcome: { //Unsuccessful Outcome
1519                 asnUnSuccsesfulMsg(pdu, sctpMap, message, rmrMessageBuffer);
1520                 break;
1521             }
1522             default:
1523                 mdclog_write(MDCLOG_ERR, "Unknown index %d in E2AP PDU", pdu->present);
1524                 break;
1525         }
1526         if (loglevel >= MDCLOG_DEBUG) {
1527             clock_gettime(CLOCK_MONOTONIC, &end);
1528             mdclog_write(MDCLOG_DEBUG,
1529                          "After processing message and sent to rmr for : %s, Read time is : %ld seconds, %ld nanoseconds",
1530                          message.peerInfo->enodbName, end.tv_sec - decodeStart.tv_sec, end.tv_nsec - decodeStart.tv_nsec);
1531         }
1532         numOfMessages++;
1533 #ifndef UNIT_TEST
1534         if (pdu != nullptr) {
1535             // ASN_STRUCT_RESET(asn_DEF_E2AP_PDU, pdu); /* With reset we were not freeing the memory and was causing the leak here. */
1536             ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
1537             pdu = nullptr;
1538         }
1539 #else
1540     done = 1;
1541     break;
1542 #endif
1543     }
1544
1545     if (done) {
1546         if (loglevel >= MDCLOG_INFO) {
1547             mdclog_write(MDCLOG_INFO, "Closed connection - descriptor = %d", message.peerInfo->fileDescriptor);
1548         }
1549         message.message.asnLength = rmrMessageBuffer.sendMessage->len =
1550                 snprintf((char *)rmrMessageBuffer.sendMessage->payload,
1551                          256,
1552                          "%s|CU disconnected unexpectedly",
1553                          message.peerInfo->enodbName);
1554         message.message.asndata = rmrMessageBuffer.sendMessage->payload;
1555 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1556         if (sendRequestToXapp(message,
1557                               RIC_SCTP_CONNECTION_FAILURE,
1558                               rmrMessageBuffer) != 0) {
1559             mdclog_write(MDCLOG_ERR, "SCTP_CONNECTION_FAIL message failed to send to xAPP");
1560         }
1561 #endif
1562
1563         /* Closing descriptor make epoll remove it from the set of descriptors which are monitored. */
1564 #ifndef UNIT_TEST
1565         pthread_mutex_lock(&thread_lock);
1566         if (fcntl(message.peerInfo->fileDescriptor, F_GETFD) != -1) {
1567             mdclog_write(MDCLOG_DEBUG, "Closing connection - descriptor = %d", message.peerInfo->fileDescriptor);
1568             close(message.peerInfo->fileDescriptor);
1569             cleanHashEntry((ConnectedCU_t *) events->data.ptr, sctpMap);
1570         }
1571         pthread_mutex_unlock(&thread_lock);
1572 #else
1573         close(message.peerInfo->fileDescriptor);
1574         cleanHashEntry((ConnectedCU_t *) events->data.ptr, sctpMap);
1575 #endif
1576     }
1577     if (loglevel >= MDCLOG_DEBUG) {
1578         clock_gettime(CLOCK_MONOTONIC, &end);
1579         mdclog_write(MDCLOG_DEBUG, "from receive SCTP to send RMR time is %ld seconds and %ld nanoseconds",
1580                      end.tv_sec - start.tv_sec, end.tv_nsec - start.tv_nsec);
1581
1582     }
1583     return 0;
1584 }
1585
1586 static void buildAndSendSetupRequest(ReportingMessages_t &message,
1587                                      RmrMessagesBuffer_t &rmrMessageBuffer,
1588                                      E2AP_PDU_t *pdu/*,
1589                                      string const &messageName,
1590                                      string const &ieName,
1591                                      vector<string> &functionsToAdd_v,
1592                                      vector<string> &functionsToModified_v*/) {
1593     auto logLevel = mdclog_level_get();
1594     // now we can send the data to e2Mgr
1595
1596     asn_enc_rval_t er;
1597     auto buffer_size = RECEIVE_SCTP_BUFFER_SIZE * 2;
1598     unsigned char *buffer = nullptr;
1599     buffer = (unsigned char *) calloc(buffer_size, sizeof(unsigned char));
1600     if(!buffer)
1601     {
1602 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1603         mdclog_write(MDCLOG_ERR, "Allocating buffer for %s failed, %s", asn_DEF_E2AP_PDU.name, strerror(errno));
1604         return;
1605 #endif
1606     }
1607     while (true) {
1608         er = asn_encode_to_buffer(nullptr, ATS_BASIC_XER, &asn_DEF_E2AP_PDU, pdu, buffer, buffer_size);
1609         if (er.encoded == -1) {
1610 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1611             mdclog_write(MDCLOG_ERR, "encoding of %s failed, %s", asn_DEF_E2AP_PDU.name, strerror(errno));
1612             return;
1613 #endif
1614         } else if (er.encoded > (ssize_t) buffer_size) {
1615             buffer_size = er.encoded + 128;
1616 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
1617             mdclog_write(MDCLOG_WARN, "Buffer of size %d is to small for %s. Reallocate buffer of size %d",
1618                          (int) buffer_size,
1619                          asn_DEF_E2AP_PDU.name, buffer_size);
1620             buffer_size = er.encoded + 128;
1621
1622             unsigned char *newBuffer = nullptr;
1623             newBuffer = (unsigned char *) realloc(buffer, buffer_size);
1624             if (!newBuffer)
1625             {
1626                 // out of memory
1627                 mdclog_write(MDCLOG_ERR, "Reallocating buffer for %s failed, %s", asn_DEF_E2AP_PDU.name, strerror(errno));
1628                 free(buffer);
1629                 buffer = nullptr;
1630                 return;
1631             }
1632             buffer = newBuffer;
1633             continue;
1634 #endif
1635         }
1636         buffer[er.encoded] = '\0';
1637         break;
1638     }
1639     // encode to xml
1640
1641     string res((char *)buffer);
1642     res.erase(std::remove(res.begin(), res.end(), '\n'), res.end());
1643     res.erase(std::remove(res.begin(), res.end(), '\t'), res.end());
1644     res.erase(std::remove(res.begin(), res.end(), ' '), res.end());
1645
1646 //    string res {};
1647 //    if (!functionsToAdd_v.empty() || !functionsToModified_v.empty()) {
1648 //        res = buildXmlData(messageName, ieName, functionsToAdd_v, functionsToModified_v, buffer, (size_t) er.encoded);
1649 //    }
1650     rmr_mbuf_t *rmrMsg;
1651 //    if (res.length() == 0) {
1652 //        rmrMsg = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, buffer_size + 256);
1653 //        rmrMsg->len = snprintf((char *) rmrMsg->payload, RECEIVE_SCTP_BUFFER_SIZE * 2, "%s:%d|%s",
1654 //                               message.peerInfo->sctpParams->myIP.c_str(),
1655 //                               message.peerInfo->sctpParams->rmrPort,
1656 //                               buffer);
1657 //    } else {
1658         rmrMsg = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, (int)res.length() + 256);
1659         rmrMsg->len = snprintf((char *) rmrMsg->payload, res.length() + 256, "%s:%d|%s",
1660                                message.peerInfo->sctpParams->myIP.c_str(),
1661                                message.peerInfo->sctpParams->rmrPort,
1662                                res.c_str());
1663 //    }
1664
1665     if (logLevel >= MDCLOG_DEBUG) {
1666         mdclog_write(MDCLOG_DEBUG, "Setup request of size %d :\n %s\n", rmrMsg->len, rmrMsg->payload);
1667     }
1668     // send to RMR
1669     rmrMsg->mtype = message.message.messageType;
1670     rmrMsg->state = 0;
1671     rmr_bytes2meid(rmrMsg, (unsigned char *) message.message.enodbName, strlen(message.message.enodbName));
1672
1673     static unsigned char tx[32];
1674     snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
1675     rmr_bytes2xact(rmrMsg, tx, strlen((const char *) tx));
1676 #ifndef UNIT_TEST
1677     rmrMsg = rmr_send_msg(rmrMessageBuffer.rmrCtx, rmrMsg);
1678 #endif
1679     if (rmrMsg == nullptr) {
1680         mdclog_write(MDCLOG_ERR, "RMR failed to send returned nullptr");
1681     } else if (rmrMsg->state != 0) {
1682         char meid[RMR_MAX_MEID]{};
1683         if (rmrMsg->state == RMR_ERR_RETRY) {
1684             usleep(5);
1685             rmrMsg->state = 0;
1686             mdclog_write(MDCLOG_INFO, "RETRY sending Message %d to Xapp from %s",
1687                          rmrMsg->mtype, rmr_get_meid(rmrMsg, (unsigned char *) meid));
1688 #ifndef UNIT_TEST
1689             rmrMsg = rmr_send_msg(rmrMessageBuffer.rmrCtx, rmrMsg);
1690 #endif
1691             if (rmrMsg == nullptr) {
1692                 mdclog_write(MDCLOG_ERR, "RMR failed send returned nullptr");
1693             } else if (rmrMsg->state != 0) {
1694                 mdclog_write(MDCLOG_ERR,
1695                              "RMR Retry failed %s sending request %d to Xapp from %s",
1696                              translateRmrErrorMessages(rmrMsg->state).c_str(),
1697                              rmrMsg->mtype,
1698                              rmr_get_meid(rmrMsg, (unsigned char *) meid));
1699             }
1700         } else {
1701             mdclog_write(MDCLOG_ERR, "RMR failed: %s. sending request %d to Xapp from %s",
1702                          translateRmrErrorMessages(rmrMsg->state).c_str(),
1703                          rmrMsg->mtype,
1704                          rmr_get_meid(rmrMsg, (unsigned char *) meid));
1705         }
1706     }
1707     message.peerInfo->gotSetup = true;
1708     buildJsonMessage(message);
1709
1710     if (rmrMsg != nullptr) {
1711         rmr_free_msg(rmrMsg);
1712     }
1713     free(buffer);
1714     buffer = nullptr;
1715
1716     return;
1717 }
1718
1719 #if 0
1720 int RAN_Function_list_To_Vector(RANfunctions_List_t& list, vector <string> &runFunXML_v) {
1721     auto index = 0;
1722     runFunXML_v.clear();
1723     for (auto j = 0; j < list.list.count; j++) {
1724         auto *raNfunctionItemIEs = (RANfunction_ItemIEs_t *)list.list.array[j];
1725         if (raNfunctionItemIEs->id == ProtocolIE_ID_id_RANfunction_Item &&
1726             (raNfunctionItemIEs->value.present == RANfunction_ItemIEs__value_PR_RANfunction_Item)) {
1727             // encode to xml
1728             E2SM_gNB_NRT_RANfunction_Definition_t *ranFunDef = nullptr;
1729             auto rval = asn_decode(nullptr, ATS_ALIGNED_BASIC_PER,
1730                                    &asn_DEF_E2SM_gNB_NRT_RANfunction_Definition,
1731                                    (void **)&ranFunDef,
1732                                    raNfunctionItemIEs->value.choice.RANfunction_Item.ranFunctionDefinition.buf,
1733                                    raNfunctionItemIEs->value.choice.RANfunction_Item.ranFunctionDefinition.size);
1734             if (rval.code != RC_OK) {
1735                 mdclog_write(MDCLOG_ERR, "Error %d Decoding (unpack) E2SM message from : %s",
1736                              rval.code,
1737                              asn_DEF_E2SM_gNB_NRT_RANfunction_Definition.name);
1738                 return -1;
1739             }
1740
1741             auto xml_buffer_size = RECEIVE_SCTP_BUFFER_SIZE * 2;
1742             unsigned char xml_buffer[RECEIVE_SCTP_BUFFER_SIZE * 2];
1743             memset(xml_buffer, 0, RECEIVE_SCTP_BUFFER_SIZE * 2);
1744             // encode to xml
1745             auto er = asn_encode_to_buffer(nullptr,
1746                                            ATS_BASIC_XER,
1747                                            &asn_DEF_E2SM_gNB_NRT_RANfunction_Definition,
1748                                            ranFunDef,
1749                                            xml_buffer,
1750                                            xml_buffer_size);
1751             if (er.encoded == -1) {
1752                 mdclog_write(MDCLOG_ERR, "encoding of %s failed, %s",
1753                              asn_DEF_E2SM_gNB_NRT_RANfunction_Definition.name,
1754                              strerror(errno));
1755             } else if (er.encoded > (ssize_t)xml_buffer_size) {
1756                 mdclog_write(MDCLOG_ERR, "Buffer of size %d is to small for %s, at %s line %d",
1757                              (int) xml_buffer_size,
1758                              asn_DEF_E2SM_gNB_NRT_RANfunction_Definition.name, __func__, __LINE__);
1759             } else {
1760                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
1761                     mdclog_write(MDCLOG_DEBUG, "Encoding E2SM %s PDU number %d : %s",
1762                                  asn_DEF_E2SM_gNB_NRT_RANfunction_Definition.name,
1763                                  index++,
1764                                  xml_buffer);
1765                 }
1766
1767                 string runFuncs = (char *)(xml_buffer);
1768                 runFunXML_v.emplace_back(runFuncs);
1769             }
1770         }
1771     }
1772     return 0;
1773 }
1774
1775 int collectServiceUpdate_RequestData(E2AP_PDU_t *pdu,
1776                                      Sctp_Map_t *sctpMap,
1777                                      ReportingMessages_t &message,
1778                                      vector <string> &RANfunctionsAdded_v,
1779                                      vector <string> &RANfunctionsModified_v) {
1780     memset(message.peerInfo->enodbName, 0 , MAX_ENODB_NAME_SIZE);
1781     for (auto i = 0; i < pdu->choice.initiatingMessage->value.choice.RICserviceUpdate.protocolIEs.list.count; i++) {
1782         auto *ie = pdu->choice.initiatingMessage->value.choice.RICserviceUpdate.protocolIEs.list.array[i];
1783         if (ie->id == ProtocolIE_ID_id_RANfunctionsAdded) {
1784             if (ie->value.present == RICserviceUpdate_IEs__value_PR_RANfunctionsID_List) {
1785                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
1786                     mdclog_write(MDCLOG_DEBUG, "Run function list have %d entries",
1787                                  ie->value.choice.RANfunctions_List.list.count);
1788                 }
1789                 if (RAN_Function_list_To_Vector(ie->value.choice.RANfunctions_List, RANfunctionsAdded_v) != 0 ) {
1790                     return -1;
1791                 }
1792             }
1793         } else if (ie->id == ProtocolIE_ID_id_RANfunctionsModified) {
1794             if (ie->value.present == RICserviceUpdate_IEs__value_PR_RANfunctions_List) {
1795                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
1796                     mdclog_write(MDCLOG_DEBUG, "Run function list have %d entries",
1797                                  ie->value.choice.RANfunctions_List.list.count);
1798                 }
1799                 if (RAN_Function_list_To_Vector(ie->value.choice.RANfunctions_List, RANfunctionsModified_v) != 0 ) {
1800                     return -1;
1801                 }
1802             }
1803         }
1804     }
1805     if (mdclog_level_get() >= MDCLOG_DEBUG) {
1806         mdclog_write(MDCLOG_DEBUG, "Run function vector have %ld entries",
1807                      RANfunctionsAdded_v.size());
1808     }
1809     return 0;
1810 }
1811
1812 #endif
1813
1814
1815 void buildE2TPrometheusCounters(sctp_params_t &sctpParams) {
1816     sctpParams.e2tCounters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_E2setup)] = &sctpParams.prometheusFamily->Add({{"counter", "SetupRequestMsgs"}});
1817     sctpParams.e2tCounters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_E2setup)] = &sctpParams.prometheusFamily->Add({{"counter", "SetupRequestBytes"}});
1818
1819     sctpParams.e2tCounters[OUT_SUCC][MSG_COUNTER][(ProcedureCode_id_E2setup)] = &sctpParams.prometheusFamily->Add({{"counter", "SetupResponseMsgs"}});
1820     sctpParams.e2tCounters[OUT_SUCC][BYTES_COUNTER][(ProcedureCode_id_E2setup)] = &sctpParams.prometheusFamily->Add({{"counter", "SetupResponseBytes"}});
1821
1822     sctpParams.e2tCounters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_E2setup] = &sctpParams.prometheusFamily->Add({{"counter", "SetupRequestFailureMsgs"}});
1823     sctpParams.e2tCounters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_E2setup] = &sctpParams.prometheusFamily->Add({{"counter", "SetupRequestFailureBytes"}});
1824
1825     sctpParams.e2tCounters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &sctpParams.prometheusFamily->Add({{"counter", "E2NodeConfigUpdateMsgs"}});
1826     sctpParams.e2tCounters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &sctpParams.prometheusFamily->Add({{"counter", "E2NodeConfigUpdateBytes"}});
1827
1828     sctpParams.e2tCounters[OUT_SUCC][MSG_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &sctpParams.prometheusFamily->Add({{"counter", "E2NodeConfigUpdateResponseMsgs"}});
1829     sctpParams.e2tCounters[OUT_SUCC][BYTES_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &sctpParams.prometheusFamily->Add({{"counter", "E2NodeConfigUpdateResponseBytes"}});
1830
1831     sctpParams.e2tCounters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "E2NodeConfigUpdateFailureMsgs"}});
1832     sctpParams.e2tCounters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "E2NodeConfigUpdateFailureBytes"}});
1833
1834     sctpParams.e2tCounters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_ErrorIndication)] = &sctpParams.prometheusFamily->Add({{"counter", "ErrorIndicationMsgs"}});
1835     sctpParams.e2tCounters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_ErrorIndication)] = &sctpParams.prometheusFamily->Add({{"counter", "ErrorIndicationBytes"}});
1836
1837     sctpParams.e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_Reset] = &sctpParams.prometheusFamily->Add({{"counter", "ResetRequestMsgs"}});
1838     sctpParams.e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_Reset] = &sctpParams.prometheusFamily->Add({{"counter", "ResetRequestBytes"}});
1839
1840     sctpParams.e2tCounters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_Reset] = &sctpParams.prometheusFamily->Add({{"counter", "ResetAckMsgs"}});
1841     sctpParams.e2tCounters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_Reset] = &sctpParams.prometheusFamily->Add({{"counter", "ResetAckBytes"}});
1842
1843     sctpParams.e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceUpdateMsgs"}});
1844     sctpParams.e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceUpdateBytes"}});
1845
1846     sctpParams.e2tCounters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceUpdateRespMsgs"}});
1847     sctpParams.e2tCounters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceUpdateRespBytes"}});
1848
1849     sctpParams.e2tCounters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceUpdateFailureMsgs"}});
1850     sctpParams.e2tCounters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceUpdateFailureBytes"}});
1851
1852     sctpParams.e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICcontrol] = &sctpParams.prometheusFamily->Add({{"counter", "RICControlMsgs"}});
1853     sctpParams.e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICcontrol] = &sctpParams.prometheusFamily->Add({{"counter", "RICControlBytes"}});
1854
1855     sctpParams.e2tCounters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICcontrol] = &sctpParams.prometheusFamily->Add({{"counter", "RICControlAckMsgs"}});
1856     sctpParams.e2tCounters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICcontrol] = &sctpParams.prometheusFamily->Add({{"counter", "RICControlAckBytes"}});
1857
1858     sctpParams.e2tCounters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICcontrol] = &sctpParams.prometheusFamily->Add({{"counter", "RICControlFailureMsgs"}});
1859     sctpParams.e2tCounters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICcontrol] = &sctpParams.prometheusFamily->Add({{"counter", "RICControlFailureBytes"}});
1860
1861     sctpParams.e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscription] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionMsgs"}});
1862     sctpParams.e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscription] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionBytes"}});
1863
1864     sctpParams.e2tCounters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscription] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionAckMsgs"}});
1865     sctpParams.e2tCounters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscription] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionAckBytes"}});
1866
1867     sctpParams.e2tCounters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscription] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionFailureMsgs"}});
1868     sctpParams.e2tCounters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscription] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionFailureBytes"}});
1869
1870     sctpParams.e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteMsgs"}});
1871     sctpParams.e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteBytes"}});
1872
1873     sctpParams.e2tCounters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteAckMsgs"}});
1874     sctpParams.e2tCounters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteAckBytes"}});
1875
1876     sctpParams.e2tCounters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteFailMsgs"}});
1877     sctpParams.e2tCounters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteFailBytes"}});
1878
1879     sctpParams.e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICindication] = &sctpParams.prometheusFamily->Add({{"counter", "RICIndicationMsgs"}});
1880     sctpParams.e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICindication] = &sctpParams.prometheusFamily->Add({{"counter", "RICIndicationBytes"}});
1881
1882     sctpParams.e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICserviceQuery] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceQueryMsgs"}});
1883     sctpParams.e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICserviceQuery] = &sctpParams.prometheusFamily->Add({{"counter", "RICServiceQueryBytes"}});
1884
1885     sctpParams.e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDeleteRequired] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteRequiredMsgs"}});
1886     sctpParams.e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDeleteRequired] = &sctpParams.prometheusFamily->Add({{"counter", "RICSubscriptionDeleteRequiredBytes"}});
1887
1888 }
1889
1890 void buildPrometheusList(ConnectedCU_t *peerInfo, Family<Counter> *prometheusFamily) {
1891     peerInfo->counters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_E2setup)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"SetupRequest", "Messages"}});
1892     peerInfo->counters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_E2setup)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"SetupRequest", "Bytes"}});
1893
1894     peerInfo->counters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"E2NodeConfigUpdate", "Messages"}});
1895     peerInfo->counters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"E2NodeConfigUpdate", "Bytes"}});
1896
1897     peerInfo->counters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_ErrorIndication)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"ErrorIndication", "Messages"}});
1898     peerInfo->counters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_ErrorIndication)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"ErrorIndication", "Bytes"}});
1899
1900     peerInfo->counters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_RICindication)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICindication", "Messages"}});
1901     peerInfo->counters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_RICindication)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICindication", "Bytes"}});
1902
1903     peerInfo->counters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"ResetRequest", "Messages"}});
1904     peerInfo->counters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"ResetRequest", "Bytes"}});
1905
1906     peerInfo->counters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_RICserviceUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICserviceUpdate", "Messages"}});
1907     peerInfo->counters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_RICserviceUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICserviceUpdate", "Bytes"}});
1908     // ---------------------------------------------
1909     peerInfo->counters[IN_SUCC][MSG_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"ResetACK", "Messages"}});
1910     peerInfo->counters[IN_SUCC][BYTES_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"ResetACK", "Bytes"}});
1911
1912     peerInfo->counters[IN_SUCC][MSG_COUNTER][(ProcedureCode_id_RICcontrol)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICcontrolACK", "Messages"}});
1913     peerInfo->counters[IN_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICcontrol)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICcontrolACK", "Bytes"}});
1914
1915     peerInfo->counters[IN_SUCC][MSG_COUNTER][(ProcedureCode_id_RICsubscription)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionACK", "Messages"}});
1916     peerInfo->counters[IN_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICsubscription)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionACK", "Bytes"}});
1917
1918     peerInfo->counters[IN_SUCC][MSG_COUNTER][(ProcedureCode_id_RICsubscriptionDelete)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionDeleteACK", "Messages"}});
1919     peerInfo->counters[IN_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICsubscriptionDelete)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionDeleteACK", "Bytes"}});
1920     //-------------------------------------------------------------
1921
1922     peerInfo->counters[IN_UN_SUCC][MSG_COUNTER][(ProcedureCode_id_RICcontrol)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICcontrolFailure", "Messages"}});
1923     peerInfo->counters[IN_UN_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICcontrol)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICcontrolFailure", "Bytes"}});
1924
1925     peerInfo->counters[IN_UN_SUCC][MSG_COUNTER][(ProcedureCode_id_RICsubscription)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionFailure", "Messages"}});
1926     peerInfo->counters[IN_UN_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICsubscription)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionFailure", "Bytes"}});
1927
1928     peerInfo->counters[IN_UN_SUCC][MSG_COUNTER][(ProcedureCode_id_RICsubscriptionDelete)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionDeleteFailure", "Messages"}});
1929     peerInfo->counters[IN_UN_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICsubscriptionDelete)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionDeleteFailure", "Bytes"}});
1930
1931     //====================================================================================
1932     peerInfo->counters[OUT_INITI][MSG_COUNTER][(ProcedureCode_id_ErrorIndication)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"ErrorIndication", "Messages"}});
1933     peerInfo->counters[OUT_INITI][BYTES_COUNTER][(ProcedureCode_id_ErrorIndication)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"ErrorIndication", "Bytes"}});
1934
1935     peerInfo->counters[OUT_INITI][MSG_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"ResetRequest", "Messages"}});
1936     peerInfo->counters[OUT_INITI][BYTES_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"ResetRequest", "Bytes"}});
1937
1938     peerInfo->counters[OUT_INITI][MSG_COUNTER][(ProcedureCode_id_RICcontrol)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICcontrol", "Messages"}});
1939     peerInfo->counters[OUT_INITI][BYTES_COUNTER][(ProcedureCode_id_RICcontrol)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICcontrol", "Bytes"}});
1940
1941     peerInfo->counters[OUT_INITI][MSG_COUNTER][(ProcedureCode_id_RICserviceQuery)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICserviceQuery", "Messages"}});
1942     peerInfo->counters[OUT_INITI][BYTES_COUNTER][(ProcedureCode_id_RICserviceQuery)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICserviceQuery", "Bytes"}});
1943
1944     peerInfo->counters[OUT_INITI][MSG_COUNTER][(ProcedureCode_id_RICsubscription)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICsubscription", "Messages"}});
1945     peerInfo->counters[OUT_INITI][BYTES_COUNTER][(ProcedureCode_id_RICsubscription)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICsubscription", "Bytes"}});
1946
1947     peerInfo->counters[OUT_INITI][MSG_COUNTER][(ProcedureCode_id_RICsubscriptionDelete)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICsubscriptionDelete", "Messages"}});
1948     peerInfo->counters[OUT_INITI][BYTES_COUNTER][(ProcedureCode_id_RICsubscriptionDelete)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICsubscriptionDelete", "Bytes"}});
1949     //---------------------------------------------------------------------------------------------------------
1950     peerInfo->counters[OUT_SUCC][MSG_COUNTER][(ProcedureCode_id_E2setup)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"SetupResponse", "Messages"}});
1951     peerInfo->counters[OUT_SUCC][BYTES_COUNTER][(ProcedureCode_id_E2setup)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"SetupResponse", "Bytes"}});
1952
1953     peerInfo->counters[OUT_SUCC][MSG_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"E2NodeConfigUpdateSuccess", "Messages"}});
1954     peerInfo->counters[OUT_SUCC][BYTES_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"E2NodeConfigUpdateSuccess", "Bytes"}});
1955
1956     peerInfo->counters[OUT_SUCC][MSG_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"ResetACK", "Messages"}});
1957     peerInfo->counters[OUT_SUCC][BYTES_COUNTER][(ProcedureCode_id_Reset)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"ResetACK", "Bytes"}});
1958
1959     peerInfo->counters[OUT_SUCC][MSG_COUNTER][(ProcedureCode_id_RICserviceUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICserviceUpdateResponse", "Messages"}});
1960     peerInfo->counters[OUT_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICserviceUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICserviceUpdateResponse", "Bytes"}});
1961     //----------------------------------------------------------------------------------------------------------------
1962     peerInfo->counters[OUT_UN_SUCC][MSG_COUNTER][(ProcedureCode_id_E2setup)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"SetupRequestFailure", "Messages"}});
1963     peerInfo->counters[OUT_UN_SUCC][BYTES_COUNTER][(ProcedureCode_id_E2setup)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"SetupRequestFailure", "Bytes"}});
1964
1965     peerInfo->counters[OUT_UN_SUCC][MSG_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"E2NodeConfigUpdateFailure", "Messages"}});
1966     peerInfo->counters[OUT_UN_SUCC][BYTES_COUNTER][(ProcedureCode_id_E2nodeConfigurationUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"E2NodeConfigUpdateFailure", "Bytes"}});
1967
1968     peerInfo->counters[OUT_UN_SUCC][MSG_COUNTER][(ProcedureCode_id_RICserviceUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICserviceUpdateFailure", "Messages"}});
1969     peerInfo->counters[OUT_UN_SUCC][BYTES_COUNTER][(ProcedureCode_id_RICserviceUpdate)] = &prometheusFamily->Add({{peerInfo->enodbName, "OUT"}, {"RICserviceUpdateFailure", "Bytes"}});
1970
1971
1972     peerInfo->counters[IN_INITI][MSG_COUNTER][(ProcedureCode_id_RICsubscriptionDeleteRequired)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionDeleteRequired", "Messages"}});
1973     peerInfo->counters[IN_INITI][BYTES_COUNTER][(ProcedureCode_id_RICsubscriptionDeleteRequired)] = &prometheusFamily->Add({{peerInfo->enodbName, "IN"}, {"RICsubscriptionDeleteRequired", "Bytes"}});
1974
1975 }
1976
1977 /**
1978  *
1979  * @param pdu
1980  * @param sctpMap
1981  * @param message
1982  * @param RANfunctionsAdded_v
1983  * @return
1984  */
1985 int collectSetupRequestData(E2AP_PDU_t *pdu,
1986                                      Sctp_Map_t *sctpMap,
1987                                      ReportingMessages_t &message /*, vector <string> &RANfunctionsAdded_v*/) {
1988     memset(message.peerInfo->enodbName, 0 , MAX_ENODB_NAME_SIZE);
1989     for (auto i = 0; i < pdu->choice.initiatingMessage->value.choice.E2setupRequest.protocolIEs.list.count; i++) {
1990         auto *ie = pdu->choice.initiatingMessage->value.choice.E2setupRequest.protocolIEs.list.array[i];
1991         if (ie->id == ProtocolIE_ID_id_GlobalE2node_ID) {
1992             // get the ran name for meid
1993             if (ie->value.present == E2setupRequestIEs__value_PR_GlobalE2node_ID) {
1994                 if (buildRanName(message.peerInfo->enodbName, ie) < 0) {
1995                     mdclog_write(MDCLOG_ERR, "Bad param in E2setupRequestIEs GlobalE2node_ID.\n");
1996                     // no message will be sent
1997                     return -1;
1998                 }
1999
2000                 memcpy(message.message.enodbName, message.peerInfo->enodbName, strlen(message.peerInfo->enodbName));
2001                 sctpMap->setkey(message.message.enodbName, message.peerInfo);
2002             }
2003         } /*else if (ie->id == ProtocolIE_ID_id_RANfunctionsAdded) {
2004             if (ie->value.present == E2setupRequestIEs__value_PR_RANfunctions_List) {
2005                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
2006                     mdclog_write(MDCLOG_DEBUG, "Run function list have %d entries",
2007                                  ie->value.choice.RANfunctions_List.list.count);
2008                 }
2009                 if (RAN_Function_list_To_Vector(ie->value.choice.RANfunctions_List, RANfunctionsAdded_v) != 0 ) {
2010                     return -1;
2011                 }
2012             }
2013         } */
2014     }
2015 //    if (mdclog_level_get() >= MDCLOG_DEBUG) {
2016 //        mdclog_write(MDCLOG_DEBUG, "Run function vector have %ld entries",
2017 //                     RANfunctionsAdded_v.size());
2018 //    }
2019     return 0;
2020 }
2021
2022 int XML_From_PER(ReportingMessages_t &message, RmrMessagesBuffer_t &rmrMessageBuffer) {
2023     E2AP_PDU_t *pdu = nullptr;
2024
2025     if (mdclog_level_get() >= MDCLOG_DEBUG) {
2026         mdclog_write(MDCLOG_DEBUG, "got PER message of size %d is:%s",
2027                      rmrMessageBuffer.sendMessage->len, rmrMessageBuffer.sendMessage->payload);
2028     }
2029     auto rval = asn_decode(nullptr, ATS_ALIGNED_BASIC_PER, &asn_DEF_E2AP_PDU, (void **) &pdu,
2030                            rmrMessageBuffer.sendMessage->payload, rmrMessageBuffer.sendMessage->len);
2031     if (rval.code != RC_OK) {
2032         mdclog_write(MDCLOG_ERR, "Error %d Decoding (unpack) setup response  from E2MGR : %s",
2033                      rval.code,
2034                      message.message.enodbName);
2035         if (pdu != nullptr) {
2036             ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2037             pdu = nullptr;
2038         }
2039         return -1;
2040     }
2041
2042     int buff_size = RECEIVE_XAPP_BUFFER_SIZE;
2043     auto er = asn_encode_to_buffer(nullptr, ATS_BASIC_XER, &asn_DEF_E2AP_PDU, pdu,
2044                                    rmrMessageBuffer.sendMessage->payload, buff_size);
2045     if (er.encoded == -1) {
2046         mdclog_write(MDCLOG_ERR, "encoding of %s failed, %s", asn_DEF_E2AP_PDU.name, strerror(errno));
2047         if (pdu != nullptr) {
2048             ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2049             pdu = nullptr;
2050         }
2051         return -1;
2052     } else if (er.encoded > (ssize_t)buff_size) {
2053         mdclog_write(MDCLOG_ERR, "Buffer of size %d is to small for %s, at %s line %d",
2054                      (int)rmrMessageBuffer.sendMessage->len,
2055                      asn_DEF_E2AP_PDU.name,
2056                      __func__,
2057                      __LINE__);
2058         if (pdu != nullptr) {
2059             ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2060             pdu = nullptr;
2061         }
2062         return -1;
2063     }
2064     rmrMessageBuffer.sendMessage->len = er.encoded;
2065     if (pdu != nullptr) {
2066         ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2067         pdu = nullptr;
2068     }
2069     return 0;
2070
2071 }
2072
2073 /**
2074  *
2075  * @param pdu
2076  * @param message
2077  * @param rmrMessageBuffer
2078  */
2079 void asnInitiatingRequest(E2AP_PDU_t *pdu,
2080                           Sctp_Map_t *sctpMap,
2081                           ReportingMessages_t &message,
2082                           RmrMessagesBuffer_t &rmrMessageBuffer, int streamId) {
2083     auto logLevel = mdclog_level_get();
2084     auto procedureCode = ((InitiatingMessage_t *) pdu->choice.initiatingMessage)->procedureCode;
2085     if (logLevel >= MDCLOG_DEBUG) {
2086         mdclog_write(MDCLOG_DEBUG, "Initiating message %ld\n", procedureCode);
2087     }
2088     switch (procedureCode) {
2089         case ProcedureCode_id_E2setup: {
2090             if (logLevel >= MDCLOG_DEBUG) {
2091                 mdclog_write(MDCLOG_DEBUG, "Got E2setup");
2092             }
2093
2094 //            vector <string> RANfunctionsAdded_v;
2095 //            vector <string> RANfunctionsModified_v;
2096 //            RANfunctionsAdded_v.clear();
2097 //            RANfunctionsModified_v.clear();
2098             if (collectSetupRequestData(pdu, sctpMap, message) != 0) {
2099                 break;
2100             }
2101             struct sctp_status status;
2102             int stat_size = sizeof(status);
2103             getsockopt( message.peerInfo->fileDescriptor, SOL_SCTP, SCTP_STATUS,(void *)&status, (socklen_t *)&stat_size );
2104             if (logLevel >= MDCLOG_DEBUG) {
2105                 mdclog_write(MDCLOG_DEBUG, "Start from SCTP %d fd", message.peerInfo->fileDescriptor);
2106                 mdclog_write(MDCLOG_DEBUG, "SCTP status assoc id %d instrms %d outstrms %d", status.sstat_assoc_id,
2107                         status.sstat_instrms, status.sstat_outstrms);
2108             }
2109             if(status.sstat_outstrms == 1 || status.sstat_instrms == 1)
2110             {
2111                 message.peerInfo->isSingleStream = true;
2112                 message.peerInfo->singleStreamId = streamId;
2113                 if (status.sstat_outstrms == 1 && status.sstat_instrms == 1){
2114                     if (logLevel >= MDCLOG_DEBUG) {
2115                         mdclog_write(MDCLOG_DEBUG, "Single SCTP stream is used for sending from now on, assoc id %d streamId %d #instrms %d #outstrms %d, %s",status.sstat_assoc_id, streamId, status.sstat_instrms, status.sstat_outstrms, __FUNCTION__);
2116                     }
2117                 }
2118                 else {
2119                     mdclog_write(MDCLOG_ERR, "Single SCTP stream used for sending messages even if there is a mismatch in number of in & out streams, assoc id %d instrms %d outstrms %d", status.sstat_assoc_id,
2120                             status.sstat_instrms, status.sstat_outstrms);
2121                 }
2122             }
2123
2124             buildPrometheusList(message.peerInfo, message.peerInfo->sctpParams->prometheusFamily);
2125
2126             string messageName("E2setupRequest");
2127             string ieName("E2setupRequestIEs");
2128             message.message.messageType = RIC_E2_SETUP_REQ;
2129             message.peerInfo->counters[IN_INITI][MSG_COUNTER][ProcedureCode_id_E2setup]->Increment();
2130             message.peerInfo->counters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_E2setup]->Increment((double)message.message.asnLength);
2131
2132             // Update E2T instance level metrics
2133             message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_E2setup]->Increment();
2134             message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_E2setup]->Increment((double)message.message.asnLength);
2135
2136             buildAndSendSetupRequest(message, rmrMessageBuffer, pdu);
2137             break;
2138         }
2139         case ProcedureCode_id_RICserviceUpdate: {
2140             if (logLevel >= MDCLOG_DEBUG) {
2141                 mdclog_write(MDCLOG_DEBUG, "Got RICserviceUpdate %s", message.message.enodbName);
2142             }
2143 //            vector <string> RANfunctionsAdded_v;
2144 //            vector <string> RANfunctionsModified_v;
2145 //            RANfunctionsAdded_v.clear();
2146 //            RANfunctionsModified_v.clear();
2147 //            if (collectServiceUpdate_RequestData(pdu, sctpMap, message,
2148 //                                                 RANfunctionsAdded_v, RANfunctionsModified_v) != 0) {
2149 //                break;
2150 //            }
2151
2152             string messageName("RICserviceUpdate");
2153             string ieName("RICserviceUpdateIEs");
2154             message.message.messageType = RIC_SERVICE_UPDATE;
2155 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2156             message.peerInfo->counters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment();
2157             message.peerInfo->counters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment((double)message.message.asnLength);
2158
2159             // Update E2T instance level metrics
2160             message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment();
2161             message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment((double)message.message.asnLength);
2162 #endif
2163             buildAndSendSetupRequest(message, rmrMessageBuffer, pdu);
2164             break;
2165         }
2166
2167 case ProcedureCode_id_E2nodeConfigurationUpdate: {
2168             if (logLevel >= MDCLOG_DEBUG) {
2169                 mdclog_write(MDCLOG_DEBUG, "Got E2nodeConfigurationUpdate %s", message.message.enodbName);
2170             }
2171
2172             string messageName("RICE2nodeConfigurationUpdate");
2173             string ieName("RICE2nodeConfigurationUpdateIEs");
2174             message.message.messageType = RIC_E2NODE_CONFIG_UPDATE;
2175 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2176             message.peerInfo->counters[IN_INITI][MSG_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment();
2177             message.peerInfo->counters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment((double)message.message.asnLength);
2178
2179             // Update E2T instance level metrics
2180             message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment();
2181             message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment((double)message.message.asnLength);
2182 #endif
2183             buildAndSendSetupRequest(message, rmrMessageBuffer, pdu);
2184             break;
2185         }
2186
2187         case ProcedureCode_id_ErrorIndication: {
2188             if (logLevel >= MDCLOG_DEBUG) {
2189                 mdclog_write(MDCLOG_DEBUG, "Got ErrorIndication %s", message.message.enodbName);
2190             }
2191 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2192             message.peerInfo->counters[IN_INITI][MSG_COUNTER][ProcedureCode_id_ErrorIndication]->Increment();
2193             message.peerInfo->counters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_ErrorIndication]->Increment((double)message.message.asnLength);
2194
2195             // Update E2T instance level metrics
2196             message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_ErrorIndication]->Increment();
2197             message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_ErrorIndication]->Increment((double)message.message.asnLength);
2198 #endif
2199             if (sendRequestToXapp(message, RIC_ERROR_INDICATION, rmrMessageBuffer) != 0) {
2200                 mdclog_write(MDCLOG_ERR, "RIC_ERROR_INDICATION failed to send to xAPP");
2201             }
2202             break;
2203         }
2204         case ProcedureCode_id_Reset: {
2205             if (logLevel >= MDCLOG_DEBUG) {
2206                 mdclog_write(MDCLOG_DEBUG, "Got Reset %s", message.message.enodbName);
2207             }
2208 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2209             message.peerInfo->counters[IN_INITI][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2210             message.peerInfo->counters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment((double)message.message.asnLength);
2211
2212             // Update E2T instance level metrics
2213             message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2214             message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment((double)message.message.asnLength);
2215 #endif
2216             if (XML_From_PER(message, rmrMessageBuffer) < 0) {
2217                 break;
2218             }
2219
2220             if (sendRequestToXapp(message, RIC_E2_RESET_REQ, rmrMessageBuffer) != 0) {
2221                 mdclog_write(MDCLOG_ERR, "RIC_E2_RESET_REQ message failed to send to xAPP");
2222             }
2223             break;
2224         }
2225         case ProcedureCode_id_RICindication: {
2226             if (logLevel >= MDCLOG_DEBUG) {
2227                 mdclog_write(MDCLOG_DEBUG, "Got RICindication %s", message.message.enodbName);
2228             }
2229             for (auto i = 0; i < pdu->choice.initiatingMessage->value.choice.RICindication.protocolIEs.list.count; i++) {
2230                 auto messageSent = false;
2231                 RICindication_IEs_t *ie = pdu->choice.initiatingMessage->value.choice.RICindication.protocolIEs.list.array[i];
2232                 if (logLevel >= MDCLOG_DEBUG) {
2233                     mdclog_write(MDCLOG_DEBUG, "ie type (ProtocolIE_ID) = %ld", ie->id);
2234                 }
2235                 if (ie->id == ProtocolIE_ID_id_RICrequestID) {
2236                     if (logLevel >= MDCLOG_DEBUG) {
2237                         mdclog_write(MDCLOG_DEBUG, "Got RIC requestId entry, ie type (ProtocolIE_ID) = %ld", ie->id);
2238                     }
2239                     if (ie->value.present == RICindication_IEs__value_PR_RICrequestID) {
2240                         static unsigned char tx[32];
2241                         message.message.messageType = rmrMessageBuffer.sendMessage->mtype = RIC_INDICATION;
2242                         snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
2243                         rmr_bytes2xact(rmrMessageBuffer.sendMessage, tx, strlen((const char *) tx));
2244                         rmr_bytes2meid(rmrMessageBuffer.sendMessage,
2245                                        (unsigned char *)message.message.enodbName,
2246                                        strlen(message.message.enodbName));
2247                         rmrMessageBuffer.sendMessage->state = 0;
2248                         rmrMessageBuffer.sendMessage->sub_id = (int)ie->value.choice.RICrequestID.ricInstanceID;
2249
2250                         //ie->value.choice.RICrequestID.ricInstanceID;
2251                         if (mdclog_level_get() >= MDCLOG_DEBUG) {
2252                             mdclog_write(MDCLOG_DEBUG, "sub id = %d, mtype = %d, ric instance id %ld, requestor id = %ld",
2253                                          rmrMessageBuffer.sendMessage->sub_id,
2254                                          rmrMessageBuffer.sendMessage->mtype,
2255                                          ie->value.choice.RICrequestID.ricInstanceID,
2256                                          ie->value.choice.RICrequestID.ricRequestorID);
2257                         }
2258 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2259                         message.peerInfo->counters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICindication]->Increment();
2260                         message.peerInfo->counters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICindication]->Increment((double)message.message.asnLength);
2261
2262                         // Update E2T instance level metrics
2263                         message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICindication]->Increment();
2264                         message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICindication]->Increment((double)message.message.asnLength);
2265 #endif
2266                         sendRmrMessage(rmrMessageBuffer, message);
2267                         messageSent = true;
2268                     } else {
2269                         mdclog_write(MDCLOG_ERR, "RIC request id missing illegal request");
2270                     }
2271                 }
2272                 if (messageSent) {
2273                     break;
2274                 }
2275             }
2276             break;
2277         }
2278         case ProcedureCode_id_RICsubscriptionDeleteRequired: {
2279             if (logLevel >= MDCLOG_DEBUG) {
2280                 mdclog_write(MDCLOG_DEBUG, "Got RICsubscriptionDeleteRequired %s", message.message.enodbName);
2281             }
2282         #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2283                     message.peerInfo->counters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDeleteRequired]->Increment();
2284                     message.peerInfo->counters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDeleteRequired]->Increment((double)message.message.asnLength);
2285
2286                     // Update E2T instance level metrics
2287                     message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDeleteRequired]->Increment();
2288                     message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDeleteRequired]->Increment((double)message.message.asnLength);
2289         #endif
2290             if (sendRequestToXapp(message, RIC_SUB_DEL_REQUIRED, rmrMessageBuffer) != 0) {
2291                 mdclog_write(MDCLOG_ERR, "Subscription Delete Required message failed to send to xAPP");
2292             }
2293             break;
2294         }
2295
2296         default: {
2297             mdclog_write(MDCLOG_ERR, "Undefined or not supported message = %ld", procedureCode);
2298             message.message.messageType = 0; // no RMR message type yet
2299
2300             buildJsonMessage(message);
2301
2302             break;
2303         }
2304     }
2305 }
2306
2307 /**
2308  *
2309  * @param pdu
2310  * @param message
2311  * @param rmrMessageBuffer
2312  */
2313 void asnSuccessfulMsg(E2AP_PDU_t *pdu,
2314                       Sctp_Map_t *sctpMap,
2315                       ReportingMessages_t &message,
2316                       RmrMessagesBuffer_t &rmrMessageBuffer) {
2317     auto procedureCode = pdu->choice.successfulOutcome->procedureCode;
2318     auto logLevel = mdclog_level_get();
2319     if (logLevel >= MDCLOG_INFO) {
2320         mdclog_write(MDCLOG_INFO, "Successful Outcome %ld", procedureCode);
2321     }
2322     switch (procedureCode) {
2323         case ProcedureCode_id_Reset: {
2324             if (logLevel >= MDCLOG_DEBUG) {
2325                 mdclog_write(MDCLOG_DEBUG, "Got Reset %s", message.message.enodbName);
2326             }
2327 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2328             message.peerInfo->counters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2329             message.peerInfo->counters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment((double)message.message.asnLength);
2330
2331             // Update E2T instance level metrics
2332             message.peerInfo->sctpParams->e2tCounters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2333             message.peerInfo->sctpParams->e2tCounters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment((double)message.message.asnLength);
2334 #endif
2335             if (XML_From_PER(message, rmrMessageBuffer) < 0) {
2336                 break;
2337             }
2338             if (sendRequestToXapp(message, RIC_E2_RESET_RESP, rmrMessageBuffer) != 0) {
2339                 mdclog_write(MDCLOG_ERR, "RIC_E2_RESET_RESP message failed to send to xAPP");
2340             }
2341             break;
2342         }
2343         case ProcedureCode_id_RICcontrol: {
2344             if (logLevel >= MDCLOG_DEBUG) {
2345                 mdclog_write(MDCLOG_DEBUG, "Got RICcontrol %s", message.message.enodbName);
2346             }
2347             for (auto i = 0;
2348                  i < pdu->choice.successfulOutcome->value.choice.RICcontrolAcknowledge.protocolIEs.list.count; i++) {
2349                 auto messageSent = false;
2350                 RICcontrolAcknowledge_IEs_t *ie = pdu->choice.successfulOutcome->value.choice.RICcontrolAcknowledge.protocolIEs.list.array[i];
2351                 if (mdclog_level_get() >= MDCLOG_DEBUG) {
2352                     mdclog_write(MDCLOG_DEBUG, "ie type (ProtocolIE_ID) = %ld", ie->id);
2353                 }
2354                 if (ie->id == ProtocolIE_ID_id_RICrequestID) {
2355                     if (mdclog_level_get() >= MDCLOG_DEBUG) {
2356                         mdclog_write(MDCLOG_DEBUG, "Got RIC requestId entry, ie type (ProtocolIE_ID) = %ld", ie->id);
2357                     }
2358                     if (ie->value.present == RICcontrolAcknowledge_IEs__value_PR_RICrequestID) {
2359                         message.message.messageType = rmrMessageBuffer.sendMessage->mtype = RIC_CONTROL_ACK;
2360                         rmrMessageBuffer.sendMessage->state = 0;
2361 //                        rmrMessageBuffer.sendMessage->sub_id = (int) ie->value.choice.RICrequestID.ricRequestorID;
2362                         rmrMessageBuffer.sendMessage->sub_id = (int)ie->value.choice.RICrequestID.ricInstanceID;
2363
2364                         static unsigned char tx[32];
2365                         snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
2366                         rmr_bytes2xact(rmrMessageBuffer.sendMessage, tx, strlen((const char *) tx));
2367                         rmr_bytes2meid(rmrMessageBuffer.sendMessage,
2368                                        (unsigned char *)message.message.enodbName,
2369                                        strlen(message.message.enodbName));
2370 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2371                         message.peerInfo->counters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICcontrol]->Increment();
2372                         message.peerInfo->counters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICcontrol]->Increment((double)message.message.asnLength);
2373
2374                         // Update E2T instance level metrics
2375                         message.peerInfo->sctpParams->e2tCounters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICcontrol]->Increment();
2376                         message.peerInfo->sctpParams->e2tCounters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICcontrol]->Increment((double)message.message.asnLength);
2377 #endif
2378                         sendRmrMessage(rmrMessageBuffer, message);
2379                         messageSent = true;
2380                     } else {
2381                         mdclog_write(MDCLOG_ERR, "RIC request id missing illegal request");
2382                     }
2383                 }
2384                 if (messageSent) {
2385                     break;
2386                 }
2387             }
2388
2389             break;
2390         }
2391         case ProcedureCode_id_RICsubscription: {
2392             if (logLevel >= MDCLOG_DEBUG) {
2393                 mdclog_write(MDCLOG_DEBUG, "Got RICsubscription %s", message.message.enodbName);
2394             }
2395 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2396             message.peerInfo->counters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscription]->Increment();
2397             message.peerInfo->counters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscription]->Increment((double)message.message.asnLength);
2398
2399             // Update E2T instance level metrics
2400             message.peerInfo->sctpParams->e2tCounters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscription]->Increment();
2401             message.peerInfo->sctpParams->e2tCounters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscription]->Increment((double)message.message.asnLength);
2402 #endif
2403             if (sendRequestToXapp(message, RIC_SUB_RESP, rmrMessageBuffer) != 0) {
2404                 mdclog_write(MDCLOG_ERR, "Subscription successful message failed to send to xAPP");
2405             }
2406             break;
2407         }
2408         case ProcedureCode_id_RICsubscriptionDelete: {
2409             if (logLevel >= MDCLOG_DEBUG) {
2410                 mdclog_write(MDCLOG_DEBUG, "Got RICsubscriptionDelete %s", message.message.enodbName);
2411             }
2412 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2413             message.peerInfo->counters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment();
2414             message.peerInfo->counters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment((double)message.message.asnLength);
2415
2416             // Update E2T instance level metrics
2417             message.peerInfo->sctpParams->e2tCounters[IN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment();
2418             message.peerInfo->sctpParams->e2tCounters[IN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment((double)message.message.asnLength);
2419 #endif
2420             if (sendRequestToXapp(message, RIC_SUB_DEL_RESP, rmrMessageBuffer) != 0) {
2421                 mdclog_write(MDCLOG_ERR, "Subscription delete successful message failed to send to xAPP");
2422             }
2423             break;
2424         }
2425         default: {
2426             mdclog_write(MDCLOG_WARN, "Undefined or not supported message = %ld", procedureCode);
2427             message.message.messageType = 0; // no RMR message type yet
2428             buildJsonMessage(message);
2429
2430             break;
2431         }
2432     }
2433 }
2434
2435 /**
2436  *
2437  * @param pdu
2438  * @param message
2439  * @param rmrMessageBuffer
2440  */
2441 void asnUnSuccsesfulMsg(E2AP_PDU_t *pdu,
2442                         Sctp_Map_t *sctpMap,
2443                         ReportingMessages_t &message,
2444                         RmrMessagesBuffer_t &rmrMessageBuffer) {
2445     auto procedureCode = pdu->choice.unsuccessfulOutcome->procedureCode;
2446     auto logLevel = mdclog_level_get();
2447     if (logLevel >= MDCLOG_INFO) {
2448         mdclog_write(MDCLOG_INFO, "Unsuccessful Outcome %ld", procedureCode);
2449     }
2450     switch (procedureCode) {
2451         case ProcedureCode_id_RICcontrol: {
2452             if (logLevel >= MDCLOG_DEBUG) {
2453                 mdclog_write(MDCLOG_DEBUG, "Got RICcontrol %s", message.message.enodbName);
2454             }
2455             for (int i = 0;
2456                  i < pdu->choice.unsuccessfulOutcome->value.choice.RICcontrolFailure.protocolIEs.list.count; i++) {
2457                 auto messageSent = false;
2458                 RICcontrolFailure_IEs_t *ie = pdu->choice.unsuccessfulOutcome->value.choice.RICcontrolFailure.protocolIEs.list.array[i];
2459                 if (logLevel >= MDCLOG_DEBUG) {
2460                     mdclog_write(MDCLOG_DEBUG, "ie type (ProtocolIE_ID) = %ld", ie->id);
2461                 }
2462                 if (ie->id == ProtocolIE_ID_id_RICrequestID) {
2463                     if (logLevel >= MDCLOG_DEBUG) {
2464                         mdclog_write(MDCLOG_DEBUG, "Got RIC requestId entry, ie type (ProtocolIE_ID) = %ld", ie->id);
2465                     }
2466                     if (ie->value.present == RICcontrolFailure_IEs__value_PR_RICrequestID) {
2467                         message.message.messageType = rmrMessageBuffer.sendMessage->mtype = RIC_CONTROL_FAILURE;
2468                         rmrMessageBuffer.sendMessage->state = 0;
2469 //                        rmrMessageBuffer.sendMessage->sub_id = (int)ie->value.choice.RICrequestID.ricRequestorID;
2470                         rmrMessageBuffer.sendMessage->sub_id = (int)ie->value.choice.RICrequestID.ricInstanceID;
2471                         static unsigned char tx[32];
2472                         snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
2473                         rmr_bytes2xact(rmrMessageBuffer.sendMessage, tx, strlen((const char *) tx));
2474                         rmr_bytes2meid(rmrMessageBuffer.sendMessage, (unsigned char *) message.message.enodbName,
2475                                        strlen(message.message.enodbName));
2476 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2477                         message.peerInfo->counters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICcontrol]->Increment();
2478                         message.peerInfo->counters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICcontrol]->Increment((double)message.message.asnLength);
2479
2480                         // Update E2T instance level metrics
2481                         message.peerInfo->sctpParams->e2tCounters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICcontrol]->Increment();
2482                         message.peerInfo->sctpParams->e2tCounters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICcontrol]->Increment((double)message.message.asnLength);
2483 #endif
2484                         sendRmrMessage(rmrMessageBuffer, message);
2485                         messageSent = true;
2486                     } else {
2487                         mdclog_write(MDCLOG_ERR, "RIC request id missing illegal request");
2488                     }
2489                 }
2490                 if (messageSent) {
2491                     break;
2492                 }
2493             }
2494             break;
2495         }
2496         case ProcedureCode_id_RICsubscription: {
2497             if (logLevel >= MDCLOG_DEBUG) {
2498                 mdclog_write(MDCLOG_DEBUG, "Got RICsubscription %s", message.message.enodbName);
2499             }
2500 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2501             message.peerInfo->counters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscription]->Increment();
2502             message.peerInfo->counters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscription]->Increment((double)message.message.asnLength);
2503
2504             // Update E2T instance level metrics
2505             message.peerInfo->sctpParams->e2tCounters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscription]->Increment();
2506             message.peerInfo->sctpParams->e2tCounters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscription]->Increment((double)message.message.asnLength);
2507 #endif
2508             if (sendRequestToXapp(message, RIC_SUB_FAILURE, rmrMessageBuffer) != 0) {
2509                 mdclog_write(MDCLOG_ERR, "Subscription unsuccessful message failed to send to xAPP");
2510             }
2511             break;
2512         }
2513         case ProcedureCode_id_RICsubscriptionDelete: {
2514             if (logLevel >= MDCLOG_DEBUG) {
2515                 mdclog_write(MDCLOG_DEBUG, "Got RICsubscriptionDelete %s", message.message.enodbName);
2516             }
2517 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2518             message.peerInfo->counters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment();
2519             message.peerInfo->counters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment((double)message.message.asnLength);
2520
2521             // Update E2T instance level metrics
2522             message.peerInfo->sctpParams->e2tCounters[IN_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment();
2523             message.peerInfo->sctpParams->e2tCounters[IN_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment((double)message.message.asnLength);
2524 #endif
2525             if (sendRequestToXapp(message, RIC_SUB_FAILURE, rmrMessageBuffer) != 0) {
2526                 mdclog_write(MDCLOG_ERR, "Subscription Delete unsuccessful message failed to send to xAPP");
2527             }
2528             break;
2529         }
2530         default: {
2531             mdclog_write(MDCLOG_WARN, "Undefined or not supported message = %ld", procedureCode);
2532             message.message.messageType = 0; // no RMR message type yet
2533 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2534             buildJsonMessage(message);
2535 #endif
2536             break;
2537         }
2538     }
2539 }
2540
2541 /**
2542  *
2543  * @param message
2544  * @param requestId
2545  * @param rmrMmessageBuffer
2546  * @return
2547  */
2548 int sendRequestToXapp(ReportingMessages_t &message,
2549                       int requestId,
2550                       RmrMessagesBuffer_t &rmrMmessageBuffer) {
2551     rmr_bytes2meid(rmrMmessageBuffer.sendMessage,
2552                    (unsigned char *)message.message.enodbName,
2553                    strlen(message.message.enodbName));
2554     message.message.messageType = rmrMmessageBuffer.sendMessage->mtype = requestId;
2555     rmrMmessageBuffer.sendMessage->state = 0;
2556     static unsigned char tx[32];
2557     snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
2558     rmr_bytes2xact(rmrMmessageBuffer.sendMessage, tx, strlen((const char *) tx));
2559
2560     auto rc = sendRmrMessage(rmrMmessageBuffer, message);
2561     return rc;
2562 }
2563
2564 /**
2565  *
2566  * @param pSctpParams
2567  */
2568 void getRmrContext(sctp_params_t &pSctpParams) {
2569     pSctpParams.rmrCtx = nullptr;
2570     pSctpParams.rmrCtx = rmr_init(pSctpParams.rmrAddress, RECEIVE_XAPP_BUFFER_SIZE, RMRFL_NONE);
2571     if (pSctpParams.rmrCtx == nullptr) {
2572         mdclog_write(MDCLOG_ERR, "Failed to initialize RMR");
2573         return;
2574     }
2575
2576     rmr_set_stimeout(pSctpParams.rmrCtx, 0);    // disable retries for any send operation
2577     // we need to find that routing table exist and we can run
2578     if (mdclog_level_get() >= MDCLOG_INFO) {
2579         mdclog_write(MDCLOG_INFO, "We are after RMR INIT wait for RMR_Ready");
2580     }
2581     int rmrReady = 0;
2582     int count = 0;
2583     while (!rmrReady) {
2584         if ((rmrReady = rmr_ready(pSctpParams.rmrCtx)) == 0) {
2585             sleep(1);
2586         }
2587         count++;
2588         if (count % 60 == 0) {
2589             mdclog_write(MDCLOG_INFO, "waiting to RMR ready state for %d seconds", count);
2590         }
2591     }
2592     if (mdclog_level_get() >= MDCLOG_INFO) {
2593         mdclog_write(MDCLOG_INFO, "RMR running");
2594     }
2595     rmr_init_trace(pSctpParams.rmrCtx, 200);
2596     // get the RMR fd for the epoll
2597     pSctpParams.rmrListenFd = rmr_get_rcvfd(pSctpParams.rmrCtx);
2598     struct epoll_event event{};
2599     // add RMR fd to epoll
2600     event.events = (EPOLLIN);
2601     event.data.fd = pSctpParams.rmrListenFd;
2602     // add listening RMR FD to epoll
2603     if (epoll_ctl(pSctpParams.epoll_fd, EPOLL_CTL_ADD, pSctpParams.rmrListenFd, &event)) {
2604         mdclog_write(MDCLOG_ERR, "Failed to add RMR descriptor to epoll");
2605         close(pSctpParams.rmrListenFd);
2606         rmr_close(pSctpParams.rmrCtx);
2607         pSctpParams.rmrCtx = nullptr;
2608     }
2609 }
2610
2611 /**
2612  *
2613  * @param message
2614  * @param rmrMessageBuffer
2615  * @return
2616  */
2617 int PER_FromXML(ReportingMessages_t &message, RmrMessagesBuffer_t &rmrMessageBuffer) {
2618     E2AP_PDU_t *pdu = nullptr;
2619
2620     if (mdclog_level_get() >= MDCLOG_DEBUG) {
2621         mdclog_write(MDCLOG_DEBUG, "got xml Format  data from xApp of size %d is:%s",
2622                 rmrMessageBuffer.rcvMessage->len, rmrMessageBuffer.rcvMessage->payload);
2623     }
2624     auto rval = asn_decode(nullptr, ATS_BASIC_XER, &asn_DEF_E2AP_PDU, (void **) &pdu,
2625                            rmrMessageBuffer.rcvMessage->payload, rmrMessageBuffer.rcvMessage->len);
2626     if (mdclog_level_get() >= MDCLOG_DEBUG) {
2627         mdclog_write(MDCLOG_DEBUG, "%s After  decoding the XML to PDU", __func__ );
2628     }
2629     if (rval.code != RC_OK) {
2630 #ifdef UNIT_TEST
2631     return 0;
2632 #endif
2633         mdclog_write(MDCLOG_ERR, "Error %d Decoding (unpack) setup response  from E2MGR : %s",
2634                      rval.code,
2635                      message.message.enodbName);
2636         if (pdu != nullptr) {
2637             ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2638             pdu = nullptr;
2639         }
2640         return -1;
2641     }
2642
2643     int buff_size = RECEIVE_XAPP_BUFFER_SIZE;
2644     auto er = asn_encode_to_buffer(nullptr, ATS_ALIGNED_BASIC_PER, &asn_DEF_E2AP_PDU, pdu,
2645                                    rmrMessageBuffer.rcvMessage->payload, buff_size);
2646     if (mdclog_level_get() >= MDCLOG_DEBUG) {
2647         mdclog_write(MDCLOG_DEBUG, "%s After encoding PDU to PER", __func__ );
2648     }
2649     if (er.encoded == -1) {
2650         mdclog_write(MDCLOG_ERR, "encoding of %s failed, %s", asn_DEF_E2AP_PDU.name, strerror(errno));
2651         if (pdu != nullptr) {
2652             ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2653             pdu = nullptr;
2654         }
2655         return -1;
2656     } else if (er.encoded > (ssize_t)buff_size) {
2657         mdclog_write(MDCLOG_ERR, "Buffer of size %d is to small for %s, at %s line %d",
2658                      (int)rmrMessageBuffer.rcvMessage->len,
2659                      asn_DEF_E2AP_PDU.name,
2660                      __func__,
2661                      __LINE__);
2662         if (pdu != nullptr) {
2663             ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2664             pdu = nullptr;
2665         }
2666         return -1;
2667     }
2668     rmrMessageBuffer.rcvMessage->len = er.encoded;
2669     if (pdu != nullptr) {
2670         ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
2671         pdu = nullptr;
2672     }
2673     return 0;
2674 }
2675
2676 /**
2677  *
2678  * @param sctpMap
2679  * @param rmrMessageBuffer
2680  * @param ts
2681  * @return
2682  */
2683 int receiveXappMessages(Sctp_Map_t *sctpMap,
2684                         RmrMessagesBuffer_t &rmrMessageBuffer,
2685                         struct timespec &ts) {
2686     int loglevel = mdclog_level_get();
2687     if (rmrMessageBuffer.rcvMessage == nullptr) {
2688         //we have error
2689         mdclog_write(MDCLOG_ERR, "RMR Allocation message, %s", strerror(errno));
2690         return -1;
2691     }
2692
2693 //    if (loglevel >= MDCLOG_DEBUG) {
2694 //        mdclog_write(MDCLOG_DEBUG, "Call to rmr_rcv_msg");
2695 //    }
2696     rmrMessageBuffer.rcvMessage = rmr_rcv_msg(rmrMessageBuffer.rmrCtx, rmrMessageBuffer.rcvMessage);
2697     if (rmrMessageBuffer.rcvMessage == nullptr) {
2698         mdclog_write(MDCLOG_ERR, "RMR Receiving message with null pointer, Reallocated rmr message buffer");
2699         rmrMessageBuffer.rcvMessage = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
2700         return -2;
2701     }
2702     ReportingMessages_t message;
2703     message.message.direction = 'D';
2704     message.message.time.tv_nsec = ts.tv_nsec;
2705     message.message.time.tv_sec = ts.tv_sec;
2706
2707     // get message payload
2708     //auto msgData = msg->payload;
2709 #ifdef UNIT_TEST
2710     rmrMessageBuffer.rcvMessage->state = 0;
2711 #endif
2712     if (rmrMessageBuffer.rcvMessage->state != 0) {
2713         mdclog_write(MDCLOG_ERR, "RMR Receiving message with stat = %d", rmrMessageBuffer.rcvMessage->state);
2714         return -1;
2715     }
2716     rmr_get_meid(rmrMessageBuffer.rcvMessage, (unsigned char *)message.message.enodbName);
2717     message.peerInfo = (ConnectedCU_t *) sctpMap->find(message.message.enodbName);
2718     if (message.peerInfo == nullptr) {
2719         auto type = rmrMessageBuffer.rcvMessage->mtype;
2720         switch (type) {
2721             case RIC_SCTP_CLEAR_ALL:
2722             case E2_TERM_KEEP_ALIVE_REQ:
2723             case RIC_HEALTH_CHECK_REQ:
2724                 break;
2725             default:
2726 #ifdef UNIT_TEST
2727     break;
2728 #endif
2729                 mdclog_write(MDCLOG_ERR, "Failed to send message no CU entry %s", message.message.enodbName);
2730                 return -1;
2731         }
2732     }
2733
2734     if (rmrMessageBuffer.rcvMessage->mtype != RIC_HEALTH_CHECK_REQ) {
2735         num_of_XAPP_messages.fetch_add(1, std::memory_order_release);
2736
2737     }
2738     switch (rmrMessageBuffer.rcvMessage->mtype) {
2739         case RIC_E2_SETUP_RESP : {
2740             if (loglevel >= MDCLOG_DEBUG) {
2741                 mdclog_write(MDCLOG_DEBUG, "RIC_E2_SETUP_RESP");
2742             }
2743             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2744                 break;
2745             }
2746 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2747             message.peerInfo->counters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_E2setup]->Increment();
2748             message.peerInfo->counters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_E2setup]->Increment(rmrMessageBuffer.rcvMessage->len);
2749
2750             // Update E2T instance level metrics
2751             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_E2setup]->Increment();
2752             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_E2setup]->Increment(rmrMessageBuffer.rcvMessage->len);
2753 #endif
2754             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2755                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_E2_SETUP_RESP");
2756                 return -6;
2757             }
2758             break;
2759         }
2760         case RIC_E2_SETUP_FAILURE : {
2761             if (loglevel >= MDCLOG_DEBUG) {
2762                 mdclog_write(MDCLOG_DEBUG, "RIC_E2_SETUP_FAILURE");
2763             }
2764             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2765                 break;
2766             }
2767 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2768             message.peerInfo->counters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_E2setup]->Increment();
2769             message.peerInfo->counters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_E2setup]->Increment(rmrMessageBuffer.rcvMessage->len);
2770
2771             // Update E2T instance level metrics
2772             message.peerInfo->sctpParams->e2tCounters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_E2setup]->Increment();
2773             message.peerInfo->sctpParams->e2tCounters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_E2setup]->Increment(rmrMessageBuffer.rcvMessage->len);
2774 #endif
2775             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2776                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_E2_SETUP_FAILURE");
2777                 return -6;
2778             }
2779             break;
2780         }
2781
2782         case RIC_E2NODE_CONFIG_UPDATE_ACK: {
2783             if (loglevel >= MDCLOG_DEBUG) {
2784                 mdclog_write(MDCLOG_DEBUG, "RIC_E2NODE_CONFIG_UPDATE_ACK");
2785             }
2786             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2787                 break;
2788             }
2789 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2790             message.peerInfo->counters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment();
2791             message.peerInfo->counters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2792
2793             // Update E2T instance level metrics
2794             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment();
2795             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2796 #endif
2797             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2798                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_E2NODE_CONFIG_UPDATE_ACK");
2799                 return -6;
2800             }
2801             break;
2802         }
2803
2804         case RIC_E2NODE_CONFIG_UPDATE_FAILURE: {
2805             if (loglevel >= MDCLOG_DEBUG) {
2806                 mdclog_write(MDCLOG_DEBUG, "RIC_E2NODE_CONFIG_UPDATE_FAILURE");
2807             }
2808             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2809                 break;
2810             }
2811 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2812             message.peerInfo->counters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment();
2813             message.peerInfo->counters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2814
2815             // Update E2T instance level metrics
2816             message.peerInfo->sctpParams->e2tCounters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment();
2817             message.peerInfo->sctpParams->e2tCounters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_E2nodeConfigurationUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2818 #endif
2819             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2820                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_E2NODE_CONFIG_UPDATE_FAILURE");
2821                 return -6;
2822             }
2823             break;
2824         }
2825
2826         case RIC_ERROR_INDICATION: {
2827             if (loglevel >= MDCLOG_DEBUG) {
2828                 mdclog_write(MDCLOG_DEBUG, "RIC_ERROR_INDICATION");
2829             }
2830 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2831             message.peerInfo->counters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_ErrorIndication]->Increment();
2832             message.peerInfo->counters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_ErrorIndication]->Increment(rmrMessageBuffer.rcvMessage->len);
2833
2834             // Update E2T instance level metrics
2835             message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_ErrorIndication]->Increment();
2836             message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_ErrorIndication]->Increment(rmrMessageBuffer.rcvMessage->len);
2837 #endif
2838             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2839                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_ERROR_INDICATION");
2840                 return -6;
2841             }
2842             break;
2843         }
2844         case RIC_SUB_REQ: {
2845             if (loglevel >= MDCLOG_DEBUG) {
2846                 mdclog_write(MDCLOG_DEBUG, "RIC_SUB_REQ");
2847             }
2848 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2849             message.peerInfo->counters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscription]->Increment();
2850             message.peerInfo->counters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscription]->Increment(rmrMessageBuffer.rcvMessage->len);
2851
2852             // Update E2T instance level metrics
2853             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscription]->Increment();
2854             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscription]->Increment(rmrMessageBuffer.rcvMessage->len);
2855 #endif
2856             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2857                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_SUB_REQ");
2858                 return -6;
2859             }
2860             break;
2861         }
2862         case RIC_SUB_DEL_REQ: {
2863             if (loglevel >= MDCLOG_DEBUG) {
2864                 mdclog_write(MDCLOG_DEBUG, "RIC_SUB_DEL_REQ");
2865             }
2866 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2867             message.peerInfo->counters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment();
2868             message.peerInfo->counters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment(rmrMessageBuffer.rcvMessage->len);
2869
2870             // Update E2T instance level metrics
2871             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment();
2872             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICsubscriptionDelete]->Increment(rmrMessageBuffer.rcvMessage->len);
2873 #endif
2874             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2875                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_SUB_DEL_REQ");
2876                 return -6;
2877             }
2878             break;
2879         }
2880         case RIC_CONTROL_REQ: {
2881             if (loglevel >= MDCLOG_DEBUG) {
2882                 mdclog_write(MDCLOG_DEBUG, "RIC_CONTROL_REQ");
2883             }
2884 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2885             message.peerInfo->counters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICcontrol]->Increment();
2886             message.peerInfo->counters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICcontrol]->Increment(rmrMessageBuffer.rcvMessage->len);
2887
2888             // Update E2T instance level metrics
2889             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICcontrol]->Increment();
2890             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICcontrol]->Increment(rmrMessageBuffer.rcvMessage->len);
2891 #endif
2892             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2893                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_CONTROL_REQ");
2894                 return -6;
2895             }
2896             break;
2897         }
2898         case RIC_SERVICE_QUERY: {
2899             if (loglevel >= MDCLOG_DEBUG) {
2900                 mdclog_write(MDCLOG_DEBUG, "RIC_SERVICE_QUERY");
2901             }
2902             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2903                 break;
2904             }
2905 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2906             message.peerInfo->counters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICserviceQuery]->Increment();
2907             message.peerInfo->counters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICserviceQuery]->Increment(rmrMessageBuffer.rcvMessage->len);
2908
2909             // Update E2T instance level metrics
2910             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_RICserviceQuery]->Increment();
2911             message.peerInfo->sctpParams->e2tCounters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_RICserviceQuery]->Increment(rmrMessageBuffer.rcvMessage->len);
2912 #endif
2913             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2914                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_SERVICE_QUERY");
2915                 return -6;
2916             }
2917             break;
2918         }
2919         case RIC_SERVICE_UPDATE_ACK: {
2920             if (loglevel >= MDCLOG_DEBUG) {
2921                 mdclog_write(MDCLOG_DEBUG, "RIC_SERVICE_UPDATE_ACK");
2922             }
2923             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2924                 mdclog_write(MDCLOG_ERR, "error in PER_FromXML");
2925                 break;
2926             }
2927 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2928             message.peerInfo->counters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment();
2929             message.peerInfo->counters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2930
2931             // Update E2T instance level metrics
2932             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment();
2933             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2934 #endif
2935             if (loglevel >= MDCLOG_DEBUG) {
2936                 mdclog_write(MDCLOG_DEBUG, "Before sending to CU");
2937             }
2938             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2939                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_SERVICE_UPDATE_ACK");
2940                 return -6;
2941             }
2942             break;
2943         }
2944         case RIC_SERVICE_UPDATE_FAILURE: {
2945             if (loglevel >= MDCLOG_DEBUG) {
2946                 mdclog_write(MDCLOG_DEBUG, "RIC_SERVICE_UPDATE_FAILURE");
2947             }
2948             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2949                 break;
2950             }
2951 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2952             message.peerInfo->counters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment();
2953             message.peerInfo->counters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2954
2955             // Update E2T instance level metrics
2956             message.peerInfo->sctpParams->e2tCounters[OUT_UN_SUCC][MSG_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment();
2957             message.peerInfo->sctpParams->e2tCounters[OUT_UN_SUCC][BYTES_COUNTER][ProcedureCode_id_RICserviceUpdate]->Increment(rmrMessageBuffer.rcvMessage->len);
2958 #endif
2959             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2960                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_SERVICE_UPDATE_FAILURE");
2961                 return -6;
2962             }
2963             break;
2964         }
2965         case RIC_E2_RESET_REQ: {
2966             if (loglevel >= MDCLOG_DEBUG) {
2967                 mdclog_write(MDCLOG_DEBUG, "RIC_E2_RESET_REQ");
2968             }
2969             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2970                 break;
2971             }
2972 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2973             message.peerInfo->counters[OUT_INITI][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2974             message.peerInfo->counters[OUT_INITI][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment(rmrMessageBuffer.rcvMessage->len);
2975
2976             // Update E2T instance level metrics
2977             message.peerInfo->sctpParams->e2tCounters[IN_INITI][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2978             message.peerInfo->sctpParams->e2tCounters[IN_INITI][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment(rmrMessageBuffer.rcvMessage->len);
2979 #endif
2980             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
2981                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_E2_RESET");
2982                 return -6;
2983             }
2984             break;
2985         }
2986         case RIC_E2_RESET_RESP: {
2987             if (loglevel >= MDCLOG_DEBUG) {
2988                 mdclog_write(MDCLOG_DEBUG, "RIC_E2_RESET_RESP");
2989             }
2990             if (PER_FromXML(message, rmrMessageBuffer) != 0) {
2991                 break;
2992             }
2993 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
2994             message.peerInfo->counters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2995             message.peerInfo->counters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment(rmrMessageBuffer.rcvMessage->len);
2996
2997             // Update E2T instance level metrics
2998             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][MSG_COUNTER][ProcedureCode_id_Reset]->Increment();
2999             message.peerInfo->sctpParams->e2tCounters[OUT_SUCC][BYTES_COUNTER][ProcedureCode_id_Reset]->Increment(rmrMessageBuffer.rcvMessage->len);
3000 #endif
3001             if (sendDirectionalSctpMsg(rmrMessageBuffer, message, 0, sctpMap) != 0) {
3002                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_E2_RESET_RESP");
3003                 return -6;
3004             }
3005             break;
3006         }
3007         case RIC_SCTP_CLEAR_ALL: {
3008             mdclog_write(MDCLOG_INFO, "RIC_SCTP_CLEAR_ALL");
3009             // loop on all keys and close socket and then erase all map.
3010             vector<char *> v;
3011             sctpMap->getKeys(v);
3012             for (auto const &iter : v) { //}; iter != sctpMap.end(); iter++) {
3013                 if (!boost::starts_with((string) (iter), "host:") && !boost::starts_with((string) (iter), "msg:")) {
3014                     auto *peerInfo = (ConnectedCU_t *) sctpMap->find(iter);
3015                     if (peerInfo == nullptr) {
3016                         continue;
3017                     }
3018                     close(peerInfo->fileDescriptor);
3019                     memcpy(message.message.enodbName, peerInfo->enodbName, sizeof(peerInfo->enodbName));
3020                     message.message.direction = 'D';
3021                     message.message.time.tv_nsec = ts.tv_nsec;
3022                     message.message.time.tv_sec = ts.tv_sec;
3023
3024                     message.message.asnLength = rmrMessageBuffer.sendMessage->len =
3025                             snprintf((char *)rmrMessageBuffer.sendMessage->payload,
3026                                      256,
3027                                      "%s|RIC_SCTP_CLEAR_ALL",
3028                                      peerInfo->enodbName);
3029                     message.message.asndata = rmrMessageBuffer.sendMessage->payload;
3030                     mdclog_write(MDCLOG_INFO, "%s", message.message.asndata);
3031                     if (sendRequestToXapp(message, RIC_SCTP_CONNECTION_FAILURE, rmrMessageBuffer) != 0) {
3032                         mdclog_write(MDCLOG_ERR, "SCTP_CONNECTION_FAIL message failed to send to xAPP");
3033                     }
3034                     free(peerInfo);
3035                     peerInfo = nullptr;
3036                 }
3037             }
3038
3039             sleep(1);
3040             sctpMap->clear();
3041             break;
3042         }
3043         case E2_TERM_KEEP_ALIVE_REQ: {
3044             // send message back
3045             rmr_bytes2payload(rmrMessageBuffer.sendMessage,
3046                               (unsigned char *)rmrMessageBuffer.ka_message,
3047                               rmrMessageBuffer.ka_message_len);
3048             rmrMessageBuffer.sendMessage->mtype = E2_TERM_KEEP_ALIVE_RESP;
3049             rmrMessageBuffer.sendMessage->state = 0;
3050             static unsigned char tx[32];
3051             auto txLen = snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
3052             rmr_bytes2xact(rmrMessageBuffer.sendMessage, tx, txLen);
3053 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
3054             rmrMessageBuffer.sendMessage = rmr_send_msg(rmrMessageBuffer.rmrCtx, rmrMessageBuffer.sendMessage);
3055 #endif
3056             if (rmrMessageBuffer.sendMessage == nullptr) {
3057                 rmrMessageBuffer.sendMessage = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
3058                 mdclog_write(MDCLOG_ERR, "Failed to send E2_TERM_KEEP_ALIVE_RESP RMR message returned NULL");
3059             } else if (rmrMessageBuffer.sendMessage->state != 0)  {
3060                 mdclog_write(MDCLOG_ERR, "Failed to send E2_TERM_KEEP_ALIVE_RESP, on RMR state = %d ( %s)",
3061                              rmrMessageBuffer.sendMessage->state, translateRmrErrorMessages(rmrMessageBuffer.sendMessage->state).c_str());
3062             } else if (loglevel >= MDCLOG_DEBUG) {
3063                 mdclog_write(MDCLOG_DEBUG, "Got Keep Alive Request send : %s", rmrMessageBuffer.ka_message);
3064             }
3065
3066             break;
3067         }
3068         case RIC_HEALTH_CHECK_REQ: {
3069             static int counter = 0;
3070             // send message back
3071             rmr_bytes2payload(rmrMessageBuffer.rcvMessage,
3072                               (unsigned char *)"OK",
3073                               2);
3074             rmrMessageBuffer.rcvMessage->mtype = RIC_HEALTH_CHECK_RESP;
3075             rmrMessageBuffer.rcvMessage->state = 0;
3076             static unsigned char tx[32];
3077             auto txLen = snprintf((char *) tx, sizeof tx, "%15ld", transactionCounter++);
3078             rmr_bytes2xact(rmrMessageBuffer.rcvMessage, tx, txLen);
3079             rmrMessageBuffer.rcvMessage = rmr_rts_msg(rmrMessageBuffer.rmrCtx, rmrMessageBuffer.rcvMessage);
3080             //rmrMessageBuffer.sendMessage = rmr_send_msg(rmrMessageBuffer.rmrCtx, rmrMessageBuffer.sendMessage);
3081             if (rmrMessageBuffer.rcvMessage == nullptr) {
3082                 rmrMessageBuffer.rcvMessage = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
3083                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_HEALTH_CHECK_RESP RMR message returned NULL");
3084             } else if (rmrMessageBuffer.rcvMessage->state != 0)  {
3085                 mdclog_write(MDCLOG_ERR, "Failed to send RIC_HEALTH_CHECK_RESP, on RMR state = %d ( %s)",
3086                              rmrMessageBuffer.rcvMessage->state, translateRmrErrorMessages(rmrMessageBuffer.rcvMessage->state).c_str());
3087             } else if (loglevel >= MDCLOG_DEBUG && (++counter % 100 == 0)) {
3088                 mdclog_write(MDCLOG_DEBUG, "Got %d RIC_HEALTH_CHECK_REQ Request send : OK", counter);
3089             }
3090
3091             break;
3092         }
3093
3094         default:
3095             mdclog_write(MDCLOG_WARN, "Message Type : %d is not supported", rmrMessageBuffer.rcvMessage->mtype);
3096             message.message.asndata = rmrMessageBuffer.rcvMessage->payload;
3097             message.message.asnLength = rmrMessageBuffer.rcvMessage->len;
3098             message.message.time.tv_nsec = ts.tv_nsec;
3099             message.message.time.tv_sec = ts.tv_sec;
3100             message.message.messageType = rmrMessageBuffer.rcvMessage->mtype;
3101
3102             buildJsonMessage(message);
3103
3104
3105             return -7;
3106     }
3107     if (mdclog_level_get() >= MDCLOG_DEBUG) {
3108         mdclog_write(MDCLOG_DEBUG, "EXIT OK from %s", __FUNCTION__);
3109     }
3110     return 0;
3111 }
3112
3113 /**
3114  * Send message to the CU that is not expecting for successful or unsuccessful results
3115  * @param messageBuffer
3116  * @param message
3117  * @param failedMsgId
3118  * @param sctpMap
3119  * @return
3120  */
3121 int sendDirectionalSctpMsg(RmrMessagesBuffer_t &messageBuffer,
3122                            ReportingMessages_t &message,
3123                            int failedMsgId,
3124                            Sctp_Map_t *sctpMap) {
3125     if (mdclog_level_get() >= MDCLOG_DEBUG) {
3126         mdclog_write(MDCLOG_DEBUG, "send message: %d to %s address", message.message.messageType, message.message.enodbName);
3127     }
3128
3129     getRequestMetaData(message, messageBuffer);
3130     if (mdclog_level_get() >= MDCLOG_INFO) {
3131         mdclog_write(MDCLOG_INFO, "send message to %s address", message.message.enodbName);
3132     }
3133
3134     auto rc = sendMessagetoCu(sctpMap, messageBuffer, message, failedMsgId);
3135     return rc;
3136 }
3137
3138 /**
3139  *
3140  * @param sctpMap
3141  * @param messageBuffer
3142  * @param message
3143  * @param failedMesgId
3144  * @return
3145  */
3146 int sendMessagetoCu(Sctp_Map_t *sctpMap,
3147                     RmrMessagesBuffer_t &messageBuffer,
3148                     ReportingMessages_t &message,
3149                     int failedMesgId) {
3150     // get the FD
3151     message.message.messageType = messageBuffer.rcvMessage->mtype;
3152     auto rc = sendSctpMsg(message.peerInfo, message, sctpMap);
3153     return rc;
3154 }
3155
3156
3157 /**
3158  *
3159  * @param epoll_fd
3160  * @param peerInfo
3161  * @param events
3162  * @param sctpMap
3163  * @param enodbName
3164  * @param msgType
3165  * @return
3166  */
3167 int addToEpoll(int epoll_fd,
3168                ConnectedCU_t *peerInfo,
3169                uint32_t events,
3170                Sctp_Map_t *sctpMap,
3171                char *enodbName,
3172                int msgType) {
3173     // Add to Epol
3174     struct epoll_event event{};
3175     event.data.ptr = peerInfo;
3176     event.events = events;
3177     if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, peerInfo->fileDescriptor, &event) < 0) {
3178 #if !(defined(UNIT_TEST) || defined(MODULE_TEST))
3179         if (mdclog_level_get() >= MDCLOG_DEBUG) {
3180             mdclog_write(MDCLOG_DEBUG, "epoll_ctl EPOLL_CTL_ADD (may check not to quit here), %s, %s %d",
3181                          strerror(errno), __func__, __LINE__);
3182         }
3183         close(peerInfo->fileDescriptor);
3184         if (enodbName != nullptr) {
3185             cleanHashEntry(peerInfo, sctpMap);
3186             char key[MAX_ENODB_NAME_SIZE * 2];
3187             snprintf(key, MAX_ENODB_NAME_SIZE * 2, "msg:%s|%d", enodbName, msgType);
3188             if (mdclog_level_get() >= MDCLOG_DEBUG) {
3189                 mdclog_write(MDCLOG_DEBUG, "remove key = %s from %s at line %d", key, __FUNCTION__, __LINE__);
3190             }
3191             auto tmp = sctpMap->find(key);
3192             if (tmp) {
3193                 free(tmp);
3194                 tmp = nullptr;
3195                 sctpMap->erase(key);
3196             }
3197         } else {
3198             peerInfo->enodbName[0] = 0;
3199         }
3200         mdclog_write(MDCLOG_ERR, "epoll_ctl EPOLL_CTL_ADD (may check not to quit here)");
3201         return -1;
3202 #endif
3203     }
3204     return 0;
3205 }
3206
3207 /**
3208  *
3209  * @param epoll_fd
3210  * @param peerInfo
3211  * @param events
3212  * @param sctpMap
3213  * @param enodbName
3214  * @param msgType
3215  * @return
3216  */
3217 int modifyToEpoll(int epoll_fd,
3218                   ConnectedCU_t *peerInfo,
3219                   uint32_t events,
3220                   Sctp_Map_t *sctpMap,
3221                   char *enodbName,
3222                   int msgType) {
3223     // Add to Epol
3224     struct epoll_event event{};
3225     event.data.ptr = peerInfo;
3226     event.events = events;
3227     if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, peerInfo->fileDescriptor, &event) < 0) {
3228         if (mdclog_level_get() >= MDCLOG_DEBUG) {
3229             mdclog_write(MDCLOG_DEBUG, "epoll_ctl EPOLL_CTL_MOD (may check not to quit here), %s, %s %d",
3230                          strerror(errno), __func__, __LINE__);
3231         }
3232         close(peerInfo->fileDescriptor);
3233         cleanHashEntry(peerInfo, sctpMap);
3234         char key[MAX_ENODB_NAME_SIZE * 2];
3235         snprintf(key, MAX_ENODB_NAME_SIZE * 2, "msg:%s|%d", enodbName, msgType);
3236         if (mdclog_level_get() >= MDCLOG_DEBUG) {
3237             mdclog_write(MDCLOG_DEBUG, "remove key = %s from %s at line %d", key, __FUNCTION__, __LINE__);
3238         }
3239         auto tmp = sctpMap->find(key);
3240         if (tmp) {
3241             free(tmp);
3242             tmp = nullptr;
3243         sctpMap->erase(key);
3244         }
3245         mdclog_write(MDCLOG_ERR, "epoll_ctl EPOLL_CTL_ADD (may check not to quit here)");
3246         return -1;
3247     }
3248     return 0;
3249 }
3250
3251
3252 int sendRmrMessage(RmrMessagesBuffer_t &rmrMessageBuffer, ReportingMessages_t &message) {
3253     buildJsonMessage(message);
3254 #ifndef UNIT_TEST
3255     rmrMessageBuffer.sendMessage = rmr_send_msg(rmrMessageBuffer.rmrCtx, rmrMessageBuffer.sendMessage);
3256 #else
3257     rmrMessageBuffer.sendMessage->state = RMR_ERR_RETRY;
3258 #endif
3259     if (rmrMessageBuffer.sendMessage == nullptr) {
3260         rmrMessageBuffer.sendMessage = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
3261         mdclog_write(MDCLOG_ERR, "RMR failed send message returned with NULL pointer");
3262         return -1;
3263     }
3264
3265     if (rmrMessageBuffer.sendMessage->state != 0) {
3266         char meid[RMR_MAX_MEID]{};
3267         if (rmrMessageBuffer.sendMessage->state == RMR_ERR_RETRY) {
3268             usleep(5);
3269             rmrMessageBuffer.sendMessage->state = 0;
3270             mdclog_write(MDCLOG_INFO, "RETRY sending Message type %d to Xapp from %s",
3271                          rmrMessageBuffer.sendMessage->mtype,
3272                          rmr_get_meid(rmrMessageBuffer.sendMessage, (unsigned char *)meid));
3273 #ifndef UNIT_TEST
3274             rmrMessageBuffer.sendMessage = rmr_send_msg(rmrMessageBuffer.rmrCtx, rmrMessageBuffer.sendMessage);
3275 #endif
3276             if (rmrMessageBuffer.sendMessage == nullptr) {
3277                 mdclog_write(MDCLOG_ERR, "RMR failed send message returned with NULL pointer");
3278                 rmrMessageBuffer.sendMessage = rmr_alloc_msg(rmrMessageBuffer.rmrCtx, RECEIVE_XAPP_BUFFER_SIZE);
3279                 return -1;
3280             } else if (rmrMessageBuffer.sendMessage->state != 0) {
3281                 mdclog_write(MDCLOG_ERR,
3282                              "Message state %s while sending request %d to Xapp from %s after retry of 10 microseconds",
3283                              translateRmrErrorMessages(rmrMessageBuffer.sendMessage->state).c_str(),
3284                              rmrMessageBuffer.sendMessage->mtype,
3285                              rmr_get_meid(rmrMessageBuffer.sendMessage, (unsigned char *)meid));
3286                 auto rc = rmrMessageBuffer.sendMessage->state;
3287                 return rc;
3288             }
3289         } else {
3290             mdclog_write(MDCLOG_ERR, "Message state %s while sending request %d to Xapp from %s",
3291                          translateRmrErrorMessages(rmrMessageBuffer.sendMessage->state).c_str(),
3292                          rmrMessageBuffer.sendMessage->mtype,
3293                          rmr_get_meid(rmrMessageBuffer.sendMessage, (unsigned char *)meid));
3294             return rmrMessageBuffer.sendMessage->state;
3295         }
3296     }
3297     return 0;
3298 }
3299
3300 void buildJsonMessage(ReportingMessages_t &message) {
3301 #ifdef UNIT_TEST
3302     jsonTrace = true;
3303 #endif
3304     if (jsonTrace) {
3305         message.outLen = sizeof(message.base64Data);
3306         base64::encode((const unsigned char *) message.message.asndata,
3307                        (const int) message.message.asnLength,
3308                        message.base64Data,
3309                        message.outLen);
3310         if (mdclog_level_get() >= MDCLOG_DEBUG) {
3311             mdclog_write(MDCLOG_DEBUG, "Tracing: ASN length = %d, base64 message length = %d ",
3312                          (int) message.message.asnLength,
3313                          (int) message.outLen);
3314         }
3315
3316         snprintf(message.buffer, sizeof(message.buffer),
3317                  "{\"header\": {\"ts\": \"%ld.%09ld\","
3318                  "\"ranName\": \"%s\","
3319                  "\"messageType\": %d,"
3320                  "\"direction\": \"%c\"},"
3321                  "\"base64Length\": %d,"
3322                  "\"asnBase64\": \"%s\"}",
3323                  message.message.time.tv_sec,
3324                  message.message.time.tv_nsec,
3325                  message.message.enodbName,
3326                  message.message.messageType,
3327                  message.message.direction,
3328                  (int) message.outLen,
3329                  message.base64Data);
3330         static src::logger_mt &lg = my_logger::get();
3331
3332         BOOST_LOG(lg) << message.buffer;
3333     }
3334 }
3335
3336
3337 /**
3338  * take RMR error code to string
3339  * @param state
3340  * @return
3341  */
3342 string translateRmrErrorMessages(int state) {
3343     string str = {};
3344     switch (state) {
3345         case RMR_OK:
3346             str = "RMR_OK - state is good";
3347             break;
3348         case RMR_ERR_BADARG:
3349             str = "RMR_ERR_BADARG - argument passed to function was unusable";
3350             break;
3351         case RMR_ERR_NOENDPT:
3352             str = "RMR_ERR_NOENDPT - send//call could not find an endpoint based on msg type";
3353             break;
3354         case RMR_ERR_EMPTY:
3355             str = "RMR_ERR_EMPTY - msg received had no payload; attempt to send an empty message";
3356             break;
3357         case RMR_ERR_NOHDR:
3358             str = "RMR_ERR_NOHDR - message didn't contain a valid header";
3359             break;
3360         case RMR_ERR_SENDFAILED:
3361             str = "RMR_ERR_SENDFAILED - send failed; errno has nano reason";
3362             break;
3363         case RMR_ERR_CALLFAILED:
3364             str = "RMR_ERR_CALLFAILED - unable to send call() message";
3365             break;
3366         case RMR_ERR_NOWHOPEN:
3367             str = "RMR_ERR_NOWHOPEN - no wormholes are open";
3368             break;
3369         case RMR_ERR_WHID:
3370             str = "RMR_ERR_WHID - wormhole id was invalid";
3371             break;
3372         case RMR_ERR_OVERFLOW:
3373             str = "RMR_ERR_OVERFLOW - operation would have busted through a buffer/field size";
3374             break;
3375         case RMR_ERR_RETRY:
3376             str = "RMR_ERR_RETRY - request (send/call/rts) failed, but caller should retry (EAGAIN for wrappers)";
3377             break;
3378         case RMR_ERR_RCVFAILED:
3379             str = "RMR_ERR_RCVFAILED - receive failed (hard error)";
3380             break;
3381         case RMR_ERR_TIMEOUT:
3382             str = "RMR_ERR_TIMEOUT - message processing call timed out";
3383             break;
3384         case RMR_ERR_UNSET:
3385             str = "RMR_ERR_UNSET - the message hasn't been populated with a transport buffer";
3386             break;
3387         case RMR_ERR_TRUNC:
3388             str = "RMR_ERR_TRUNC - received message likely truncated";
3389             break;
3390         case RMR_ERR_INITFAILED:
3391             str = "RMR_ERR_INITFAILED - initialisation of something (probably message) failed";
3392             break;
3393         case RMR_ERR_NOTSUPP:
3394             str = "RMR_ERR_NOTSUPP - the request is not supported, or RMr was not initialised for the request";
3395             break;
3396         default:
3397             char buf[128]{};
3398             snprintf(buf, sizeof buf, "UNDOCUMENTED RMR_ERR : %d", state);
3399             str = buf;
3400             break;
3401     }
3402     return str;
3403 }
3404 int fetchStreamId(ConnectedCU_t *peerInfo, ReportingMessages_t &message)
3405 {
3406     auto loglevel = mdclog_level_get();
3407     int streamId = INVALID_STREAM_ID;
3408     if(message.peerInfo->isSingleStream != false)
3409     {
3410         streamId = message.peerInfo->singleStreamId;
3411         if (loglevel >= MDCLOG_DEBUG) {
3412         mdclog_write(MDCLOG_DEBUG, "Send SCTP message for SINGLE_STREAM streamId %d , Messeage Type %d ,%s",
3413                      streamId,message.message.messageType,  __FUNCTION__);
3414         }
3415         return streamId;
3416     }
3417     int msgType = message.message.messageType;
3418     switch (msgType){
3419         case RIC_E2_RESET_REQ:
3420         case RIC_E2_RESET_RESP:
3421         case RIC_E2_SETUP_RESP:
3422         case RIC_E2_SETUP_FAILURE:
3423         case RIC_ERROR_INDICATION:
3424         case RIC_SERVICE_QUERY:
3425         case RIC_SERVICE_UPDATE_ACK:
3426         case RIC_SERVICE_UPDATE_FAILURE:
3427             streamId = 0;
3428             break;
3429         case RIC_SUB_REQ:
3430         case RIC_SUB_DEL_REQ:
3431         case RIC_CONTROL_REQ:
3432             streamId = 1;
3433             break;
3434         default:
3435             streamId = 0;
3436             break;
3437     }
3438     if (loglevel >= MDCLOG_DEBUG) {
3439         mdclog_write(MDCLOG_DEBUG, "Send SCTP message for streamId %d Messeage Type %d, %s",
3440                      streamId, message.message.messageType, __FUNCTION__);
3441     }
3442     return streamId;
3443 }