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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
+ import requests
13
+ import shutil
14
+
15
+ BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200') # 备份时间 10800秒 2小时
16
+ HF_USER1 = os.environ.get('HF_USER1', 'jkuiii') # HF 备份仓库的用户名
17
+ HF_REPO = os.environ.get('HF_REPO', 'st13') # HF 备份的Models仓库名
18
+ HF_EMAIL = os.environ.get('HF_EMAIL', 'st13-bf@282820.xyz') # HF的邮箱
19
+ HF_TOKEN1 = os.environ.get('HF_TOKEN1', '') # HF备份账号的TOKEN
20
+
21
+ HF_USER2 = os.environ.get('HF_USER2', '') # huggingface 用户名
22
+ HF_ID = os.environ.get('HF_ID', '') # huggingface space 名
23
+ HF_TOKON2 = os.environ.get('HF_TOKON2', '') # huggingface TOKEN
24
+
25
+
26
+
27
+ def get_latest_local_package(directory, pattern='*.tar.gz'):
28
+ try:
29
+ # 构建完整的搜索路径
30
+ search_pattern = os.path.join(directory, pattern)
31
+
32
+ # 查找所有匹配的文件
33
+ files = glob.glob(search_pattern)
34
+
35
+ if not files:
36
+ print("未找到匹配的 nezha-hf 压缩包")
37
+ return None
38
+
39
+ # 获取最新的文件
40
+ latest_file = max(files, key=os.path.getmtime)
41
+
42
+ print(f"找到最新的包: {latest_file}")
43
+ return latest_file
44
+
45
+ except Exception as e:
46
+ print(f"获取最新包时发生错误: {e}")
47
+ return None
48
+
49
+
50
+ def delete_huggingface_lfs_file(filename, repo_id, token):
51
+ """
52
+ 通过Hugging Face API删除LFS文件记录
53
+ """
54
+ try:
55
+ # 1. 查询LFS文件列表
56
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
57
+ headers = {
58
+ "content-type": "application/json",
59
+ "Authorization": f"Bearer {token}",
60
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
61
+ }
62
+
63
+ response = requests.get(url, headers=headers)
64
+ if response.status_code != 200:
65
+ print(f"查询LFS文件失败: {response.status_code} - {response.text}")
66
+ return False
67
+
68
+ lfs_files = response.json()
69
+
70
+ # 2. 查找匹配的文件
71
+ file_to_delete = None
72
+ for file_info in lfs_files:
73
+ if file_info.get('filename') == filename:
74
+ file_to_delete = file_info
75
+ break
76
+
77
+ if not file_to_delete:
78
+ print(f"未找到对应的LFS文件记录: {filename}")
79
+ return False
80
+
81
+ # 3. 删除LFS文件记录
82
+ file_oid = file_to_delete['fileOid']
83
+ delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
84
+
85
+ delete_response = requests.delete(delete_url, headers=headers)
86
+ if delete_response.status_code == 200:
87
+ print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
88
+ return True
89
+ else:
90
+ print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
91
+ return False
92
+
93
+ except Exception as e:
94
+ print(f"删除LFS文件记录时出错: {e}")
95
+ return False
96
+
97
+
98
+ def safe_git_cleanup(repo_path, files_to_remove):
99
+ """
100
+ 安全的Git清理,不会影响现有的备份文件
101
+ """
102
+ try:
103
+ original_dir = os.getcwd()
104
+ os.chdir(repo_path)
105
+
106
+ print(f"执行安全Git清理: {files_to_remove}")
107
+
108
+ # 1. 首先确保工作目录是干净的
109
+ result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
110
+ if result.stdout.strip():
111
+ print("工作目录有未提交的更改,先提交...")
112
+ subprocess.run(['git', 'add', '.'], capture_output=True)
113
+ subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
114
+
115
+ # 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
116
+ for filename in files_to_remove:
117
+ if os.path.exists(filename):
118
+ print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
119
+ subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
120
+ else:
121
+ print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
122
+
123
+ # 3. 提交删除操作
124
+ if files_to_remove:
125
+ subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
126
+
127
+ # 4. 执行GC清理但不删除最近的文件
128
+ subprocess.run(['git', 'gc', '--auto'], capture_output=True)
129
+ subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
130
+
131
+ print("安全Git清理完成")
132
+ os.chdir(original_dir)
133
+ return True
134
+
135
+ except Exception as e:
136
+ print(f"安全Git清理时出错: {e}")
137
+ os.chdir(original_dir)
138
+ return False
139
+
140
+
141
+ def get_remote_lfs_files(repo_id, token):
142
+ """
143
+ 获取远程所有的LFS文件列表
144
+ """
145
+ try:
146
+ url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
147
+ headers = {
148
+ "content-type": "application/json",
149
+ "Authorization": f"Bearer {token}",
150
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
151
+ }
152
+
153
+ response = requests.get(url, headers=headers)
154
+ if response.status_code == 200:
155
+ return response.json()
156
+ else:
157
+ print(f"获取远程LFS文件失败: {response.status_code}")
158
+ return []
159
+ except Exception as e:
160
+ print(f"获取远程LFS文件时出错: {e}")
161
+ return []
162
+
163
+
164
+ def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
165
+ """
166
+ 清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
167
+ """
168
+ try:
169
+ original_dir = os.getcwd()
170
+ os.chdir(repo_path)
171
+
172
+ print("检查孤儿LFS引用...")
173
+
174
+ # 获取远程LFS文件
175
+ remote_files = get_remote_lfs_files(repo_id, token)
176
+ if not remote_files:
177
+ print("无法获取远程LFS文件列表")
178
+ return
179
+
180
+ # 获取本地文件
181
+ local_files = set(glob.glob('*.tar.gz'))
182
+
183
+ # 找出远程存在但本地不存在的文件
184
+ orphaned_files = []
185
+ for remote_file in remote_files:
186
+ filename = remote_file.get('filename')
187
+ if filename and filename not in local_files:
188
+ orphaned_files.append(filename)
189
+
190
+ if orphaned_files:
191
+ print(f"发现孤儿LFS引用: {orphaned_files}")
192
+
193
+ # 删除这些孤儿引用
194
+ for filename in orphaned_files:
195
+ print(f"删除孤儿LFS引用: {filename}")
196
+ delete_huggingface_lfs_file(filename, repo_id, token)
197
+
198
+ print("孤儿LFS引用清理完成")
199
+ os.chdir(original_dir)
200
+
201
+ except Exception as e:
202
+ print(f"清理孤儿LFS引用时出错: {e}")
203
+ os.chdir(original_dir)
204
+
205
+
206
+ def compress_folder(folder_path, output_dir, keep_days=3):
207
+ try:
208
+ # 确保输出目录存在
209
+ os.makedirs(output_dir, exist_ok=True)
210
+
211
+ # 设置中国时区
212
+ china_tz = pytz.timezone('Asia/Shanghai')
213
+
214
+ # 获取当前中国时间
215
+ current_time = datetime.now(china_tz)
216
+ # 当前日期字符串 (YYYYMMDD 格式)
217
+ current_date_str = current_time.strftime('%Y%m%d')
218
+
219
+ # 使用日期和时间戳组合命名文件,确保同一天的文件可以按时间排序
220
+ timestamp = str(int(current_time.timestamp() * 1000))
221
+ output_filename = f'{current_date_str}_{timestamp}.tar.gz'
222
+ output_path = os.path.join(output_dir, output_filename)
223
+
224
+ print(f"新备份文件名:{output_filename}")
225
+
226
+ # 获取所有压缩包
227
+ existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
228
+
229
+ # 提取日期和时间戳
230
+ def extract_date_and_timestamp(filename):
231
+ basename = os.path.basename(filename)
232
+ # 尝试匹配新格式 YYYYMMDD_timestamp.tar.gz
233
+ match = re.search(r'(\d{8})_(\d+)\.tar\.gz$', basename)
234
+ if match:
235
+ return match.group(1), int(match.group(2))
236
+
237
+ # 尝试匹配旧格式 timestamp.tar.gz (按日期分类为当前日期)
238
+ match = re.search(r'(\d+)\.tar\.gz$', basename)
239
+ if match:
240
+ return current_date_str, int(match.group(1))
241
+
242
+ return "00000000", 0 # 默认值,确保任何不匹配的文件排序在前面
243
+
244
+ # 按日期对文件分组
245
+ files_by_date = {}
246
+ for archive in existing_archives:
247
+ date_str, timestamp = extract_date_and_timestamp(archive)
248
+ if date_str not in files_by_date:
249
+ files_by_date[date_str] = []
250
+ files_by_date[date_str].append((archive, timestamp))
251
+
252
+ # 在每个日期组内按时间戳排序,并只保留最新的
253
+ latest_per_date = {}
254
+ for date_str, files in files_by_date.items():
255
+ # 按时间戳降序排序
256
+ files.sort(key=lambda x: x[1], reverse=True)
257
+ # 只保留每天最新的备份
258
+ latest_per_date[date_str] = files[0][0] # 取第一个文件路径
259
+
260
+ # 删除同一天的其他备份
261
+ for file_path, _ in files[1:]:
262
+ try:
263
+ filename = os.path.basename(file_path)
264
+ print(f"删除同一天的旧备份:{filename}")
265
+ os.remove(file_path)
266
+ # 删除Hugging Face LFS文件记录
267
+ delete_huggingface_lfs_file(filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
268
+ except Exception as e:
269
+ print(f"删除失败 {file_path}: {e}")
270
+
271
+ # 按日期排序,保留最近keep_days天的备份
272
+ dates = list(latest_per_date.keys())
273
+ dates.sort(reverse=True) # 降序排序,最新的日期在前
274
+
275
+ # 如果有超过keep_days天的备份,删除最旧的
276
+ files_to_cleanup = []
277
+ if len(dates) >= keep_days:
278
+ for old_date in dates[keep_days-1:]:
279
+ file_path = latest_per_date[old_date]
280
+ filename = os.path.basename(file_path)
281
+ try:
282
+ print(f"删除最旧日期的备份:{filename} (日期: {old_date})")
283
+ os.remove(file_path)
284
+ files_to_cleanup.append(filename)
285
+ # 删除Hugging Face LFS文件记录
286
+ delete_huggingface_lfs_file(filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
287
+ except Exception as e:
288
+ print(f"删除失败 {file_path}: {e}")
289
+
290
+ # 如果有文件需要从Git历史中清理,执行安全清理
291
+ if files_to_cleanup:
292
+ print(f"执行安全Git清理: {files_to_cleanup}")
293
+ safe_git_cleanup(output_dir, files_to_cleanup)
294
+
295
+ # tar.gz 压缩
296
+ result = subprocess.run(
297
+ ['tar', '-czf', output_path, folder_path],
298
+ capture_output=True,
299
+ text=True
300
+ )
301
+
302
+ if result.returncode == 0:
303
+ # 计算压缩包大小
304
+ file_size = os.path.getsize(output_path) / 1024 / 1024
305
+
306
+ # 格式化中国时区的时间
307
+ china_time = datetime.now(china_tz)
308
+ formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
309
+
310
+ print(f"压缩成功:{output_path}")
311
+ print(f"压缩大小:{file_size:.2f} MB")
312
+ print(f"压缩时间:{formatted_time}")
313
+ print(f"保留策略:最多保留 {keep_days} 天的备份,每天只保留最新的备份")
314
+
315
+ # 返回压缩包名和大小信息
316
+ return f"{os.path.basename(output_path)} MB:{file_size:.2f} MB TIME:{formatted_time}"
317
+ else:
318
+ print("压缩失败")
319
+ print("错误信息:", result.stderr)
320
+ return None
321
+
322
+ except Exception as e:
323
+ print(f"压缩出错: {e}")
324
+ return None
325
+
326
+
327
+ def github(type):
328
+ if type == 1:
329
+ os.system(f'rm -rf /data/{HF_REPO} /data/ST-server /data/data')
330
+ print(f'删除已完成: /data/{HF_REPO} /data/ST-server /data/data')
331
+ if not os.path.exists(f'/data/{HF_REPO}'):
332
+ git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
333
+ print(git)
334
+ os.system(git)
335
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
336
+ os.system(f'git config --global user.name "{HF_USER1}"')
337
+ os.system("ls")
338
+ latest_package = get_latest_local_package(f'/data/{HF_REPO}')
339
+ print(f"最新压缩包路径: {latest_package}")
340
+ if latest_package:
341
+ os.system(f"tar -xzf {latest_package} -C /data")
342
+ os.system("mv /data/f/ST-server /data/")
343
+ os.system("mv /data/data/f/ST-server /data/")
344
+ os.system("rm -rf /data/data /data/f")
345
+
346
+ if type == 2:
347
+ print(f"开始备份上传HF仓库:{HF_REPO}")
348
+ os.system("mkdir -p /data/f")
349
+
350
+ # 检查源目录是否存在
351
+ if not os.path.exists("/data/ST-server"):
352
+ print("错误:/data/ST-server 目录不存在!创建空目录作为占位符")
353
+ # 创建空的备份目录,以保证后续处理能够继续
354
+ os.makedirs("/data/f/ST-server", exist_ok=True)
355
+ # 创建一个标记文件标记这是空备份
356
+ with open("/data/f/ST-server/README_EMPTY_BACKUP.txt", "w") as f:
357
+ f.write("这是一个空的备份,因为备份时/data/ST-server目录不存在\n")
358
+ f.write(f"备份时间: {datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')}\n")
359
+ else:
360
+ # 创建ST-server目录但排除logs和data目录
361
+ os.system("mkdir -p /data/f/ST-server")
362
+
363
+ # 首先备份SQLite数据库以确保完整性
364
+ print("备份SQLite数据库以确保数据完整性...")
365
+ # 检查database.sqlite是否存在
366
+ if os.path.exists("/data/ST-server/database.sqlite"):
367
+ try:
368
+ # 使用Python的shutil直接复制数据库文件 - 可能会有一定风险但在无sqlite3工具的情况下是备选方案
369
+ print("复制数据库文件(注意:数据库可能正在使用中,不保证完全一致性)")
370
+ # 确保目标目录存在
371
+ os.makedirs("/data/f/ST-server", exist_ok=True)
372
+ # 使用shutil复制文件
373
+ shutil.copy2("/data/ST-server/database.sqlite", "/data/f/ST-server/database.sqlite")
374
+ print("数据库复制完成,但请注意其可能不完全一致")
375
+ except Exception as e:
376
+ print(f"复制数据库时出错: {e}")
377
+ else:
378
+ print("数据库文件不存在,跳过数据库备份")
379
+
380
+ # 复制所有文件和目录,但排除logs、data和数据库文件(已单独备份)
381
+ os.system("find /data/ST-server -maxdepth 1 -not -path '/data/ST-server/logs' -not -path '/data/ST-server/data' -not -path '/data/ST-server' -not -name 'database.sqlite' -exec cp -rf {} /data/f/ST-server/ \;")
382
+
383
+ # 复制单个文件(除了数据库)
384
+ os.system("find /data/ST-server -maxdepth 1 -type f -not -name 'database.sqlite' -exec cp -f {} /data/f/ST-server/ \;")
385
+
386
+ print("ST-server目录备份完成(排除logs和data目录)")
387
+
388
+ repo_path = f'/data/{HF_REPO}'
389
+ repo_id = f"{HF_USER1}/{HF_REPO}"
390
+
391
+ # 确保仓库目录存在
392
+ os.makedirs(repo_path, exist_ok=True)
393
+
394
+ # 尝试切换到仓库目录
395
+ try:
396
+ os.chdir(repo_path)
397
+ except Exception as e:
398
+ print(f"切换到仓库目录失败: {e}")
399
+ print(f"创建仓库目录: {repo_path}")
400
+ os.makedirs(repo_path, exist_ok=True)
401
+ os.chdir(repo_path)
402
+ os.system(f'git config --global user.email "{HF_EMAIL}"')
403
+ os.system(f'git config --global user.name "{HF_USER1}"')
404
+
405
+ # 先清理孤儿LFS引用
406
+ cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
407
+
408
+ # 执行Git清理(不影响现有文件)
409
+ os.system('git lfs prune')
410
+ os.system('git gc --auto')
411
+
412
+ # 备份上传仓库 - 保存三天的备份,每天只保留最新的备份
413
+ new_archive_info = compress_folder('/data/f', repo_path, keep_days=3)
414
+ if new_archive_info:
415
+ new_archive, file_size_info = new_archive_info.split(' MB:')
416
+
417
+ os.system("pwd")
418
+
419
+ # 检查是否有备份文件需要推送
420
+ backup_files = glob.glob(os.path.join(repo_path, '*.tar.gz'))
421
+ if not backup_files:
422
+ print("仓库中没有备份文件,跳过推送步骤")
423
+ else:
424
+ print(f"检测到 {len(backup_files)} 个备份文件,准备推送")
425
+
426
+ # 首先拉取最新更改以减少冲突
427
+ print("先拉取远程仓库的最新更改...")
428
+ pull_result = os.system('git pull origin main')
429
+ if pull_result != 0:
430
+ print("拉取远程仓库有冲突,采用强制重置方式解决...")
431
+ # 取消当前可能的冲突状态
432
+ os.system('git reset --hard')
433
+ # 拉取远程并覆盖本地
434
+ os.system('git fetch origin main')
435
+ os.system('git reset --hard origin/main')
436
+
437
+ # 确保所有文件在工作目录中可见
438
+ os.system(f'git add -A')
439
+ os.system(f'git commit -m "{file_size_info}"')
440
+
441
+ # 尝试推送,如果失败则使用强制推送
442
+ print("尝试推送到远程仓库...")
443
+ push_result = os.system('git push origin main')
444
+ if push_result != 0:
445
+ print("标准推送失败,尝试强制推送...")
446
+ # 使用强制推送
447
+ force_push_result = os.system('git push -f origin main')
448
+ if force_push_result != 0:
449
+ print("强制推送也失败,请手动检查仓库状态")
450
+ else:
451
+ print("强制推送成功")
452
+ else:
453
+ print("推送成功")
454
+
455
+ # 轻度清理
456
+ os.system('git gc --auto')
457
+ os.system('git lfs prune')
458
+ else:
459
+ print("压缩失败,无法提交")
460
+
461
+ # 清理临时文件夹
462
+ print("清理临时文件夹 /data/f...")
463
+ os.system("rm -rf /data/f")
464
+ print("临时文件夹已清理")
465
+
466
+ def _reconstruct_token(partial_token):
467
+ return partial_token.replace(" ", "")
468
+ github(1)