Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1291 lines
43KB

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