Qilan2 commited on
Commit
29e9175
·
verified ·
1 Parent(s): ac2e301

Create app2.py

Browse files
Files changed (1) hide show
  1. nv1/app2.py +673 -0
nv1/app2.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import os
3
+ import threading
4
+ import time
5
+ import yaml
6
+ from datetime import datetime
7
+ import signal
8
+ import psutil
9
+ import glob
10
+ import re
11
+ import pytz
12
+ import requests
13
+
14
+
15
+ N_PORT = os.environ.get('N_PORT', '8008') # N Z端口 默认8008
16
+ ARGO_PORT = os.environ.get('ARGO_PORT', '8009') # Argo(nginx的反代端口)固定隧道端口,留空默认8009
17
+ ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', '') # Argo固定隧道域名,留空即使用临时隧道
18
+ ARGO_AUTH = os.environ.get('ARGO_AUTH', '') # Argo固定隧道密钥,留空即使用临时隧道
19
+ DASHBOARD_VERSION = os.environ.get('DASHBOARD_VERSION', 'v1.13.2')# 指定面板的版本,以 v0.00.00 的格式,后续将固定在该版本不会升级,不填则使用默认的 v1.13.2
20
+ NZV1_VERSION = os.environ.get('NZV1_VERSION', 'v1.13.1')# 哪吒V1的版本默认v1.13.1
21
+ BACKUP_TIME = os.environ.get('BACKUP_TIME', '3600')# 备份时间 10800秒 2小时
22
+
23
+
24
+ HF_USER1 = os.environ.get('HF_USER1', '')# HF 备份仓库的用户名
25
+ HF_REPO = os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
26
+ HF_EMAIL = os.environ.get('HF_EMAIL', '') #HF的邮箱
27
+ HF_TOKEN1 = os.environ.get('HF_TOKEN1', '')#HF备份账号的TOKEN
28
+
29
+ HF_USER2 = os.environ.get('HF_USER2', '')# huggingface 用户名
30
+ HF_ID = os.environ.get('HF_ID', '')# huggingface space 名
31
+ HF_TOKEN2 = os.environ.get('HF_TOKEN2', '')# huggingface TOKEN
32
+ #JUPYTER_TOKEN
33
+ agent_config = {
34
+ 'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
35
+ 'debug': False,
36
+ 'disable_auto_update': True,
37
+ 'disable_command_execute': False,
38
+ 'disable_force_update': False,
39
+ 'disable_nat': False,
40
+ 'disable_send_query': False,
41
+ 'gpu': False,
42
+ 'insecure_tls': False,
43
+ 'ip_report_period': 1800,
44
+ 'report_delay': 3,
45
+ 'self_update_period': 0,
46
+ 'server': f'{ARGO_DOMAIN}:443',
47
+ 'skip_connection_count': False,
48
+ 'skip_procs_count': False,
49
+ 'temperature': True,
50
+ 'tls': True,
51
+ 'use_gitee_to_upgrade': False,
52
+ 'use_ipv6_country_code': False,
53
+ 'uuid': '18a49016-bc2d-4be9-0ddb-5357fdbf0b3d'
54
+ }
55
+ dashboard_config = {
56
+ 'admin_template': 'admin-dist',
57
+ 'agent_secret_key': '',
58
+ 'avg_ping_count': 2,
59
+ 'cover': 1,
60
+ 'https': {}, # 空字典
61
+ 'install_host': f'{ARGO_DOMAIN}:443',
62
+ 'ip_change_notification_group_id': 0,
63
+ 'jwt_secret_key': '',
64
+ 'jwt_timeout': 300,
65
+ 'language': 'zh_CN',
66
+ 'listen_port': f'{N_PORT}',
67
+ 'location': 'Asia/Shanghai',
68
+ 'site_name': '鸡子探针平台-柒蓝',
69
+ 'tls': True,
70
+ 'user_template': 'user-dist'
71
+ }
72
+
73
+ mime_types_content = """types {
74
+ text/html html htm shtml;
75
+ text/css css;
76
+ text/javascript js;
77
+ image/gif gif;
78
+ image/jpeg jpeg jpg;
79
+ image/png png;
80
+ text/plain txt;
81
+ application/json json;
82
+ application/xml xml;
83
+ application/octet-stream bin;
84
+ }"""
85
+
86
+ nginx_conf = """
87
+ # 全局配置
88
+ worker_processes auto;
89
+ pid /tmp/nginx.pid;
90
+ error_log /tmp/nginx_error.log;
91
+
92
+ events {
93
+ worker_connections 768;
94
+ }
95
+
96
+ http {
97
+ sendfile on;
98
+ tcp_nopush on;
99
+ tcp_nodelay on;
100
+ keepalive_timeout 65;
101
+ types_hash_max_size 2048;
102
+
103
+ # 修改 mime.types 路径
104
+ include /data/nginx1.24/mime.types;
105
+ default_type application/octet-stream;
106
+
107
+ # SSL配置
108
+ ssl_protocols TLSv1.2 TLSv1.3;
109
+ ssl_prefer_server_ciphers on;
110
+
111
+ access_log /tmp/nginx_access.log;
112
+ gzip on;
113
+
114
+ # 上游服务器配置
115
+ upstream dashboard {
116
+ server 127.0.0.1:%s;
117
+ keepalive 512;
118
+ }
119
+
120
+ # 服务器块
121
+ server {
122
+ listen %s;
123
+ listen [::]:%s;
124
+
125
+ server_name %s;
126
+
127
+ # 删除所有 real_ip 相关配置
128
+ underscores_in_headers on;
129
+
130
+ # gRPC相关
131
+ location ^~ /proto.NezhaService/ {
132
+ grpc_set_header Host $host;
133
+ grpc_read_timeout 600s;
134
+ grpc_send_timeout 600s;
135
+ grpc_socket_keepalive on;
136
+ client_max_body_size 10m;
137
+ grpc_buffer_size 4m;
138
+ grpc_pass grpc://dashboard;
139
+ }
140
+
141
+ # WebSocket相关
142
+ location ~* ^/api/v1/ws/(server|terminal|file)(.*)$ {
143
+ proxy_set_header Host $host;
144
+ proxy_set_header Origin https://$host;
145
+ proxy_set_header Upgrade $http_upgrade;
146
+ proxy_set_header Connection "upgrade";
147
+ proxy_read_timeout 3600s;
148
+ proxy_send_timeout 3600s;
149
+ proxy_pass http://127.0.0.1:%s;
150
+ }
151
+
152
+ # Web请求处理
153
+ location / {
154
+ proxy_set_header Host $host;
155
+ proxy_read_timeout 3600s;
156
+ proxy_send_timeout 3600s;
157
+ proxy_buffer_size 128k;
158
+ proxy_buffers 4 256k;
159
+ proxy_busy_buffers_size 256k;
160
+ proxy_max_temp_file_size 0;
161
+ proxy_pass http://127.0.0.1:%s;
162
+ }
163
+
164
+ # 安全头部
165
+ add_header X-Frame-Options SAMEORIGIN;
166
+ add_header X-Content-Type-Options nosniff;
167
+ add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
168
+ }
169
+ }
170
+ """ % (N_PORT, ARGO_PORT, ARGO_PORT, ARGO_DOMAIN, N_PORT, N_PORT)
171
+
172
+ stop_event = threading.Event()
173
+
174
+ def kill_processes():
175
+ # 要结束的进程名列表
176
+ target_processes = [
177
+ 'cf',
178
+ 'nv1',
179
+ 'dv1',
180
+ 'nginx'
181
+ ]
182
+
183
+ # 存储已结束的进程
184
+ killed_processes = []
185
+
186
+ # 遍历所有正在运行的进程
187
+ for proc in psutil.process_iter(['name']):
188
+ try:
189
+ # 检查进程名是否在目标列表中
190
+ if proc.info['name'] in target_processes:
191
+ # 获取进程ID
192
+ pid = proc.pid
193
+
194
+ # 先尝试优雅地结束进程
195
+ proc.terminate()
196
+
197
+ # 等待进程结束
198
+ try:
199
+ proc.wait(timeout=3)
200
+ except psutil.TimeoutExpired:
201
+ # 如果进程未响应,强制杀死
202
+ proc.kill()
203
+
204
+ killed_processes.append(f"{proc.info['name']} (PID: {pid})")
205
+
206
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
207
+ pass
208
+
209
+ # 打印已结束的进程
210
+ if killed_processes:
211
+ print("已结束以下进程:")
212
+ for process in killed_processes:
213
+ print(process)
214
+ else:
215
+ print("未找到匹配的进程")
216
+ kill_processes()
217
+ def get_latest_local_package(directory, pattern='*.tar.gz'):
218
+ try:
219
+ # 构建完整的搜索路径
220
+ search_pattern = os.path.join(directory, pattern)
221
+
222
+ # 查找所有匹配的文件
223
+ files = glob.glob(search_pattern)
224
+
225
+ if not files:
226
+ print("未找到匹配的 nezha-hf 压缩包")
227
+ return None
228
+
229
+ # 获取最新的文件
230
+ latest_file = max(files, key=os.path.getmtime)
231
+
232
+ print(f"找到最新的包: {latest_file}")
233
+ return latest_file
234
+
235
+ except Exception as e:
236
+ print(f"获取最新包时发生错误: {e}")
237
+ return None
238
+
239
+ def delete_huggingface_lfs_file(filename, repo_id, token):
240
+ """
241
+ 通过Hugging Face API删除LFS文件记录
242
+ """
243
+ try:
244
+ # 1. 查询LFS文件列表
245
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
246
+ headers = {
247
+ "content-type": "application/json",
248
+ "Authorization": f"Bearer {token}",
249
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
250
+ }
251
+
252
+ response = requests.get(url, headers=headers)
253
+ if response.status_code != 200:
254
+ print(f"查询LFS文件失败: {response.status_code} - {response.text}")
255
+ return False
256
+
257
+ lfs_files = response.json()
258
+
259
+ # 2. 查找匹配的文件
260
+ file_to_delete = None
261
+ for file_info in lfs_files:
262
+ if file_info.get('filename') == filename:
263
+ file_to_delete = file_info
264
+ break
265
+
266
+ if not file_to_delete:
267
+ print(f"未找到对应的LFS文件记录: {filename}")
268
+ return False
269
+
270
+ # 3. 删除LFS文件记录
271
+ file_oid = file_to_delete['fileOid']
272
+ delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
273
+
274
+ delete_response = requests.delete(delete_url, headers=headers)
275
+ if delete_response.status_code == 200:
276
+ print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
277
+ return True
278
+ else:
279
+ print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
280
+ return False
281
+
282
+ except Exception as e:
283
+ print(f"删除LFS文件记录时出错: {e}")
284
+ return False
285
+
286
+
287
+ def safe_git_cleanup(repo_path, files_to_remove):
288
+ """
289
+ 安全的Git清理,不会影响现有的备份文件
290
+ """
291
+ try:
292
+ original_dir = os.getcwd()
293
+ os.chdir(repo_path)
294
+
295
+ print(f"执行安全Git清理: {files_to_remove}")
296
+
297
+ # 1. 首先确保工作目录是干净的
298
+ result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
299
+ if result.stdout.strip():
300
+ print("工作目录有未提交的更改,先提交...")
301
+ subprocess.run(['git', 'add', '.'], capture_output=True)
302
+ subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
303
+
304
+ # 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
305
+ for filename in files_to_remove:
306
+ if os.path.exists(filename):
307
+ print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
308
+ subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
309
+ else:
310
+ print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
311
+
312
+ # 3. 提交删除操作
313
+ if files_to_remove:
314
+ subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
315
+
316
+ # 4. 执行GC清理但不删除最近的文件
317
+ subprocess.run(['git', 'gc', '--auto'], capture_output=True)
318
+ subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
319
+
320
+ print("安全Git清理完成")
321
+ os.chdir(original_dir)
322
+ return True
323
+
324
+ except Exception as e:
325
+ print(f"安全Git清理时出错: {e}")
326
+ os.chdir(original_dir)
327
+ return False
328
+
329
+
330
+ def get_remote_lfs_files(repo_id, token):
331
+ """
332
+ 获取远程所有的LFS文件列表
333
+ """
334
+ try:
335
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
336
+ headers = {
337
+ "content-type": "application/json",
338
+ "Authorization": f"Bearer {token}",
339
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
340
+ }
341
+
342
+ response = requests.get(url, headers=headers)
343
+ if response.status_code == 200:
344
+ return response.json()
345
+ else:
346
+ print(f"获取远程LFS文件失败: {response.status_code}")
347
+ return []
348
+ except Exception as e:
349
+ print(f"获取远程LFS文件时出错: {e}")
350
+ return []
351
+
352
+
353
+ def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
354
+ """
355
+ 清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
356
+ """
357
+ try:
358
+ original_dir = os.getcwd()
359
+ os.chdir(repo_path)
360
+
361
+ print("检查孤儿LFS引用...")
362
+
363
+ # 获取远程LFS文件
364
+ remote_files = get_remote_lfs_files(repo_id, token)
365
+ if not remote_files:
366
+ print("无法获取远程LFS文件列表")
367
+ return
368
+
369
+ # 获取本地文件
370
+ local_files = set(glob.glob('*.tar.gz'))
371
+
372
+ # 找出远程存在但本地不存在的文件
373
+ orphaned_files = []
374
+ for remote_file in remote_files:
375
+ filename = remote_file.get('filename')
376
+ if filename and filename not in local_files:
377
+ orphaned_files.append(filename)
378
+
379
+ if orphaned_files:
380
+ print(f"发现孤儿LFS引用: {orphaned_files}")
381
+
382
+ # 删除这些孤儿引用
383
+ for filename in orphaned_files:
384
+ print(f"删除孤儿LFS引用: {filename}")
385
+ delete_huggingface_lfs_file(filename, repo_id, token)
386
+
387
+ print("孤儿LFS引用清理完成")
388
+ os.chdir(original_dir)
389
+
390
+ except Exception as e:
391
+ print(f"清理孤儿LFS引用时出错: {e}")
392
+ os.chdir(original_dir)
393
+
394
+
395
+ def compress_folder(folder_path, output_dir, keep_count=3):
396
+ try:
397
+ # 确保输出目录存在
398
+ os.makedirs(output_dir, exist_ok=True)
399
+
400
+ # 设置中国时区
401
+ china_tz = pytz.timezone('Asia/Shanghai')
402
+
403
+ # 获取当前中国时间的时间戳
404
+ timestamp = str(int(datetime.now(china_tz).timestamp() * 1000))
405
+ output_path = os.path.join(output_dir, f'{timestamp}.tar.gz')
406
+
407
+ # 获取所有压缩包
408
+ existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
409
+
410
+ # 安全地提取时间戳
411
+ def extract_timestamp(filename):
412
+ match = re.search(r'(\d+)\.tar\.gz$', filename)
413
+ return int(match.group(1)) if match else 0
414
+
415
+ files_to_cleanup = []
416
+
417
+ # 如果压缩包数量超过保留数量,删除最旧的
418
+ if len(existing_archives) >= keep_count:
419
+ # 按时间戳排序(从小到大,最旧的在前面)
420
+ existing_archives.sort(key=extract_timestamp)
421
+
422
+ # 计算需要删除的数量
423
+ delete_count = len(existing_archives) - keep_count + 1
424
+
425
+ # 删除最旧的压缩包
426
+ for i in range(delete_count):
427
+ oldest_archive = existing_archives[i]
428
+ oldest_filename = os.path.basename(oldest_archive)
429
+
430
+ try:
431
+ # 删除本地文件
432
+ os.remove(oldest_archive)
433
+ print(f"删除最旧的压缩包:{oldest_filename}")
434
+
435
+ # 记录需要清理的文件名
436
+ files_to_cleanup.append(oldest_filename)
437
+
438
+ # 删除Hugging Face LFS文件记录
439
+ print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
440
+ delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
441
+
442
+ except Exception as e:
443
+ print(f"删除失败 {oldest_archive}: {e}")
444
+
445
+ # 如果有文件需要从Git历史中清理,执行安全清理
446
+ if files_to_cleanup:
447
+ print(f"执行安全Git清理: {files_to_cleanup}")
448
+ safe_git_cleanup(output_dir, files_to_cleanup)
449
+
450
+ # tar.gz 压缩
451
+ result = subprocess.run(
452
+ ['tar', '-czf', output_path, folder_path],
453
+ capture_output=True,
454
+ text=True
455
+ )
456
+
457
+ if result.returncode == 0:
458
+ # 计算压缩包大小
459
+ file_size = os.path.getsize(output_path) / 1024 / 1024
460
+
461
+ # 格式化中国时区的时间
462
+ china_time = datetime.now(china_tz)
463
+ formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
464
+
465
+ print(f"压缩成功:{output_path}")
466
+ print(f"压缩大小:{file_size:.2f} MB")
467
+ print(f"压缩时间:{formatted_time}")
468
+ print(f"保留策略:最多保留 {keep_count} 个备份包")
469
+
470
+ # 返回压缩包名和大小信息
471
+ return f"{os.path.basename(output_path)} MB:{file_size:.2f}MB TIME:{formatted_time}"
472
+ else:
473
+ print("压缩失败")
474
+ print("错误信息:", result.stderr)
475
+ return None
476
+
477
+ except Exception as e:
478
+ print(f"压缩出错: {e}")
479
+ return None
480
+
481
+
482
+ # 调用函数
483
+ # new_archive = compress_folder('/data/dv1', 'nezha-hf')
484
+ def github(type):
485
+ if type == 1:
486
+ os.system(f'rm -rf /data/{HF_REPO}')
487
+ if not os.path.exists(f'/data/{HF_REPO}'):
488
+ git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
489
+ print(git)
490
+ os.system(git)
491
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
492
+ os.system(f'git config --global user.name "{HF_USER1}"')
493
+ os.chdir(f'/data/{HF_REPO}')
494
+ if type == 2:
495
+ repo_path = f'/data/{HF_REPO}'
496
+ repo_id = f"{HF_USER1}/{HF_REPO}"
497
+ os.chdir(f'/data/{HF_REPO}')
498
+ print("开始备份上传HF")
499
+ #先清理孤儿LFS引用
500
+ cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
501
+ # 执行Git清理(不影响现有文件)
502
+ os.system('git lfs prune')
503
+ os.system('git gc --auto')
504
+ # 备份上传仓库
505
+ new_archive_info = compress_folder('/data/dv1', f'/data/{HF_REPO}', keep_count=3)
506
+ if new_archive_info:
507
+ new_archive, file_size_info = new_archive_info.split('MB:')
508
+ os.system(f'git add .')
509
+ os.system(f'git commit -m "{file_size_info}"')
510
+ # 正常推送(不再需要强制推送)
511
+ push_result = os.system('git push origin main')
512
+ if push_result != 0:
513
+ print("推送失败,可能有冲突,尝试拉取并合并...")
514
+ os.system('git pull origin main --rebase')
515
+ os.system('git push origin main')
516
+
517
+ # 轻度清理
518
+ os.system('git gc --auto')
519
+ os.system('git lfs prune')
520
+ else:
521
+ print("压缩失败,无法提交")
522
+ def nginx():
523
+ # 确保目录存在
524
+ os.makedirs('/data/nginx1.24', exist_ok=True)
525
+ # 写入文件
526
+ with open('/data/nginx1.24/mime.types', 'w') as f:
527
+ f.write(mime_types_content)
528
+ # 设置文件权限(可选)
529
+ os.chmod('/data/nginx1.24/mime.types', 0o644)
530
+ print("mime.types 文件已创建")
531
+ # time.sleep(10)
532
+ # os.system("rm -rf /data/nginx.conf")
533
+ # os.system("wget -O '/data/nginx.conf' -q 'https://raw.githubusercontent.com/qilan28/hf-nezha/refs/heads/main/nginx.conf'")
534
+ with open('/data/nginx.conf', 'w') as f:
535
+ f.write(nginx_conf)
536
+ os.system("/data/nginx1.24/sbin/nginx -c /data/nginx.conf")
537
+
538
+ def dv1():
539
+ os.system("rm -rf /data/dv1.zip /data/dashboard-linux-amd64 /data/dv1 /data/data")
540
+ latest_package = get_latest_local_package(f'/data/{HF_REPO}')
541
+ if latest_package:
542
+
543
+ print(f"最新压缩包路径: {latest_package}")
544
+ print("通过备份包启动")
545
+ # tar -xzvf /data/nezha-hf/1759393184994.tar.gz -C /data
546
+ # tar -xzvf /data/nezha-hf/1759393184994.tar.gz --strip-components=2 -C /data dv1/
547
+ print(f"解压:tar -xzvf {latest_package} -C /data")
548
+ os.system(f"tar -xzvf {latest_package} -C /data")
549
+
550
+ os.system("mv /data/data/dv1/ /data")
551
+ os.system("rm -rf /data/data")
552
+ os.chdir('/data/dv1')
553
+
554
+ # 读取 YAML 文件
555
+ with open('/data/dv1/data/config.yaml', 'r') as f:
556
+ config = yaml.safe_load(f)
557
+ # 修改 listen_port
558
+ config['listen_port'] = int(N_PORT) # 如果端口号需要是整数
559
+ # 写回文件
560
+ with open('/data/dv1/data/config.yaml', 'w') as f:
561
+ yaml.dump(config, f, default_flow_style=False)
562
+
563
+ else:
564
+ print("通过下载程序启动")
565
+ if not os.path.exists('/data/dv1'):
566
+ os.makedirs('/data/dv1')
567
+ if not os.path.exists('/data/dv1/data'):
568
+ os.system("rm -rf /data/dv1/data/config.yaml /data/dv1/data/sqlite.db")
569
+ os.makedirs('/data/dv1/data')
570
+ with open('/data/dv1/data/config.yaml', 'w') as file:
571
+ yaml.dump(dashboard_config, file, default_flow_style=False)
572
+ print("配置文件已写入 /data/dv1/data/config.yaml")
573
+ print("下载'https://github.com/qilan28/hf-nezha/raw/refs/heads/main/sqlite.db'")
574
+ os.system("wget -O '/data/dv1/data/sqlite.db' 'https://github.com/qilan28/hf-nezha/raw/refs/heads/main/sqlite.db'")
575
+ os.chdir('/data/dv1')
576
+ print(f"下载'https://github.com/nezhahq/nezha/releases/download/{DASHBOARD_VERSION}/dashboard-linux-amd64.zip'")
577
+ os.system(f"wget -O '/data/dv1/dv1.zip' -q 'https://github.com/nezhahq/nezha/releases/download/{DASHBOARD_VERSION}/dashboard-linux-amd64.zip'")
578
+ os.system("unzip -o /data/dv1/dv1.zip -d /data/dv1")
579
+ os.system("rm -rf /data/dv1/dv1.zip")
580
+ os.system("chmod +x /data/dv1/dashboard-linux-amd64")
581
+ os.system("mv /data/dv1/dashboard-linux-amd64 /data/dv1/dv1")
582
+ if os.path.exists('/data/dv1/dv1') and os.path.isfile('/data/dv1/dv1'):
583
+ print("dv1存在开始启动")
584
+ threading.Thread(target=repeat_task, daemon=True).start()
585
+ threading.Thread(target=nginx, daemon=True).start()
586
+ threading.Thread(target=cf, daemon=True).start()
587
+ threading.Thread(target=nv1_agent, daemon=True).start()
588
+ threading.Thread(target=check_system_resources, daemon=True).start()
589
+ # os.system('/data/dv1/dv1')
590
+ os.system('nohup /data/dv1/dv1 >> /dev/null 2>&1 &')
591
+ else:
592
+ print("dv1不存在")
593
+
594
+ def nv1_agent():
595
+ # time.sleep(10)
596
+ os.system("rm -rf /data/nv1.zip /data/nezha-agent /data/nv1")
597
+ print(f"下载'https://github.com/nezhahq/agent/releases/download/{NZV1_VERSION}/nezha-agent_linux_amd64.zip'")
598
+ os.system(f"wget -O '/data/nv1.zip' -q 'https://github.com/nezhahq/agent/releases/download/{NZV1_VERSION}/nezha-agent_linux_amd64.zip'")
599
+ time.sleep(2)
600
+ os.system("unzip -o /data/nv1.zip -d /data")
601
+ os.system("chmod +x /data/nezha-agent")
602
+ os.makedirs('/data', exist_ok=True)
603
+ # 写入 YAML 文件
604
+ with open('/data/config.yml', 'w') as file:
605
+ yaml.dump(agent_config, file, default_flow_style=False)
606
+ print("配置文件已写入 /data/config.yml")
607
+ time.sleep(2)
608
+ os.system("rm -rf /data/nv1.zip")
609
+ os.system("mv /data/nezha-agent /data/nv1")
610
+ os.system("nohup /data/nv1 -c /data/config.yml >> /dev/null 2>&1 &")
611
+
612
+ def cf():
613
+ os.system("rm -rf /data/cf")
614
+ os.system("wget -O '/data/cf' -q 'https://huggingface.co/datasets/Qilan2/ff/resolve/main/nv1/cf-linux-amd64?download=true'")
615
+ os.system("chmod +x /data/cf")
616
+ os.system(f'nohup /data/cf tunnel run --protocol http2 --token {ARGO_AUTH} >> /dev/null 2>&1 &')
617
+ def _reconstruct_token(partial_token):
618
+ return partial_token.replace(" ", "")
619
+ def restart_huggingface_space(space_name, space_id, partial_token):
620
+ token = _reconstruct_token(partial_token)
621
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
622
+ headers = {
623
+ "Content-Type": "application/json",
624
+ "Authorization": f"Bearer {token}",
625
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
626
+ }
627
+ try:
628
+ response = requests.post(url, headers=headers, json={})
629
+ return {
630
+ "status_code": response.status_code,
631
+ "success": response.status_code == 200,
632
+ "message": response.text
633
+ }
634
+ except requests.RequestException as e:
635
+ return {
636
+ "status_code": None,
637
+ "success": False,
638
+ "message": str(e)
639
+ }
640
+ def check_system_resources():
641
+ time.sleep(120)
642
+ cpu_usage = psutil.cpu_percent(interval=1)
643
+ memory = psutil.virtual_memory()
644
+ memory_usage = memory.percent
645
+ # if cpu_usage >= 90:
646
+ if cpu_usage >= 90 or memory_usage >= 95:
647
+ print("占用过高")
648
+ print(HF_USER2, HF_ID, HF_TOKEN2)
649
+ result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKEN2)
650
+ print(result)
651
+ else:
652
+ print("系统资源正常")
653
+
654
+ def repeat_task():
655
+ print('备份线程启动')
656
+ while True:
657
+ print(f"打包时间:{BACKUP_TIME} 秒")
658
+ time.sleep(int(BACKUP_TIME))# 2小时
659
+ github(2)
660
+ github(1)
661
+ os.chdir('/data/')
662
+ dv1()
663
+ if os.path.exists('/data/dv1/dv1') and os.path.isfile('/data/dv1/dv1'):
664
+ print('等待重启中。。。')
665
+ while True:
666
+ time.sleep(14400)# 4小时 14400 6小时 21600
667
+ github(2)
668
+ print(HF_USER2, HF_ID, HF_TOKEN2)
669
+ result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKEN2)
670
+ print(result)
671
+ # break
672
+ # github(2)
673
+ # nv1_agent()