Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
838 lines (740 loc) · 27.5 KB
/
Copy pathrun.py
File metadata and controls
838 lines (740 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
# Standard library imports
import time
import csv
from argparse import ArgumentParser, BooleanOptionalAction
# Define struct for arguments
import signal
from src.UESim import UESim
from src.SCTP import SCTPClient
from src.affinity import process_cpus
from src.NGAPSim import GNB
from src.ranlink import PipeLink
from src.shmlink import ShmLink
from src.userplane import Context, UserPlane, providers_from_config
from src.bpf.ipstats import IPStats
from src.UE import *
from multiprocessing import Process, active_children, Value
import logging
import yaml
import json
import netifaces
import socket
import os
import sys
GTP_UDP_PORT = 2152
protocol_names = {
# socket.IPPROTO_TCP: "tcp",
# socket.IPPROTO_UDP: "udp",
# socket.IPPROTO_ICMP: "icmp",
socket.IPPROTO_SCTP: "sctp",
GTP_UDP_PORT: "gtpu",
# ... Add other protocols as needed
}
pkt_s = "pkts/s"
bytes_s = "kb/s"
logger = logging.getLogger("__app__")
#######################################################################
# Data Structure Classes
#######################################################################
class Arguments:
def __init__(
self,
log,
console,
file,
interval,
num_pkts,
ue_config_file,
gnb_config_file,
statistics,
ebpf,
verbose,
):
self.log = log
self.console = console
self.interval = interval
self.num_pkts = num_pkts
self.file = file
self.ue_config_file = ue_config_file
self.gnb_config_file = gnb_config_file
self.statistics = statistics
self.ebpf = ebpf
self.verbose = verbose
class TimeRange:
def __init__(
self,
start_time,
end_time,
min_interval,
sum_interval,
max_interval,
duration,
completed_in,
success,
failed,
):
self.start_time = Value("d", start_time)
self.end_time = Value("d", end_time)
self.min_interval = Value("d", min_interval)
self.sum_interval = Value("d", sum_interval)
self.max_interval = Value("d", max_interval)
self.duration = Value("d", duration)
self.completed_in = Value("d", completed_in)
self.success = Value("i", success)
self.failed = Value("i", failed)
#######################################################################
# Network Utility Functions
#######################################################################
def get_network_interfaces_map():
"""
Creates a mapping between interface indices and interface names.
Returns:
dict: A dictionary mapping interface indices to interface names
"""
interface_map = {}
interfaces = netifaces.interfaces() # Get interface names using netifaces
for interface_name in interfaces:
try:
if_index = socket.if_nametoindex(interface_name)
interface_map[if_index] = interface_name
except OSError:
print(f"Error retrieving if_index for interface: {interface_name}")
return interface_map
#######################################################################
# UE Management Functions
#######################################################################
def create_ues(ue_profiles, x):
"""
Creates UE instances based on the provided profiles and distributes them
across the specified number of processes.
Args:
ue_profiles: List of UE configuration profiles
x: Number of processes to distribute UEs across
Returns:
tuple: A tuple containing a list of UE dictionaries and the total number of UEs
"""
dict_list = [{} for _ in range(x)]
p = 0
for ue_config in ue_profiles:
count, base_imsi, init_imsi = (
ue_config["count"],
ue_config["supi"][:-10],
int(ue_config["supi"][-10:]),
)
for i in range(init_imsi, init_imsi + count):
imsi = f"{base_imsi}{i:010d}"
ue = UE({**ue_config, "supi": imsi})
dict_list[p % x][i] = ue
p += 1
if p < x:
dict_list = dict_list[:p]
return dict_list, p
def split_ues(ue_list, k):
"""
Splits a gNB's UEs across its k UE simulators, in turn, so that a UE keeps its place in the gNB's
start order (simulator j has the gNB's UEs j, j + k, ...). Empty parts are left out.
"""
parts = [{} for _ in range(k)]
for p, (ue_id, ue) in enumerate(ue_list.items()):
parts[p % k][ue_id] = ue
return [part for part in parts if part]
def share(total, n, j):
"""
Simulator j's share of a per-gNB limit split across n simulators: they add up to total, and each
gets at least one while total > 0 (0 stays 0, the open loop).
"""
if total <= 0:
return 0
return max(1, total // n + (1 if j < total % n else 0))
def make_link(kind, stop, ring_kib=32):
"""
A UE-RAN link of this kind (--link): pipe (PipeLink, a multiprocessing.Pipe) or shm (ShmLink, two
rings of ring_kib KiB in shared memory with eventfd wake-ups; Linux on x86-64). A full link blocks
its sender until stop().
"""
if kind == "shm":
return ShmLink(stop=stop, size=ring_kib * 1024)
if kind == "pipe":
return PipeLink(stop=stop)
raise ValueError(f"unknown link type {kind!r}")
def run_process(target, cpu, links, own):
"""
A UE simulator's or a gNB's process. It closes the links that are not its own, which a forked
child holds as well, so that a peer's exit ends a link (the process's own ends are attached by
target).
"""
for link in links:
if link not in own:
link.close()
target(cpu)
#######################################################################
# Statistics and Monitoring Functions
#######################################################################
def print_state_states(ue_fg_msg_states, state_writer):
"""
Records the current UE state counts to a CSV file.
Args:
ue_fg_msg_states: Array of UE state counts
state_writer: CSV writer for state output
"""
entry = {}
for value, code in fg_msg_codes.items():
ue_count = ue_fg_msg_states[code - FGMM_MIN_TYPE]
entry[value] = ue_count
state_writer.writerow(entry.values())
def print_stats(
previous_data, min_data, max_data, ipstats, gtpuTrafficgen, interfaces_map
):
try:
print()
print(
f"{'':<8} | {' '.join(f'{interfaces_map[if_index]:^20}' for if_index in sorted(interfaces_map))}"
) # Headers
print(
f"{'':<8} | {' '.join(f'{pkt_s:>10}{bytes_s:>10}' for _ in sorted(interfaces_map))}"
) # Subheaders
ip_stats = ipstats.get_stats()
gtpu_stats = gtpuTrafficgen.get_stats() if gtpuTrafficgen else {}
# Merge GTPU stats with ip stats
for key, value in gtpu_stats.items():
group = ip_stats[key]
for field in ("rx_bytes", "rx_packets", "tx_bytes", "tx_packets"):
group[field] += value[field] # Dynamically access fields
for proto, p_name in protocol_names.items():
for direction, label in ("rx", "rx"), ("tx", "tx"):
row_data = [
# f"{delta_packets:>10}{delta_bytes / 1024:>10.0f}"
(delta_packets, delta_bytes / 1024)
for if_index in sorted(interfaces_map.keys())
for delta_packets, delta_bytes in [
(
ip_stats.get((if_index, proto), {}).get(
f"{direction}_packets", 0
)
- previous_data.get((if_index, proto), {}).get(
f"{direction}_packets", 0
),
ip_stats.get((if_index, proto), {}).get(
f"{direction}_bytes", 0
)
- previous_data.get((if_index, proto), {}).get(
f"{direction}_bytes", 0
),
)
]
]
print(
f"{p_name:<6}{label:<2} | {' '.join(f'{dp:>10.0f}{db:>10.0f}' for dp, db in row_data)}"
)
# Update min_data and max_data
for if_index, (delta_packets, delta_bytes) in enumerate(row_data):
key = (if_index, proto, direction)
min_data[key] = min(min_data.get(key, delta_packets), delta_packets)
max_data[key] = max(max_data.get(key, delta_packets), delta_packets)
previous_data = ip_stats
except KeyboardInterrupt:
print()
#######################################################################
# SCTP Tracing Functions
#######################################################################
def setup_sctp_tracers(args, exit_program):
"""
Sets up SCTP tracers for monitoring SCTP-related metrics.
Args:
args: Command line arguments
exit_program: Shared value to signal program exit
Returns:
Process: A process for running the tracers, or None if no tracers enabled
"""
# Ensure output directory exists
if args.folder and not os.path.exists(args.folder):
os.makedirs(args.folder)
# Dictionary to hold all active tracers
tracers = {}
def register_tracer(name, module_name, class_name, output_name):
output_file = os.path.join(args.folder, output_name) if args.folder else None
try:
module = __import__(module_name, fromlist=[class_name])
tracer_class = getattr(module, class_name)
tracers[name] = tracer_class(
interval=args.period, csv_output=True, output_file=output_file
)
except Exception as exc:
print(
f"Warning: disabling SCTP {name.lower()} tracer: {exc}",
file=sys.stderr,
)
# Only import the modules when needed to avoid dependencies for users
# who don't use SCTP tracing
if args.sctp_rtt:
register_tracer(
"RTT", "sctptrace.tools.sctp_rtt", "SCTPRttTracer", "sctp_rtt.csv"
)
if args.sctp_rto:
register_tracer(
"RTO", "sctptrace.tools.sctp_rto", "SCTPRtoTracer", "sctp_rto.csv"
)
if args.sctp_bufmon:
register_tracer(
"Buffer",
"sctptrace.tools.sctp_bufmon",
"SCTPBufmonTracer",
"sctp_bufmon.csv",
)
if args.sctp_stream:
register_tracer(
"Stream",
"sctptrace.tools.sctp_streamutil",
"SCTPStreamTracer",
"sctp_stream.csv",
)
if args.sctp_jitter:
register_tracer(
"Jitter",
"sctptrace.tools.sctp_jitter",
"SCTPJitterTracer",
"sctp_jitter.csv",
)
# Create a process to handle all tracers with proper signal handling
if tracers:
tracer_process = Process(
target=run_tracers, args=(tracers, args.period, exit_program)
)
tracer_process.daemon = True
return tracer_process
return None
def run_tracers(tracers, interval, exit_flag):
"""
Run all tracers in a single process with proper signal handling.
Args:
tracers: Dictionary of tracer instances
interval: Polling interval
exit_flag: Shared value to signal program exit
"""
active_tracers = {}
# Shared with the signal handler so a tracer is not cleaned up twice
cleaned_tracers = {}
# Set up signal handlers for graceful shutdown
def handle_exit_signal(signum, frame):
cleanup_tracers(active_tracers, cleaned_tracers)
sys.exit(0)
signal.signal(signal.SIGTERM, handle_exit_signal)
signal.signal(signal.SIGINT, handle_exit_signal)
# Setup all tracers
for name, tracer in tracers.items():
try:
tracer.setup()
active_tracers[name] = tracer
except Exception as e:
print(f"Warning: tracer {name} disabled during setup: {e}")
if not active_tracers:
print("Warning: no SCTP tracers could be started")
return
try:
while not exit_flag.value:
for name, tracer in active_tracers.items():
tracer.poll_events() # Short timeout to check exit flag
time.sleep(0.1) # Small sleep to avoid CPU spinning
except Exception as e:
print(f"Error in tracer process: {e}")
finally:
cleanup_tracers(active_tracers, cleaned_tracers)
def cleanup_tracers(tracers, cleaned_tracers):
"""
Ensure all tracers are properly cleaned up.
Args:
tracers: Dictionary of tracer instances
cleaned_tracers: Dictionary tracking which tracers have been cleaned
"""
if cleaned_tracers is None:
cleaned_tracers = {name: False for name in tracers.keys()}
for name, tracer in tracers.items():
if cleaned_tracers.get(name, False):
continue
try:
tracer.print_summary()
time.sleep(2)
tracer.cleanup()
cleaned_tracers[name] = True
print(f"Tracer {name} cleaned up")
except Exception as e:
print(f"Error cleaning up tracer {name}: {e}")
#######################################################################
# Main Application Logic
#######################################################################
def main(args):
"""
Main function that runs the 5G Core traffic generator.
Args:
args: Command line arguments
"""
# Read server configuration
with open(args.gnb_config_file, "r") as stream:
try:
server_config = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
with open(args.ue_config_file, "r") as stream:
try:
ue_config = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
cpus = sorted(os.sched_getaffinity(0))
num_cpus = len(cpus)
exit_program = multiprocessing.Value("i", 0)
interfaces_map = get_network_interfaces_map()
# The user plane: the providers that give each PDU session its traffic as it comes up
# (src/userplane: file, xdp, trex). Without a userPlane section, gtpuConfig configures the
# XDP generator, as before. It runs in a process of its own, started before the gNBs.
userplane = UserPlane(
providers_from_config(server_config),
Context(folder=args.folder, verbose=args.verbose, num_pkts=int(args.num_pkts), num_cpus=num_cpus),
)
userplane.start()
gtpuTrafficgen = None # the XDP generator and its counters live in the user plane process
# Start SCTP tracers if requested
tracer_process = None
if (
args.sctp
or args.sctp_rtt
or args.sctp_rto
or args.sctp_bufmon
or args.sctp_stream
or args.sctp_jitter
):
tracer_process = setup_sctp_tracers(args, exit_program)
if tracer_process:
tracer_process.start()
# Wait a for ebpf programs to attach
time.sleep(5)
# This will store the start and end time of the UE simulation/emulation
ue_sim_time = TimeRange(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0)
ue_fg_msg_states = multiprocessing.Array(
"i", tuple([0] * (FGSM_MAX_TYPE - FGMM_MIN_TYPE + 1)), lock=True
)
state_writer = None
if args.statistics:
state_log_file = os.path.join(args.folder, "ue_states.csv")
os.makedirs(os.path.dirname(state_log_file), exist_ok=True)
state_file = open(state_log_file, "w", newline="")
state_writer = csv.writer(state_file)
# Write headers
state_writer.writerow(list(fg_msg_codes.keys()))
processes = []
# Each gNB process has --ue-procs-per-ran UE simulators, each on a UE-RAN link of its own
per_ran = max(1, args.ue_procs_per_ran)
num_gnbs = args.gnbs or max(1, (num_cpus - 1) // (per_ran + 1))
ue_lists, num_ues = create_ues(ue_config["ue_profiles"], num_gnbs)
# A CPU per process (see src/affinity.py), or no pinning
placement = iter(process_cpus(len(ue_lists), cpus, per_ran + 1) if args.pin else [None] * ((per_ran + 1) * len(ue_lists)))
links = []
for i in range(len(ue_lists)):
sctp_client = SCTPClient(server_config, nodelay=args.sctp_nodelay)
# The gNB's UEs, split across its UE simulators; a full link blocks its sender until the run ends
sims = split_ues(ue_lists[i], per_ran)
gnb_links = [make_link(args.link, lambda: exit_program.value, args.link_ring_kib) for _ in sims]
links += gnb_links
config = {}
gnb = GNB(
exit_program,
sctp_client,
userplane,
server_config,
[link.ran_end for link in gnb_links],
args.verbose,
gnb_index=i,
ngap_fastpath=args.ngap_fastpath,
)
for k, (sim_ues, link) in enumerate(zip(sims, gnb_links)):
# UE simulator j: one per gNB (j = i) by default. With several, they take turns to start
# the gNB's UEs, so that the gNB still starts one every interval, and share --inflight
j = i * per_ran + k
ueSim = UESim(
ue_fg_msg_states,
exit_program,
sim_ues,
link.ue_end,
args.interval * len(sims),
args.statistics,
args.verbose,
ue_sim_time,
folder=args.folder,
index=j,
poisson=args.poisson,
seed=args.seed + j,
inflight=share(args.inflight, len(sims), k),
ue_timeout=args.ue_timeout,
phase=args.interval * k,
)
processes.append(
Process(name=f"ueSIM-{j}", target=run_process, args=(ueSim.run, next(placement), links, [link]))
)
processes.append(
Process(name=f"gnb-{i}", target=run_process, args=(gnb.run, next(placement), links, gnb_links))
)
for process in processes:
process.start()
# The processes have their ends of the links
for link in links:
link.close()
# SIGTERM (docker/nerdctl stop) ends the run like Ctrl-C. Set after the children are
# started, so that terminate() still ends them.
def handle_sigterm(signum, frame):
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, handle_sigterm)
ipstats = None
if args.ebpf:
ipstats = IPStats()
previous_data = {}
min_data = {}
max_data = {}
while True:
try:
if args.statistics:
print_state_states(ue_fg_msg_states, state_writer)
if args.ebpf:
print_stats(
previous_data,
min_data,
max_data,
ipstats,
gtpuTrafficgen,
interfaces_map,
)
# If all UEs are in state 74 (5GMMANConnectionReleaseComplete) exit processes
if ue_fg_msg_states[74 - FGMM_MIN_TYPE] == num_ues:
exit_program.value = True
break
# report the value
if len(active_children()) == 0:
break
# Wait for a short time before checking again
time.sleep(args.period)
except KeyboardInterrupt:
# Let the UE and gNB processes stop by themselves, so that they write their results
exit_program.value = True
break
# Allow for sime for process to exit after setting exit_program.value = True
time.sleep(2)
if tracer_process:
tracer_process.join()
# Stop the sessions' traffic before the gNB processes go
userplane.stop()
for process in processes:
process.join(timeout=0.2)
# TODO: fix processes requiring forceful termination
children = multiprocessing.active_children()
for child in children:
child.terminate()
# Collect the time on each UE
table = [
[
"Duration",
f" {ue_sim_time.end_time.value - ue_sim_time.start_time.value} seconds",
],
# ["Completed in",f" {latest_time - start_time} seconds"],
["N# of UEs", num_ues],
["Successful procedures ", f"{ue_sim_time.success.value} UEs"],
["Failed procedures", f"{num_ues - ue_sim_time.success.value} UEs"],
["Min interval", f"{ue_sim_time.min_interval.value} seconds"],
[
"Avg interval",
f"{ue_sim_time.sum_interval.value/ue_sim_time.success.value if ue_sim_time.success.value > 0 else -1} seconds",
],
["Max interval", f"{ue_sim_time.max_interval.value} seconds"],
]
print("\n\n")
print(tabulate(table, ["Item", "Results"], tablefmt="heavy_outline"))
summary_log_file = os.path.join(args.folder, "summary_stats.csv")
os.makedirs(os.path.dirname(summary_log_file), exist_ok=True)
summary_file = open(summary_log_file, "w", newline="")
summary_writer = csv.writer(summary_file)
summary_writer.writerow(
[
"Duration",
"N# of UEs",
"Successful procedures",
"Failed procedures",
"Min interval",
"Avg interval",
"Max interval",
]
)
summary_writer.writerow(
[
ue_sim_time.end_time.value - ue_sim_time.start_time.value,
num_ues,
ue_sim_time.success.value,
num_ues - ue_sim_time.success.value,
ue_sim_time.min_interval.value,
(
ue_sim_time.sum_interval.value / ue_sim_time.success.value
if ue_sim_time.success.value > 0
else -1
),
ue_sim_time.max_interval.value,
]
)
#######################################################################
# Entry Point
#######################################################################
if __name__ == "__main__":
# Define parser arguments
parser = ArgumentParser(description="Run 5G Core traffic generator")
parser.add_argument("-l", "--log", type=float, default=1, help="Log to file")
parser.add_argument("-c", "--console", action="store_true", help="Print to console")
parser.add_argument(
"-i",
"--interval",
type=float,
default=0,
help="Interval between starting UEs, in seconds, per gNB (0: all at once)",
)
parser.add_argument(
"--poisson",
action="store_true",
help="Start UEs as a Poisson process whose mean gap is the interval",
)
parser.add_argument("--seed", type=int, default=1, help="Seed of the Poisson starts (gNB i uses seed + i)")
parser.add_argument(
"--inflight",
type=int,
default=0,
help="Closed loop: at most this many UEs per gNB in their procedures at once (0: open loop); a UE "
"is done at the end of its procedures or, with 5GSMPDUSessionTransmission, once it holds its PDU "
"session (at its PDU Session Establishment Accept)",
)
parser.add_argument(
"--ue-timeout",
type=float,
default=30.0,
help="With --inflight: free the place of a UE that has not finished after this many seconds",
)
parser.add_argument(
"--gnbs",
type=int,
default=0,
help="Number of gNBs, each with its own NG setup, a process and --ue-procs-per-ran UE simulator "
"processes (default: the CPUs less one, over the processes per gNB)",
)
parser.add_argument(
"--ue-procs-per-ran",
type=int,
default=1,
help="UE simulator processes per gNB process, each on a link of its own; a gNB's UEs are split "
"across them, and -i and --inflight stay per gNB (default 1)",
)
parser.add_argument(
"--link",
choices=["pipe", "shm"],
default="pipe",
help="The UE-RAN link between each UE simulator and its gNB: pipe (a multiprocessing pipe) or shm "
"(rings in shared memory, eventfd wake-ups; Linux on x86-64) (default pipe)",
)
parser.add_argument(
"--link-ring-kib",
type=int,
default=32,
help="With --link shm: each ring's size in KiB, a power of two (two rings per link); the default holds "
"about as many messages as a pipe (default 32)",
)
parser.add_argument(
"--pin",
action=BooleanOptionalAction,
default=True,
help="Pin each UE simulator and gNB process to a CPU of its own (--no-pin: let the scheduler place them)",
)
parser.add_argument(
"-n",
"--num_pkts",
type=float,
default=(1 << 20),
help="Number of num-packets to send per second",
)
parser.add_argument(
"-u",
"--ue_config_file",
type=str,
default="./config/ue.yaml",
help="UE configuration file",
)
parser.add_argument(
"-g",
"--gnb_config_file",
type=str,
default="./config/gnb.yaml",
help="GNB configuration file",
)
parser.add_argument(
"-f",
"--folder",
type=str,
default=".",
help="Directory for output (stats and logs)",
)
parser.add_argument(
"-v",
"--verbose",
action="count",
default=0,
help="Increase verbosity (can be specified multiple times)",
)
parser.add_argument(
"-s", "--statistics", action="store_true", help="Enable print of statistics"
)
parser.add_argument(
"-e", "--ebpf", action="store_true", help="Enable print of ebpf statistics"
)
parser.add_argument(
"-p",
"--period",
type=float,
default=1,
help="Period/interval (seconds) for printing statistics",
)
parser.add_argument(
"--sctp-nodelay",
action=BooleanOptionalAction,
default=True,
help="Send each NGAP message at once (SCTP_NODELAY); --no-sctp-nodelay keeps Nagle's algorithm",
)
parser.add_argument(
"--ngap-fastpath",
action=BooleanOptionalAction,
default=True,
help="Build the gNB's NGAP messages of a registration, a PDU session's setup and a UE context release from "
"byte templates and parse the downlink ones without pycrate (src/ngapfast.py); --no-ngap-fastpath: "
"pycrate for every message",
)
# Add SCTP-specific arguments
parser.add_argument(
"--sctp", action="store_true", help="Enable all SCTP tracing modules"
)
parser.add_argument(
"--sctp-rtt", action="store_true", help="Enable SCTP RTT tracing"
)
parser.add_argument(
"--sctp-rto", action="store_true", help="Enable SCTP RTO tracing"
)
parser.add_argument(
"--sctp-bufmon", action="store_true", help="Enable SCTP buffer monitoring"
)
parser.add_argument(
"--sctp-stream",
action="store_true",
help="Enable SCTP stream utilization analysis",
)
parser.add_argument(
"--sctp-jitter", action="store_true", help="Enable SCTP jitter measurement"
)
args = parser.parse_args()
if args.link_ring_kib < 1 or args.link_ring_kib & (args.link_ring_kib - 1):
parser.error(f"--link-ring-kib must be a power of two, not {args.link_ring_kib}")
# If --sctp is specified, enable all SCTP tracing modules
if args.sctp:
args.sctp_rtt = True
args.sctp_rto = True
args.sctp_bufmon = True
args.sctp_stream = True
args.sctp_jitter = True
main(args)