From 9e26787e429a9ce6fce97506e8ca9bb6ea000363 Mon Sep 17 00:00:00 2001 From: Nikolaos Karaolidis Date: Sat, 23 Apr 2022 13:42:07 +0300 Subject: [PATCH] Add logging --- src/app.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/app.py b/src/app.py index 1d965c5..fac00c3 100644 --- a/src/app.py +++ b/src/app.py @@ -1,7 +1,7 @@ from flask import Flask, request from reconnect import reboot from os import environ -from subprocess import call +from subprocess import call, DEVNULL, STDOUT app = Flask(__name__) @@ -15,47 +15,58 @@ path = environ.get('ROUTER_PATH') or '/ws' @app.route('/', methods=['POST']) def result(): - print(request.json) - return 'Received request, printing to console!' + app.logger.debug(request.json) + return 'Received request!' @app.route('/safe', methods=['POST']) def safe(): + app.logger.info('Initializing safe reboot process') + # Try to ping the router 100 times for i in range(50): - if call(['ping', '-c', '1', url]) == 0: + if call(['ping', '-c', '1', url], stdout=DEVNULL, stderr=STDOUT) == 0: + app.logger.info('Router is online') break else: + app.logger.error('Router is offline') return 'Error: Unable to ping and reboot router automatically!' - # Try to nslookup 5 different websites + # Try to nslookup 5 different websites to see if DNS is working websites = ['www.google.com', 'www.facebook.com', 'www.twitter.com', 'www.reddit.com', 'www.amazon.com'] success = 0 - for website in websites: - if call(['nslookup', website]) == 0: + if call(['nslookup', website], stdout=DEVNULL, stderr=STDOUT) == 0: + app.logger.info(f'Successfully resolved {website}') success += 1 if success > 3: + app.logger.error('Websites resolved successfully') return 'Error: DNS seems to be working, debug manually!' # Reboot router + app.logger.info('Rebooting router') status = reboot(url, path, username, password).text if '{"status":true}' not in status: + app.logger.error('Reboot failed') return 'Error: Something went wrong while rebooting router!' + app.logger.info('Reboot successful') return 'Success: Rebooted router!' @app.route('/force', methods=['POST']) def force(): + app.logger.info('Initializing force reboot process') status = reboot(url, path, username, password).text if '{"status":true}' not in status: + app.logger.error('Reboot failed') return 'Error: Something went wrong while rebooting router!' + app.logger.info('Reboot successful') return 'Success: Rebooted router!' @app.route('/grafana', methods=['POST']) def grafana(): if request.json['state'] == 'alerting': - safe() + return safe()