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
|
from flask import Flask, request, jsonify
|
||||||
import json
|
import json
|
||||||
import subprocess
|
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 os
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
# Setup the Flask-JWT-Extended extension
|
# 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)
|
jwt = JWTManager(app)
|
||||||
|
|
||||||
# split path to folder and file
|
|
||||||
def split_directory_and_file(path):
|
def split_directory_and_file(path):
|
||||||
directory, file_with_wildcard = os.path.split(path)
|
directory, file_with_wildcard = os.path.split(path)
|
||||||
file_name_parts = file_with_wildcard.split('*')
|
file_name = file_with_wildcard.split('*')[0] # Get the part before the wildcard
|
||||||
file_name = file_name_parts[0] # Get the part before the wildcard
|
|
||||||
return directory, file_name
|
return directory, file_name
|
||||||
|
|
||||||
# Function to read logs from folder
|
|
||||||
def read_log_from_dir(dir_path, pattern, lines):
|
def read_log_from_dir(dir_path, pattern, lines):
|
||||||
|
|
||||||
# return variable
|
|
||||||
ret_var = ""
|
ret_var = ""
|
||||||
|
three_hours_ago = datetime.datetime.now() - datetime.timedelta(hours=3)
|
||||||
# Get current time
|
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]
|
||||||
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
|
|
||||||
for file_name in log_files:
|
for file_name in log_files:
|
||||||
file_path = os.path.join(dir_path, file_name)
|
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"
|
||||||
# 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"
|
|
||||||
|
|
||||||
return ret_var
|
return ret_var
|
||||||
|
|
||||||
|
|
||||||
# Function to read logs
|
|
||||||
def read_log(log_file, lines):
|
def read_log(log_file, lines):
|
||||||
return subprocess.check_output(['tail', '-n', str(lines), log_file]).decode('utf-8')
|
return subprocess.check_output(['tail', '-n', str(lines), log_file]).decode('utf-8')
|
||||||
|
|
||||||
# Function to read top
|
|
||||||
def read_top():
|
def read_top():
|
||||||
return subprocess.check_output(['top', '-b', '-n', '1']).decode('utf-8')
|
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'])
|
@app.route('/login', methods=['POST'])
|
||||||
def login():
|
def login():
|
||||||
username = request.json.get("username", None)
|
username = request.json.get("username")
|
||||||
password = request.json.get("password", None)
|
password = request.json.get("password")
|
||||||
|
|
||||||
# Validate user credentials here (this is just a placeholder logic)
|
|
||||||
if username != "admin" or password != "password":
|
if username != "admin" or password != "password":
|
||||||
return jsonify({"msg": "Bad username or password"}), 401
|
return jsonify({"msg": "Bad username or password"}), 401
|
||||||
|
|
||||||
access_token = create_access_token(identity=username)
|
access_token = create_access_token(identity=username)
|
||||||
return jsonify(access_token=access_token)
|
return jsonify(access_token=access_token)
|
||||||
|
|
||||||
# Updated get_logs route to require token authentication
|
|
||||||
@app.route('/get_logs', methods=['GET'])
|
@app.route('/get_logs', methods=['GET'])
|
||||||
# @jwt_required()
|
|
||||||
def get_logs():
|
def get_logs():
|
||||||
issue_type = request.args.get("issue_type")
|
issue_type = request.args.get("issue_type")
|
||||||
response = {}
|
|
||||||
try:
|
try:
|
||||||
with open('./src/config.json') as config_file:
|
with open('./src/config.json') as config_file:
|
||||||
config = json.load(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]
|
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']}
|
||||||
# logs
|
response.update({comm.get('tag'): os.popen(comm.get('comm')).read() for comm in issue_config['commands']})
|
||||||
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"}
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
response = {"error": str(e)}
|
return jsonify({"error": str(e)})
|
||||||
return jsonify(response)
|
return jsonify(response)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user