ajout de nouvelles routes pour redemarrer le système et pour savoir si le processus KineIntercom est vivant

This commit is contained in:
Vincent BENOIT
2022-11-28 11:41:36 +01:00
parent 1f81f221a3
commit ec9ecae0c7
2 changed files with 81 additions and 4 deletions

View File

@@ -22,6 +22,7 @@ from flask_jwt_extended import jwt_required, decode_token
import json
import shutil
import hashlib
import subprocess
from werkzeug.exceptions import HTTPException
#########################################################
@@ -63,6 +64,41 @@ def refresh_expiring_tokens(response):
except (RuntimeError, KeyError):
return response
def execute_cmd(self, args=""):
''' Execute system command
'''
out = None
err = None
if len(args) == 0:
current_app.logger.error("Paramètre d'entrée invalide")
return False
current_app.logger.debug("La commande système executée est : {}".format(args))
try:
cmd = subprocess.Popen(args,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = cmd.communicate(timeout=10)
except subprocess.CalledProcessError as e:
current_app.logger.error("Error executing system command : {} - {}".format(e.output, e.returncode))
return False
except subprocess.TimeoutExpired:
cmd.kill()
current_app.logger.error("Timeout when executing system command")
return False
except FileNotFoundError:
current_app.logger.error("System command not found")
return False
if cmd.returncode != 0:
current_app.logger.error('Error executing system command ({})'.format(cmd.returncode))
current_app.logger.error('{}'.format(err))
return False
return True
@auth.route('/login', methods=['POST'])
def login():
''' Authenticate User
@@ -71,7 +107,7 @@ def login():
current_app.logger.info("Connexion de l'utilisateur : {}".format(auth.username))
if not auth or not auth.username or not auth.password:
current_app.logger.error("Login and Password required !")
abort(401, description='Login and Password required')
abort(status.HTTP_401_UNAUTHORIZED, description='Login and Password required')
try:
hashstr = hashlib.sha256(auth.password.encode('utf-8')).hexdigest()
@@ -93,8 +129,8 @@ def login():
current_app.logger.error("Authorization failed !")
except Exception as e:
current_app.logger.error("Erreur : {}".format(e))
abort(500, description='Authentification impossible')
abort(401, description="Authorization failed !")
abort(status.HTTP_500_INTERNAL_SERVER_ERROR, description='Authentification impossible')
abort(status.HTTP_401_UNAUTHORIZED, description="Authorization failed !")
@auth.route('/logout', methods=['POST'])
@jwt_required()
@@ -119,6 +155,25 @@ def current_user():
current_user = get_jwt_identity()
return jsonify(current_user)
@auth.route('/alive', methods=['POST'])
@jwt_required()
def isAlive():
''' Handles HTTP requests to URL: /api/configurateur/alive
'''
current_app.logger.info("Reboot du système ...")
current_user = get_jwt_identity()
unset_jwt_cookies(content)
userpath = os.path.join("/tmp", current_app.config['PROJECT'])
if os.path.exists(userpath):
shutil.rmtree(userpath)
reboot_cmd = ['sudo', '/usr/bin/systemctl', 'reboot']
if not self.execute_cmd(reboot_cmd):
abort(status.HTTP_500_INTERNAL_SERVER_ERROR, description='Redémarrage du système impossible')
content = jsonify({'message': 'reboot successful !'})
return content, status.HTTP_200_OK
@auth.route('/userConnected', methods=['GET'])
def user_connected():
''' retourne "oui" si un utilisateur est déjà connecté sinon "non"

View File

@@ -23,6 +23,7 @@ import platform
import psutil
from werkzeug.exceptions import HTTPException
from ConfBack.manager import Sock
#########################################################
# Class et Methods #
@@ -93,7 +94,7 @@ def get_infos():
content['signal_qos'] = data['INFOS']['control']['signal_qos']
content['sim_inserted'] = data['INFOS']['control']['sim_inserted']
content['call_ready'] = data['INFOS']['control']['call_ready']
content['system'] = {'arch':platform.architecture()[0],
content['system'] = {'arch':platform.architecture()[0],
'machine':platform.machine(),
'version':platform.release(),
'os':platform.system(),
@@ -109,3 +110,24 @@ def get_infos():
'percent_used_disk':disk.percent}
return jsonify(content), status.HTTP_200_OK
@info.route('/alive', methods=['GET'])
@jwt_required()
def is_alive():
''' Processus KineIntercom is alive ? '''
ret = True
conn = Sock(addr=current_app.config['UNIX_ADDR'], logger=current_app.logger)
if not conn.connect():
current_app.logger.error("impossible de se connecter au serveur")
abort(status.HTTP_406_NOT_ACCEPTABLE, description="Impossible de se connecter au serveur")
# send order to KineIntercom process
if not conn.send(b"ALIVE\n"):
conn.disconnect()
current_app.logger.error("impossible de communiquer avec le serveur")
abort(status.HTTP_406_NOT_ACCEPTABLE, description="Impossible de communiquer avec le serveur")
conn.disconnect()
content = {'alive':ret}
return jsonify(content), status.HTTP_200_OK