2024-02-23 15:36:06 +05:00

60 lines
2.6 KiB
Python

from flask import Flask, request, jsonify
import json
import subprocess
from flask_jwt_extended import JWTManager, create_access_token
import os
import datetime
app = Flask(__name__)
# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY", "default-secret-key")
jwt = JWTManager(app)
def split_directory_and_file(path):
directory, file_with_wildcard = os.path.split(path)
file_name = file_with_wildcard.split('*')[0] # Get the part before the wildcard
return directory, file_name
def read_log_from_dir(dir_path, pattern, lines):
ret_var = ""
three_hours_ago = datetime.datetime.now() - datetime.timedelta(hours=3)
log_files = [f for f in os.listdir(dir_path) if pattern in f and datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(dir_path, f))) > three_hours_ago]
for file_name in log_files:
file_path = os.path.join(dir_path, file_name)
ret_var += f"{file_name}\n{subprocess.check_output(['tail', '-n', str(lines), file_path]).decode('utf-8')}\n\n"
return ret_var
def read_log(log_file, lines):
return subprocess.check_output(['tail', '-n', str(lines), log_file]).decode('utf-8')
def read_top():
return subprocess.check_output(['top', '-b', '-n', '1']).decode('utf-8')
@app.route('/login', methods=['POST'])
def login():
username = request.json.get("username")
password = request.json.get("password")
if username != "admin" or password != "password":
return jsonify({"msg": "Bad username or password"}), 401
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
@app.route('/get_logs', methods=['GET'])
def get_logs():
issue_type = request.args.get("issue_type")
try:
with open('./src/config.json') as config_file:
config = json.load(config_file)
if issue_type not in config:
return jsonify({"error": "Invalid issue type"})
issue_config = config[issue_type]
response = {log.get('log_file').split('*')[0]: read_log_from_dir(*split_directory_and_file(log.get('log_file')), log['lines']) if '*' in log.get('log_file') else read_log(log['log_file'], log['lines']) for log in issue_config['logs']}
response.update({comm.get('tag'): os.popen(comm.get('comm')).read() for comm in issue_config['commands']})
except Exception as e:
return jsonify({"error": str(e)})
return jsonify(response)
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0")