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.

1135 line
37KB

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