No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1082 líneas
36KB

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