optimize code
This commit is contained in:
parent
3b14fbf0b3
commit
e8230582ce
81
src/app.py
81
src/app.py
@ -1,113 +1,58 @@
|
||||
# pip install Flask
|
||||
# pip install flask-jwt-extended
|
||||
|
||||
from flask import Flask, request, jsonify
|
||||
import json
|
||||
import subprocess
|
||||
from flask_jwt_extended import JWTManager, create_access_token, jwt_required
|
||||
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"] = "your-secret-key" # Change this to a random secret key
|
||||
app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY", "default-secret-key")
|
||||
jwt = JWTManager(app)
|
||||
|
||||
# split path to folder and file
|
||||
def split_directory_and_file(path):
|
||||
directory, file_with_wildcard = os.path.split(path)
|
||||
file_name_parts = file_with_wildcard.split('*')
|
||||
file_name = file_name_parts[0] # Get the part before the wildcard
|
||||
file_name = file_with_wildcard.split('*')[0] # Get the part before the wildcard
|
||||
return directory, file_name
|
||||
|
||||
# Function to read logs from folder
|
||||
def read_log_from_dir(dir_path, pattern, lines):
|
||||
|
||||
# return variable
|
||||
ret_var = ""
|
||||
|
||||
# Get current time
|
||||
current_time = datetime.datetime.now()
|
||||
|
||||
# Calculate the time 3 hours ago
|
||||
three_hours_ago = current_time - datetime.timedelta(hours=3)
|
||||
|
||||
# List all files in the directory
|
||||
log_files = [file for file in os.listdir(dir_path) if pattern in file]
|
||||
|
||||
# Iterate through log files
|
||||
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)
|
||||
|
||||
# Check if file was modified in the last 3 hours
|
||||
modified_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
|
||||
if modified_time > three_hours_ago:
|
||||
ret_var += file_name + "\n"
|
||||
ret_var += subprocess.check_output(['tail', '-n', str(lines), file_path]).decode('utf-8')
|
||||
ret_var += "\n\n"
|
||||
|
||||
ret_var += f"{file_name}\n{subprocess.check_output(['tail', '-n', str(lines), file_path]).decode('utf-8')}\n\n"
|
||||
return ret_var
|
||||
|
||||
|
||||
# Function to read logs
|
||||
def read_log(log_file, lines):
|
||||
return subprocess.check_output(['tail', '-n', str(lines), log_file]).decode('utf-8')
|
||||
|
||||
# Function to read top
|
||||
def read_top():
|
||||
return subprocess.check_output(['top', '-b', '-n', '1']).decode('utf-8')
|
||||
|
||||
# Login route to authenticate users and return a token
|
||||
@app.route('/login', methods=['POST'])
|
||||
def login():
|
||||
username = request.json.get("username", None)
|
||||
password = request.json.get("password", None)
|
||||
|
||||
# Validate user credentials here (this is just a placeholder logic)
|
||||
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)
|
||||
|
||||
# Updated get_logs route to require token authentication
|
||||
@app.route('/get_logs', methods=['GET'])
|
||||
# @jwt_required()
|
||||
def get_logs():
|
||||
issue_type = request.args.get("issue_type")
|
||||
response = {}
|
||||
try:
|
||||
with open('./src/config.json') as config_file:
|
||||
config = json.load(config_file)
|
||||
if issue_type in config:
|
||||
if issue_type not in config:
|
||||
return jsonify({"error": "Invalid issue type"})
|
||||
issue_config = config[issue_type]
|
||||
|
||||
# logs
|
||||
for log in issue_config['logs']:
|
||||
|
||||
directory, file_name = split_directory_and_file(log.get('log_file'))
|
||||
|
||||
if '*' in log.get('log_file'):
|
||||
# directory, file_name = split_directory_and_file(log.get('log_file'))
|
||||
log_output = read_log_from_dir(directory, file_name, log['lines'])
|
||||
else:
|
||||
log_output = read_log(log['log_file'], log['lines'])
|
||||
|
||||
# response[log['log_file']] = log_output
|
||||
response[file_name] = log_output
|
||||
|
||||
# commands
|
||||
for comm in issue_config['commands']:
|
||||
# response[comm.get('tag')] = subprocess.check_output([comm.get('comm')]).decode('utf-8')
|
||||
response[comm.get('tag')] = os.popen(comm.get('comm')).read()
|
||||
# response[comm.get('tag')] = subprocess.run(comm.get('comm'), shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
# response[comm.get('tag')] = read_top()
|
||||
|
||||
else:
|
||||
response = {"error": "Invalid 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:
|
||||
response = {"error": str(e)}
|
||||
return jsonify({"error": str(e)})
|
||||
return jsonify(response)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user