v8.0: Refactor HA cluster master selection logic

Remove obsolete HTML template and streamline server selection to use JSON. Enhanced server selection and error handling in AJAX calls, fixed minor syntax issues, and updated various routes for consistency.
pull/399/head
Aidaho 2024-08-27 15:57:45 +03:00
parent 0391dff9eb
commit 5b71fb257e
9 changed files with 26 additions and 31 deletions

View File

@ -44,13 +44,12 @@ def register_api_id_ip(view, endpoint, url: str = '', methods: list = ['GET', 'P
register_api(HAView, 'ha_cluster', '/ha/<service>', 'cluster_id')
register_api(HAVIPView, 'ha_vip', '/ha/<service>/<int:cluster_id>/vip', 'vip_id')
bp.add_url_rule('/ha/<service>/<int:cluster_id>/vips', view_func=HAVIPsView.as_view('ha_vips'), methods=['GET'])
register_api(UDPListener, 'udp_listener', '/<service>/listener', 'listener_id')
bp.add_url_rule('/<service>/listener/<int:listener_id>/<any(start, stop, reload, restart):action>', view_func=UDPListenerActionView.as_view('listener_action'), methods=['GET'])
bp.add_url_rule('/<service>/listeners', view_func=UDPListeners.as_view('listeners'), methods=['GET'])
bp.add_url_rule('/ha/<service>/<int:cluster_id>/vip/<int:router_id>', view_func=HAVIPView.as_view('ha_vip_g'), methods=['GET'])
bp.add_url_rule('/ha/<service>/<int:cluster_id>/vip', view_func=HAVIPView.as_view('ha_vip'), methods=['POST', 'PUT'])
bp.add_url_rule('/ha/<service>/<int:router_id>/vip', view_func=HAVIPView.as_view('ha_vip_d'), methods=['DELETE'])
bp.add_url_rule('/ha/<service>/<int:cluster_id>/vips', view_func=HAVIPsView.as_view('ha_vips'), methods=['GET'])
register_api_id_ip(ServiceView, 'service', '/status', ['GET'])
register_api_id_ip(ServiceBackendView, 'service_backend', '/backend', ['GET'])

View File

@ -97,7 +97,7 @@ def show_userlist(server_ip: str) -> str:
except Exception as e:
roxywi_common.logging('Roxy-WI server', f' Cannot generate a cfg path {e}', roxywi=1)
try:
error = config_mod.get_config(server_ip, cfg)
config_mod.get_config(server_ip, cfg)
except Exception as e:
roxywi_common.logging('Roxy-WI server', f' Cannot download a config {e}', roxywi=1)
try:

View File

@ -157,7 +157,7 @@ def get_ldap_email(username) -> str:
results = [entry for dn, entry in result if isinstance(entry, dict)]
try:
return f'["' + results[0][ldap_search_field][0].decode("utf-8") + '","' + domain + '"]'
return f'["{results[0][ldap_search_field][0].decode("utf-8")}","{domain}"]'
except Exception:
raise Exception('user not found')
except Exception as e:

View File

@ -1,5 +1,6 @@
from flask import render_template, g, request
from flask import render_template, g, request, jsonify
from flask_jwt_extended import jwt_required
from playhouse.shortcuts import model_to_dict
from app.modules.roxywi.exception import RoxywiResourceNotFound
from app.routes.ha import bp
@ -119,7 +120,6 @@ def get_slaves(service, cluster_id, vip_id):
if request.method == 'GET':
router_id = ha_sql.get_router_id(cluster_id, default_router=1)
else:
# router_id = int(request.form.get('router_id'))
vip = ha_sql.select_cluster_vip_by_vip_id(cluster_id, vip_id)
router_id = vip.router_id
slaves = ha_sql.select_cluster_slaves(cluster_id, router_id)
@ -148,6 +148,9 @@ def get_server_slaves(service, cluster_id):
@get_user_params()
def get_masters(service):
group_id = g.user_params['group_id']
free_servers = ha_sql.select_ha_cluster_not_masters_not_slaves(group_id)
try:
free_servers = ha_sql.select_ha_cluster_not_masters_not_slaves(group_id)
except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot get free servers')
return render_template('ajax/ha/masters.html', free_servers=free_servers)
return jsonify([model_to_dict(free) for free in free_servers])

View File

@ -8,6 +8,7 @@ import app.modules.db.portscanner as ps_sql
import app.modules.server.server as server_mod
import app.modules.roxywi.common as roxywi_common
import app.modules.tools.common as tools_common
import app.modules.common.common as common
@bp.before_request
@ -76,9 +77,9 @@ def change_settings_portscanner():
def scan_port():
json_data = request.get_json()
if 'id' in json_data:
ip = server_sql.select_server_ip_by_id(json_data['id'])
ip = server_sql.select_server_ip_by_id(int(json_data['id']))
else:
ip = json_data['ip']
ip = common.is_ip_or_dns(json_data['ip'])
cmd = f"sudo nmap -sS {ip} |grep -E '^[[:digit:]]'|sed 's/ */ /g'"
cmd1 = f"sudo nmap -sS {ip} |head -5|tail -2"
@ -91,4 +92,4 @@ def scan_port():
else:
lang = roxywi_common.get_user_lang_for_flask()
temp = render_template('ajax/scan_ports.html', ports=stdout, info=stdout1, lang=lang)
return jsonify({'status': 'success', 'data': temp})
return jsonify({'status': 'Ok', 'data': temp})

View File

@ -105,7 +105,7 @@ def waf_rule_edit(service, server_ip, rule_id):
try:
cfg = f"{configs_dir}{server_ip}-{get_date.return_date('config')}-{waf_rule_file}"
config_mod.get_config(server_ip, cfg, waf=service, waf_rule_file=waf_rule_file)
except Exception as e:
except Exception:
pass
config_file_name = common.return_nice_path(config_path) + 'waf/rules/' + waf_rule_file

View File

@ -100,11 +100,14 @@ function createHaClusterStep1(edited=false, cluster_id=0, clean=true) {
url: "/ha/cluster/masters",
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.indexOf('error:') != '-1') {
toastr.error(data);
if (data.status === 'failed') {
toastr.error(data.error);
} else {
$("#ha-cluster-master").html(data);
for (let i in data) {
$('#ha-cluster-master').append('<option value="' + data[i]['ip'] + '" selected="selected" data-id="'+data[i]['server_id']+'">' + data[i]['hostname'] + '</option>');
}
$('#ha-cluster-master').selectmenu("refresh");
}
}
@ -757,15 +760,11 @@ function createJsonCluster(div_id) {
jsonData['servers'].push({
'id': $('#ha-cluster-master option:selected').attr('data-id'),
'eth': $('#ha-cluster-master-interface').val(),
// 'ip': $('#ha-cluster-master option:selected').val(),
// 'name': $('#ha-cluster-master option:selected').text(),
'master': 1
});
$(div_id).each(function () {
let this_id = $(this).attr('id').split('-')[1];
let eth = $('#slave_int-' + this_id).val();
// let ip = $('#slave_int_div-' + this_id).attr('data-ip');
// let name = $('#slave_int_div-' + this_id).parent().text().replace('\n','').replace('\t','').trim();
jsonData['servers'].push({'id': this_id, 'eth': eth, 'master': 0});
});
return jsonData;
@ -776,11 +775,7 @@ function createJsonVip(div_id) {
$(div_id).each(function () {
let this_id = $(this).attr('id').split('-')[1];
let eth1 = $('#slave_int-' + this_id).val();
// let ip1 = $('#slave_int_div-' + this_id).attr('data-ip');
// let name1 = $('#slave_int_div-' + this_id).parent().text().replace('\n','').replace('\t','').trim();
let eth = $('#master_int-' + this_id).val();
// let ip = $('#master_int_div-' + this_id).attr('data-ip');
// let name = $('#master_int_div-' + this_id).parent().text().replace('\n','').replace('\t','').trim();
if (eth) {
jsonData['servers'].push({'id': this_id, 'eth': eth, 'master': 1});
} else {
@ -825,6 +820,7 @@ function clearClusterDialog(edited=0) {
$("input[type=checkbox]").checkboxradio("refresh");
$('#ha-cluster-master option:selected').remove();
$("#ha-cluster-master option").each(function (index) {
$(this).remove();
$(this).prop('disabled', false);
});
$('#ha-cluster-master option').attr('selected', false);

View File

@ -1,4 +0,0 @@
<option value="------" disabled selected>-------</option>
{% for server in free_servers %}
<option value="{{server.ip}}">{{server.hostname}}</option>
{% endfor %}

View File

@ -75,7 +75,7 @@ class SettingsView(MethodView):
try:
group_id = SupportClass.return_group_id(query)
except Exception as e:
return roxywi_common.handle_json_exceptions(e, f'Cannot get Settings')
return roxywi_common.handle_json_exceptions(e, 'Cannot get Settings')
settings = sql.get_setting('', group_id=group_id, section=section, all=1)
@ -131,7 +131,7 @@ class SettingsView(MethodView):
try:
group_id = SupportClass.return_group_id(query)
except Exception as e:
return roxywi_common.handle_json_exceptions(e, f'Cannot get Settings')
return roxywi_common.handle_json_exceptions(e, 'Cannot get Settings')
try:
sql.update_setting(body.param, val, group_id)
except Exception as e: