From 9baefec5413552c721cd842b12c9e1ec56cb2234 Mon Sep 17 00:00:00 2001 From: Donald Zou Date: Tue, 18 Jun 2024 03:40:25 +0800 Subject: [PATCH] Figuring out with Gunicorn... --- src/dashboard.py | 30 ++++++++---- src/gunicorn.conf.py | 4 +- src/util.py | 113 ------------------------------------------- src/wgd.sh | 2 +- 4 files changed, 24 insertions(+), 125 deletions(-) delete mode 100644 src/util.py diff --git a/src/dashboard.py b/src/dashboard.py index 72ed2c3..53f268b 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -11,23 +11,16 @@ import secrets import subprocess import time import re -import urllib.parse -import urllib.request -import urllib.error import uuid -from dataclasses import dataclass from datetime import datetime, timedelta -from json import JSONEncoder -from operator import itemgetter -from typing import Dict, Any, Tuple +from typing import Any import bcrypt # PIP installed library import ifcfg import psutil import pyotp -from flask import Flask, request, render_template, redirect, url_for, session, jsonify, g -from flask.json.provider import JSONProvider +from flask import Flask, request, render_template, session from json import JSONEncoder from icmplib import ping, traceroute @@ -1547,6 +1540,25 @@ def backGroundThread(): time.sleep(10) +def gunicornConfig(): + _, app_ip = DashboardConfig.GetConfig("Server", "app_ip") + _, app_port = DashboardConfig.GetConfig("Server", "app_port") + return app_ip, app_port + + +def runGunicorn(): + sqldb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard.db'), check_same_thread=False) + sqldb.row_factory = sqlite3.Row + cursor = sqldb.cursor() + _, app_ip = DashboardConfig.GetConfig("Server", "app_ip") + _, app_port = DashboardConfig.GetConfig("Server", "app_port") + WireguardConfigurations = _getConfigurationList() + bgThread = threading.Thread(target=backGroundThread) + bgThread.daemon = True + bgThread.start() + return app + + if __name__ == "__main__": sqldb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard.db'), check_same_thread=False) sqldb.row_factory = sqlite3.Row diff --git a/src/gunicorn.conf.py b/src/gunicorn.conf.py index 56b82ce..5f18f8e 100644 --- a/src/gunicorn.conf.py +++ b/src/gunicorn.conf.py @@ -1,11 +1,11 @@ import multiprocessing import dashboard -app_host, app_port = dashboard.get_host_bind() +app_host, app_port = dashboard.gunicornConfig() worker_class = 'gthread' workers = multiprocessing.cpu_count() * 2 + 1 -threads = 4 +threads = 2 bind = f"{app_host}:{app_port}" daemon = True pidfile = './gunicorn.pid' diff --git a/src/util.py b/src/util.py deleted file mode 100644 index 6f95a62..0000000 --- a/src/util.py +++ /dev/null @@ -1,113 +0,0 @@ -import re -import subprocess -import dashboard -""" -Helper Functions -""" - - -# Regex Match -def regex_match(regex, text): - pattern = re.compile(regex) - return pattern.search(text) is not None - - -# Check IP format -def check_IP(ip): - ip_patterns = ( - r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}", - r"[0-9a-fA-F]{0,4}(:([0-9a-fA-F]{0,4})){1,7}$" - ) - for match_pattern in ip_patterns: - match_result = regex_match(match_pattern, ip) - if match_result: - result = match_result - break - else: - result = None - - return result - - -# Clean IP -def clean_IP(ip): - return ip.replace(' ', '') - - -# Clean IP with range -def clean_IP_with_range(ip): - return clean_IP(ip).split(',') - - -# Check IP with range -def check_IP_with_range(ip): - ip_patterns = ( - r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|\/)){4}([0-9]{1,2})(,|$)", - r"[0-9a-fA-F]{0,4}(:([0-9a-fA-F]{0,4})){1,7}\/([0-9]{1,3})(,|$)" - ) - - for match_pattern in ip_patterns: - match_result = regex_match(match_pattern, ip) - if match_result: - result = match_result - break - else: - result = None - - return result - - -# Check allowed ips list -def check_Allowed_IPs(ip): - ip = clean_IP_with_range(ip) - for i in ip: - if not check_IP_with_range(i): return False - return True - - -# Check DNS -def check_DNS(dns): - dns = dns.replace(' ', '').split(',') - status = True - for i in dns: - if not (check_IP(i) or regex_match("(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z]{0,61}[a-z]", i)): - return False - return True - - -# Check remote endpoint -def check_remote_endpoint(address): - return (check_IP(address) or regex_match("(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z]{0,61}[a-z]", - address)) - - -def deletePeers(config_name, delete_keys, cur, db): - sql_command = [] - wg_command = ["wg", "set", config_name] - for delete_key in delete_keys: - if delete_key not in dashboard.get_conf_peer_key(config_name): - return "This key does not exist" - sql_command.append("DELETE FROM " + config_name + " WHERE id = '" + delete_key + "';") - wg_command.append("peer") - wg_command.append(delete_key) - wg_command.append("remove") - try: - print("deleting...") - remove_wg = subprocess.check_output(" ".join(wg_command), - shell=True, stderr=subprocess.STDOUT) - save_wg = subprocess.check_output(f"wg-quick save {config_name}", shell=True, stderr=subprocess.STDOUT) - cur.executescript(' '.join(sql_command)) - db.commit() - except subprocess.CalledProcessError as exc: - return exc.output.strip() - return "true" - -def checkJSONAllParameter(required, data): - if len(data) == 0: - return False - for i in required: - if i not in list(data.keys()) or len(data[i]) == 0: - return False - return True - - diff --git a/src/wgd.sh b/src/wgd.sh index 4424fba..fcfee55 100755 --- a/src/wgd.sh +++ b/src/wgd.sh @@ -102,7 +102,7 @@ gunicorn_start () { export PATH=$PATH:/usr/local/bin:$HOME/.local/bin fi gunicorn --access-logfile log/access_"$d".log \ - --error-logfile log/error_"$d".log 'dashboard:run_dashboard()' + --error-logfile log/error_"$d".log 'dashboard:runGunicorn()' printf "| Log files is under log/ |\n" printf "%s\n" "$dashes" }