main.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import subprocess
  2. import os
  3. import re
  4. import argparse
  5. from flask import Flask, render_template, redirect, request, url_for
  6. BANDWIDTH_UNITS = [
  7. "bit", # Bits per second
  8. "kbit", # Kilobits per second
  9. "mbit", # Megabits per second
  10. "gbit", # Gigabits per second
  11. "tbit", # Terabits per second
  12. "bps", # Bytes per second
  13. "kbps", # Kilobytes per second
  14. "mbps", # Megabytes per second
  15. "gbps", # Gigabytes per second
  16. "tbps", # Terabytes per second
  17. ]
  18. STANDARD_UNIT = "mbit"
  19. app = Flask(__name__)
  20. pattern = None
  21. dev_list = None
  22. app.static_folder = "static"
  23. def parse_arguments():
  24. parser = argparse.ArgumentParser(description="TC web GUI")
  25. parser.add_argument(
  26. "--ip", type=str, required=False, help="The IP where the server is listening"
  27. )
  28. parser.add_argument(
  29. "--port",
  30. type=int,
  31. required=False,
  32. help="The port where the server is listening",
  33. )
  34. parser.add_argument(
  35. "--dev",
  36. type=str,
  37. nargs="*",
  38. required=False,
  39. help="The interfaces to restrict to",
  40. )
  41. parser.add_argument(
  42. "--regex", type=str, required=False, help="A regex to match interfaces"
  43. )
  44. parser.add_argument("--debug", action="store_true", help="Run Flask in debug mode")
  45. return parser.parse_args()
  46. @app.route("/")
  47. def main():
  48. rules = get_active_rules()
  49. return render_template(
  50. "main.html", rules=rules, units=BANDWIDTH_UNITS, standard_unit=STANDARD_UNIT
  51. )
  52. @app.route("/new_rule/<interface>", methods=["POST"])
  53. def new_rule(interface):
  54. delay = request.form["Delay"]
  55. delay_variance = request.form["DelayVariance"]
  56. loss = request.form["Loss"]
  57. loss_correlation = request.form["LossCorrelation"]
  58. duplicate = request.form["Duplicate"]
  59. reorder = request.form["Reorder"]
  60. reorder_correlation = request.form["ReorderCorrelation"]
  61. corrupt = request.form["Corrupt"]
  62. limit = request.form["Limit"]
  63. rate = request.form["Rate"]
  64. rate_unit = request.form["rate_unit"]
  65. # remove old setup
  66. command = "tc qdisc del dev %s root netem" % interface
  67. command = command.split(" ")
  68. proc = subprocess.Popen(command)
  69. proc.wait()
  70. # apply new setup
  71. command = "tc qdisc add dev %s root netem" % interface
  72. if rate != "":
  73. command += " rate %s%s" % (rate, rate_unit)
  74. if delay != "":
  75. command += " delay %sms" % delay
  76. if delay_variance != "":
  77. command += " %sms" % delay_variance
  78. if loss != "":
  79. command += " loss %s%%" % loss
  80. if loss_correlation != "":
  81. command += " %s%%" % loss_correlation
  82. if duplicate != "":
  83. command += " duplicate %s%%" % duplicate
  84. if reorder != "":
  85. command += " reorder %s%%" % reorder
  86. if reorder_correlation != "":
  87. command += " %s%%" % reorder_correlation
  88. if corrupt != "":
  89. command += " corrupt %s%%" % corrupt
  90. if limit != "":
  91. command += " limit %s" % limit
  92. print(command)
  93. command = command.split(" ")
  94. proc = subprocess.Popen(command)
  95. proc.wait()
  96. return redirect(url_for("main"))
  97. @app.route("/remove_rule/<interface>", methods=["POST"])
  98. def remove_rule(interface):
  99. # remove old setup
  100. command = "tc qdisc del dev %s root netem" % interface
  101. command = command.split(" ")
  102. proc = subprocess.Popen(command)
  103. proc.wait()
  104. return redirect(url_for("main"))
  105. def get_active_rules():
  106. proc = subprocess.Popen(["tc", "qdisc"], stdout=subprocess.PIPE)
  107. output = proc.communicate()[0].decode()
  108. lines = output.split("\n")[:-1]
  109. rules = []
  110. dev = set()
  111. for line in lines:
  112. arguments = line.split()
  113. rule = parse_rule(arguments)
  114. if rule["name"] and rule["name"] not in dev:
  115. rules.append(rule)
  116. dev.add(rule["name"])
  117. return rules
  118. def parse_rule(split_rule):
  119. rule = {
  120. "name": None,
  121. "rate": None,
  122. "delay": None,
  123. "delayVariance": None,
  124. "loss": None,
  125. "lossCorrelation": None,
  126. "duplicate": None,
  127. "reorder": None,
  128. "reorderCorrelation": None,
  129. "corrupt": None,
  130. "limit": None,
  131. }
  132. i = 0
  133. for argument in split_rule:
  134. if argument == "dev":
  135. # Both regex pattern and dev name can be given
  136. # An interface could match the pattern and/or
  137. # be in the interface list
  138. if pattern is None and dev_list is None:
  139. rule["name"] = split_rule[i + 1]
  140. if pattern:
  141. if pattern.match(split_rule[i + 1]):
  142. rule["name"] = split_rule[i + 1]
  143. if dev_list:
  144. if split_rule[i + 1] in dev_list:
  145. rule["name"] = split_rule[i + 1]
  146. elif argument == "rate":
  147. rule["rate"] = split_rule[i + 1].split("Mbit")[0]
  148. elif argument == "delay":
  149. rule["delay"] = split_rule[i + 1]
  150. if len(split_rule) > (i + 2) and "ms" in split_rule[i + 2]:
  151. rule["delayVariance"] = split_rule[i + 2]
  152. elif argument == "loss":
  153. rule["loss"] = split_rule[i + 1]
  154. if len(split_rule) > (i + 2) and "%" in split_rule[i + 2]:
  155. rule["lossCorrelation"] = split_rule[i + 2]
  156. elif argument == "duplicate":
  157. rule["duplicate"] = split_rule[i + 1]
  158. elif argument == "reorder":
  159. rule["reorder"] = split_rule[i + 1]
  160. if len(split_rule) > (i + 2) and "%" in split_rule[i + 2]:
  161. rule["reorderCorrelation"] = split_rule[i + 2]
  162. elif argument == "corrupt":
  163. rule["corrupt"] = split_rule[i + 1]
  164. elif argument == "limit":
  165. rule["limit"] = split_rule[i + 1]
  166. i += 1
  167. return rule
  168. if __name__ == "__main__":
  169. if os.geteuid() != 0:
  170. print(
  171. "You need to have root privileges to run this script.\n"
  172. "Please try again, this time using 'sudo'. Exiting."
  173. )
  174. exit(1)
  175. # TC Variables
  176. args = parse_arguments()
  177. pattern = os.environ.get("TCGUI_REGEX")
  178. if args.regex:
  179. pattern = re.compile(args.regex)
  180. dev_list = os.environ.get("TCGUI_DEV")
  181. if args.dev:
  182. dev_list = args.dev
  183. # Flask Variable
  184. app_args = {}
  185. app_args["host"] = os.environ.get("TCGUI_IP")
  186. app_args["port"] = os.environ.get("TCGUI_PORT")
  187. if args.ip:
  188. app_args["host"] = args.ip
  189. if args.port:
  190. app_args["port"] = args.port
  191. if not args.debug:
  192. app_args["debug"] = False
  193. app.debug = True
  194. app.run(**app_args)