|
|
from flask import Flask, request, jsonify, Response, render_template_string |
|
|
import os |
|
|
import time |
|
|
import gc |
|
|
import threading |
|
|
import sys |
|
|
import urllib.parse |
|
|
import subprocess |
|
|
from datetime import datetime |
|
|
import signal |
|
|
import psutil |
|
|
import glob |
|
|
import re |
|
|
import pytz |
|
|
|
|
|
HF_USER1 = os.environ.get('HF_USER1', '') |
|
|
HF_REPO = os.environ.get('HF_REPO', '') |
|
|
HF_EMAIL = os.environ.get('HF_EMAIL', '') |
|
|
HF_TOKEN1 = os.environ.get('HF_TOKEN1', '') |
|
|
def jupyter(): |
|
|
os.system('jupyter lab --ip=0.0.0.0 --port=8002 --no-browser --allow-root --notebook-dir=/data --NotebookApp.token=qilan --ServerApp.disable_check_xsrf=True') |
|
|
|
|
|
|
|
|
app = Flask(__name__) |
|
|
|
|
|
|
|
|
HTML_PAGE = """ |
|
|
<!DOCTYPE html> |
|
|
<html lang="zh-CN"> |
|
|
<head> |
|
|
<meta charset="UTF-8"> |
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
|
<title>Flask 应用</title> |
|
|
<style> |
|
|
body { |
|
|
font-family: Arial, sans-serif; |
|
|
max-width: 800px; |
|
|
margin: 0 auto; |
|
|
padding: 20px; |
|
|
background-color: #f5f5f5; |
|
|
} |
|
|
.container { |
|
|
background: white; |
|
|
padding: 30px; |
|
|
border-radius: 10px; |
|
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1); |
|
|
} |
|
|
h1 { |
|
|
color: #333; |
|
|
text-align: center; |
|
|
} |
|
|
.link { |
|
|
display: inline-block; |
|
|
margin: 10px; |
|
|
padding: 10px 20px; |
|
|
background: #007bff; |
|
|
color: white; |
|
|
text-decoration: none; |
|
|
border-radius: 5px; |
|
|
} |
|
|
.link:hover { |
|
|
background: #0056b3; |
|
|
} |
|
|
</style> |
|
|
</head> |
|
|
<body> |
|
|
<div class="container"> |
|
|
<h1>🚀 Flask 应用主页</h1> |
|
|
<p>欢迎来到 Flask 应用!这是一个简单的 HTML 页面。</p> |
|
|
<p>您可以访问以下端点:</p> |
|
|
<a href="/hello" class="link">/hello - JSON API</a> |
|
|
<a href="/" class="link">/ - 主页</a> |
|
|
</div> |
|
|
</body> |
|
|
</html> |
|
|
""" |
|
|
def compress_folder(folder_path, output_dir): |
|
|
try: |
|
|
|
|
|
os.makedirs(output_dir, exist_ok=True) |
|
|
|
|
|
|
|
|
import pytz |
|
|
from datetime import datetime |
|
|
|
|
|
|
|
|
china_tz = pytz.timezone('Asia/Shanghai') |
|
|
|
|
|
|
|
|
timestamp = str(int(datetime.now(china_tz).timestamp() * 1000)) |
|
|
output_path = os.path.join(output_dir, f'{timestamp}.tar.gz') |
|
|
|
|
|
|
|
|
existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz')) |
|
|
|
|
|
|
|
|
def extract_timestamp(filename): |
|
|
|
|
|
match = re.search(r'(\d+)\.tar\.gz$', filename) |
|
|
return int(match.group(1)) if match else 0 |
|
|
|
|
|
|
|
|
if len(existing_archives) >= 5: |
|
|
|
|
|
existing_archives.sort(key=extract_timestamp) |
|
|
|
|
|
|
|
|
oldest_archive = existing_archives[0] |
|
|
os.remove(oldest_archive) |
|
|
print(f"删除最旧的压缩包:{oldest_archive}") |
|
|
|
|
|
|
|
|
result = subprocess.run( |
|
|
['tar', '-czvf', output_path, folder_path], |
|
|
capture_output=True, |
|
|
text=True |
|
|
) |
|
|
|
|
|
if result.returncode == 0: |
|
|
|
|
|
file_size = os.path.getsize(output_path) / 1024 / 1024 |
|
|
|
|
|
|
|
|
china_time = datetime.now(china_tz) |
|
|
formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S') |
|
|
|
|
|
print(f"压缩成功:{output_path}") |
|
|
print(f"压缩大小:{file_size:.2f} MB") |
|
|
print(f"压缩时间:{formatted_time}") |
|
|
|
|
|
|
|
|
return f"{os.path.basename(output_path)} MB:{file_size:.2f} MB TIME:{formatted_time}" |
|
|
else: |
|
|
print("压缩失败") |
|
|
print("错误信息:", result.stderr) |
|
|
return None |
|
|
|
|
|
except Exception as e: |
|
|
print(f"压缩出错: {e}") |
|
|
return None |
|
|
def github(type): |
|
|
if type == 1: |
|
|
os.system(f'rm -rf /data/{HF_REPO}') |
|
|
if not os.path.exists(f'/data/{HF_REPO}'): |
|
|
git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}" |
|
|
print(git) |
|
|
os.system(git) |
|
|
os.system(f'git config --global user.email "{HF_EMAIL}"') |
|
|
os.system(f'git config --global user.name "{HF_USER1}"') |
|
|
os.chdir(f'/data/{HF_REPO}') |
|
|
if type == 2: |
|
|
os.chdir(f'/data/{HF_REPO}') |
|
|
print("开始备份上传HF") |
|
|
|
|
|
os.system('git lfs prune') |
|
|
|
|
|
new_archive_info = compress_folder('/data/dv1', f'/data/{HF_REPO}') |
|
|
if new_archive_info: |
|
|
new_archive, file_size_info = new_archive_info.split(' MB:') |
|
|
os.system(f'git add .') |
|
|
os.system(f'git commit -m "{file_size_info}"') |
|
|
|
|
|
|
|
|
os.system('git push -f origin main') |
|
|
os.system('git gc --prune=now') |
|
|
else: |
|
|
print("压缩失败,无法提交") |
|
|
@app.route('/') |
|
|
def index(): |
|
|
"""根路由,返回 HTML 页面""" |
|
|
return render_template_string(HTML_PAGE) |
|
|
|
|
|
@app.route('/hello', methods=['GET']) |
|
|
def hello(): |
|
|
return jsonify({"message": "Hello, World!"}) |
|
|
|
|
|
@app.route('/greet', methods=['POST']) |
|
|
def greet(): |
|
|
data = request.json |
|
|
name = data.get('name', 'Guest') |
|
|
return jsonify({"greeting": f"Hello, {name}!"}) |
|
|
@app.route('/bf', methods=['GET']) |
|
|
def bf(): |
|
|
github(2) |
|
|
return jsonify({"message": "OK"}) |
|
|
@app.route('/log', methods=['GET']) |
|
|
def get_log_content(): |
|
|
try: |
|
|
|
|
|
file_path = '/data/app.log' |
|
|
|
|
|
|
|
|
if not os.path.exists(file_path): |
|
|
return jsonify({"error": "File not found"}), 404 |
|
|
|
|
|
|
|
|
with open(file_path, 'r', encoding='utf-8') as file: |
|
|
|
|
|
lines = file.readlines()[-1000:] |
|
|
content = ''.join(lines) |
|
|
|
|
|
|
|
|
return Response( |
|
|
content, |
|
|
mimetype='text/plain; charset=utf-8' |
|
|
) |
|
|
|
|
|
except PermissionError: |
|
|
return jsonify({"error": "Permission denied to read the file"}), 403 |
|
|
except Exception as e: |
|
|
return jsonify({"error": str(e)}), 500 |
|
|
|
|
|
@app.route('/sub', methods=['GET']) |
|
|
def get_sub_content(): |
|
|
try: |
|
|
|
|
|
file_path = '/data/sub.txt' |
|
|
|
|
|
|
|
|
if not os.path.exists(file_path): |
|
|
return jsonify({"error": "File not found"}), 404 |
|
|
|
|
|
|
|
|
with open(file_path, 'r', encoding='utf-8') as file: |
|
|
content = file.read() |
|
|
|
|
|
|
|
|
return content |
|
|
|
|
|
except PermissionError: |
|
|
return jsonify({"error": "Permission denied to read the file"}), 403 |
|
|
except Exception as e: |
|
|
return jsonify({"error": str(e)}), 500 |
|
|
|
|
|
def perform_cleanup(): |
|
|
"""执行清理操作的函数""" |
|
|
|
|
|
collected = gc.collect() |
|
|
|
|
|
|
|
|
for module in list(sys.modules.keys()): |
|
|
if module.startswith('temp') or module.startswith('_'): |
|
|
del sys.modules[module] |
|
|
|
|
|
|
|
|
temp_dir = '/tmp' |
|
|
if os.path.exists(temp_dir) and os.access(temp_dir, os.W_OK): |
|
|
for f in os.listdir(temp_dir): |
|
|
if f.startswith('flask-') or f.startswith('tmp'): |
|
|
try: |
|
|
os.remove(os.path.join(temp_dir, f)) |
|
|
except: |
|
|
pass |
|
|
|
|
|
return collected |
|
|
|
|
|
@app.route('/xx', methods=['GET']) |
|
|
def system_info(): |
|
|
try: |
|
|
|
|
|
cleanup = request.args.get('cleanup', 'false').lower() == 'true' |
|
|
|
|
|
|
|
|
if cleanup: |
|
|
|
|
|
def cleanup_task(): |
|
|
collected = perform_cleanup() |
|
|
print(f"清理完成,回收了 {collected} 个对象") |
|
|
|
|
|
thread = threading.Thread(target=cleanup_task) |
|
|
thread.daemon = True |
|
|
thread.start() |
|
|
|
|
|
cleanup_message = "已开始执行清理操作(Python垃圾回收和临时文件清理)\n\n" |
|
|
else: |
|
|
cleanup_message = "" |
|
|
|
|
|
|
|
|
cpu_cores = os.cpu_count() |
|
|
|
|
|
|
|
|
def get_cpu_usage(): |
|
|
with open('/proc/stat', 'r') as f: |
|
|
lines = f.readlines() |
|
|
for line in lines: |
|
|
if line.startswith('cpu '): |
|
|
fields = line.split() |
|
|
total_time = sum(int(x) for x in fields[1:]) |
|
|
idle_time = int(fields[4]) |
|
|
return total_time, idle_time |
|
|
return 0, 0 |
|
|
|
|
|
|
|
|
total1, idle1 = get_cpu_usage() |
|
|
time.sleep(0.1) |
|
|
|
|
|
total2, idle2 = get_cpu_usage() |
|
|
|
|
|
if total2 - total1 > 0: |
|
|
cpu_usage = 100 * (1 - (idle2 - idle1) / (total2 - total1)) |
|
|
else: |
|
|
cpu_usage = 0 |
|
|
|
|
|
|
|
|
with open('/proc/meminfo', 'r') as f: |
|
|
mem_lines = f.readlines() |
|
|
|
|
|
mem_total = 0 |
|
|
mem_available = 0 |
|
|
mem_free = 0 |
|
|
|
|
|
for line in mem_lines: |
|
|
if line.startswith('MemTotal:'): |
|
|
mem_total = int(line.split()[1]) |
|
|
elif line.startswith('MemAvailable:'): |
|
|
mem_available = int(line.split()[1]) |
|
|
elif line.startswith('MemFree:'): |
|
|
mem_free = int(line.split()[1]) |
|
|
|
|
|
mem_used = mem_total - mem_available if mem_available > 0 else mem_total - mem_free |
|
|
mem_usage_percent = 100 * mem_used / mem_total if mem_total > 0 else 0 |
|
|
|
|
|
|
|
|
mem_total_gb = round(mem_total / 1024 / 1024, 2) |
|
|
mem_used_gb = round(mem_used / 1024 / 1024, 2) |
|
|
mem_free_gb = round(mem_free / 1024 / 1024, 2) |
|
|
|
|
|
|
|
|
with open('/proc/uptime', 'r') as f: |
|
|
uptime_seconds = float(f.readline().split()[0]) |
|
|
|
|
|
|
|
|
uptime_days = int(uptime_seconds // 86400) |
|
|
uptime_hours = int((uptime_seconds % 86400) // 3600) |
|
|
uptime_minutes = int((uptime_seconds % 3600) // 60) |
|
|
|
|
|
|
|
|
with open('/proc/loadavg', 'r') as f: |
|
|
load_avg = f.readline().split()[0:3] |
|
|
|
|
|
|
|
|
response_text = f""" |
|
|
============ 系统信息 ============ |
|
|
{cleanup_message} |
|
|
CPU信息: |
|
|
核心数: {cpu_cores} 核 |
|
|
使用率: {cpu_usage:.2f}% |
|
|
|
|
|
内存信息: |
|
|
总内存: {mem_total_gb} GB |
|
|
已使用: {mem_used_gb} GB |
|
|
空闲内存: {mem_free_gb} GB |
|
|
使用率: {mem_usage_percent:.2f}% |
|
|
|
|
|
系统运行时间: |
|
|
{uptime_days}天 {uptime_hours}小时 {uptime_minutes}分钟 |
|
|
|
|
|
系统负载: |
|
|
1分钟平均: {load_avg[0]} |
|
|
5分钟平均: {load_avg[1]} |
|
|
15分钟平均: {load_avg[2]} |
|
|
|
|
|
================================== |
|
|
提示: 访问 /xx?cleanup=true 可以尝试清理Python资源 |
|
|
注意: 由于权限限制,只能清理Python层面的资源 |
|
|
""" |
|
|
print(response_text) |
|
|
return Response(response_text, mimetype='text/plain; charset=utf-8') |
|
|
|
|
|
except Exception as e: |
|
|
error_text = f"获取系统信息时出错: {str(e)}" |
|
|
return Response(error_text, mimetype='text/plain; charset=utf-8'), 500 |
|
|
|
|
|
if __name__ == '__main__': |
|
|
app.run(host='0.0.0.0', port=7860, debug=True) |