163 lines
6.3 KiB
Python
163 lines
6.3 KiB
Python
# -*- encoding: utf-8 -*-
|
|
|
|
# @author : vincent.benoit@benserv.fr
|
|
# @brief : info routes
|
|
|
|
#########################################################
|
|
# Importation de modules externes #
|
|
|
|
import sys, re, os
|
|
import logging as log
|
|
from datetime import datetime, timezone
|
|
|
|
from flask import Flask, Blueprint, request, abort, jsonify, current_app
|
|
from flask_api import status
|
|
from flask_jwt_extended import create_access_token
|
|
from flask_jwt_extended import get_jwt
|
|
from flask_jwt_extended import set_access_cookies
|
|
from flask_jwt_extended import get_jwt_identity
|
|
from flask_jwt_extended import jwt_required
|
|
|
|
import json
|
|
import platform
|
|
import psutil
|
|
|
|
from werkzeug.exceptions import HTTPException
|
|
from ConfBack.manager import Sock, TimeoutError
|
|
|
|
#########################################################
|
|
# Class et Methods #
|
|
|
|
info = Blueprint('info', __name__, url_prefix='/api/configurateur')
|
|
|
|
@info.errorhandler(HTTPException)
|
|
def handle_exception(e):
|
|
''' return JSON instead of HTML for HTTP errors '''
|
|
response = e.get_response()
|
|
# replace the body with JSON
|
|
response.data = json.dumps({
|
|
'code': e.code,
|
|
'name': e.name,
|
|
'description': e.description,
|
|
})
|
|
response.content_type = "application/json"
|
|
return response
|
|
|
|
@info.after_request
|
|
def refresh_expiring_tokens(response):
|
|
''' Using an 'after_request' callback, we refresh any token that is within
|
|
30 minutes of expiring.'''
|
|
try:
|
|
exp_timestamp = get_jwt()['exp']
|
|
now = datetime.now(timezone.utc)
|
|
target_timestamp = datetime.timestamp(now + current_app.config['DELTA'])
|
|
if target_timestamp > exp_timestamp:
|
|
current_app.logger.warning("On doit recréer un token ....")
|
|
access_token = create_access_token(identity=get_jwt_identity())
|
|
# refresh token in storage place
|
|
if os.path.exists(os.path.join("/tmp", current_app.config['PROJECT'])):
|
|
with open(os.path.join("/tmp", current_app.config['PROJECT'], get_jwt_identity()['id']), 'w') as f:
|
|
f.write(access_token)
|
|
# Modifiy a Flask Response to set a cookie containing the access JWT.
|
|
set_access_cookies(response, access_token)
|
|
return response
|
|
except (RuntimeError, KeyError):
|
|
return response
|
|
|
|
def find_procs_by_name(name):
|
|
''' Return a list of processes matching 'name'.
|
|
'''
|
|
ls = []
|
|
for p in psutil.process_iter(["name", "exe", "cmdline"]):
|
|
if name == p.info['name'] or \
|
|
p.info['exe'] and os.path.basename(p.info['exe']) == name or \
|
|
p.info['cmdline'] and p.info['cmdline'][0] == name:
|
|
ls.append(p)
|
|
return ls
|
|
|
|
@info.route('/infos', methods=['GET'])
|
|
@jwt_required()
|
|
def get_infos():
|
|
''' Retreive informations '''
|
|
# Access the identity of the current user with get_jwt_identity
|
|
current_user = get_jwt_identity()
|
|
content = {}
|
|
# load data from JSON database
|
|
with open(current_app.config['DB_PATH'], 'r') as f:
|
|
data = json.load(f)
|
|
mem = psutil.virtual_memory()
|
|
disk = psutil.disk_usage('/')
|
|
content['manufacturer'] = data['INFOS']['manufacturer']
|
|
content['operator'] = data['INFOS']['control']['operator']
|
|
content['provider'] = data['INFOS']['control']['service_provider']
|
|
content['signal_dbm'] = data['INFOS']['control']['signal_dbm']
|
|
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],
|
|
'machine':platform.machine(),
|
|
'version':platform.release(),
|
|
'os':platform.system(),
|
|
'total_cpu':psutil.cpu_count(logical=True),
|
|
'cpu_usage':psutil.cpu_percent(),
|
|
'total_mem':str("{:.2f}".format(mem.total/(1024 * 1024))),
|
|
'avail_mem':str("{:.2f}".format(mem.available/(1024 * 1024))),
|
|
'used_mem':str("{:.2f}".format(mem.used/(1024 * 1024))),
|
|
'percent_used_mem':mem.percent,
|
|
'total_disk':str("{:.2f}".format(disk.total/(1024 * 1024))),
|
|
'free_disk':str("{:.2f}".format(disk.free/(1024 * 1024))),
|
|
'used_disk':str("{:.2f}".format(disk.used/(1024 * 1024))),
|
|
'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 IPC AF_UNIX")
|
|
ret = False
|
|
content = {'alive':ret}
|
|
return jsonify(content), status.HTTP_200_OK
|
|
|
|
current_app.logger.info("envoie de la demande de message de vie ...")
|
|
# send order to KineIntercom process
|
|
if not conn.send(b"ALIVE?\n"):
|
|
conn.disconnect()
|
|
current_app.logger.error("impossible de communiquer avec le serveur IPC AF_UNIX")
|
|
ret = False
|
|
content = {'alive':ret}
|
|
return jsonify(content), status.HTTP_200_OK
|
|
|
|
try:
|
|
datas = conn.recv_timeout(6, 10)
|
|
if not datas.decode('utf-8').startswith('ALIVE'):
|
|
current_app.logger.warning("message de vie non valide ...")
|
|
ret = False
|
|
else:
|
|
current_app.logger.info("message de vie valide ...")
|
|
except TimeoutError as e:
|
|
current_app.logger.warning("Pas de message de vie de la part du processus KineIntercom")
|
|
ret = False
|
|
conn.disconnect()
|
|
|
|
content = {'alive':ret}
|
|
return jsonify(content), status.HTTP_200_OK
|
|
|
|
@info.route('/rtc_alive', methods=['GET'])
|
|
@jwt_required()
|
|
def rtc_alive():
|
|
''' RTC is alive ? '''
|
|
ret = False
|
|
if os.path.exists("/dev/rtc0"):
|
|
current_app.logger.info("L'horloge matérielle est présente ...")
|
|
ret = True
|
|
else:
|
|
current_app.logger.warning("L'horloge matérielle n'est pas présente ...")
|
|
|
|
content = {'RTCalive':ret}
|
|
return jsonify(content), status.HTTP_200_OK
|