You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1078 lines
35KB

  1. #!/usr/bin/env python3
  2. import json
  3. import requests
  4. import os
  5. import re
  6. import socket
  7. import subprocess
  8. import asyncio
  9. import serial
  10. from argparse import ArgumentParser
  11. from datetime import datetime
  12. from threading import Thread
  13. from time import sleep
  14. # {} for interface
  15. GET_IPV4_SHELL_COMMAND = "ip a | grep {} | grep inet | cut -d' ' -f6 | cut -d'/' -f1"
  16. NR_CQI_COMMAND = b'AT+QNWCFG="nr5g_csi"\r\n'
  17. NR_SERVINGCELL_COMMAND = b'AT+QENG="servingcell"\r\n'
  18. NR_EN_DC_STATUS_COMMAND = b"AT+QENDC\r\n"
  19. NR_SERIAL_RESPOND_TOME = 0.3 # s
  20. CMD_TIME_EPOCH = "date +%s"
  21. class ProcessHandler:
  22. def __init__(self):
  23. self.processList = []
  24. def add_process(self, process, logfile=None):
  25. if logfile is not None:
  26. self.processList.append(dict(process=process, logfile=logfile))
  27. else:
  28. self.processList.append(process)
  29. def kill_all(self):
  30. for p in self.processList:
  31. if isinstance(p, dict):
  32. p["logfile"].close()
  33. p["process"].kill()
  34. else:
  35. p.kill()
  36. def parse_var(s):
  37. """
  38. Parse a key, value pair, separated by '='
  39. That's the reverse of ShellArgs.
  40. On the command line (argparse) a declaration will typically look like:
  41. foo=hello
  42. or
  43. foo="hello world"
  44. """
  45. items = s.split("=")
  46. key = items[0].strip() # we remove blanks around keys, as is logical
  47. value = ""
  48. if len(items) > 1:
  49. # rejoin the rest:
  50. value = "=".join(items[1:])
  51. return (key, value)
  52. def parse_vars(items):
  53. """
  54. Parse a series of key-value pairs and return a dictionary
  55. """
  56. d = {}
  57. if items:
  58. for item in items:
  59. key, value = parse_var(item)
  60. d[key] = value
  61. return d
  62. def write_to_file(filepath, content, overwrite=False):
  63. mode = None
  64. if overwrite:
  65. mode = "w"
  66. else:
  67. mode = "a"
  68. try:
  69. f = open(filepath, mode)
  70. f.write(content)
  71. f.close()
  72. except IOError:
  73. print_message("ERROR: Could not write to file: {}".format(filepath))
  74. # For none blocking filewrite
  75. def background_write_to_file(filepath, content, overwrite=False):
  76. thread = Thread(
  77. target=write_to_file,
  78. args=(
  79. filepath,
  80. content,
  81. overwrite,
  82. ),
  83. )
  84. thread.start()
  85. def execute_tcp_dump(processHandler, interface, outputfile, ws_filter, flags=[]):
  86. cmd = ["tcpdump", "-i" + interface, "-U", "-w", outputfile, ws_filter]
  87. if len(flags) > 0:
  88. # insert after -U
  89. n = 3
  90. for flag in flags:
  91. cmd.insert(n, flag)
  92. n += 1
  93. process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  94. processHandler.add_process(process)
  95. def save_tcp_trace(processHandler, filename, sender_ip, port):
  96. cmd_uptime = ["cat", "/proc/uptime"]
  97. logfile = open(filename, "a")
  98. subprocess.call(cmd_uptime, stdout=logfile)
  99. # /sys/kernel/debug/tracing/events/tcp/tcp_probe/enable
  100. cmd = ["cat", "/sys/kernel/debug/tracing/trace_pipe"]
  101. process = subprocess.Popen(cmd, stdout=logfile)
  102. processHandler.add_process(process, logfile=logfile)
  103. def get_ip_from_interface(interface):
  104. c = GET_IPV4_SHELL_COMMAND.format(interface)
  105. ip = (
  106. subprocess.check_output(c, shell=True)
  107. .decode("utf-8")
  108. .replace(" ", "")
  109. .replace("\n", "")
  110. )
  111. return ip
  112. def config2json(args):
  113. config = vars(args).copy()
  114. # parse the key-value pairs from set arg
  115. set_args = parse_vars(args.set)
  116. config["set"] = set_args
  117. # delete not used keys
  118. del config["interface"]
  119. del config["server"]
  120. del config["client"]
  121. del config["folder"]
  122. return bytes(json.dumps(config), "utf-8")
  123. def json2config(json_string):
  124. return json.loads(json_string)
  125. def print_message(m):
  126. print("[{}]\t{}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), m))
  127. def deactivate_hystart():
  128. print_message("Deactivate HyStart")
  129. os.system('echo "0" > /sys/module/tcp_cubic/parameters/hystart')
  130. def activate_hystart():
  131. print_message("Activate HyStart")
  132. os.system('echo "1" > /sys/module/tcp_cubic/parameters/hystart')
  133. def is_hystart_activated():
  134. return (
  135. subprocess.check_output(
  136. "cat /sys/module/tcp_cubic/parameters/hystart", shell=True
  137. )
  138. == "1"
  139. )
  140. def is_tcp_probe_enabled():
  141. return (
  142. subprocess.check_output(
  143. "cat /sys/kernel/debug/tracing/events/tcp/tcp_probe/enable", shell=True
  144. )
  145. == "1"
  146. )
  147. def enable_tcp_probe():
  148. os.system("echo '1' > /sys/kernel/debug/tracing/events/tcp/tcp_probe/enable")
  149. def set_default_receive_window():
  150. print_message("Set receive window to default values")
  151. os.system('echo "212992" > /proc/sys/net/core/rmem_max')
  152. os.system('echo "212992" > /proc/sys/net/core/rmem_default')
  153. os.system('echo "4096 131072 6291456" > /proc/sys/net/ipv4/tcp_rmem')
  154. def raise_receive_window():
  155. print_message("Multiply receive windows by factor 10")
  156. os.system('echo "2129920" > /proc/sys/net/core/rmem_max')
  157. os.system('echo "2129920" > /proc/sys/net/core/rmem_default')
  158. os.system('echo "40960 1310720 62914560" > /proc/sys/net/ipv4/tcp_rmem')
  159. def monitor_serial(ser, output_file):
  160. run_cmds = [NR_CQI_COMMAND, NR_SERVINGCELL_COMMAND, NR_EN_DC_STATUS_COMMAND]
  161. try:
  162. while ser.is_open:
  163. response = subprocess.check_output(CMD_TIME_EPOCH, shell=True).decode(
  164. "utf-8"
  165. )
  166. for cmd in run_cmds:
  167. ser.write(cmd)
  168. sleep(0.3)
  169. response += ser.read(ser.inWaiting()).decode("utf-8")
  170. response = (
  171. response.replace("\n", ";")
  172. .replace("\r", "")
  173. .replace(";;OK", ";")
  174. .replace(";;", ";")
  175. )
  176. write_to_file(output_file, response + "\n")
  177. except:
  178. if not ser.is_open:
  179. print_message("Serial port is closed. Exit monitoring thread.")
  180. else:
  181. print_message(
  182. "Something went wrong while monitoring serial interface. Exit monitoring thread."
  183. )
  184. return
  185. class Server:
  186. def __init__(self, config):
  187. self.config = config
  188. def measure(self):
  189. print("Received config:")
  190. print(self.config)
  191. print_message("Start measurement")
  192. if self.config["bandwidth"]:
  193. self.bandwidth()
  194. elif self.config["drx"]:
  195. self.drx()
  196. elif self.config["harq"]:
  197. self.harq()
  198. elif self.config["cbr"]:
  199. self.cbr()
  200. elif self.config["tcp_parallel"]:
  201. self.tcp_parallel_flows()
  202. else:
  203. print_message("Nothing to do on server side.")
  204. def drx(self):
  205. print_message("DRX nothing to do on server side.")
  206. def harq(self):
  207. print_message("HARQ nothing to do on server side.")
  208. def bandwidth(self):
  209. server_is_sender = False
  210. if "reverse" in self.config["set"]:
  211. server_is_sender = self.config["set"]["server_is_sender"]
  212. print_message("Use reverse mode: {}".format(server_is_sender))
  213. tcp_algo = list()
  214. if "algo" in self.config["set"]:
  215. for s in self.config["set"]["algo"].split(","):
  216. tcp_algo.append(s)
  217. print_message("Using {} for TCP transmissions.".format(s))
  218. else:
  219. tcp_algo.append("cubic")
  220. print_message("Using {} for TCP transmissions.".format(tcp_algo[0]))
  221. alternate_hystart = False
  222. if "alternate_hystart" in self.config["set"]:
  223. if self.config["set"]["alternate_hystart"] == "true":
  224. alternate_hystart = True
  225. # prevent address already in use
  226. sleep(2)
  227. ws_filter = ""
  228. if server_is_sender:
  229. # server sends
  230. if not is_tcp_probe_enabled():
  231. print_message("tcp probe is not enabled!")
  232. enable_tcp_probe()
  233. print_message("tcp probe is now enabled")
  234. for n in range(1, self.config["number_of_measurements"] + 1):
  235. print_message(
  236. "{} of {}".format(n, self.config["number_of_measurements"])
  237. )
  238. print_message(
  239. "Using {} for congestion control".format(
  240. tcp_algo[congestion_control_index]
  241. )
  242. )
  243. iperf_command = [
  244. "iperf3",
  245. "-s",
  246. "--port",
  247. str(self.config["port"]),
  248. "--one-off",
  249. ]
  250. filepath_tcp_trace = "{}{}_bandwidth_reverse_{}_{}_{}.txt".format(
  251. self.config["folder"], self.config["prefix"], "tcp", "tcp_trace", n
  252. )
  253. save_tcp_trace(
  254. processHandler,
  255. filepath_tcp_trace,
  256. self.config["server"],
  257. self.config["port"],
  258. )
  259. subprocess.call(iperf_command)
  260. processHandler.kill_all()
  261. congestion_control_index = (congestion_control_index + 1) % len(
  262. tcp_algo
  263. )
  264. else:
  265. # client sends
  266. ws_filter = "{} and port {}".format("tcp", self.config["port"])
  267. print_message("Use ws filter: {}".format(ws_filter))
  268. name_option = ""
  269. state_counter = 0
  270. congestion_control_index = 0
  271. for n in range(1, self.config["number_of_measurements"] + 1):
  272. print_message(
  273. "Measurement {} of {}".format(
  274. n, self.config["number_of_measurements"]
  275. )
  276. )
  277. tcpdump_flags = []
  278. if alternate_hystart:
  279. if state_counter == 0:
  280. tcp_algo = "cubic"
  281. raise_receive_window()
  282. name_option = "_cubic_slowstart_raise_"
  283. state_counter = 1
  284. elif state_counter == 1:
  285. tcp_algo = "cubic"
  286. set_default_receive_window()
  287. name_option = "_cubic_hystart_default_"
  288. state_counter = 2
  289. elif state_counter == 2:
  290. tcp_algo = "bbr"
  291. raise_receive_window()
  292. name_option = "_bbr_raise_"
  293. state_counter = 3
  294. elif state_counter == 3:
  295. tcp_algo = "bbr"
  296. set_default_receive_window()
  297. name_option = "_bbr_default_"
  298. state_counter = 0
  299. else:
  300. name_option = ""
  301. filepath = "{}{}{}_bandwidth_{}_{}_{}.pcap".format(
  302. self.config["folder"],
  303. self.config["prefix"],
  304. name_option,
  305. "tcp",
  306. tcp_algo[congestion_control_index],
  307. n,
  308. )
  309. tcpdump_flags.append("-s96")
  310. thread = Thread(
  311. target=execute_tcp_dump,
  312. args=(
  313. processHandler,
  314. args.interface,
  315. filepath,
  316. ws_filter,
  317. tcpdump_flags,
  318. ),
  319. )
  320. thread.start()
  321. sleep(2)
  322. iperf_command = [
  323. "iperf3",
  324. "-s",
  325. "--port",
  326. str(self.config["port"]),
  327. "--one-off",
  328. ]
  329. subprocess.call(iperf_command)
  330. sleep(2)
  331. processHandler.kill_all()
  332. congestion_control_index = (congestion_control_index + 1) % len(
  333. tcp_algo
  334. )
  335. def cbr(self):
  336. use_reverse_mode = False
  337. if "reverse" in self.config["set"]:
  338. use_reverse_mode = self.config["set"]["reverse"] == "true"
  339. print_message("Use reverse mode: {}".format(use_reverse_mode))
  340. # bitrate is only used for filenames on server side
  341. bitrate = "1M"
  342. if "bitrate" in self.config["set"]:
  343. bitrate = self.config["set"]["bitrate"]
  344. sleep_time = 60.0
  345. if "sleep" in self.config["set"]:
  346. sleep_time = float(self.config["set"]["sleep"])
  347. print_message("Sleep time for each measurement: {}s".format(sleep_time))
  348. # build wireshark filter
  349. if use_reverse_mode:
  350. ws_filter = "{} and src {}".format("udp", self.config["server"])
  351. else:
  352. ws_filter = "{} and dst {} and port {}".format(
  353. "udp", self.config["server"], self.config["port"]
  354. )
  355. print_message("Use ws filter: {}".format(ws_filter))
  356. # build iperf3 command
  357. iperf_command = [
  358. "iperf3",
  359. "-s",
  360. "--port",
  361. str(self.config["port"]),
  362. "--one-off",
  363. ]
  364. for n in range(1, self.config["number_of_measurements"] + 1):
  365. print_message("{} of {}".format(n, self.config["number_of_measurements"]))
  366. sleep(sleep_time)
  367. pcap_filepath = "{}{}_cbr_server_{}_bitrate{}_{}.pcap".format(
  368. self.config["folder"],
  369. self.config["prefix"],
  370. "sender" if use_reverse_mode else "receiver",
  371. bitrate,
  372. n,
  373. )
  374. thread = Thread(
  375. target=execute_tcp_dump,
  376. args=(
  377. processHandler,
  378. self.config["interface"],
  379. pcap_filepath,
  380. ws_filter,
  381. ),
  382. )
  383. thread.start()
  384. sleep(1)
  385. subprocess.call(iperf_command)
  386. sleep(1)
  387. processHandler.kill_all()
  388. def tcp_parallel_flows(self):
  389. # for n in range(1, (self.config["number_of_measurements"] * 2) + 1):
  390. # print_message(
  391. # "Measurement {} of {}".format(
  392. # n, self.config["number_of_measurements"]
  393. # )
  394. # )
  395. sleep(4)
  396. iperf_command = [
  397. "iperf3",
  398. "-s",
  399. "--port",
  400. str(self.config["port"]),
  401. # "--one-off",
  402. ]
  403. subprocess.call(iperf_command)
  404. class Client:
  405. def __init__(self, config):
  406. self.config = config
  407. def measure(self):
  408. print("Config:")
  409. print(self.config)
  410. sleep(1)
  411. print_message("Start measurement")
  412. ser = None
  413. if self.config["serial"] is not None:
  414. print_message("Opening serial port for {}".format(self.config["serial"]))
  415. ser = serial.Serial(
  416. port=self.config["serial"],
  417. baudrate=self.config["baudrate"],
  418. )
  419. ser.isOpen()
  420. ser_filepath = "{}{}_serial_monitor_output.txt".format(
  421. self.config["folder"], self.config["prefix"]
  422. )
  423. ser_thread = Thread(
  424. target=monitor_serial,
  425. args=(
  426. ser,
  427. ser_filepath,
  428. ),
  429. )
  430. ser_thread.start()
  431. if self.config["bandwidth"]:
  432. self.bandwidth()
  433. elif self.config["drx"]:
  434. self.drx()
  435. elif self.config["harq"]:
  436. self.harq()
  437. elif self.config["cbr"]:
  438. self.cbr()
  439. elif self.config["tcp_parallel"]:
  440. self.tcp_parallel_flows()
  441. elif self.config["ping"]:
  442. self.ping()
  443. if ser is not None:
  444. print_message("Closing serial port...")
  445. ser.close()
  446. sleep(2)
  447. print_message("done...")
  448. def ping(self):
  449. c = "ping {} -I {} -i {} -c {}".format(
  450. self.config["server"],
  451. self.config["interface"],
  452. 0,
  453. self.config["number_of_measurements"],
  454. )
  455. command = [c]
  456. print_message(
  457. "Start sending {} pings with nog gap.".format(
  458. self.config["number_of_measurements"]
  459. )
  460. )
  461. ping_out = subprocess.check_output(command, shell=True).decode("utf-8")
  462. filepath = "{}{}_ping_no_gap.txt".format(
  463. self.config["folder"], self.config["prefix"]
  464. )
  465. print_message("Write measured pings to: {}".format(filepath))
  466. write_to_file(filepath, ping_out)
  467. def drx(self):
  468. # send ICMP pings to server and increase the gab
  469. # check for set args
  470. if "pre_ping" in self.config["set"]:
  471. is_pre_ping_enabled = (
  472. True if self.config["set"]["pre_ping"] == "true" else False
  473. )
  474. else:
  475. is_pre_ping_enabled = False
  476. if "intervals" in self.config["set"]:
  477. intervals = []
  478. interval_ranges = self.config["set"]["intervals"].split(",")
  479. for interval_range in interval_ranges:
  480. start, end, increase = [float(x) for x in interval_range.split(":")]
  481. curr = start
  482. while curr <= end:
  483. intervals.append(curr)
  484. curr += increase
  485. else:
  486. intervals = []
  487. filepath = "{}{}_ping_drx_raw.txt".format(
  488. self.config["folder"], self.config["prefix"]
  489. )
  490. if is_pre_ping_enabled:
  491. print_message("Send pre pings.")
  492. c = "ping {} -I {} -i {} -c {}".format(
  493. self.config["server"],
  494. self.config["interface"],
  495. intervals[0],
  496. self.config["number_of_measurements"],
  497. )
  498. command = [c]
  499. subprocess.check_output(command, shell=True)
  500. else:
  501. print_message("Preping is disabled. Wait 60s for drx-long-sleep...")
  502. sleep(60)
  503. for i in intervals:
  504. current = i
  505. if not is_pre_ping_enabled:
  506. sleep(current)
  507. c = "echo 'gap={}s' && ping {} -I {} -i {} -c {} && echo ';;;'".format(
  508. current,
  509. self.config["server"],
  510. self.config["interface"],
  511. current,
  512. self.config["number_of_measurements"],
  513. )
  514. command = [c]
  515. print_message("ping with {}s gap".format(current))
  516. background_write_to_file(
  517. filepath,
  518. subprocess.check_output(command, shell=True).decode("utf-8"),
  519. )
  520. # Read raw out and format it to csv
  521. regex = r"gap=(.*)s|64 bytes from (.*\..*\..*\..*) icmp_seq=(\d+) ttl=(\d+) time=(.*) ms"
  522. filepath = "{}{}_ping_drx_raw.txt".format(
  523. self.config["folder"], self.config["prefix"]
  524. )
  525. print_message("Format script output")
  526. f = open(filepath, "r")
  527. raw = f.read()
  528. f.close()
  529. lines = raw.split("\n")
  530. csv_out = "n,gap,rtt\n"
  531. n = 1
  532. gap = ""
  533. for l in lines:
  534. match = re.match(regex, l)
  535. if match:
  536. if match.group(5):
  537. time = match.group(5)
  538. csv_out = csv_out + "{},{},{}\n".format(n, gap, time)
  539. n += 1
  540. else:
  541. gap = match.group(1)
  542. filepath = "{}{}_ping_drx.csv".format(
  543. self.config["folder"], self.config["prefix"]
  544. )
  545. print_message("Write file {}".format(filepath))
  546. write_to_file(filepath, csv_out)
  547. def harq(self):
  548. ws_filter = "tcp[tcpflags] & (tcp-syn) != 0"
  549. print_message("Use ws filter: {}".format(ws_filter))
  550. filepath = "{}{}_{}_tcp_handshakes_http_client.pcap".format(
  551. self.config["folder"],
  552. self.config["prefix"],
  553. self.config["number_of_measurements"],
  554. )
  555. thread = Thread(
  556. target=execute_tcp_dump,
  557. args=(
  558. processHandler,
  559. self.config["interface"],
  560. filepath,
  561. ws_filter,
  562. ),
  563. )
  564. thread.start()
  565. sleep(5)
  566. for n in range(1, self.config["number_of_measurements"] + 1):
  567. print_message("{} of {}".format(n, self.config["number_of_measurements"]))
  568. requests.get("http://{}".format(self.config["server"]))
  569. sleep(5)
  570. processHandler.kill_all()
  571. def bandwidth(self):
  572. server_is_sender = False
  573. if "reverse" in self.config["set"]:
  574. server_is_sender = self.config["set"]["reverse"] == "true"
  575. print_message("Use reverse mode: {}".format(server_is_sender))
  576. tcp_algo = list()
  577. if "algo" in self.config["set"]:
  578. for s in self.config["set"]["algo"].split(","):
  579. tcp_algo.append(s)
  580. print_message("Using {} for TCP transmissions.".format(s))
  581. else:
  582. tcp_algo.append("cubic")
  583. print_message("Using {} for TCP transmissions.".format(tcp_algo[0]))
  584. alternate_hystart = False
  585. if "alternate_hystart" in self.config["set"]:
  586. if self.config["set"]["alternate_hystart"] == "true":
  587. alternate_hystart = True
  588. print_message("Alternate between HyStart and Slowstart for Cubic.")
  589. time = "10"
  590. if "time" in self.config["set"]:
  591. time = self.config["set"]["time"]
  592. sleep(2)
  593. congestion_control_index = 0
  594. if server_is_sender:
  595. # server is sending
  596. ws_filter = "{} and port {}".format("tcp", self.config["port"])
  597. print_message("Use ws filter: {}".format(ws_filter))
  598. for n in range(1, self.config["number_of_measurements"] + 1):
  599. print_message(
  600. "{} of {}".format(n, self.config["number_of_measurements"])
  601. )
  602. print_message(
  603. "Using {} for congestion control".format(
  604. tcp_algo[congestion_control_index]
  605. )
  606. )
  607. tcpdump_flags = []
  608. filepath = "{}{}_bandwidth_reverse_{}_{}_{}.pcap".format(
  609. self.config["folder"],
  610. self.config["prefix"],
  611. "tcp",
  612. tcp_algo[congestion_control_index],
  613. n,
  614. )
  615. tcpdump_flags.append("-s96")
  616. thread = Thread(
  617. target=execute_tcp_dump,
  618. args=(
  619. processHandler,
  620. self.config["interface"],
  621. filepath,
  622. ws_filter,
  623. tcpdump_flags,
  624. ),
  625. )
  626. thread.start()
  627. sleep(5)
  628. iperf_command = [
  629. "iperf3",
  630. "-c",
  631. self.config["server"],
  632. "-R",
  633. "-t",
  634. time,
  635. "-C",
  636. tcp_algo[congestion_control_index],
  637. ]
  638. subprocess.call(iperf_command)
  639. sleep(4)
  640. processHandler.kill_all()
  641. congestion_control_index = (congestion_control_index + 1) % len(
  642. tcp_algo
  643. )
  644. else:
  645. # client is sending
  646. state_counter = 0
  647. name_option = ""
  648. if not is_tcp_probe_enabled():
  649. print_message("tcp probe is not enabled!")
  650. enable_tcp_probe()
  651. print_message("tcp probe is now enabled")
  652. for n in range(1, self.config["number_of_measurements"] + 1):
  653. print_message(
  654. "{} of {}".format(n, self.config["number_of_measurements"])
  655. )
  656. iperf_command = ["iperf3", "-c", self.config["server"], "-t", time]
  657. if alternate_hystart:
  658. if state_counter == 0:
  659. tcp_algo = "cubic"
  660. deactivate_hystart()
  661. name_option = "_cubic_slowstart_raise_"
  662. state_counter = 1
  663. elif state_counter == 1:
  664. tcp_algo = "cubic"
  665. activate_hystart()
  666. name_option = "_cubic_hystart_default_"
  667. state_counter = 2
  668. elif state_counter == 2:
  669. tcp_algo = "bbr"
  670. deactivate_hystart()
  671. name_option = "_bbr_raise_"
  672. state_counter = 3
  673. elif state_counter == 3:
  674. tcp_algo = "bbr"
  675. activate_hystart()
  676. name_option = "_bbr_default_"
  677. state_counter = 0
  678. iperf_command.append("-C")
  679. iperf_command.append(tcp_algo[congestion_control_index])
  680. filepath_tcp_trace = "{}{}_bandwidth_{}_{}_{}.txt".format(
  681. self.config["folder"], self.config["prefix"], "tcp", "tcp_trace", n
  682. )
  683. save_tcp_trace(
  684. processHandler,
  685. filepath_tcp_trace,
  686. self.config["client"],
  687. self.config["port"],
  688. )
  689. sleep(2)
  690. subprocess.call(iperf_command)
  691. processHandler.kill_all()
  692. congestion_control_index = (congestion_control_index + 1) % len(
  693. tcp_algo
  694. )
  695. sleep(4)
  696. def cbr(self):
  697. bitrate = "1M"
  698. if "bitrate" in self.config["set"]:
  699. bitrate = self.config["set"]["bitrate"]
  700. print("Set bitrate to {}.".format(bitrate))
  701. time = "2"
  702. if "time" in self.config["set"]:
  703. time = self.config["set"]["time"]
  704. use_reverse_mode = False
  705. if "reverse" in self.config["set"]:
  706. use_reverse_mode = self.config["set"]["reverse"] == "true"
  707. print_message("Use reverse mode: {}".format(use_reverse_mode))
  708. sleep_time = 60.0
  709. if "sleep" in self.config["set"]:
  710. sleep_time = float(self.config["set"]["sleep"])
  711. print_message("Sleep time for each measurement: {}s".format(sleep_time))
  712. # build wireshark filter
  713. if use_reverse_mode:
  714. ws_filter = "{} and dst {}".format("udp", self.config["client"])
  715. else:
  716. ws_filter = "{} and src {} and port {}".format(
  717. "udp", self.config["client"], self.config["port"]
  718. )
  719. print_message("Use ws filter: {}".format(ws_filter))
  720. # build iperf3 command
  721. iperf_command = [
  722. "iperf3",
  723. "-c",
  724. self.config["server"],
  725. "-t",
  726. time,
  727. "--udp",
  728. "-b",
  729. bitrate,
  730. ]
  731. if use_reverse_mode:
  732. iperf_command.append("-R")
  733. for n in range(1, self.config["number_of_measurements"] + 1):
  734. print_message("{} of {}".format(n, self.config["number_of_measurements"]))
  735. sleep(sleep_time)
  736. pcap_filepath = "{}{}_cbr_client_{}_bitrate{}_{}.pcap".format(
  737. self.config["folder"],
  738. self.config["prefix"],
  739. "receiver" if use_reverse_mode else "sender",
  740. bitrate,
  741. n,
  742. )
  743. thread = Thread(
  744. target=execute_tcp_dump,
  745. args=(
  746. processHandler,
  747. self.config["interface"],
  748. pcap_filepath,
  749. ws_filter,
  750. ),
  751. )
  752. thread.start()
  753. sleep(2)
  754. subprocess.call(iperf_command)
  755. sleep(2)
  756. processHandler.kill_all()
  757. def tcp_parallel_flows(self):
  758. tcp_algo = "cubic"
  759. if "algo" in self.config["set"]:
  760. tcp_algo = self.config["set"]["algo"]
  761. print_message("Using {} for tcp.".format(tcp_algo))
  762. time = "12"
  763. if "time" in self.config["set"]:
  764. time = self.config["set"]["time"]
  765. start = "1"
  766. if "start" in self.config["set"]:
  767. start = self.config["set"]["start"]
  768. end = "2"
  769. if "end" in self.config["set"]:
  770. end = self.config["set"]["end"]
  771. # build flow seq
  772. flows = []
  773. runs = []
  774. for i in range(int(start), int(end) + 1):
  775. flows.append(i)
  776. flows.append(i)
  777. for i in range(1, self.config["number_of_measurements"] + 1):
  778. runs.append(i)
  779. runs.append(i)
  780. print_message(
  781. "{} to {} flows, with {} runs.".format(
  782. start, end, self.config["number_of_measurements"]
  783. )
  784. )
  785. sleep(5)
  786. for flow in flows:
  787. for run in runs:
  788. if tcp_algo == "cubic":
  789. tcp_algo = "bbr"
  790. else:
  791. tcp_algo = "cubic"
  792. filepath = "{}{}_{}parallel_tcp_{}_flows_{}.txt".format(
  793. self.config["folder"], self.config["prefix"], flow, tcp_algo, run
  794. )
  795. c = "iperf3 -c {} -t {} -C {} -P {}".format(
  796. self.config["server"], time, tcp_algo, flow
  797. )
  798. iperf_command = [c]
  799. print_message("{} parallel {} flows".format(flow, tcp_algo))
  800. retry = True
  801. while retry:
  802. try:
  803. out = subprocess.check_output(iperf_command, shell=True).decode(
  804. "utf-8"
  805. )
  806. write_to_file(filepath, out)
  807. retry = False
  808. except:
  809. print("iPerf Error.\t{}".format(iperf_command))
  810. sleep(1)
  811. if retry:
  812. print_message("Retry in 5s")
  813. sleep(5)
  814. async def start_server(args):
  815. # get configuration from client
  816. print_message("Start Server")
  817. config = None
  818. ip = get_ip_from_interface(args.interface)
  819. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  820. s.setblocking(True)
  821. s.bind((ip, args.port))
  822. s.listen(1)
  823. conn, addr = s.accept()
  824. print_message("Got connection from {}".format(addr))
  825. while True:
  826. data = conn.recv(1024)
  827. if not data:
  828. break
  829. config = json2config(data.decode("utf-8"))
  830. conn.close()
  831. s.close()
  832. # add interface and ip to config
  833. config["interface"] = args.interface
  834. config["client"] = addr[0]
  835. config["server"] = ip
  836. config["folder"] = args.folder
  837. server = Server(config)
  838. server.measure()
  839. async def start_client(args):
  840. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  841. s.connect((args.client, args.port))
  842. s.send(config2json(args))
  843. s.close()
  844. print("Config send.")
  845. # overwrite ip
  846. config = vars(args).copy()
  847. config["server"] = args.client
  848. config["client"] = get_ip_from_interface(args.interface)
  849. new_set = dict()
  850. if config["set"] is not None:
  851. for pair in config["set"]:
  852. tmp = pair.split("=")
  853. new_set[tmp[0]] = tmp[1]
  854. config["set"] = new_set
  855. client = Client(config)
  856. client.measure()
  857. if __name__ == "__main__":
  858. now = datetime.now()
  859. processHandler = ProcessHandler()
  860. parser = ArgumentParser()
  861. # common arguments
  862. # required
  863. parser.add_argument("-i", "--interface", required=True, help="Interface.")
  864. # optional
  865. parser.add_argument("-p", "--port", default=5201, type=int, help="Port.")
  866. parser.add_argument(
  867. "-f",
  868. "--folder",
  869. default=os.path.dirname(os.path.realpath(__file__)) + "/",
  870. help="Folder for the pcap files.",
  871. )
  872. # server exclusive arguments
  873. parser.add_argument(
  874. "-s",
  875. "--server",
  876. action="store_true",
  877. default=False,
  878. help="Starts the script in server mode.",
  879. )
  880. # client exclusive arguments
  881. parser.add_argument(
  882. "-c",
  883. "--client",
  884. default=None,
  885. help="Start in client mode and set the server IPv4 address.",
  886. )
  887. parser.add_argument(
  888. "--prefix", default=now.strftime("%Y-%m-%d"), help="Prefix on filename."
  889. )
  890. parser.add_argument(
  891. "--set",
  892. metavar="KEY=VALUE",
  893. nargs="+",
  894. help="Set a number of key-value pairs "
  895. "(do not put spaces before or after the = sign). "
  896. "If a value contains spaces, you should define "
  897. "it with double quotes: "
  898. 'foo="this is a sentence". Note that '
  899. "values are always treated as strings.",
  900. )
  901. parser.add_argument(
  902. "-n",
  903. "--number_of_measurements",
  904. type=int,
  905. default=10,
  906. help="Number of measurements",
  907. )
  908. parser.add_argument(
  909. "--ping",
  910. action="store_true",
  911. default=False,
  912. help="Sending ICMP pings.",
  913. )
  914. parser.add_argument(
  915. "--bandwidth",
  916. action="store_true",
  917. default=False,
  918. help="Measure greedy tcp throughput with iperf3."
  919. "Use the --set flag for: "
  920. "server_is_sender=false if enable server is sending."
  921. "algo=cubic set tcp algorithm. Can be a comma separated string for multiple congestion control algorithms."
  922. "alternate_hystart=false if enabled alternate reproduce every Cubic measurement wicht and without HyStart (Also raises the receive window.). "
  923. "time=10 length of transmission in seconds.",
  924. )
  925. parser.add_argument(
  926. "--tcp_parallel",
  927. action="store_true",
  928. default=False,
  929. help="Measure greedy tcp throughput with parallel tcp flows. Alternate between bbr and cubic."
  930. "Use the --set flag for: "
  931. "start=1 Start value for flows "
  932. "end=2 End value for flows "
  933. "time=12 transmission time. ",
  934. )
  935. parser.add_argument(
  936. "--cbr",
  937. action="store_true",
  938. default=False,
  939. help="Measure Udp CBR traffic."
  940. "Use the --set flag for: "
  941. "reverse=false enable reverse mode. Server is sending. "
  942. "bitrate=1M target bitrate in bits/sec (0 for unlimited) "
  943. "[KMG] indicates options that support a K/M/G suffix for kilo-, mega-, or giga-. "
  944. "time=2 time in seconds to transmit for. "
  945. "sleep=60 sleep before each cbr traffic in seconds. ",
  946. )
  947. parser.add_argument(
  948. "--drx",
  949. action="store_true",
  950. default=False,
  951. help="Measure RTTs with ping tool. To detect DRX cycles. "
  952. "Use the --set flag for: "
  953. "intervals=start:end:increase,start2:end2:increase2... set intervals for gaps, end is inclusive, "
  954. "values in [s]. At least one interval is required. E.g.: 0:3:1 creates values [0,1,2,3]"
  955. "pre_ping=false if enabled pings are send before measurements to set device in continuous reception mode. ",
  956. )
  957. parser.add_argument(
  958. "--harq",
  959. action="store_true",
  960. default=False,
  961. help="Captures http transmissions on client side.",
  962. )
  963. parser.add_argument(
  964. "--serial",
  965. default=None,
  966. help="Serial device e.g. /dev/ttyUSB2",
  967. )
  968. parser.add_argument(
  969. "--baudrate",
  970. default=115200,
  971. type=int,
  972. help="Serial device baudrate",
  973. )
  974. args = parser.parse_args()
  975. if args.server:
  976. asyncio.run(start_server(args))
  977. elif args.client is not None:
  978. asyncio.run(start_client(args))