Update server9-bf.py
Browse files- server9-bf.py +173 -56
server9-bf.py
CHANGED
|
@@ -27,7 +27,7 @@ from IPython.display import clear_output
|
|
| 27 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 28 |
|
| 29 |
# ==========================================
|
| 30 |
-
# 1. 全局配置参数
|
| 31 |
# ==========================================
|
| 32 |
ini_content = {"username": "natclghpe", "key": "21e32070151c7fe0fbd5af3287d7e489"}
|
| 33 |
cf_token = 'eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiNjMyNTRkZjYtNWY0ZC00YjM2LTlmZjMtY2M1MzMxMzQ1ODUyIiwicyI6IlpXSTFNV1JsTkRndFlqWmhZUzAwWW1VNUxUZzFOemN0Wm1GbE1tUTFNREZrTldSaiJ9'
|
|
@@ -150,7 +150,7 @@ configs = [
|
|
| 150 |
# 2. 核心通用工具函数
|
| 151 |
# ==========================================
|
| 152 |
def run_cmd(command, ignore_errors=False, quiet=False):
|
| 153 |
-
"""统一的命令执行工具,替代 os.system
|
| 154 |
try:
|
| 155 |
stdout = subprocess.DEVNULL if quiet else None
|
| 156 |
stderr = subprocess.DEVNULL if quiet else None
|
|
@@ -177,13 +177,12 @@ def is_installed(package):
|
|
| 177 |
|
| 178 |
def install_package(package):
|
| 179 |
logging.info(f"正在安装 {package}...")
|
| 180 |
-
run_cmd(f"sudo apt install {package} -y")
|
| 181 |
|
| 182 |
# ==========================================
|
| 183 |
-
# 3. 环境初始化与
|
| 184 |
# ==========================================
|
| 185 |
def init_environment():
|
| 186 |
-
"""初始化基础环境和依赖"""
|
| 187 |
logging.info('-----------更新软件包列表开始-------------')
|
| 188 |
run_cmd("rm -r /sync.sh", ignore_errors=True, quiet=True)
|
| 189 |
run_cmd("wget -q -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
|
|
@@ -218,7 +217,6 @@ def setup_cloudflared(install_ssh_config=True):
|
|
| 218 |
with open(config_path, "w") as f:
|
| 219 |
f.write(ssh_config_content)
|
| 220 |
os.chmod(config_path, 0o600)
|
| 221 |
-
logging.info(f"✅ SSH config for {cf_ssh} generated successfully.")
|
| 222 |
else:
|
| 223 |
run_cmd(f"sudo cloudflared service install {cf_token}", quiet=True)
|
| 224 |
|
|
@@ -232,13 +230,11 @@ def setup_ssh():
|
|
| 232 |
run_cmd("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
|
| 233 |
run_cmd("service ssh restart", quiet=True)
|
| 234 |
run_cmd("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
|
| 235 |
-
logging.info('-----------SSH配置结束-------------')
|
| 236 |
|
| 237 |
def generate_ssh_key():
|
| 238 |
run_cmd("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub", quiet=True)
|
| 239 |
run_cmd("ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''", quiet=True)
|
| 240 |
run_cmd('chmod 600 ~/.ssh/id_rsa')
|
| 241 |
-
logging.info("SSH key pair generated.")
|
| 242 |
|
| 243 |
def copy_public_key_to_remote(host, port, user, password):
|
| 244 |
try:
|
|
@@ -247,75 +243,202 @@ def copy_public_key_to_remote(host, port, user, password):
|
|
| 247 |
child.expect("password:", timeout=10)
|
| 248 |
child.sendline(password)
|
| 249 |
child.expect(pexpect.EOF)
|
| 250 |
-
logging.info("SSH公钥复制成功")
|
| 251 |
except Exception as e:
|
| 252 |
logging.error(f"复制公钥失败: {e}")
|
| 253 |
|
| 254 |
# ==========================================
|
| 255 |
-
# 4.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
# ==========================================
|
| 257 |
def get_folder_size(folder):
|
| 258 |
try:
|
| 259 |
result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 260 |
if result.returncode == 0:
|
| 261 |
return int(result.stdout.split()[0])
|
| 262 |
-
except
|
| 263 |
-
|
| 264 |
-
return 0
|
| 265 |
|
| 266 |
def compress_folder():
|
| 267 |
global last_uploaded_size
|
| 268 |
-
run_cmd('rm -rf /a/', ignore_errors=True, quiet=True)
|
| 269 |
os.makedirs('/a', exist_ok=True)
|
| 270 |
|
| 271 |
with lock:
|
| 272 |
current_folder_size = get_folder_size(data_folder)
|
| 273 |
-
logging.info(f"当前文件夹大小: {current_folder_size} 字节")
|
| 274 |
-
|
| 275 |
if current_folder_size < (800 * 1024 ** 2):
|
| 276 |
-
logging.info("文件夹小于800MB,跳过压缩上传。")
|
| 277 |
return
|
| 278 |
|
| 279 |
if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
|
| 280 |
-
logging.info('开始压缩数据...')
|
| 281 |
run_cmd(f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path}', quiet=True)
|
| 282 |
|
| 283 |
file_path = "/a/sillytavern.ctk"
|
| 284 |
run_cmd(f'mv {zip_file_path} {file_path}', ignore_errors=True)
|
| 285 |
if not os.path.exists(file_path):
|
| 286 |
-
logging.error("压缩文件未生成!")
|
| 287 |
return
|
| 288 |
|
| 289 |
file_size = os.path.getsize(file_path)
|
| 290 |
-
|
| 291 |
if file_size < (800 * 1024 ** 2):
|
| 292 |
-
logging.info("压缩文件小于800MB,不执行上传。")
|
| 293 |
return
|
| 294 |
|
| 295 |
-
logging.info("准备上传至 Kaggle...")
|
| 296 |
with open(metadata_file_path, 'w') as json_fid:
|
| 297 |
json.dump(kaggle_metadata, json_fid)
|
| 298 |
|
| 299 |
-
run_cmd('kaggle datasets version -m "
|
| 300 |
last_uploaded_size = file_size
|
| 301 |
-
else:
|
| 302 |
-
logging.info("文件夹大小未发生明显变化,跳过备份。")
|
| 303 |
|
| 304 |
def repeat_task():
|
| 305 |
-
logging.info('------打包备份线程启动-------------')
|
| 306 |
while True:
|
| 307 |
-
time.sleep(18000) #
|
| 308 |
compress_folder()
|
| 309 |
|
| 310 |
def kill_frpc_processes():
|
| 311 |
try:
|
| 312 |
subprocess.run(['pkill', '-f', 'frpc'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 313 |
-
logging.info("旧的 frpc 进程已清理。")
|
| 314 |
except subprocess.CalledProcessError:
|
| 315 |
-
pass
|
| 316 |
|
| 317 |
def frp(configs, backstage):
|
| 318 |
-
logging.info('-----------启动 FRP-------------')
|
| 319 |
for config_data, config_file_path in configs:
|
| 320 |
with open(config_file_path, 'w') as config_file:
|
| 321 |
config_file.write(config_data)
|
|
@@ -331,24 +454,25 @@ def Run_SillyTavern():
|
|
| 331 |
os.chdir(data_folder)
|
| 332 |
try:
|
| 333 |
run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
|
| 334 |
-
logging.info("server.js 已启动")
|
| 335 |
except Exception as e:
|
| 336 |
-
logging.error(f"启动失败: {e}")
|
| 337 |
|
| 338 |
def monitor_port():
|
| 339 |
while True:
|
| 340 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
| 341 |
result = sock.connect_ex(('localhost', 8000))
|
| 342 |
if result != 0:
|
| 343 |
-
logging.warning("检测到端口 8000 未运行,尝试重启服务...")
|
| 344 |
config = configparser.ConfigParser()
|
| 345 |
config.read('/config.ini')
|
| 346 |
if config.getboolean('general', 'monitor_port_enabled', fallback=False):
|
| 347 |
threading.Thread(target=Run_SillyTavern, daemon=True).start()
|
| 348 |
time.sleep(5)
|
| 349 |
|
|
|
|
|
|
|
|
|
|
| 350 |
def setup_sillytavern():
|
| 351 |
-
logging.info('-----------SillyTavern 部署开始-------------')
|
| 352 |
os.makedirs(os.path.expanduser("~/.kaggle"), exist_ok=True)
|
| 353 |
with open('/root/.kaggle/kaggle.json', 'w') as json_file:
|
| 354 |
json.dump(ini_content, json_file, indent=4)
|
|
@@ -362,14 +486,11 @@ def setup_sillytavern():
|
|
| 362 |
while download_n <= 6:
|
| 363 |
run_cmd(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
|
| 364 |
if os.path.exists(f'/{huggingface_Data_name}.zip'):
|
| 365 |
-
logging.info("数据集下载成功!")
|
| 366 |
break
|
| 367 |
-
logging.warning("下载失败,重试中...")
|
| 368 |
download_n += 1
|
| 369 |
time.sleep(5)
|
| 370 |
|
| 371 |
if not os.path.exists(f'/{huggingface_Data_name}.zip'):
|
| 372 |
-
logging.info("备用方案:启用 rsync 实时同步。")
|
| 373 |
generate_ssh_key()
|
| 374 |
copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
|
| 375 |
run_cmd(f"sshpass -p 'qilan' rsync -avz --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/")
|
|
@@ -388,13 +509,9 @@ def setup_sillytavern():
|
|
| 388 |
run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
|
| 389 |
|
| 390 |
threading.Thread(target=Run_SillyTavern, daemon=True).start()
|
| 391 |
-
logging.info('-----------SillyTavern 部署结束-------------')
|
| 392 |
|
| 393 |
-
# ==========================================
|
| 394 |
-
# 5. 主程序执行入口
|
| 395 |
-
# ==========================================
|
| 396 |
if __name__ == '__main__':
|
| 397 |
-
# 1. 基础环境
|
| 398 |
init_environment()
|
| 399 |
kill_frpc_processes()
|
| 400 |
setup_cloudflared(True)
|
|
@@ -403,28 +520,29 @@ if __name__ == '__main__':
|
|
| 403 |
generate_ssh_key()
|
| 404 |
copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
|
| 405 |
|
| 406 |
-
# 2. 启动
|
| 407 |
threading.Thread(target=setup_sillytavern, daemon=True).start()
|
| 408 |
|
| 409 |
-
#
|
| 410 |
logging.info("正在等待数据下载和解压,这可能需要几分钟,请耐心等待...")
|
| 411 |
-
|
| 412 |
-
# 智能等待机制:不再死等60秒,而是每5秒检查一次,直到文件出现(最多等30分钟防止卡死)
|
| 413 |
wait_seconds = 0
|
| 414 |
while not os.path.exists(f'{data_folder}/start.sh'):
|
| 415 |
time.sleep(5)
|
| 416 |
wait_seconds += 5
|
| 417 |
-
if wait_seconds
|
| 418 |
-
logging.info(f"已等待 {wait_seconds // 60} 分钟,继续解压中...")
|
| 419 |
-
if wait_seconds > 1800: # 30分钟超时检测
|
| 420 |
logging.error("下载/解压超时(超过30分钟)!")
|
| 421 |
break
|
| 422 |
|
| 423 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 424 |
logging.info("SillyTavern 基础文件已就绪!")
|
| 425 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 426 |
|
| 427 |
-
#
|
| 428 |
config = configparser.ConfigParser()
|
| 429 |
config.add_section('general')
|
| 430 |
config.set('general', 'monitor_port_enabled', 'True')
|
|
@@ -433,23 +551,22 @@ if __name__ == '__main__':
|
|
| 433 |
|
| 434 |
run_cmd("rm -rf /qilan-st9.zip /sillytavern.tar.gz", ignore_errors=True, quiet=True)
|
| 435 |
|
| 436 |
-
#
|
| 437 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 438 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 439 |
backup_thread.start()
|
| 440 |
|
| 441 |
-
logging.info("
|
| 442 |
frp(configs, True)
|
| 443 |
setup_cloudflared(False)
|
| 444 |
threading.Thread(target=monitor_port, daemon=True).start()
|
| 445 |
|
| 446 |
-
#
|
| 447 |
while True:
|
| 448 |
if not backup_thread.is_alive():
|
| 449 |
-
logging.warning("备份线程异常退出,正在重启...")
|
| 450 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 451 |
backup_thread.start()
|
| 452 |
time.sleep(60)
|
| 453 |
else:
|
| 454 |
-
logging.error(f"{data_folder} 初始化失败,
|
| 455 |
compress_folder()
|
|
|
|
| 27 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 28 |
|
| 29 |
# ==========================================
|
| 30 |
+
# 1. 全局配置参数
|
| 31 |
# ==========================================
|
| 32 |
ini_content = {"username": "natclghpe", "key": "21e32070151c7fe0fbd5af3287d7e489"}
|
| 33 |
cf_token = 'eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiNjMyNTRkZjYtNWY0ZC00YjM2LTlmZjMtY2M1MzMxMzQ1ODUyIiwicyI6IlpXSTFNV1JsTkRndFlqWmhZUzAwWW1VNUxUZzFOemN0Wm1GbE1tUTFNREZrTldSaiJ9'
|
|
|
|
| 150 |
# 2. 核心通用工具函数
|
| 151 |
# ==========================================
|
| 152 |
def run_cmd(command, ignore_errors=False, quiet=False):
|
| 153 |
+
"""统一的命令执行工具,替代 os.system"""
|
| 154 |
try:
|
| 155 |
stdout = subprocess.DEVNULL if quiet else None
|
| 156 |
stderr = subprocess.DEVNULL if quiet else None
|
|
|
|
| 177 |
|
| 178 |
def install_package(package):
|
| 179 |
logging.info(f"正在安装 {package}...")
|
| 180 |
+
run_cmd(f"sudo apt install {package} -y", quiet=True)
|
| 181 |
|
| 182 |
# ==========================================
|
| 183 |
+
# 3. 环境初始化与基础设置
|
| 184 |
# ==========================================
|
| 185 |
def init_environment():
|
|
|
|
| 186 |
logging.info('-----------更新软件包列表开始-------------')
|
| 187 |
run_cmd("rm -r /sync.sh", ignore_errors=True, quiet=True)
|
| 188 |
run_cmd("wget -q -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
|
|
|
|
| 217 |
with open(config_path, "w") as f:
|
| 218 |
f.write(ssh_config_content)
|
| 219 |
os.chmod(config_path, 0o600)
|
|
|
|
| 220 |
else:
|
| 221 |
run_cmd(f"sudo cloudflared service install {cf_token}", quiet=True)
|
| 222 |
|
|
|
|
| 230 |
run_cmd("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
|
| 231 |
run_cmd("service ssh restart", quiet=True)
|
| 232 |
run_cmd("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
|
|
|
|
| 233 |
|
| 234 |
def generate_ssh_key():
|
| 235 |
run_cmd("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub", quiet=True)
|
| 236 |
run_cmd("ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''", quiet=True)
|
| 237 |
run_cmd('chmod 600 ~/.ssh/id_rsa')
|
|
|
|
| 238 |
|
| 239 |
def copy_public_key_to_remote(host, port, user, password):
|
| 240 |
try:
|
|
|
|
| 243 |
child.expect("password:", timeout=10)
|
| 244 |
child.sendline(password)
|
| 245 |
child.expect(pexpect.EOF)
|
|
|
|
| 246 |
except Exception as e:
|
| 247 |
logging.error(f"复制公钥失败: {e}")
|
| 248 |
|
| 249 |
# ==========================================
|
| 250 |
+
# 4. 接力信息修改模块 (IP与接力时间)
|
| 251 |
+
# ==========================================
|
| 252 |
+
def get_current_ip():
|
| 253 |
+
"""获取当前公共 IP 地址"""
|
| 254 |
+
try:
|
| 255 |
+
response = requests.get("https://ipinfo.io/ip", timeout=5)
|
| 256 |
+
return response.text.strip()
|
| 257 |
+
except:
|
| 258 |
+
return "Unknown IP"
|
| 259 |
+
|
| 260 |
+
def get_geo_info(ip_address):
|
| 261 |
+
"""根据 IP 地址获取地理位置信息"""
|
| 262 |
+
url = "https://api.qjqq.cn/api/Local"
|
| 263 |
+
headers = {
|
| 264 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
| 265 |
+
}
|
| 266 |
+
try:
|
| 267 |
+
response = requests.get(url, headers=headers, timeout=5)
|
| 268 |
+
if response.status_code == 200:
|
| 269 |
+
geo_info = response.json()
|
| 270 |
+
if geo_info.get('code') == 200:
|
| 271 |
+
data = geo_info['data']
|
| 272 |
+
return {'ip': data['ip'], 'country': data['country'], 'isp': data['isp']}
|
| 273 |
+
except Exception as e:
|
| 274 |
+
logging.error(f"获取地理位置失败: {e}")
|
| 275 |
+
return None
|
| 276 |
+
|
| 277 |
+
def get_next_relay_time():
|
| 278 |
+
"""获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
|
| 279 |
+
try:
|
| 280 |
+
boot_time = datetime.fromtimestamp(psutil.boot_time())
|
| 281 |
+
utc = pytz.UTC
|
| 282 |
+
boot_time = utc.localize(boot_time)
|
| 283 |
+
china_tz = pytz.timezone('Asia/Shanghai')
|
| 284 |
+
boot_time_china = boot_time.astimezone(china_tz)
|
| 285 |
+
next_time = boot_time_china + timedelta(hours=12)
|
| 286 |
+
return next_time.strftime("%Y-%m-%d %H:%M:%S")
|
| 287 |
+
except Exception as e:
|
| 288 |
+
logging.error(f"计算接力时间失败: {e}")
|
| 289 |
+
return "未知时间"
|
| 290 |
+
|
| 291 |
+
def replace_info_in_file(file_path):
|
| 292 |
+
"""修改 ST 登录界面的 IP 和接力时间信息"""
|
| 293 |
+
try:
|
| 294 |
+
if not os.path.exists(file_path):
|
| 295 |
+
logging.warning(f"找不到文件进行替换: {file_path}")
|
| 296 |
+
return
|
| 297 |
+
|
| 298 |
+
ip_address = get_current_ip()
|
| 299 |
+
geo_info = get_geo_info(ip_address)
|
| 300 |
+
next_relay_time = get_next_relay_time()
|
| 301 |
+
|
| 302 |
+
if geo_info is not None:
|
| 303 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 304 |
+
content = file.read()
|
| 305 |
+
|
| 306 |
+
time_pattern = r'接力时间\[.*?\]'
|
| 307 |
+
time_replacement = f'接力时间[{next_relay_time}]'
|
| 308 |
+
content = re.sub(time_pattern, time_replacement, content)
|
| 309 |
+
|
| 310 |
+
ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
|
| 311 |
+
ip_replacement = f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
|
| 312 |
+
content = re.sub(ip_pattern, ip_replacement, content)
|
| 313 |
+
|
| 314 |
+
with open(file_path, 'w', encoding='utf-8') as file:
|
| 315 |
+
file.write(content)
|
| 316 |
+
|
| 317 |
+
logging.info(f"成功更新前端页面信息: 接力时间[{next_relay_time}], IP[{ip_address}]")
|
| 318 |
+
except Exception as e:
|
| 319 |
+
logging.error(f"替换前端信息时发生错误: {e}")
|
| 320 |
+
|
| 321 |
+
# ==========================================
|
| 322 |
+
# 5. 双机接力 rsync 数据同步核心
|
| 323 |
+
# ==========================================
|
| 324 |
+
def sync_data_via_rsync():
|
| 325 |
+
"""检测本地和远程接口,并进行 rsync 数据同步 (双机接力核心)"""
|
| 326 |
+
logging.info("------ 开始执行双机接力同步检测 (原 check_api1) ------")
|
| 327 |
+
|
| 328 |
+
# 第一步:等待本地 ST 服务完全启动
|
| 329 |
+
retry_n = 0
|
| 330 |
+
while True:
|
| 331 |
+
retry_n += 1
|
| 332 |
+
if not os.path.exists(data_folder):
|
| 333 |
+
logging.error(f"{data_folder} 不存在,结束接力检测。")
|
| 334 |
+
return
|
| 335 |
+
try:
|
| 336 |
+
response = requests.get("http://127.0.0.1:8000/v1", timeout=10)
|
| 337 |
+
if response.status_code == 403:
|
| 338 |
+
logging.info("SillyTavern 本地接口已启动!")
|
| 339 |
+
break
|
| 340 |
+
except requests.exceptions.RequestException:
|
| 341 |
+
pass
|
| 342 |
+
|
| 343 |
+
if retry_n % 12 == 0:
|
| 344 |
+
logging.info("等待本地 SillyTavern 启动中...")
|
| 345 |
+
time.sleep(5)
|
| 346 |
+
|
| 347 |
+
# 第二步:检测旧机器(远程)接口 token,触发 rsync 数据拉取
|
| 348 |
+
logging.info('ST本地已就绪,开始探测前置机器(旧机器)以触发同步...')
|
| 349 |
+
fail_count = 0
|
| 350 |
+
while fail_count <= 5:
|
| 351 |
+
if not os.path.exists(data_folder):
|
| 352 |
+
break
|
| 353 |
+
|
| 354 |
+
url = f"{cf_jg}/csrf-token"
|
| 355 |
+
try:
|
| 356 |
+
response = requests_retry_session().get(url, timeout=15)
|
| 357 |
+
response.raise_for_status()
|
| 358 |
+
response_json = response.json()
|
| 359 |
+
|
| 360 |
+
if "token" in response_json:
|
| 361 |
+
logging.info(f"成功探测到前置机器的 Token: {response_json}")
|
| 362 |
+
logging.info("开始执行 rsync 从旧机器接力拉取最新数据...")
|
| 363 |
+
try:
|
| 364 |
+
subprocess.run(
|
| 365 |
+
f"sshpass -p 'qilan' rsync -avz --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/",
|
| 366 |
+
shell=True, check=True
|
| 367 |
+
)
|
| 368 |
+
logging.info("数据接力拉取完美收官!当前机器已获取最新状态。")
|
| 369 |
+
break # 同步成功后安全退出循环
|
| 370 |
+
except subprocess.CalledProcessError as e:
|
| 371 |
+
fail_count += 1
|
| 372 |
+
logging.error(f"Rsync 失败,正在重试 ({fail_count}/5)...")
|
| 373 |
+
generate_ssh_key()
|
| 374 |
+
else:
|
| 375 |
+
logging.warning(f"接口未返回 token: {response_json}")
|
| 376 |
+
fail_count += 1
|
| 377 |
+
|
| 378 |
+
except Exception as e:
|
| 379 |
+
fail_count += 1
|
| 380 |
+
logging.error(f"前置机器探测异常 ({fail_count}/5): {e}")
|
| 381 |
+
if fail_count > 5:
|
| 382 |
+
logging.warning("前置机器可能已宕机,接力同步取消,将使用当前本地数据继续。")
|
| 383 |
+
|
| 384 |
+
time.sleep(5)
|
| 385 |
+
logging.info("------ 双机接力环节执行完毕 ------")
|
| 386 |
+
|
| 387 |
+
# ==========================================
|
| 388 |
+
# 6. 后台备份、FRP 与进程守护
|
| 389 |
# ==========================================
|
| 390 |
def get_folder_size(folder):
|
| 391 |
try:
|
| 392 |
result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 393 |
if result.returncode == 0:
|
| 394 |
return int(result.stdout.split()[0])
|
| 395 |
+
except:
|
| 396 |
+
return 0
|
|
|
|
| 397 |
|
| 398 |
def compress_folder():
|
| 399 |
global last_uploaded_size
|
| 400 |
+
run_cmd('rm -rf /a/', ignore_errors=True, quiet=True)
|
| 401 |
os.makedirs('/a', exist_ok=True)
|
| 402 |
|
| 403 |
with lock:
|
| 404 |
current_folder_size = get_folder_size(data_folder)
|
|
|
|
|
|
|
| 405 |
if current_folder_size < (800 * 1024 ** 2):
|
|
|
|
| 406 |
return
|
| 407 |
|
| 408 |
if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
|
| 409 |
+
logging.info('开始压缩打包数据用于备份...')
|
| 410 |
run_cmd(f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path}', quiet=True)
|
| 411 |
|
| 412 |
file_path = "/a/sillytavern.ctk"
|
| 413 |
run_cmd(f'mv {zip_file_path} {file_path}', ignore_errors=True)
|
| 414 |
if not os.path.exists(file_path):
|
|
|
|
| 415 |
return
|
| 416 |
|
| 417 |
file_size = os.path.getsize(file_path)
|
|
|
|
| 418 |
if file_size < (800 * 1024 ** 2):
|
|
|
|
| 419 |
return
|
| 420 |
|
| 421 |
+
logging.info("准备将压缩包上传至 Kaggle...")
|
| 422 |
with open(metadata_file_path, 'w') as json_fid:
|
| 423 |
json.dump(kaggle_metadata, json_fid)
|
| 424 |
|
| 425 |
+
run_cmd('kaggle datasets version -m "Auto Backup Update" -p /a')
|
| 426 |
last_uploaded_size = file_size
|
|
|
|
|
|
|
| 427 |
|
| 428 |
def repeat_task():
|
| 429 |
+
logging.info('------后台定时打包备份线程已启动-------------')
|
| 430 |
while True:
|
| 431 |
+
time.sleep(18000) # 每 5 小时备份一次
|
| 432 |
compress_folder()
|
| 433 |
|
| 434 |
def kill_frpc_processes():
|
| 435 |
try:
|
| 436 |
subprocess.run(['pkill', '-f', 'frpc'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
| 437 |
except subprocess.CalledProcessError:
|
| 438 |
+
pass
|
| 439 |
|
| 440 |
def frp(configs, backstage):
|
| 441 |
+
logging.info('-----------启动 FRP 内网穿透-------------')
|
| 442 |
for config_data, config_file_path in configs:
|
| 443 |
with open(config_file_path, 'w') as config_file:
|
| 444 |
config_file.write(config_data)
|
|
|
|
| 454 |
os.chdir(data_folder)
|
| 455 |
try:
|
| 456 |
run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
|
|
|
|
| 457 |
except Exception as e:
|
| 458 |
+
logging.error(f"SillyTavern 启动失败: {e}")
|
| 459 |
|
| 460 |
def monitor_port():
|
| 461 |
while True:
|
| 462 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
| 463 |
result = sock.connect_ex(('localhost', 8000))
|
| 464 |
if result != 0:
|
|
|
|
| 465 |
config = configparser.ConfigParser()
|
| 466 |
config.read('/config.ini')
|
| 467 |
if config.getboolean('general', 'monitor_port_enabled', fallback=False):
|
| 468 |
threading.Thread(target=Run_SillyTavern, daemon=True).start()
|
| 469 |
time.sleep(5)
|
| 470 |
|
| 471 |
+
# ==========================================
|
| 472 |
+
# 7. 主程序部署流程
|
| 473 |
+
# ==========================================
|
| 474 |
def setup_sillytavern():
|
| 475 |
+
logging.info('-----------SillyTavern 基础数据部署开始-------------')
|
| 476 |
os.makedirs(os.path.expanduser("~/.kaggle"), exist_ok=True)
|
| 477 |
with open('/root/.kaggle/kaggle.json', 'w') as json_file:
|
| 478 |
json.dump(ini_content, json_file, indent=4)
|
|
|
|
| 486 |
while download_n <= 6:
|
| 487 |
run_cmd(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
|
| 488 |
if os.path.exists(f'/{huggingface_Data_name}.zip'):
|
|
|
|
| 489 |
break
|
|
|
|
| 490 |
download_n += 1
|
| 491 |
time.sleep(5)
|
| 492 |
|
| 493 |
if not os.path.exists(f'/{huggingface_Data_name}.zip'):
|
|
|
|
| 494 |
generate_ssh_key()
|
| 495 |
copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
|
| 496 |
run_cmd(f"sshpass -p 'qilan' rsync -avz --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/")
|
|
|
|
| 509 |
run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
|
| 510 |
|
| 511 |
threading.Thread(target=Run_SillyTavern, daemon=True).start()
|
|
|
|
| 512 |
|
|
|
|
|
|
|
|
|
|
| 513 |
if __name__ == '__main__':
|
| 514 |
+
# 1. 基础环境预热
|
| 515 |
init_environment()
|
| 516 |
kill_frpc_processes()
|
| 517 |
setup_cloudflared(True)
|
|
|
|
| 520 |
generate_ssh_key()
|
| 521 |
copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
|
| 522 |
|
| 523 |
+
# 2. 在后台线程启动 ST 解压与下载任务
|
| 524 |
threading.Thread(target=setup_sillytavern, daemon=True).start()
|
| 525 |
|
| 526 |
+
# 3. 智能等待基础数据就绪
|
| 527 |
logging.info("正在等待数据下载和解压,这可能需要几分钟,请耐心等待...")
|
|
|
|
|
|
|
| 528 |
wait_seconds = 0
|
| 529 |
while not os.path.exists(f'{data_folder}/start.sh'):
|
| 530 |
time.sleep(5)
|
| 531 |
wait_seconds += 5
|
| 532 |
+
if wait_seconds > 1800:
|
|
|
|
|
|
|
| 533 |
logging.error("下载/解压超时(超过30分钟)!")
|
| 534 |
break
|
| 535 |
|
| 536 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 537 |
logging.info("SillyTavern 基础文件已就绪!")
|
| 538 |
+
|
| 539 |
+
# 4. 执行核心双机接力逻辑 (同步旧数据覆盖本地)
|
| 540 |
+
sync_data_via_rsync()
|
| 541 |
+
|
| 542 |
+
# 5. 替换登录页面显示接力时间与当前机器IP
|
| 543 |
+
replace_info_in_file(f'{data_folder}/public/login.html')
|
| 544 |
|
| 545 |
+
# 6. 配置环境收尾工作
|
| 546 |
config = configparser.ConfigParser()
|
| 547 |
config.add_section('general')
|
| 548 |
config.set('general', 'monitor_port_enabled', 'True')
|
|
|
|
| 551 |
|
| 552 |
run_cmd("rm -rf /qilan-st9.zip /sillytavern.tar.gz", ignore_errors=True, quiet=True)
|
| 553 |
|
| 554 |
+
# 7. 启动常驻守护服务 (备份、FRP、穿透隧道、状态监控)
|
| 555 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 556 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 557 |
backup_thread.start()
|
| 558 |
|
| 559 |
+
logging.info("前置任务全部完结!启动端口监控和网络穿透通道...")
|
| 560 |
frp(configs, True)
|
| 561 |
setup_cloudflared(False)
|
| 562 |
threading.Thread(target=monitor_port, daemon=True).start()
|
| 563 |
|
| 564 |
+
# 存活守护循环
|
| 565 |
while True:
|
| 566 |
if not backup_thread.is_alive():
|
|
|
|
| 567 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 568 |
backup_thread.start()
|
| 569 |
time.sleep(60)
|
| 570 |
else:
|
| 571 |
+
logging.error(f"{data_folder} 初始化彻底失败,执行保底打包逻辑。")
|
| 572 |
compress_folder()
|