main.py 6.4 KB

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