92 lines
3.3 KiB
Python
92 lines
3.3 KiB
Python
from flask import Blueprint, render_template, request
|
|
import subprocess
|
|
from auth.auth_middleware import requires_auth
|
|
|
|
edit_bp = Blueprint('edit', __name__)
|
|
|
|
@edit_bp.route('/edit', methods=['GET', 'POST'])
|
|
@requires_auth
|
|
def edit_haproxy_config():
|
|
if request.method == 'POST':
|
|
edited_config = request.form['haproxy_config']
|
|
|
|
try:
|
|
with open('/etc/haproxy/haproxy.cfg', 'w') as f:
|
|
f.write(edited_config)
|
|
except Exception as e:
|
|
return render_template(
|
|
'edit.html',
|
|
config_content=edited_config,
|
|
check_output=f"Error writing configuration: {e}",
|
|
check_level="danger"
|
|
)
|
|
|
|
def run_check():
|
|
result = subprocess.run(
|
|
['haproxy', '-c', '-V', '-f', '/etc/haproxy/haproxy.cfg'],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
text=True
|
|
)
|
|
out = (result.stdout or '').strip()
|
|
|
|
if result.returncode == 0:
|
|
if not out:
|
|
out = "Configuration file is valid ✅"
|
|
level = "success"
|
|
if "Warning" in out or "Warnings" in out:
|
|
level = "warning"
|
|
else:
|
|
if not out:
|
|
out = f"Check failed with return code {result.returncode}"
|
|
level = "danger"
|
|
|
|
return result.returncode, out, level
|
|
|
|
check_output = ""
|
|
check_level = "success"
|
|
|
|
if 'save_check' in request.form:
|
|
_, check_output, check_level = run_check()
|
|
|
|
elif 'save_reload' in request.form:
|
|
rc, out, level = run_check()
|
|
check_output, check_level = out, level
|
|
|
|
if rc == 0:
|
|
try:
|
|
supervisor_result = subprocess.run(
|
|
['pkill', '-f', 'haproxy'],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
text=True,
|
|
timeout=10
|
|
)
|
|
if supervisor_result.returncode == 0:
|
|
check_output += f"\n\nHAProxy Restarted:\n{supervisor_result.stdout}"
|
|
else:
|
|
check_output += (
|
|
f"\n\nRestart attempt returned {supervisor_result.returncode}:\n"
|
|
f"{supervisor_result.stdout}"
|
|
)
|
|
except Exception as e:
|
|
check_output += f"\n\nRestart failed: {e}"
|
|
check_level = "warning"
|
|
|
|
return render_template(
|
|
'edit.html',
|
|
config_content=edited_config,
|
|
check_output=check_output,
|
|
check_level=check_level
|
|
)
|
|
|
|
try:
|
|
with open('/etc/haproxy/haproxy.cfg', 'r') as f:
|
|
config_content = f.read()
|
|
except FileNotFoundError:
|
|
config_content = "# HAProxy configuration file not found\n# Please create /etc/haproxy/haproxy.cfg"
|
|
except PermissionError:
|
|
config_content = "# Permission denied reading HAProxy configuration file"
|
|
|
|
return render_template('edit.html', config_content=config_content)
|