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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
13
+ N_PORT = os.environ.get('N_PORT', '8008') # N Z端口 默认8008
14
+ ARGO_PORT = os.environ.get('ARGO_PORT', '8009') # Argo(nginx的反代端口)固定隧道端口,留空默认8009
15
+ ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', '') # Argo固定隧道域名,留空即使用临时隧道
16
+ ARGO_AUTH = os.environ.get('ARGO_AUTH', '') # Argo固定隧道密钥,留空即使用临时隧道
17
+ DASHBOARD_VERSION = os.environ.get('DASHBOARD_VERSION', 'v1.13.2')# 指定面板的版本,以 v0.00.00 的格式,后续将固定在该版本不会升级,不填则使用默认的 v1.13.2
18
+ NZV1_VERSION = os.environ.get('NZV1_VERSION', 'v1.13.1')# 哪吒V1的版本默认v1.13.1
19
+ BACKUP_TIME = os.environ.get('BACKUP_TIME', '10800')# 备份时间 10800秒 2小时
20
+ BACKUP_TIME =120
21
+
22
+ HF_USER1 = os.environ.get('HF_USER1', '')# HF 备份仓库的用户名
23
+ HF_REPO = os.environ.get('HF_REPO', '')#HF 备份的Models仓库名
24
+ HF_EMAIL = os.environ.get('HF_EMAIL', '') #HF的邮箱
25
+ HF_TOKEN1 = os.environ.get('HF_TOKEN1', '')#HF备份账号的TOKEN
26
+
27
+ HF_USER2 = os.environ.get('HF_USER2', '')# huggingface 用户名
28
+ HF_ID = os.environ.get('HF_ID', '')# huggingface space 名
29
+ HF_TOKEN2 = os.environ.get('HF_TOKEN2', '')# huggingface TOKEN
30
+ #JUPYTER_TOKEN
31
+ agent_config = {
32
+ 'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
33
+ 'debug': False,
34
+ 'disable_auto_update': True,
35
+ 'disable_command_execute': False,
36
+ 'disable_force_update': False,
37
+ 'disable_nat': False,
38
+ 'disable_send_query': False,
39
+ 'gpu': False,
40
+ 'insecure_tls': False,
41
+ 'ip_report_period': 1800,
42
+ 'report_delay': 3,
43
+ 'self_update_period': 0,
44
+ 'server': f'{ARGO_DOMAIN}:443',
45
+ 'skip_connection_count': False,
46
+ 'skip_procs_count': False,
47
+ 'temperature': True,
48
+ 'tls': True,
49
+ 'use_gitee_to_upgrade': False,
50
+ 'use_ipv6_country_code': False,
51
+ 'uuid': '18a49016-bc2d-4be9-0ddb-5357fdbf0b3d'
52
+ }
53
+ dashboard_config = {
54
+ 'admin_template': 'admin-dist',
55
+ 'agent_secret_key': '',
56
+ 'avg_ping_count': 2,
57
+ 'cover': 1,
58
+ 'https': {}, # 空字典
59
+ 'install_host': f'{ARGO_DOMAIN}:443',
60
+ 'ip_change_notification_group_id': 0,
61
+ 'jwt_secret_key': '',
62
+ 'jwt_timeout': 300,
63
+ 'language': 'zh_CN',
64
+ 'listen_port': f'{N_PORT}',
65
+ 'location': 'Asia/Shanghai',
66
+ 'site_name': '鸡子探针平台-柒蓝',
67
+ 'tls': True,
68
+ 'user_template': 'user-dist'
69
+ }
70
+
71
+ mime_types_content = """types {
72
+ text/html html htm shtml;
73
+ text/css css;
74
+ text/javascript js;
75
+ image/gif gif;
76
+ image/jpeg jpeg jpg;
77
+ image/png png;
78
+ text/plain txt;
79
+ application/json json;
80
+ application/xml xml;
81
+ application/octet-stream bin;
82
+ }"""
83
+
84
+ nginx_conf = """
85
+ # 全局配置
86
+ worker_processes auto;
87
+ pid /tmp/nginx.pid;
88
+ error_log /tmp/nginx_error.log;
89
+
90
+ events {
91
+ worker_connections 768;
92
+ }
93
+
94
+ http {
95
+ sendfile on;
96
+ tcp_nopush on;
97
+ tcp_nodelay on;
98
+ keepalive_timeout 65;
99
+ types_hash_max_size 2048;
100
+
101
+ # 修改 mime.types 路径
102
+ include /data/nginx1.24/mime.types;
103
+ default_type application/octet-stream;
104
+
105
+ # SSL配置
106
+ ssl_protocols TLSv1.2 TLSv1.3;
107
+ ssl_prefer_server_ciphers on;
108
+
109
+ access_log /tmp/nginx_access.log;
110
+ gzip on;
111
+
112
+ # 上游服务器配置
113
+ upstream dashboard {
114
+ server 127.0.0.1:%s;
115
+ keepalive 512;
116
+ }
117
+
118
+ # 服务器块
119
+ server {
120
+ listen %s;
121
+ listen [::]:%s;
122
+
123
+ server_name %s;
124
+
125
+ # 删除所有 real_ip 相关配置
126
+ underscores_in_headers on;
127
+
128
+ # gRPC相关
129
+ location ^~ /proto.NezhaService/ {
130
+ grpc_set_header Host $host;
131
+ grpc_read_timeout 600s;
132
+ grpc_send_timeout 600s;
133
+ grpc_socket_keepalive on;
134
+ client_max_body_size 10m;
135
+ grpc_buffer_size 4m;
136
+ grpc_pass grpc://dashboard;
137
+ }
138
+
139
+ # WebSocket相关
140
+ location ~* ^/api/v1/ws/(server|terminal|file)(.*)$ {
141
+ proxy_set_header Host $host;
142
+ proxy_set_header Origin https://$host;
143
+ proxy_set_header Upgrade $http_upgrade;
144
+ proxy_set_header Connection "upgrade";
145
+ proxy_read_timeout 3600s;
146
+ proxy_send_timeout 3600s;
147
+ proxy_pass http://127.0.0.1:%s;
148
+ }
149
+
150
+ # Web请求处理
151
+ location / {
152
+ proxy_set_header Host $host;
153
+ proxy_read_timeout 3600s;
154
+ proxy_send_timeout 3600s;
155
+ proxy_buffer_size 128k;
156
+ proxy_buffers 4 256k;
157
+ proxy_busy_buffers_size 256k;
158
+ proxy_max_temp_file_size 0;
159
+ proxy_pass http://127.0.0.1:%s;
160
+ }
161
+
162
+ # 安全头部
163
+ add_header X-Frame-Options SAMEORIGIN;
164
+ add_header X-Content-Type-Options nosniff;
165
+ add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
166
+ }
167
+ }
168
+ """ % (N_PORT, ARGO_PORT, ARGO_PORT, ARGO_DOMAIN, N_PORT, N_PORT)
169
+
170
+ stop_event = threading.Event()
171
+
172
+ def kill_processes():
173
+ # 要结束的进程名列表
174
+ target_processes = [
175
+ 'cf',
176
+ 'nv1',
177
+ 'dv1',
178
+ 'nginx'
179
+ ]
180
+
181
+ # 存储已结束的进程
182
+ killed_processes = []
183
+
184
+ # 遍历所有正在运行的进程
185
+ for proc in psutil.process_iter(['name']):
186
+ try:
187
+ # 检查进程名是否在目标列表中
188
+ if proc.info['name'] in target_processes:
189
+ # 获取进程ID
190
+ pid = proc.pid
191
+
192
+ # 先尝试优雅地结束进程
193
+ proc.terminate()
194
+
195
+ # 等待进程结束
196
+ try:
197
+ proc.wait(timeout=3)
198
+ except psutil.TimeoutExpired:
199
+ # 如果进程未响应,强制杀死
200
+ proc.kill()
201
+
202
+ killed_processes.append(f"{proc.info['name']} (PID: {pid})")
203
+
204
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
205
+ pass
206
+
207
+ # 打印已结束的进程
208
+ if killed_processes:
209
+ print("已结束以下进程:")
210
+ for process in killed_processes:
211
+ print(process)
212
+ else:
213
+ print("未找到匹配的进程")
214
+ kill_processes()
215
+ def get_latest_local_package(directory, pattern='*.tar.gz'):
216
+ try:
217
+ # 构建完整的搜索路径
218
+ search_pattern = os.path.join(directory, pattern)
219
+
220
+ # 查找所有匹配的文件
221
+ files = glob.glob(search_pattern)
222
+
223
+ if not files:
224
+ print("未找到匹配的 nezha-hf 压缩包")
225
+ return None
226
+
227
+ # 获取最新的文件
228
+ latest_file = max(files, key=os.path.getmtime)
229
+
230
+ print(f"找到最新的包: {latest_file}")
231
+ return latest_file
232
+
233
+ except Exception as e:
234
+ print(f"获取最新包时发生错误: {e}")
235
+ return None
236
+
237
+ def compress_folder(folder_path, output_dir, keep_count=3):
238
+ try:
239
+ # 确保输出目录存在
240
+ os.makedirs(output_dir, exist_ok=True)
241
+
242
+ # 使用 pytz 获取中国时区的当前时间戳(毫秒级)
243
+ import pytz
244
+ from datetime import datetime
245
+
246
+ # 设置中国时区
247
+ china_tz = pytz.timezone('Asia/Shanghai')
248
+
249
+ # 获取当前中国时间的时间戳
250
+ timestamp = str(int(datetime.now(china_tz).timestamp() * 1000))
251
+ output_path = os.path.join(output_dir, f'{timestamp}.tar.gz')
252
+
253
+ # 获取所有压缩包
254
+ existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
255
+
256
+ # 安全地提取时间戳
257
+ def extract_timestamp(filename):
258
+ # 提取文件名中的数字部分
259
+ match = re.search(r'(\d+)\.tar\.gz$', filename)
260
+ return int(match.group(1)) if match else 0
261
+
262
+ # 如果压缩包数量超过保留数量,删除最旧的
263
+ if len(existing_archives) >= keep_count:
264
+ # 按时间戳排序(从小到大,最旧的在前面)
265
+ existing_archives.sort(key=extract_timestamp)
266
+
267
+ # 计算需要删除的数量
268
+ delete_count = len(existing_archives) - keep_count + 1
269
+
270
+ # 删除最旧的压缩包
271
+ for i in range(delete_count):
272
+ oldest_archive = existing_archives[i]
273
+ try:
274
+ os.remove(oldest_archive)
275
+ print(f"删除最旧的压缩包:{os.path.basename(oldest_archive)}")
276
+ except Exception as e:
277
+ print(f"删除失败 {oldest_archive}: {e}")
278
+
279
+ # tar.gz 压缩
280
+ result = subprocess.run(
281
+ ['tar', '-czvf', output_path, folder_path],
282
+ capture_output=True,
283
+ text=True
284
+ )
285
+
286
+ if result.returncode == 0:
287
+ # 计算压缩包大小
288
+ file_size = os.path.getsize(output_path) / 1024 / 1024
289
+
290
+ # 格式化中国时区的时间
291
+ china_time = datetime.now(china_tz)
292
+ formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
293
+
294
+ print(f"压缩成功:{output_path}")
295
+ print(f"压缩大小:{file_size:.2f} MB")
296
+ print(f"压缩时间:{formatted_time}")
297
+ print(f"保留策略:最多保留 {keep_count} 个备份包")
298
+
299
+ # 返回压缩包名和大小信息
300
+ return f"{os.path.basename(output_path)} MB:{file_size:.2f} MB TIME:{formatted_time}"
301
+ else:
302
+ print("压缩失败")
303
+ print("错误信息:", result.stderr)
304
+ return None
305
+
306
+ except Exception as e:
307
+ print(f"压缩出错: {e}")
308
+ return None
309
+
310
+
311
+ # 调用函数
312
+ # new_archive = compress_folder('/data/dv1', 'nezha-hf')
313
+ def github(type):
314
+ if type == 1:
315
+ os.system(f'rm -rf /data/{HF_REPO}')
316
+ if not os.path.exists(f'/data/{HF_REPO}'):
317
+ git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
318
+ print(git)
319
+ os.system(git)
320
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
321
+ os.system(f'git config --global user.name "{HF_USER1}"')
322
+ os.chdir(f'/data/{HF_REPO}')
323
+ if type == 2:
324
+ os.chdir(f'/data/{HF_REPO}')
325
+ print("开始备份上传HF")
326
+ # 清理 LFS 存储
327
+ os.system('git lfs prune')
328
+ # 备份上传仓库
329
+ new_archive_info = compress_folder('/data/dv1', f'/data/{HF_REPO}', keep_count=3)
330
+ if new_archive_info:
331
+ new_archive, file_size_info = new_archive_info.split(' MB:')
332
+ os.system(f'git add .')
333
+ os.system(f'git commit -m "{file_size_info}"')
334
+ # os.system('git push -u origin main')
335
+ # 使用强制推送并清理
336
+ os.system('git push -f origin main')
337
+ os.system('git gc --prune=now')
338
+ else:
339
+ print("压缩失败,无法提交")
340
+ def nginx():
341
+ # 确保目录存在
342
+ os.makedirs('/data/nginx1.24', exist_ok=True)
343
+ # 写入文件
344
+ with open('/data/nginx1.24/mime.types', 'w') as f:
345
+ f.write(mime_types_content)
346
+ # 设置文件权限(可选)
347
+ os.chmod('/data/nginx1.24/mime.types', 0o644)
348
+ print("mime.types 文件已创建")
349
+ # time.sleep(10)
350
+ # os.system("rm -rf /data/nginx.conf")
351
+ # os.system("wget -O '/data/nginx.conf' -q 'https://raw.githubusercontent.com/qilan28/hf-nezha/refs/heads/main/nginx.conf'")
352
+ with open('/data/nginx.conf', 'w') as f:
353
+ f.write(nginx_conf)
354
+ os.system("/data/nginx1.24/sbin/nginx -c /data/nginx.conf")
355
+ def dv1():
356
+ os.system("rm -rf /data/dv1.zip /data/dashboard-linux-amd64 /data/dv1 /data/data")
357
+ latest_package = get_latest_local_package(f'/data/{HF_REPO}')
358
+ if latest_package:
359
+
360
+ print(f"最新压缩包路径: {latest_package}")
361
+ print("通过备份包启动")
362
+ # tar -xzvf /data/nezha-hf/1759393184994.tar.gz -C /data
363
+ # tar -xzvf /data/nezha-hf/1759393184994.tar.gz --strip-components=2 -C /data dv1/
364
+ print(f"解压:tar -xzvf {latest_package} -C /data")
365
+ os.system(f"tar -xzvf {latest_package} -C /data")
366
+
367
+ os.system("mv /data/data/dv1/ /data")
368
+ os.system("rm -rf /data/data")
369
+
370
+ os.chdir('/data/dv1')
371
+ else:
372
+ print("通过下载程序启动")
373
+ if not os.path.exists('/data/dv1'):
374
+ os.makedirs('/data/dv1')
375
+ if not os.path.exists('/data/dv1/data'):
376
+ os.system("rm -rf /data/dv1/data/config.yaml /data/dv1/data/sqlite.db")
377
+ os.makedirs('/data/dv1/data')
378
+ with open('/data/dv1/data/config.yaml', 'w') as file:
379
+ yaml.dump(dashboard_config, file, default_flow_style=False)
380
+ print("配置文件已写入 /data/dv1/data/config.yaml")
381
+ print("下载'https://github.com/qilan28/hf-nezha/raw/refs/heads/main/sqlite.db'")
382
+ os.system("wget -O '/data/dv1/data/sqlite.db' 'https://github.com/qilan28/hf-nezha/raw/refs/heads/main/sqlite.db'")
383
+ os.chdir('/data/dv1')
384
+ print(f"下载'https://github.com/nezhahq/nezha/releases/download/{DASHBOARD_VERSION}/dashboard-linux-amd64.zip'")
385
+ os.system(f"wget -O '/data/dv1/dv1.zip' -q 'https://github.com/nezhahq/nezha/releases/download/{DASHBOARD_VERSION}/dashboard-linux-amd64.zip'")
386
+ os.system("unzip -o /data/dv1/dv1.zip -d /data/dv1")
387
+ os.system("rm -rf /data/dv1/dv1.zip")
388
+ os.system("chmod +x /data/dv1/dashboard-linux-amd64")
389
+ os.system("mv /data/dv1/dashboard-linux-amd64 /data/dv1/dv1")
390
+ if os.path.exists('/data/dv1/dv1') and os.path.isfile('/data/dv1/dv1'):
391
+ print("dv1存在开始启动")
392
+ threading.Thread(target=repeat_task, daemon=True).start()
393
+ threading.Thread(target=nginx, daemon=True).start()
394
+ threading.Thread(target=cf, daemon=True).start()
395
+ threading.Thread(target=nv1_agent, daemon=True).start()
396
+ threading.Thread(target=check_system_resources, daemon=True).start()
397
+ os.system('/data/dv1/dv1')
398
+ # os.system('nohup /data/dv1/dv1 >> /dev/null 2>&1 &')
399
+ else:
400
+ print("dv1不存在")
401
+
402
+ def nv1_agent():
403
+ # time.sleep(10)
404
+ os.system("rm -rf /data/nv1.zip /data/nezha-agent /data/nv1")
405
+ print(f"下载'https://github.com/nezhahq/agent/releases/download/{NZV1_VERSION}/nezha-agent_linux_amd64.zip'")
406
+ os.system(f"wget -O '/data/nv1.zip' -q 'https://github.com/nezhahq/agent/releases/download/{NZV1_VERSION}/nezha-agent_linux_amd64.zip'")
407
+ time.sleep(2)
408
+ os.system("unzip -o /data/nv1.zip -d /data")
409
+ os.system("chmod +x /data/nezha-agent")
410
+ os.makedirs('/data', exist_ok=True)
411
+ # 写入 YAML 文件
412
+ with open('/data/config.yml', 'w') as file:
413
+ yaml.dump(agent_config, file, default_flow_style=False)
414
+ print("配置文件已写入 /data/config.yml")
415
+ time.sleep(2)
416
+ os.system("rm -rf /data/nv1.zip")
417
+ os.system("mv /data/nezha-agent /data/nv1")
418
+ os.system("nohup /data/nv1 -c /data/config.yml >> /dev/null 2>&1 &")
419
+
420
+ def cf():
421
+ os.system("rm -rf /data/cf")
422
+ os.system("wget -O '/data/cf' -q 'https://github.com/cloudflare/cloudflared/releases/download/2025.9.0/cloudflared-linux-amd64'")
423
+ os.system("chmod +x /data/cf")
424
+ os.system(f'nohup /data/cf tunnel run --protocol http2 --token {ARGO_AUTH} >> /dev/null 2>&1 &')
425
+ def _reconstruct_token(partial_token):
426
+ return partial_token.replace(" ", "")
427
+ def restart_huggingface_space(space_name, space_id, partial_token):
428
+ token = _reconstruct_token(partial_token)
429
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
430
+ headers = {
431
+ "Content-Type": "application/json",
432
+ "Authorization": f"Bearer {token}",
433
+ "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"
434
+ }
435
+ try:
436
+ response = requests.post(url, headers=headers, json={})
437
+ return {
438
+ "status_code": response.status_code,
439
+ "success": response.status_code == 200,
440
+ "message": response.text
441
+ }
442
+ except requests.RequestException as e:
443
+ return {
444
+ "status_code": None,
445
+ "success": False,
446
+ "message": str(e)
447
+ }
448
+ def check_system_resources():
449
+ time.sleep(120)
450
+ cpu_usage = psutil.cpu_percent(interval=1)
451
+ memory = psutil.virtual_memory()
452
+ memory_usage = memory.percent
453
+ # if cpu_usage >= 90:
454
+ if cpu_usage >= 90 or memory_usage >= 95:
455
+ print("占用过高")
456
+ print(HF_USER2, HF_ID, HF_TOKEN2)
457
+ result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKEN2)
458
+ print(result)
459
+ else:
460
+ print("系统资源正常")
461
+
462
+ def repeat_task():
463
+ print('备份线程启动')
464
+ while True:
465
+ print(f"打包时间:{BACKUP_TIME} 秒")
466
+ time.sleep(int(BACKUP_TIME))# 2小时
467
+ github(2)
468
+ github(1)
469
+ os.chdir('/data/')
470
+ dv1()
471
+ if os.path.exists('/data/dv1/dv1') and os.path.isfile('/data/dv1/dv1'):
472
+ print('等待重启中。。。')
473
+ while True:
474
+ time.sleep(14400)# 4小时 14400 6小时 21600
475
+ github(2)
476
+ print(HF_USER2, HF_ID, HF_TOKEN2)
477
+ result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKEN2)
478
+ print(result)
479
+ # break
480
+ # github(2)
481
+ # nv1_agent()