diff --git a/routes/edit_routes.py b/routes/edit_routes.py index d714a56..9e499f8 100644 --- a/routes/edit_routes.py +++ b/routes/edit_routes.py @@ -9,43 +9,58 @@ edit_bp = Blueprint('edit', __name__) def edit_haproxy_config(): if request.method == 'POST': edited_config = request.form['haproxy_config'] - with open('/etc/haproxy/haproxy.cfg', 'w') as f: - f.write(edited_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}" + ) + + 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" + else: + if not out: + out = f"Check failed with return code {result.returncode}" + return result.returncode, out check_output = "" if 'save_check' in request.form: - check_result = subprocess.run(['haproxy', '-c', '-V', '-f', '/etc/haproxy/haproxy.cfg'], capture_output=True, text=True) - check_output = check_result.stdout - - if check_result.returncode != 0: - error_message = check_result.stderr - check_output += f"\n\nError occurred:\n{error_message}" - - if check_result.returncode == 0: - error_message = check_result.stderr - check_output += f"\n\nConfiguration OK. You can restart." + rc, out = run_check() + check_output = out elif 'save_reload' in request.form: - check_result = subprocess.run(['haproxy', '-c', '-V', '-f', '/etc/haproxy/haproxy.cfg'], capture_output=True, text=True) - check_output = check_result.stdout - - if check_result.returncode != 0: - error_message = check_result.stderr - check_output += f"\n\nError occurred:\n{error_message}" - else: - reload_success = False + rc, out = run_check() + check_output = out + if rc == 0: reload_output = "" - try: - supervisor_result = subprocess.run(['pkill', '-f', 'haproxy'], capture_output=True, text=True, timeout=10) + supervisor_result = subprocess.run( + ['pkill', '-f', 'haproxy'], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=10 + ) if supervisor_result.returncode == 0: - reload_output = f"\n\n HAProxy Restarted via Supervisor:\n{supervisor_result.stdout}" - reload_success = True - print(f"[HAPROXY] Supervisor restart successful", flush=True) + reload_output = f"\n\nHAProxy Restarted:\n{supervisor_result.stdout}" + else: + reload_output = f"\n\nRestart attempt returned {supervisor_result.returncode}:\n{supervisor_result.stdout}" except Exception as e: - print(f"[HAPROXY] Supervisor restart failed: {e}", flush=True) - + reload_output = f"\n\nRestart failed: {e}" + check_output += reload_output return render_template('edit.html', config_content=edited_config, check_output=check_output)