File size: 12,514 Bytes
f7c69af
cf026e2
6dc418f
31f09c4
 
 
44d982f
5339f7b
 
 
 
 
 
 
 
 
 
 
 
e3a307d
 
 
f7c69af
 
cfb2b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5339f7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfb2b9e
 
 
 
cf026e2
 
 
 
 
 
 
 
 
 
5339f7b
10d68cc
5339f7b
 
99de11a
0ac116c
99de11a
 
cfb2b9e
99de11a
 
 
 
 
522ba5c
99de11a
522ba5c
 
 
 
 
 
 
 
 
99de11a
 
 
 
 
522ba5c
cf026e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31f09c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dc418f
 
 
31f09c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dc418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31f09c4
6dc418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31f09c4
 
6dc418f
29a65fb
6dc418f
 
 
 
 
 
cf026e2
6dc418f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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 备份仓库的用户名
HF_REPO	= os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
HF_EMAIL = os.environ.get('HF_EMAIL', '') #HF的邮箱
HF_TOKEN1 = os.environ.get('HF_TOKEN1', '')#HF备份账号的TOKEN
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')

# threading.Thread(target=jupyter, daemon=True).start()
app = Flask(__name__)

# HTML 页面内容
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)
        
        # 使用 pytz 获取中国时区的当前时间戳(毫秒级)
        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
        
        # 如果压缩包数量超过5个,删除最旧的
        if len(existing_archives) >= 5:
            # 按时间戳排序
            existing_archives.sort(key=extract_timestamp)
            
            # 删除最旧的压缩包
            oldest_archive = existing_archives[0]
            os.remove(oldest_archive)
            print(f"删除最旧的压缩包:{oldest_archive}")
        
        # tar.gz 压缩
        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")
        # 清理 LFS 存储
        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 -u origin main')
            # 使用强制推送并清理
            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:
            # 读取最后1000行
            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 jsonify({"content": content})
        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():
    """执行清理操作的函数"""
    # Python垃圾回收
    collected = gc.collect()
    
    # 清理Python模块缓存
    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信息
        cpu_cores = os.cpu_count()
        
        # 获取CPU使用率 - 使用/proc/stat计算
        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
        
        # 转换为GB
        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)