diff options
author | Alejandro Sirgo Rica <asirgo@soleta.eu> | 2024-12-17 13:55:36 +0100 |
---|---|---|
committer | Alejandro Sirgo Rica <asirgo@soleta.eu> | 2024-12-17 16:04:09 +0100 |
commit | 05cba727e05308ada6ef65950724c5dc8dca45e4 (patch) | |
tree | 267decd77b30e8f736fa9460cf3534c15bc54c85 | |
parent | fd8da5de26c9a18a069e66c554ffd51f32cf86b8 (diff) |
views: refactor http error handling
Throw ServerError in get(), post(), delete() server methods
in case of connection error or status code with an error.
Log the cause of the error to show it in the web.
Add a function wrapper into every endpoint to handle the
error redirection needed for the ServerError exception.
The wrapper is defined by adding @handle_server_errors('XXX')
on top of the function declaration, where XXX is the name
of the function (endpoint) to be invoked by the redirection.
This change removes the need of specific checks after every
request and cleanups the endpoint code.
Fix the endpoint of the main views to work with an unavailable
ogserver.
-rw-r--r-- | ogcp/og_server.py | 77 | ||||
-rw-r--r-- | ogcp/views.py | 885 |
2 files changed, 257 insertions, 705 deletions
diff --git a/ogcp/og_server.py b/ogcp/og_server.py index 872798e..6aeb20d 100644 --- a/ogcp/og_server.py +++ b/ogcp/og_server.py @@ -6,10 +6,22 @@ # (at your option) any later version. from ogcp import app +from flask import session, flash +from flask_babel import _ import requests import json +class ServerError(Exception): + pass + +def flash_once(message, category='message'): + if '_flashes' not in session: + session['_flashes'] = [] + + if (category, message) not in session['_flashes']: + flash(message, category) + class OGServer: def __init__(self, name, ip, port, api_token): self.name = name @@ -22,32 +34,57 @@ class OGServer: self.URL = f'http://{self.ip}:{self.port}' self.HEADERS = {'Authorization' : self.api_token} - def get(self, path, payload=None): + def _log_http_status_code(self, res): + if res.status_code == 400: + err_msg = _('Invalid payload') + elif res.status_code == 404: + err_msg = _('Object not found') + elif res.status_code == 405: + err_msg = _('Method not allowed') + elif res.status_code == 409: + err_msg = _('Object already exists') + elif res.status_code == 423: + err_msg = _('Object in use') + elif res.status_code == 501: + err_msg = _('Cannot connect to database') + elif res.status_code == 507: + err_msg = _('Disk full') + else: + err_msg = _(f'Received status code {res.status_code}') + + flash_once(err_msg, category='error') + + def _request(self, method, path, payload, expected_status): try: - r = requests.get(f'{self.URL}{path}', - headers=self.HEADERS, - json=payload) + res = requests.request( + method, + f'{self.URL}{path}', + headers=self.HEADERS, + json=payload, + ) + if res.status_code not in expected_status: + self._log_http_status_code(res) + raise ServerError + return res + except requests.exceptions.ConnectionError: - return None - return r + flash_once(_('Cannot connect to ogserver'), category='error') + except requests.exceptions.Timeout: + flash_once(_('Request to ogserver timed out'), category='error') + except requests.exceptions.TooManyRedirects: + flash_once(_('Too many redirects occurred while contacting ogserver'), category='error') + except requests.exceptions.RequestException as e: + flash_once(_('An error occurred while contacting ogserver: %(error)s', error=str(e)), category='error') + raise ServerError + + def get(self, path, payload=None): + return self._request('GET', path, payload, expected_status={200}) def post(self, path, payload): - try: - r = requests.post(f'{self.URL}{path}', - headers=self.HEADERS, - json=payload) - except requests.exceptions.ConnectionError: - return None - return r + return self._request('POST', path, payload, expected_status={200, 202}) def delete(self, path, payload): - try: - r = requests.delete(f'{self.URL}{path}', - headers=self.HEADERS, - json=payload) - except requests.exceptions.ConnectionError: - return None - return r + return self._request('DELETE', path, payload, expected_status={200}) @property def id(self): diff --git a/ogcp/views.py b/ogcp/views.py index 1049675..f6c1933 100644 --- a/ogcp/views.py +++ b/ogcp/views.py @@ -27,11 +27,12 @@ from pathlib import Path from ogcp.models import User from ogcp.forms.auth import LoginForm, UserForm, DeleteUserForm, EditUserForm -from ogcp.og_server import OGServer, servers +from ogcp.og_server import OGServer, servers, ServerError from flask_babel import lazy_gettext as _l from flask_babel import gettext, _ from ogcp import app, ogcp_cfg_path from wtforms import StringField +from functools import wraps import unicodedata import ipaddress import requests @@ -93,11 +94,16 @@ login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' -class ServerError(Exception): - pass - -class ServerErrorCode(Exception): - pass +def handle_server_errors(redirect_endpoint): + def decorator(view_func): + @wraps(view_func) + def wrapper(*args, **kwargs): + try: + return view_func(*args, **kwargs) + except ServerError: + return redirect(url_for(redirect_endpoint)) + return wrapper + return decorator def split_csv(s): return re.split(r'\s*,\s*', s) @@ -130,31 +136,6 @@ def remove_accents(text): normalized_text = unicodedata.normalize('NFD', text) return ''.join(c for c in normalized_text if unicodedata.category(c) != 'Mn') -def ogserver_down(view): - flash(_('Cannot talk to ogserver. Is ogserver down?'), category='error') - return redirect(url_for(view)) - -def ogserver_error(res, view): - if res.status_code == 400: - err_msg = _('Error 400: invalid payload') - elif res.status_code == 404: - err_msg = _('Error 404: object not found') - elif res.status_code == 405: - err_msg = _('Error 405: method not allowed') - elif res.status_code == 409: - err_msg = _('Error 409: object already exists') - elif res.status_code == 423: - err_msg = _('Error 423: object in use') - elif res.status_code == 501: - err_msg = _('Error 501: cannot connect to database') - elif res.status_code == 507: - err_msg = _('Error 500: disk full') - else: - err_msg = _(f'Received status code {res.status_code}') - - flash(err_msg, category='error') - return redirect(url_for(view)) - def validate_elements(elements, min_len=1, max_len=float('inf')): valid = True if len(elements) < min_len: @@ -178,10 +159,6 @@ def parse_elements(checkboxes_dict): def client_setup_add_image_names(server, setup_data): r = server.get('/images') - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode images = r.json()['images'] @@ -201,17 +178,10 @@ def get_client_setup(ip): payload = {'clients': [ip]} r = server.post('/refresh', payload) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode payload = {'client': [ip]} r = server.get('/client/setup', payload) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode + db_partitions = r.json()['partitions'] res = {} for partition in db_partitions: @@ -256,12 +226,7 @@ def get_clients(state_filter=None): def get_repository(repository_id, server): - try: - repositories = get_repositories(server) - except ServerError: - raise ServerError - except ServerErrorCode: - raise ServerErrorCode + repositories = get_repositories(server) [repository] = [repository for repository in repositories if repository['id'] == repository_id] return repository @@ -269,10 +234,6 @@ def get_repository(repository_id, server): def get_repositories(server): r = server.get('/repositories') - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode repositories = r.json()['repositories'] return repositories @@ -342,11 +303,6 @@ def multi_request(method, uri, payload=None): else: raise Exception('Invalid method, use get or post') - if not r: - continue - if r.status_code != requests.codes.ok: - continue - response['server'] = server response['json'] = r.json() responses.append(response) @@ -510,13 +466,9 @@ def server_error(error): def image_modified_date_from_str(image): return datetime.datetime.strptime(image['modified'], '%a %b %d %H:%M:%S %Y') -@app.route('/') -def index(): - if not current_user.is_authenticated: - return redirect(url_for('login')) - - images_response = multi_request('get', '/images') +def get_dashboard_data(): dashboard_servers = {} + images_response = multi_request('get', '/images') for i in images_response: server_name = i['server'].name server_id = i['server'].id @@ -556,7 +508,6 @@ def index(): time_dict = {'now': now, 'boot': boot, 'start': start} dashboard_servers[server_id]['time_dict'] = time_dict else: - timestamp = datetime.datetime.today() dashboard_servers[server.id] = {} dashboard_servers[server.id]['online'] = False dashboard_servers[server.id]['name'] = server.name @@ -571,7 +522,18 @@ def index(): for i in clients_response: server_id = i['server'].id dashboard_servers[server_id]['clients'] = i['json']['clients'] + return dashboard_servers + +@app.route('/') +def index(): + if not current_user.is_authenticated: + return redirect(url_for('login')) + try: + dashboard_servers = get_dashboard_data() + except ServerError: + dashboard_servers = {} + timestamp = datetime.datetime.today() now = timestamp.strftime('%Y-%m-%d %H:%M:%S') return render_template('dashboard.html', servers=dashboard_servers, now=now, colsize="6") @@ -602,7 +564,10 @@ def logout(): @app.route('/scopes/status') @login_required def scopes_status(): - scopes, _clients = get_scopes() + try: + scopes, _clients = get_scopes() + except ServerError: + scopes = {} return jsonify(scopes) @@ -612,7 +577,10 @@ def get_client_mac(): ip = parse_elements(request.args.to_dict()) payload = {'client': list(ip)} server = get_server_from_clients(list(ip)) - resp = server.get('/client/info', payload) + try: + resp = server.get('/client/info', payload) + except ServerError: + return {} client_info = resp.json() mac = client_info.get('mac') pretty_mac = prettify_mac(mac) @@ -645,6 +613,7 @@ def get_server_data_from_scopes(scopes, clients): return servers_data @app.route('/client/list', methods=['GET']) +@handle_server_errors('index') @login_required def client_list(): scopes, clients = get_scopes() @@ -660,10 +629,15 @@ def client_list(): @app.route('/scopes/') @login_required def scopes(): - scopes, clients = get_scopes() + try: + scopes, clients = get_scopes() + except ServerError: + scopes = {} + clients = {} return render_template('scopes.html', scopes=scopes, clients=clients) @app.route('/action/poweroff', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_poweroff(): form = GenericForm(request.form) @@ -675,10 +649,6 @@ def action_poweroff(): payload = {'clients': ips} server = get_server_from_clients(ips) r = server.post('/poweroff', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Client powered off successfully'), category='info') return redirect(url_for('commands')) @@ -696,6 +666,7 @@ def action_poweroff(): @app.route('/action/wol', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_wol(): form = WOLForm(request.form) @@ -751,6 +722,7 @@ def get_common_disk_data(ips): return disk_data @app.route('/action/setup/select', methods=['GET']) +@handle_server_errors('commands') @login_required def action_setup_select(): args = request.args.copy() @@ -770,10 +742,6 @@ def action_setup_select(): client_choices = [] for ip in ips: r = server.get('/client/info', payload={'client': [ip]}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') client_name = r.json()['name'] client_choices.append((ip, f"{client_name} ({ip})")) @@ -791,6 +759,7 @@ def action_setup_select(): @app.route('/action/setup', methods=['GET']) +@handle_server_errors('commands') @login_required def action_setup_show(): args = request.args.copy() @@ -804,12 +773,7 @@ def action_setup_show(): ips = set(args['ips'].split(' ')) base_client = args['selected_client'] - try: - setup_data = get_client_setup(base_client) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + setup_data = get_client_setup(base_client) if not setup_data: flash(_('Partition information is not available. Boot client in ogLive mode to obtain it'), category='error') @@ -843,6 +807,7 @@ def action_setup_show(): scopes=scopes) @app.route('/action/setup', methods=['POST']) +@handle_server_errors('commands') @login_required def action_setup_modify(): form = SetupForm(request.form) @@ -908,10 +873,6 @@ def action_setup_modify(): server = get_server_from_clients(list(ips)) r = server.post('/setup', payload=payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_(f'Setup command sent sucessfully'), category='info') return redirect(url_for('commands')) @@ -925,10 +886,6 @@ def filter_images_allowed_in_center(server, images, center_id): res = [] for image in images: r = server.get('/image/restrict', {'image': image['id']}) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode allowed_scopes = r.json().get('scopes') if not allowed_scopes or center_id in allowed_scopes: res.append(image) @@ -936,10 +893,6 @@ def filter_images_allowed_in_center(server, images, center_id): def get_images_from_repo(server, repo_id): r = server.get('/images') - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode images = r.json()['images'] res=[] for image in images: @@ -957,10 +910,6 @@ def get_clients_repo(server, ips): repo_id=None for ip in ips: r = server.get('/client/info', payload={'client': [ip]}) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode repo_id_aux = r.json()['repo_id'] if repo_id is None: repo_id = repo_id_aux @@ -1040,6 +989,7 @@ class PartitionCollection: return self.clients[idx] @app.route('/action/image/restore', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_image_restore(): form = ImageRestoreForm(request.form) @@ -1055,10 +1005,6 @@ def action_image_restore(): image_id = form.image.data server = get_server_from_clients(ips) r = server.get('/images') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') images_list = r.json()['images'] image = search_image(images_list, int(image_id)) @@ -1073,10 +1019,6 @@ def action_image_restore(): return redirect(url_for('commands')) r = server.get('/cache/list', payload={'clients': ips}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') clients_info = r.json()['clients'] @@ -1092,10 +1034,6 @@ def action_image_restore(): 'profile': str(image['software_id']), 'id': str(image['id'])} r = server.post('/image/restore', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_(f'Image restore command sent sucessfully'), category='info') return redirect(url_for('commands')) else: @@ -1108,28 +1046,19 @@ def action_image_restore(): server = get_server_from_clients(ips) - try: - repo_id = get_clients_repo(server, ips) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + repo_id = get_clients_repo(server, ips) if repo_id is None: flash(_(f'Computers have different repos assigned'), category='error') return redirect(url_for('commands')) - try: - images = get_images_from_repo(server, repo_id) - if not images: - flash(_(f'Computer(s) assigned to a repo with no images'), category='error') - return redirect(url_for('commands')) + images = get_images_from_repo(server, repo_id) + + if not images: + flash(_(f'Computer(s) assigned to a repo with no images'), category='error') + return redirect(url_for('commands')) - images = filter_images_allowed_in_center(server, images, center_id) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + images = filter_images_allowed_in_center(server, images, center_id) sort_images(images) @@ -1142,10 +1071,6 @@ def action_image_restore(): for ip in ips: r = server.get('/client/setup', payload={'client': [ip]}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') has_cache = False @@ -1203,6 +1128,7 @@ def action_image_restore(): scopes=scopes) @app.route('/action/hardware', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_hardware(): form = HardwareForm(request.form) @@ -1210,10 +1136,6 @@ def action_hardware(): ips = form.ips.data.split(' ') server = get_server_from_clients(ips) r = server.post('/hardware', payload={'clients': ips}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_(f'Hardware inventory command sent sucessfully'), category='info') return redirect(url_for('commands')) else: @@ -1225,16 +1147,13 @@ def action_hardware(): form.ips.data = ' '.join(ips) server = get_server_from_clients(ips) r = server.get('/hardware', payload={'client': list(ips)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') hardware = r.json()['hardware'] return render_template('actions/hardware.html', form=form, hardware=hardware, scopes=scopes) @app.route('/action/software', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_software(): form = SoftwareForm(request.form) @@ -1244,12 +1163,8 @@ def action_software(): server = get_server_from_clients(ips) if form.view.data: r = server.get('/software', payload={'client': ips, - 'disk': int(disk), - 'partition': int(partition)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') + 'disk': int(disk), + 'partition': int(partition)}) software = r.json()['software'] scopes, clients = get_scopes(set(ips)) @@ -1259,10 +1174,6 @@ def action_software(): r = server.post('/software', payload={'clients': ips, 'disk': disk, 'partition': partition}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Software profile request sent successfully'), category='info') else: flash(_('Error processing software profile form'), category='error') @@ -1276,10 +1187,6 @@ def action_software(): form.ips.data = ' '.join(ips) server = get_server_from_clients(ips) r = server.get('/client/setup', payload={'client': list(ips)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') if not r.json()['partitions']: flash(_('Software inventory is not available. Boot client in ogLive mode to obtain it'), category='error') @@ -1295,6 +1202,7 @@ def action_software(): return render_template('actions/software.html', form=form, scopes=scopes) @app.route('/action/session', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_session(): form = SessionForm(request.form) @@ -1304,10 +1212,6 @@ def action_session(): server = get_server_from_clients(list(ips)) r = server.get('/session', payload={'clients': ips}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') sessions = r.json()['sessions'] if not sessions: @@ -1332,10 +1236,6 @@ def action_session(): r = server.post('/session', payload={'clients': valid_ips, 'disk': str(disk), 'partition': str(partition)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') if excluded_ips: flash('The following clients didn\'t match the boot configuration: ' + str(excluded_ips)) return redirect(url_for('commands')) @@ -1352,10 +1252,6 @@ def action_session(): form.ips.data = ' '.join(ips_list) r = server.get('/session', payload={'clients': ips_list}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') sessions = r.json()['sessions'] if not sessions: @@ -1388,6 +1284,7 @@ def action_session(): scopes=scopes, os_groups=os_groups) @app.route('/action/cache', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_client_cache(): form = CacheForm(request.form) @@ -1413,10 +1310,6 @@ def action_client_cache(): r = server.post('/cache/delete', payload={'clients': client_list, 'images': image_list}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Cache delete request sent successfully'), category='info') return redirect(url_for('commands')) else: @@ -1429,10 +1322,6 @@ def action_client_cache(): server = get_server_from_clients(ips_list) r = server.get('/cache/list', payload={'clients': ips_list}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') clients_info = r.json()['clients'] @@ -1462,6 +1351,7 @@ def action_client_cache(): client_images=client_images) @app.route('/action/cache/fetch', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_image_fetch(): form = ImageFetchForm(request.form) @@ -1472,10 +1362,6 @@ def action_image_fetch(): image_id = form.image.data server = get_server_from_clients(ips) r = server.get('/images') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') images_list = r.json()['images'] image = search_image(images_list, int(image_id)) @@ -1484,10 +1370,6 @@ def action_image_fetch(): return redirect(url_for('commands')) r = server.get('/cache/list', payload={'clients': ips}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') clients_info = r.json()['clients'] @@ -1500,10 +1382,6 @@ def action_image_fetch(): 'image': image['name']} r = server.post('/cache/fetch', payload=payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Cache fetch request sent successfully'), category='info') return redirect(url_for('commands')) else: @@ -1519,28 +1397,18 @@ def action_image_fetch(): server = get_server_from_clients(ips) - try: - repo_id = get_clients_repo(server, ips) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + repo_id = get_clients_repo(server, ips) if repo_id is None: flash(_(f'Computers have different repos assigned'), category='error') return redirect(url_for('commands')) - try: - images = get_images_from_repo(server, repo_id) + images = get_images_from_repo(server, repo_id) - if not images: - flash(_(f'Computer(s) assigned to a repo with no images'), category='error') - return redirect(url_for('commands')) + if not images: + flash(_(f'Computer(s) assigned to a repo with no images'), category='error') + return redirect(url_for('commands')) - images = filter_images_allowed_in_center(server, images, center_id) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + images = filter_images_allowed_in_center(server, images, center_id) sort_images(images) @@ -1554,6 +1422,7 @@ def action_image_fetch(): scopes=scopes) @app.route('/action/client/info', methods=['GET']) +@handle_server_errors('commands') @login_required def action_client_info(): form = ClientDetailsForm() @@ -1565,10 +1434,6 @@ def action_client_info(): payload = {'client': list(ips)} r = server.get('/client/info', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') db_client = r.json() @@ -1586,12 +1451,7 @@ def action_client_info(): form.remote.render_kw = {'readonly': True} form.maintenance.data = db_client['maintenance'] form.maintenance.render_kw = {'readonly': True} - try: - repositories = get_repositories(server) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + repositories = get_repositories(server) form.repo.choices = [(repo["id"], repo["name"]) for repo in repositories if db_client['repo_id'] == repo["id"]] form.repo.render_kw = {'readonly': True} @@ -1601,10 +1461,6 @@ def action_client_info(): form.boot.render_kw = {'readonly': True} r = server.get('/scopes') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') rooms = parse_scopes_from_tree(r.json(), 'room') rooms = [(room['id'], room['name']) for room in rooms @@ -1614,13 +1470,8 @@ def action_client_info(): form.submit.render_kw = {"style": "visibility:hidden;"} ip = list(ips)[0] - try: - setup_data = get_client_setup(ip) - client_setup_add_image_names(server, setup_data) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + setup_data = get_client_setup(ip) + client_setup_add_image_names(server, setup_data) disk_form = SetupForm() selected_disk = 1 @@ -1628,10 +1479,6 @@ def action_client_info(): disk_form.disk.data = selected_disk r = server.get('/cache/list', payload={'clients': [ip]}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') clients_info = r.json()['clients'] @@ -1646,10 +1493,6 @@ def action_client_info(): get_cache_info(clients_info, storage_data, images_data, client_images) r = server.get('/efi', payload={'clients': [ip]}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') efi_data = r.json()['clients'][0] @@ -1666,6 +1509,7 @@ def action_client_info(): efi_data=efi_data) @app.route('/action/client/update', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_client_update(): form = ClientDetailsForm(request.form) @@ -1696,13 +1540,8 @@ def action_client_update(): "mac": mac_address } server = get_server_from_ip_port(form.server.data) r = server.post('/client/update', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error updating client'), - category='error') - else: - flash(_('Client updated successfully'), category='info') + + flash(_('Client updated successfully'), category='info') return redirect(url_for("scopes")) else: ips = parse_elements(request.args.to_dict()) @@ -1714,10 +1553,6 @@ def action_client_update(): payload = {'client': list(ips)} r = server.get('/client/info', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') db_client = r.json() @@ -1733,10 +1568,6 @@ def action_client_update(): current_mode = db_client['boot'] r = server.get('/mode') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') available_modes = [(current_mode, current_mode)] available_modes.extend([(mode, mode) for mode in r.json()['modes'] @@ -1745,10 +1576,6 @@ def action_client_update(): form.boot.render_kw = {'readonly': True} r = server.get('/scopes') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') room_id = db_client['room'] rooms = parse_scopes_from_tree(r.json(), 'room') @@ -1757,24 +1584,14 @@ def action_client_update(): form.room.choices = list(rooms) form.room.render_kw = {'readonly': True} - try: - repositories = get_repositories(server) - except ServerError: - return ogserver_down('scopes') - except ServerErrorCode: - return ogserver_error(r, 'scopes') + repositories = get_repositories(server) form.repo.choices = [(repo["id"], repo["name"]) for repo in repositories if db_client['repo_id'] == repo["id"]] form.repo.choices.extend([(repo["id"], repo["name"]) for repo in repositories if db_client['repo_id'] != repo["id"]]) ip = list(ips)[0] - try: - setup_data = get_client_setup(ip) - client_setup_add_image_names(server, setup_data) - except ServerError: - return ogserver_down('scopes') - except ServerErrorCode: - return ogserver_error(r, 'scopes') + setup_data = get_client_setup(ip) + client_setup_add_image_names(server, setup_data) disk_form = SetupForm() selected_disk = 1 @@ -1804,6 +1621,7 @@ def find_folder(folder_id, scopes): return None @app.route('/action/folder/delete', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_folder_delete(): form = FolderForm(request.form) @@ -1811,13 +1629,7 @@ def action_folder_delete(): payload = {"id": int(form.folder_id.data)} server = get_server_from_ip_port(form.server.data) r = server.post('/folder/delete', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error deleting folder'), - category='error') - else: - flash(_('Folder deleted successfully'), category='info') + flash(_('Folder deleted successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -1838,6 +1650,7 @@ def action_folder_delete(): parent="scopes.html", scopes=scopes, ancestors=ancestors, children=children) @app.route('/action/folder/update', methods=['GET','POST']) +@handle_server_errors('scopes') def action_folder_update(): form = FolderForm(request.form) if request.method == 'POST': @@ -1846,13 +1659,7 @@ def action_folder_update(): server = get_server_from_ip_port(form.server.data) r = server.post('/folder/update', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error updating folder'), - category='error') - else: - flash(_('Folder updated successfully'), category='info') + flash(_('Folder updated successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -1872,6 +1679,7 @@ def action_folder_update(): parent="scopes.html", scopes=scopes) @app.route('/action/folder/add', methods=['GET']) +@handle_server_errors('scopes') @login_required def action_folder_add(): form = FolderForm() @@ -1896,6 +1704,7 @@ def action_folder_add(): parent="scopes.html", scopes=scopes) @app.route('/action/folder/add', methods=['POST']) +@handle_server_errors('scopes') def action_folder_add_post(): form = FolderForm(request.form) payload = {"name": form.name.data} @@ -1906,16 +1715,11 @@ def action_folder_add_post(): server = get_server_from_ip_port(form.server.data) r = server.post('/folder/add', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error adding folder'), - category='error') - else: - flash(_('Folder added successfully'), category='info') + flash(_('Folder added successfully'), category='info') return redirect(url_for("scopes")) @app.route('/action/client/add', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_client_add(): form = ClientDetailsForm(request.form) @@ -1958,13 +1762,7 @@ def action_client_add(): server = get_server_from_ip_port(form.server.data) r = server.post('/client/add', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error adding client'), - category='error') - else: - flash(_('Client added successfully'), category='info') + flash(_('Client added successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -1974,10 +1772,6 @@ def action_client_add(): form.server.data = params['scope-server'] server = get_server_from_ip_port(params['scope-server']) r = server.get('/mode') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') available_modes = [(mode, mode) for mode in r.json()['modes'] if mode == 'pxe'] available_modes.extend([(mode, mode) for mode in r.json()['modes'] if mode != 'pxe']) @@ -1986,10 +1780,6 @@ def action_client_add(): form.mac.render_kw = {'placeholder': 'aa:bb:cc:dd:ee:aa'} r = server.get('/scopes') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') room_id = params['scope-room'] rooms = parse_scopes_from_tree(r.json(), 'room') @@ -1998,12 +1788,7 @@ def action_client_add(): form.room.choices = list(rooms) form.room.render_kw = {'readonly': True} - try: - repositories = get_repositories(server) - except ServerError: - return ogserver_down('scopes') - except ServerErrorCode: - return ogserver_error(r, 'scopes') + repositories = get_repositories(server) form.repo.choices = [(repo["id"], repo["name"]) for repo in repositories] if params.get('folder'): @@ -2038,6 +1823,7 @@ def get_client_move_choices(scopes): return choices @app.route('/action/client/move', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_client_move(): form = ClientMoveForm(request.form) @@ -2053,14 +1839,7 @@ def action_client_move(): "folder_id": int(folder_id)} server = get_server_from_clients(ips) r = server.post('/client/move', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error moving client'), - category='error') - else: - flash(_('Client moved successfully'), - category='info') + flash(_('Client moved successfully'), category='info') return redirect(url_for('scopes')) else: ips = parse_elements(request.args.to_dict()) @@ -2082,6 +1861,7 @@ PLACEHOLDER_CLIENT_IMPORT_TEXT = '''client_name1,94:c6:91:a6:25:1a,10.141.10.100 client_name2,94:c6:91:a6:25:1b,10.141.10.101''' @app.route('/action/clients/import', methods=['GET']) +@handle_server_errors('scopes') @login_required def action_clients_import_get(): params = request.args.to_dict() @@ -2093,10 +1873,6 @@ def action_clients_import_get(): form.server.data = params['scope-server'] server = get_server_from_ip_port(params['scope-server']) r = server.get('/scopes') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') rooms = parse_scopes_from_tree(r.json(), 'room') selected_room_id = params['scope-room'] @@ -2104,12 +1880,7 @@ def action_clients_import_get(): for room in rooms if room['id'] == int(selected_room_id)] form.room.choices = selected_room form.room.render_kw = {'readonly': True} - try: - repositories = get_repositories(server) - except ServerError: - return ogserver_down('scopes') - except ServerErrorCode: - return ogserver_error(r, 'scopes') + repositories = get_repositories(server) form.repo.choices = [(repo["id"], repo["name"]) for repo in repositories] form.client_conf.render_kw = {'placeholder': PLACEHOLDER_CLIENT_IMPORT_TEXT} @@ -2127,6 +1898,7 @@ OG_CLIENT_DEFAULT_REMOTE = False @app.route('/action/clients/import', methods=['POST']) +@handle_server_errors('scopes') @login_required def action_clients_import_post(): form = ImportClientsForm(request.form) @@ -2178,13 +1950,7 @@ def action_clients_import_post(): for client in clients: for key, value in client.items(): payload[key] = value - resp = server.post('/client/add', payload) - - if resp.status_code != requests.codes.ok: - flash(_('ogServer: error adding client {}').format(client['name']), - category='error') - return redirect(url_for('scopes')) - + res = server.post('/client/add', payload) flash(_('Clients imported successfully'), category='info') return redirect(url_for('scopes')) @@ -2204,6 +1970,7 @@ def get_selected_clients(scopes): return selected_clients @app.route('/action/client/delete', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_client_delete(): form = GenericForm(request.form) @@ -2215,14 +1982,7 @@ def action_client_delete(): payload = {'clients': ips} server = get_server_from_clients(ips) r = server.post('/client/delete', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error deleting client'), - category='error') - else: - flash(_('Client deleted successfully'), - category='info') + flash(_('Client deleted successfully'), category='info') return redirect(url_for('scopes')) else: ips = parse_elements(request.args.to_dict()) @@ -2237,6 +1997,7 @@ def action_client_delete(): return redirect(url_for('scopes')) @app.route('/action/cmd/run', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_run_cmd(): form = RunCmdForm(request.form) @@ -2253,11 +2014,6 @@ def action_run_cmd(): server = get_server_from_clients(ips) r = server.post('/shell/run', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') - flash(_('Command sent successfully'), category='info') return redirect(url_for('commands')) else: @@ -2273,6 +2029,7 @@ def action_run_cmd(): scopes=scopes) @app.route('/action/script/run', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_run_script(): form = RunScriptForm(request.form) @@ -2292,11 +2049,6 @@ def action_run_script(): server = get_server_from_clients(ips) r = server.post('/shell/run', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') - flash(_('Script run sent successfully'), category='info') return redirect(url_for('commands')) else: @@ -2310,10 +2062,6 @@ def action_run_script(): reference_patitioning = None for ip in ips: r = server.get('/client/setup', payload={'client': [ip]}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') partitions = r.json()['partitions'][1:] if not reference_patitioning: @@ -2325,10 +2073,6 @@ def action_run_script(): flash(_('Some clients don\'t have same configuration'), category='info') r = server.get('/shell/list') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') scripts = r.json()['scripts'] @@ -2342,6 +2086,7 @@ def action_run_script(): scopes=scopes) @app.route('/action/script/output', methods=['GET']) +@handle_server_errors('commands') @login_required def action_script_display_output(): ips = parse_elements(request.args.to_dict()) @@ -2352,10 +2097,6 @@ def action_script_display_output(): server = get_server_from_clients(ips) r = server.get('/shell/output', payload={'clients': list(ips)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') client_data = r.json()['clients'] @@ -2387,10 +2128,6 @@ def get_clients_modes(ips, server): modes = {} for ip in ips: r = server.get('/client/info', payload={"client": [ip]}) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode resp = r.json() current_boot = resp['boot'] client_name = resp['name'] @@ -2401,6 +2138,7 @@ def get_clients_modes(ips, server): return modes @app.route('/action/mode', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_mode(): form = BootModeForm(request.form) @@ -2410,10 +2148,6 @@ def action_mode(): server = get_server_from_clients(ips) r = server.post('/mode', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Client set boot mode request sent successfully'), category='info') return redirect(url_for('commands')) @@ -2424,17 +2158,8 @@ def action_mode(): return redirect(url_for('commands')) server = get_server_from_clients(ips) - try: - modes_set = get_clients_modes(ips, server) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + modes_set = get_clients_modes(ips, server) r = server.get('/mode') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') mode_descriptions = { 'pxe': 'ogLive (pxe)', @@ -2474,10 +2199,6 @@ def get_client_list_by_key(ips, server, key): ret = {} for ip in ips: r = server.get('/client/info', payload={"client": [ip]}) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode resp = r.json() val = resp[key] if val not in ret: @@ -2487,6 +2208,7 @@ def get_client_list_by_key(ips, server, key): return ret @app.route('/action/oglive', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_oglive(): form = OgliveForm(request.form) @@ -2495,10 +2217,6 @@ def action_oglive(): payload = {'clients': ips, 'name': form.oglive.data} server = get_server_from_clients(ips) r = server.post('/oglive/set', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Client set ogLive request sent successfully'), category='info') return redirect(url_for('commands')) @@ -2510,18 +2228,9 @@ def action_oglive(): server = get_server_from_clients(list(ips)) - try: - oglives_set = get_client_list_by_key(ips, server, key='livedir') - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + oglives_set = get_client_list_by_key(ips, server, key='livedir') r = server.get('/oglive/list') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') oglive_list = r.json()['oglive'] most_used_live = max(oglives_set, key=lambda l: len(oglives_set[l])) @@ -2558,10 +2267,6 @@ def get_clients_repo_dictionary(ips, server, repositories): for ip in ips: r = server.get('/client/info', payload={"client": [ip]}) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode resp = r.json() repo_name = repo_id_to_name[resp['repo_id']] if repo_name not in repos: @@ -2571,6 +2276,7 @@ def get_clients_repo_dictionary(ips, server, repositories): return repos @app.route('/action/repo/set', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_repo_set(): form = SetRepoForm(request.form) @@ -2579,10 +2285,6 @@ def action_repo_set(): payload = {'clients': ips, 'id': int(form.repo.data)} server = get_server_from_clients(ips) r = server.post('/client/repo', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Repo set ogLive request sent successfully'), category='info') return redirect(url_for('commands')) @@ -2593,22 +2295,12 @@ def action_repo_set(): return redirect(url_for('commands')) server = get_server_from_clients(list(ips)) - try: - repositories = get_repositories(server) - repos_set = get_clients_repo_dictionary(ips, server, repositories) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + repositories = get_repositories(server) + repos_set = get_clients_repo_dictionary(ips, server, repositories) scopes, clients = get_scopes(set(ips)) - try: - repo_set = get_client_list_by_key(ips, server, key='repo_id') - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + repo_set = get_client_list_by_key(ips, server, key='repo_id') most_used_repo_id = max(repo_set, key=lambda id: len(repo_set[id])) @@ -2626,6 +2318,7 @@ def action_repo_set(): @app.route('/action/image/create', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_image_create(): form = ImageCreateForm(request.form) @@ -2633,10 +2326,6 @@ def action_image_create(): ip = form.ip.data server = get_server_from_clients([ip]) r = server.get('/client/info', payload={"client": [ip]}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') image_name = remove_accents(form.name.data.strip()) if ' ' in image_name: @@ -2655,10 +2344,6 @@ def action_image_create(): "group_id": 0, # Default group. "center_id": r.json()["center"]} r = server.post('/image/create', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') return redirect(url_for('commands')) else: ips = parse_elements(request.args.to_dict()) @@ -2668,10 +2353,6 @@ def action_image_create(): server = get_server_from_clients(ips) r = server.get('/client/setup', payload={'client': list(ips)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') invalid_part_types = get_invalid_image_partition_types() @@ -2691,18 +2372,9 @@ def action_image_create(): f"{FS_CODES.get(part.get('filesystem'), 'UNKNOWN')}") ) r = server.get('/client/info', payload={'client': list(ips)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') client_repo_id = r.json()['repo_id'] - try: - repositories = get_repositories(server) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + repositories = get_repositories(server) form.repository.choices = [ (repo['id'], repo['name']) for repo in repositories if client_repo_id == repo['id']] form.repository.render_kw = {'readonly': True} @@ -2716,6 +2388,7 @@ def action_image_create(): @app.route('/action/image/update', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_image_update(): form = ImageUpdateForm(request.form) @@ -2725,22 +2398,14 @@ def action_image_update(): image_id = form.image.data server = get_server_from_clients([ip]) r = server.get('/images') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') images_list = r.json()['images'] image = search_image(images_list, int(image_id)) if not image: flash(_('Image to restore was not found'), category='error') return redirect(url_for('commands')) - try: - repository = get_repository(image['repo_id'], server) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + + repository = get_repository(image['repo_id'], server) payload = {'clients': [ip], 'disk': disk, 'partition': partition, @@ -2753,10 +2418,6 @@ def action_image_update(): 'group_id': 0, 'center_id': 0} r = server.post('/image/update', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') flash(_('Image update command sent sucessfully'), category='info') return redirect(url_for('commands')) @@ -2769,24 +2430,15 @@ def action_image_update(): server = get_server_from_clients(ips) r = server.get('/client/info', payload={'client': list(ips)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') repo_id = r.json()['repo_id'] - try: - images = get_images_from_repo(server, repo_id) + images = get_images_from_repo(server, repo_id) - if not images: - flash(_(f'Computer(s) assigned to a repo with no images'), category='error') - return redirect(url_for('commands')) + if not images: + flash(_(f'Computer(s) assigned to a repo with no images'), category='error') + return redirect(url_for('commands')) - images = filter_images_allowed_in_center(server, images, center_id) - except ServerError: - return ogserver_down('commands') - except ServerErrorCode: - return ogserver_error(r, 'commands') + images = filter_images_allowed_in_center(server, images, center_id) sort_images(images) @@ -2794,10 +2446,6 @@ def action_image_update(): form.image.choices.append((image['id'], image['name'])) r = server.get('/client/setup', payload={'client': list(ips)}) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') invalid_part_types = get_invalid_image_partition_types() @@ -2838,6 +2486,7 @@ def action_image_update(): @app.route('/action/reboot', methods=['GET', 'POST']) +@handle_server_errors('commands') @login_required def action_reboot(): form = GenericForm(request.form) @@ -2849,14 +2498,7 @@ def action_reboot(): payload = {'clients': ips} server = get_server_from_clients(ips) r = server.post('/reboot', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error rebooting client'), - category='error') - else: - flash(_('Client rebooted successfully'), - category='info') + flash(_('Client rebooted successfully'), category='info') return redirect(url_for('commands')) else: ips = parse_elements(request.args.to_dict()) @@ -2872,6 +2514,7 @@ def action_reboot(): @app.route('/action/refresh', methods=['POST']) +@handle_server_errors('commands') @login_required def action_refresh(): ips = parse_elements(request.form.to_dict()) @@ -2881,15 +2524,11 @@ def action_refresh(): server = get_server_from_clients(list(ips)) payload = {'clients': list(ips)} r = server.post('/refresh', payload) - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - flash(_('OgServer replied with a non ok status code'), category='error') - else: - flash(_('Refresh request processed successfully'), category='info') + flash(_('Refresh request processed successfully'), category='info') return redirect(url_for('commands')) @app.route('/action/center/add', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_center_add(): form = CenterForm(request.form) @@ -2898,13 +2537,7 @@ def action_center_add(): "comment": form.comment.data} server = get_server_from_ip_port(form.server.data) r = server.post('/center/add', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('Server replied with error code when adding the center'), - category='error') - else: - flash(_('Center added successfully'), category='info') + flash(_('Center added successfully'), category='info') return redirect(url_for("scopes")) else: server_choices = [(server.ip + ':' + str(server.port), server.name) @@ -2915,6 +2548,7 @@ def action_center_add(): scopes=scopes) @app.route('/action/center/update', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_center_update(): form = CenterForm(request.form) @@ -2924,13 +2558,7 @@ def action_center_update(): "comment": form.comment.data} server = get_server_from_ip_port(form.server.data) r = server.post('/center/update', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('Server replied with error code when updating the center'), - category='error') - else: - flash(_('Center updated successfully'), category='info') + flash(_('Center updated successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -2952,10 +2580,6 @@ def action_center_update(): payload = {"id": int(center)} r = server.get('/center/info', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') form.comment.data = r.json()['comment'] form.name.data = r.json()['name'] @@ -2966,6 +2590,7 @@ def action_center_update(): scopes=scopes) @app.route('/action/center/info', methods=['GET']) +@handle_server_errors('scopes') @login_required def action_center_info(): form = CenterForm(request.form) @@ -2989,10 +2614,6 @@ def action_center_info(): payload = {"id": int(center)} r = server.get('/center/info', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') form.comment.data = r.json()['comment'] form.comment.render_kw = {'readonly': True} @@ -3037,6 +2658,7 @@ def get_scope_context(elem_id, elem_type, scopes): return (ancestors, children) @app.route('/action/center/delete', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_center_delete(): form = DeleteCenterForm(request.form) @@ -3044,13 +2666,7 @@ def action_center_delete(): server = get_server_from_ip_port(form.server.data) payload = {"id": form.center.data} r = server.post('/center/delete', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('Server replied with error code when deleting the center'), - category='error') - else: - flash(_('Center deleted successfully'), category='info') + flash(_('Center deleted successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -3059,10 +2675,6 @@ def action_center_delete(): return redirect(url_for('scopes')) server = get_server_from_ip_port(params['scope-server']) r = server.get('/scopes') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') form.center.data = params['scope-center'] form.server.data = params['scope-server'] @@ -3072,6 +2684,7 @@ def action_center_delete(): scopes=scopes, ancestors=ancestors, children=children) @app.route('/action/room/add', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_room_add(): form = RoomForm(request.form) @@ -3083,12 +2696,7 @@ def action_room_add(): "gateway": form.gateway.data, "folder_id": int(form.folder_id.data)} r = server.post('/room/add', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('Server replied with error code when adding the room'), category='error') - else: - flash(_('Room added successfully'), category='info') + flash(_('Room added successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -3097,10 +2705,6 @@ def action_room_add(): return redirect(url_for('scopes')) server = get_server_from_ip_port(params['scope-server']) r = server.get('/scopes') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') selected_center_id = params['scope-center'] centers = parse_scopes_from_tree(r.json(), 'center') @@ -3120,6 +2724,7 @@ def action_room_add(): scopes=scopes) @app.route('/action/room/update', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_room_update(): form = RoomForm(request.form) @@ -3130,12 +2735,7 @@ def action_room_update(): "gateway": form.gateway.data, "id": int(form.room.data)} r = server.post('/room/update', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('Server replied with error code when updating the room'), category='error') - else: - flash(_('Room updated successfully'), category='info') + flash(_('Room updated successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -3151,10 +2751,6 @@ def action_room_update(): payload = {"id": int(room_id)} r = server.get('/room/info', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') form.name.data = r.json()['name'] form.gateway.data = r.json()['gateway'] form.netmask.data = r.json()['netmask'] @@ -3166,6 +2762,7 @@ def action_room_update(): scopes=scopes) @app.route('/action/room/info', methods=['GET']) +@handle_server_errors('scopes') @login_required def action_room_info(): form = RoomForm(request.form) @@ -3180,10 +2777,6 @@ def action_room_info(): payload = {"id": int(room_id)} r = server.get('/room/info', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') form.name.data = r.json()['name'] form.name.render_kw = {'readonly': True} form.gateway.data = r.json()['gateway'] @@ -3198,6 +2791,7 @@ def action_room_info(): scopes=scopes) @app.route('/action/room/delete', methods=['GET', 'POST']) +@handle_server_errors('scopes') @login_required def action_room_delete(): form = DeleteRoomForm(request.form) @@ -3205,13 +2799,7 @@ def action_room_delete(): payload = {"id": form.room.data} server = get_server_from_ip_port(form.server.data) r = server.post('/room/delete', payload) - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - flash(_('Server replied with error code when deleting the room'), - category='error') - else: - flash(_('Room deleted successfully'), category='info') + flash(_('Room deleted successfully'), category='info') return redirect(url_for("scopes")) else: params = request.args.to_dict() @@ -3220,10 +2808,6 @@ def action_room_delete(): return redirect(url_for('scopes')) server = get_server_from_ip_port(params['scope-server']) r = server.get('/scopes') - if not r: - return ogserver_down('scopes') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'scopes') form.room.data = params['scope-room'] form.room.render_kw = {'readonly': True} @@ -3236,7 +2820,11 @@ def action_room_delete(): @app.route('/commands/', methods=['GET']) @login_required def commands(): - scopes, clients = get_scopes() + try: + scopes, clients = get_scopes() + except ServerError: + scopes = {} + clients = {} return render_template('commands.html', scopes=scopes, clients=clients) def _get_sorted_repos(repos): @@ -3249,12 +2837,7 @@ def get_images_grouped_by_repos(): server={} server['server'] = resp['server'] images=resp['json']['images'] - try: - all_repos=get_repositories(resp['server']) - except ServerError: - continue - except ServerErrorCode: - continue + all_repos=get_repositories(resp['server']) repos={} sort_images(images) @@ -3280,14 +2863,20 @@ def get_images_grouped_by_repos(): @app.route('/images/', methods=['GET']) @login_required def images(): - responses = get_images_grouped_by_repos() + try: + responses = get_images_grouped_by_repos() + except ServerError: + responses = [] return render_template('images.html', responses=responses) @app.route('/repos/', methods=['GET']) @login_required def manage_repos(): - responses = get_all_repositories() + try: + responses = get_all_repositories() + except ServerError: + responses = [] return render_template('repos.html', repos_resp=responses) def repo_addr_is_valid(form): @@ -3320,6 +2909,7 @@ def repo_addr_is_valid(form): return res @app.route('/action/repo/add', methods=['POST', 'GET']) +@handle_server_errors('manage_repos') @login_required def action_repo_add(): form = RepoForm(request.form) @@ -3338,13 +2928,7 @@ def action_repo_add(): "center": 1} server = get_server_from_ip_port(form.server.data) r = server.post('/repository/add', payload) - if not r: - return ogserver_down('manage_repos') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error adding repo'), - category='error') - else: - flash(_('Repo added successfully'), category='info') + flash(_('Repo added successfully'), category='info') return redirect(url_for("manage_repos")) else: params = request.args.to_dict() @@ -3360,6 +2944,7 @@ def action_repo_add(): repos_resp=responses) @app.route('/action/repo/update', methods=['GET', 'POST']) +@handle_server_errors('manage_repos') @login_required def action_repo_update(): form = RepoForm(request.form) @@ -3376,14 +2961,7 @@ def action_repo_update(): 'addr': addr, 'center': 1} r = server.post('/repository/update', payload) - if not r: - return ogserver_down('manage_repos') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error updating repo'), - category='error') - else: - flash(_('Repo updated successfully'), - category='info') + flash(_('Repo updated successfully'), category='info') return redirect(url_for('manage_repos')) else: params = request.args.to_dict() @@ -3397,12 +2975,7 @@ def action_repo_update(): flash(_('Please, select a server'), category='error') return redirect(url_for('manage_repos')) server = get_server_from_ip_port(server_ip_port) - try: - repository = get_repository(int(repo_id), server) - except ServerError: - return ogserver_down('manage_repos') - except ServerErrorCode: - return ogserver_error(r, 'manage_repos') + repository = get_repository(int(repo_id), server) form.server.data = server_ip_port form.repo_id.data = repo_id @@ -3415,6 +2988,7 @@ def action_repo_update(): repos_resp=responses) @app.route('/action/repo/delete', methods=['GET', 'POST']) +@handle_server_errors('manage_repos') @login_required def action_repo_delete(): form = RepoForm(request.form) @@ -3422,14 +2996,8 @@ def action_repo_delete(): server = get_server_from_ip_port(form.server.data) payload = { 'id': int(form.repo_id.data) } r = server.post('/repository/delete', payload) - if not r: - return ogserver_down('manage_repos') - if r.status_code != requests.codes.ok: - flash(_('ogServer: error deleting repo'), - category='error') - else: - flash(_('Repo deleted successfully'), - category='info') + + flash(_('Repo deleted successfully'), category='info') return redirect(url_for('manage_repos')) else: params = request.args.to_dict() @@ -3448,12 +3016,7 @@ def action_repo_delete(): flash(_('Please, select a server'), category='error') return redirect(url_for('manage_repos')) server = get_server_from_ip_port(server_ip_port) - try: - repository = get_repository(repo_id, server) - except ServerError: - return ogserver_down('manage_repos') - except ServerErrorCode: - return ogserver_error(r, 'manage_repos') + repository = get_repository(repo_id, server) form.server.data = server_ip_port form.repo_id.data = repo_id form.name.data = repository['name'] @@ -3469,6 +3032,7 @@ def action_repo_delete(): @app.route('/action/repo/info', methods=['GET']) +@handle_server_errors('manage_repos') @login_required def action_repo_info(): form = RepoForm() @@ -3487,12 +3051,7 @@ def action_repo_info(): flash(_('Please, select a server'), category='error') return redirect(url_for('manage_repos')) server = get_server_from_ip_port(server_ip_port) - try: - repository = get_repository(repo_id, server) - except ServerError: - return ogserver_down('manage_repos') - except ServerErrorCode: - return ogserver_error(r, 'manage_repos') + repository = get_repository(repo_id, server) form.name.data = repository['name'] form.name.render_kw = {'readonly': True} for addr in repository['addr']: @@ -3510,6 +3069,7 @@ def manage_servers(): return render_template('servers.html', servers=servers) @app.route('/server/update', methods=['GET']) +@handle_server_errors('manage_servers') @login_required def server_update_get(): params = request.args.to_dict() @@ -3520,10 +3080,6 @@ def server_update_get(): return redirect(url_for('manage_servers')) r = selected_server.get('/server') - if not r: - return ogserver_down('manage_servers') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'manage_servers') form = ServerConfigurationForm() server_config = r.json()['servers'] @@ -3536,6 +3092,7 @@ def server_update_get(): servers=servers) @app.route('/server/update', methods=['POST']) +@handle_server_errors('manage_servers') @login_required def server_update_post(): form = ServerConfigurationForm(request.form) @@ -3557,10 +3114,6 @@ def server_update_post(): return redirect(url_for('manage_servers')) r = server.get('/server') - if not r: - return ogserver_down('manage_servers') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'manage_servers') server_config = r.json()['servers'] # Remove @@ -3570,10 +3123,6 @@ def server_update_post(): payload = {'id': c['id']} rd = server.delete('/server', payload=payload) - if not rd: - return ogserver_down('manage_servers') - if rd.status_code != requests.codes.ok: - return ogserver_error(r, 'manage_servers') # Add for ip in addr_list: @@ -3588,16 +3137,13 @@ def server_update_post(): payload = {'address': ip} ra = server.post('/server', payload=payload) - if not ra: - return ogserver_down('manage_servers') - if ra.status_code != requests.codes.ok: - return ogserver_error(r, 'manage_servers') flash(_('Server update request sent successfully'), category='info') return redirect(url_for('manage_servers')) @app.route('/server/add', methods=['GET']) +@handle_server_errors('manage_servers') @login_required def server_add_get(): form = ServerForm() @@ -3606,6 +3152,7 @@ def server_add_get(): @app.route('/server/add', methods=['POST']) +@handle_server_errors('manage_servers') @login_required def server_add_post(): form = ServerForm(request.form) @@ -3623,6 +3170,7 @@ def server_add_post(): @app.route('/server/delete', methods=['GET']) +@handle_server_errors('manage_servers') @login_required def server_delete_get(): params = request.args.to_dict() @@ -3646,6 +3194,7 @@ def server_delete_get(): @app.route('/server/delete', methods=['POST']) +@handle_server_errors('manage_servers') @login_required def server_delete_post(): form = ServerForm(request.form) @@ -3665,10 +3214,14 @@ def server_delete_post(): @app.route('/lives/', methods=['GET']) @login_required def manage_lives(): - oglive_list = multi_request('get', '/oglive/list') + try: + oglive_list = multi_request('get', '/oglive/list') + except ServerError: + oglive_list = [] return render_template('lives.html', oglive_list=oglive_list, servers=servers) @app.route('/action/live/default', methods=['GET', 'POST']) +@handle_server_errors('manage_lives') @login_required def action_live_default(): form = OgliveForm(request.form) @@ -3680,10 +3233,6 @@ def action_live_default(): return redirect(url_for('manage_lives')) payload = {'name': form.oglive.data} r = server.post('/oglive/default', payload) - if not r: - return ogserver_down('manage_lives') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'manage_lives') flash(_('Set default ogLive request sent successfully'), category='info') return redirect(url_for('manage_lives')) else: @@ -3694,10 +3243,6 @@ def action_live_default(): flash(_('Please, select one server'), category='error') return redirect(url_for('manage_lives')) r = server.get('/oglive/list') - if not r: - return ogserver_down('commands') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'commands') oglive_list = r.json()['oglive'] @@ -3895,6 +3440,7 @@ def delete_user(username): @app.route('/user/add', methods=['GET']) +@handle_server_errors('users') @login_required def user_add_get(): form = UserForm() @@ -3903,6 +3449,7 @@ def user_add_get(): @app.route('/user/add', methods=['POST']) +@handle_server_errors('users') @login_required def user_add_post(): form = UserForm(request.form) @@ -3921,6 +3468,7 @@ def user_add_post(): @app.route('/user/edit', methods=['GET']) +@handle_server_errors('users') @login_required def user_edit_get(): username_set = parse_elements(request.args.to_dict()) @@ -3972,6 +3520,7 @@ def user_edit_get(): @app.route('/user/edit', methods=['POST']) +@handle_server_errors('users') @login_required def user_edit_post(): form = EditUserForm(request.form) @@ -3996,6 +3545,7 @@ def user_edit_post(): @app.route('/user/delete', methods=['GET']) +@handle_server_errors('users') @login_required def user_delete_get(): username_set = parse_elements(request.args.to_dict()) @@ -4015,6 +3565,7 @@ def user_delete_get(): @app.route('/action/image/list', methods=['GET']) +@handle_server_errors('images') @login_required def action_image_list(): params = request.args.to_dict() @@ -4024,31 +3575,27 @@ def action_image_list(): flash(_('Please, select one more images to be listed'), category='error') return redirect(url_for('images')) server = get_server_from_ip_port(params['image-server']) - try: - responses = get_images_grouped_by_repos() - servers = [] - for server in responses: - repos = [] - for unused, repo in server['repos'].items(): - images=[] - for img in repo['images']: - if int(img['id']) in ids: - images.append(img) - if images: - repos.append((repo['name'], images)) - if repos: - s={} - s['name'] = server['server'].name - s['repos'] = repos - servers.append(s) - except ServerError: - return ogserver_down('images') - except ServerErrorCode: - return ogserver_error(r, 'images') + responses = get_images_grouped_by_repos() + servers = [] + for server in responses: + repos = [] + for unused, repo in server['repos'].items(): + images=[] + for img in repo['images']: + if int(img['id']) in ids: + images.append(img) + if images: + repos.append((repo['name'], images)) + if repos: + s={} + s['name'] = server['server'].name + s['repos'] = repos + servers.append(s) return render_template('actions/list_images.html', servers=servers, responses=responses) @app.route('/user/delete', methods=['POST']) +@handle_server_errors('users') @login_required def user_delete_post(): form = DeleteUserForm(request.form) @@ -4068,6 +3615,7 @@ def user_delete_post(): @app.route('/action/image/info', methods=['GET']) +@handle_server_errors('images') @login_required def action_image_info(): form = ImageDetailsForm() @@ -4079,10 +3627,6 @@ def action_image_info(): id = ids.pop() server = get_server_from_ip_port(params['image-server']) r = server.get('/images') - if not r: - return ogserver_down('images') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'images') images = r.json()['images'] image = next(img for img in images if img['id'] == int(id)) @@ -4102,18 +3646,9 @@ def action_image_info(): form.checksum.data = checksum - try: - responses = get_images_grouped_by_repos() - except ServerError: - return ogserver_down('images') - except ServerErrorCode: - return ogserver_error(r, 'images') + responses = get_images_grouped_by_repos() r = server.get('/image/restrict', {'image': image['id']}) - if not r: - raise ServerError - if r.status_code != requests.codes.ok: - raise ServerErrorCode form.scopes.choices = get_available_centers() form.scopes.data = [str(scope) for scope in r.json().get('scopes')] @@ -4122,6 +3657,7 @@ def action_image_info(): responses=responses) @app.route('/action/image/delete', methods=['GET', 'POST']) +@handle_server_errors('images') @login_required def action_image_delete(): form = GenericForm(request.form) @@ -4135,10 +3671,6 @@ def action_image_delete(): for id in ids: payload = {'image': id} r = server.post('/image/delete', payload) - if not r: - return ogserver_down('images') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'images') flash(_('Image deletion request sent successfully'), category='info') return redirect(url_for('images')) @@ -4151,12 +3683,7 @@ def action_image_delete(): return redirect(url_for('images')) server = get_server_from_ip_port(params['image-server']) - try: - responses = get_images_grouped_by_repos() - except ServerError: - return ogserver_down('images') - except ServerErrorCode: - return ogserver_error(r, 'images') + responses = get_images_grouped_by_repos() form.ids.data = ' '.join(image_ids) form.server.data = params['image-server'] @@ -4166,6 +3693,7 @@ def action_image_delete(): responses=responses) @app.route('/action/image/config', methods=['GET', 'POST']) +@handle_server_errors('images') @login_required def action_image_config(): form = ImageConfigForm(request.form) @@ -4178,10 +3706,6 @@ def action_image_config(): payload = {'image': image_id, 'scopes': scope_list} r = server.post('/image/restrict', payload) - if not r: - return ogserver_down('images') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'images') flash(_('Image updated successfully'), category='info') return redirect(url_for('images')) @@ -4200,21 +3724,12 @@ def action_image_config(): form.name.data = image_name r = server.get('/image/restrict', {'image': int(image_id)}) - if not r: - return ogserver_down('images') - if r.status_code != requests.codes.ok: - return ogserver_error(r, 'images') form.server.data = params['image-server'] form.scopes.choices = get_available_centers() form.scopes.data = [str(scope) for scope in r.json().get('scopes')] - try: - responses = get_images_grouped_by_repos() - except ServerError: - return ogserver_down('images') - except ServerErrorCode: - return ogserver_error(r, 'images') + responses = get_images_grouped_by_repos() return render_template('actions/image_config.html', form=form, responses=responses) |