import tornado.ioloop
import tornado.web
import json
import argparse
import os
import subprocess
import logging
from o_manager import OManager
dir_path = os.path.dirname(os.path.realpath(__file__))
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--interface", required=False,
help="interface (default: eth0)", default="eth0")
ap.add_argument("-s", "--session_folder", required=True,
help="path to the session folder")
ap.add_argument("-l", "--load_instance_config", required=False,
help="instance config file (default: /config/instance.json)", default="/config/instance.json")
args = vars(ap.parse_args())
session_folder = args["session_folder"]
interface = args["interface"]
om = OManager(session_folder, interface)
root = os.path.dirname(__file__)
instance_config_fp = args["load_instance_config"]
try:
instance_config = json.load(open(instance_config_fp, "r"))
om.load_instance_config(instance_config)
except Exception as err:
logging.warn(f"Cannot load instances config: {err}")
class MainHandler(tornado.web.RequestHandler):
def get(self):
buf = "\n
\n"
buf += "\n"
buf += f"ops len: {len(om.instances)}, lb pids: {om.pids}
\n"
if len(om.instances):
for i in om.instances:
op = i["op"]
idx = i["idx"]
weight = i["weight"]
buf += f"op #{idx}, name: {op.name}
\n"
buf += f"status: {op.status}, weight: {weight}
\n"
buf += f"op pids: {op.pids}
\n"
buf += "log:
\n"
buf += "\n"
buf += "\n".join(op.get_log(lines=10))
buf += f"\nSpeed: {op.get_latest_speed()}\n"
buf += "\nio_stat\n"
buf += "\n".join(op.get_io_stat(lines=5))
buf += "\nping_stat\n"
buf += "\n".join(op.get_ping_stat(lines=5))
buf += "\n\n"
buf += "\n"
self.write(buf)
class StateHandler(tornado.web.RequestHandler):
def get(self):
self.write(json.dumps(om.serialize()))
class StatHandler(tornado.web.RequestHandler):
def get(self):
self.write(json.dumps(om.get_stat()))
class ConfigsHandeler(tornado.web.RequestHandler):
def get(self):
cfgs = json.loads(open("profiles.json", "r").read())
buf = "Select one configuration to create.
\n"
for idx, cfg in enumerate(cfgs):
buf += f"{cfg['name']}
\n"
self.write(buf)
class CreateInstantceHandler(tornado.web.RequestHandler):
def get(self):
idx = self.get_query_argument("i", None)
if idx != None:
idx = int(idx)
cfgs = json.loads(open("profiles.json", "r").read())
cfg = cfgs[idx]
om.new_op_old(cfg["cfg_fp"], cfg["name"],
additional_cfg=cfg["additional_cfg"])
self.write("create sucess!")
else:
self.write("need idx")
class StartInstatnceHandler(tornado.web.RequestHandler):
def get(self):
idx = self.get_query_argument("i", None)
if idx != None:
om.start_op(int(idx))
self.write("start sucess!")
else:
om.start_all()
self.write("start all")
class StopInstatnceHandler(tornado.web.RequestHandler):
def get(self):
idx = self.get_query_argument("i", None)
if idx != None:
om.stop_op(int(idx))
self.write("stop sucess!")
else:
om.stop_all()
self.write("stop all")
class RemoveInstatnceHandler(tornado.web.RequestHandler):
def get(self):
idx = self.get_query_argument("i", None)
if idx != None:
om.remove_op(int(idx))
self.write("remove sucess!")
else:
om.remove_all_op()
self.write("remove all")
class ClearCacheInstatnceHandler(tornado.web.RequestHandler):
def get(self):
om.clear_cache()
class SaveInstanceHandler(tornado.web.RequestHandler):
def get(self):
instances = om.serialize_instance_config()
with open(instance_config_fp, "w") as f:
f.write(json.dumps(instances))
self.write("OK")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/state", StateHandler),
(r"/stat", StatHandler),
(r"/select", ConfigsHandeler),
(r"/create", CreateInstantceHandler),
(r"/start", StartInstatnceHandler),
(r"/stop", StopInstatnceHandler),
(r"/remove", RemoveInstatnceHandler),
(r"/clear_cache", ClearCacheInstatnceHandler),
(r"/save_instance", SaveInstanceHandler),
(r"/dashboard", tornado.web.RedirectHandler, {"url": "/dashboard/"}),
(r"/dashboard/(.*)", tornado.web.StaticFileHandler,
{"path": os.path.join(root, "tabler"), "default_filename": "index.html"})
])
if __name__ == "__main__":
app = make_app()
app.listen(8000)
proc = subprocess.Popen([os.path.join(dir_path, "iptable_docker.sh"), interface],
stdout=subprocess.PIPE)
outs, errs = proc.communicate()
print(outs.decode())
tornado.ioloop.IOLoop.current().start()