Qilan2 commited on
Commit
0dea49a
·
verified ·
1 Parent(s): 41a0891

Update server6.py

Browse files
Files changed (1) hide show
  1. server6.py +210 -297
server6.py CHANGED
@@ -1,9 +1,9 @@
1
- ini_content = {"username":"hdsg142saa","key":"2da57ac0c245c1ebba26017f161d5558"}
2
  frp_url = '119.8.118.149'
3
  ssh_port = '7079'
4
  ssh_url = '43.135.135.22'
5
  st_url = f'http://{frp_url}:7077'
6
- huggingface_name = 'hdsg142saa'
7
  huggingface_Data_name = 'qilan-st5'
8
  configs = [
9
  ("""
@@ -11,13 +11,13 @@ configs = [
11
  server_addr = 47.237.156.222
12
  server_port = 7000
13
 
14
- [safsa666]
15
  type = tcp
16
  local_ip = 127.0.0.1
17
  local_port = 8000
18
  remote_port = 7082
19
 
20
- [sascb2f666]
21
  type = tcp
22
  local_ip = 127.0.0.1
23
  local_port = 22
@@ -32,38 +32,38 @@ configs = [
32
  type = tcp
33
  local_ip = 127.0.0.1
34
  local_port = 8000
35
- remote_port = 7077
36
  """, '/content/frp/frpc1.ini'),
37
- # ("""
38
- # [common]
39
- # server_addr = 47.237.78.158
40
- # server_port = 7000
41
- # [kjas2]
42
- # type = tcp
43
- # local_ip = 127.0.0.1
44
- # local_port = 8000
45
- # remote_port = 7075
46
- # """, '/content/frp/frpc2.ini'),
47
- # ("""
48
- # [common]
49
- # server_addr = 45.94.69.159
50
- # server_port = 7000
51
- # [kja1sh5]
52
- # type = tcp
53
- # local_ip = 127.0.0.1
54
- # local_port = 8000
55
- # remote_port = 7075
56
- # """, '/content/frp/frpc3.ini'),
57
- # ("""
58
- # [common]
59
- # server_addr = 43.128.135.88
60
- # server_port=7000
61
- # [kkji1mk5]
62
- # type=tcp
63
- # local_ip=127.0.0.1
64
- # local_port=8000
65
- # remote_port=7075
66
- # """, '/content/frp/frpc4.ini'),
67
  (f"""
68
  [common]
69
  server_addr = {ssh_url}
@@ -84,6 +84,7 @@ st_status = True
84
  import subprocess
85
  import os
86
  import sys
 
87
  from IPython.display import clear_output
88
  import urllib.request
89
  from pathlib import Path
@@ -92,16 +93,18 @@ import json
92
  import threading
93
  import time
94
  import pexpect
 
 
95
  import glob # 导入 glob 模块
96
  from requests.adapters import HTTPAdapter
97
  from requests.packages.urllib3.util.retry import Retry
98
  os.system("rm -r /sync.sh")
99
  os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
100
  os.system("export LC_ALL=zh_CN.UTF-8")
 
101
  os.system("mkdir -p /content/frp")
102
  os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
103
  os.system("chmod +x /content/frp/frpc")
104
-
105
  # 更新软件包列表
106
  def is_installed(package):
107
  """Check if a package is installed."""
@@ -115,7 +118,7 @@ def is_installed(package):
115
  def install_package(package):
116
  """Install a package using apt."""
117
  print(f"Installing {package}...")
118
- os.system(f"sudo apt install {package} -y > /dev/null 2>&1")
119
  def update():
120
  print('-----------更新软件包列表开始-------------')
121
  # os.system("sudo apt update")
@@ -128,18 +131,17 @@ def update():
128
 
129
  if not is_installed('npm'):
130
  install_package('npm')
131
- os.system("pip install -U kaggle > /dev/null 2>&1")
 
 
132
  os.system("pip uninstall -y kaggle > /dev/null 2>&1")
133
- os.system("pip install kaggle==1.5.6 > /dev/null 2>&1")
134
- # os.system("apt-get install inotify-tools > /dev/null 2>&1")
135
- os.system("pip install ruamel.yaml > /dev/null 2>&1") # install ruamel.yaml to solve the import issue
136
- os.system("pip install pexpect > /dev/null 2>&1")
137
- os.system("pip install pytz > /dev/null 2>&1")
138
- os.system('pip install paramiko > /dev/null 2>&1')
139
- os.system('apt-get install pigz -y > /dev/null 2>&1')
140
- os.system('apt-get install pv -y > /dev/null 2>&1')
141
- os.system("sudo apt install p7zip-full -y > /dev/null 2>&1")
142
-
143
  print('-----------更新软件包列表结束-------------')
144
  update()
145
 
@@ -157,6 +159,7 @@ def kill_frpc_processes():
157
  print(f"结束frpc进程时出错: {e}")
158
  kill_frpc_processes()
159
 
 
160
  # SSH
161
  def run_command(command):
162
  try:
@@ -184,89 +187,87 @@ def ssh():
184
  ssh()
185
  clear_output()
186
 
187
- import json
188
- import os
189
- import subprocess
190
- import threading
191
- import time
192
 
193
  # 创建一个锁
194
  lock = threading.Lock()
195
- # data_folder = '/sillytavern/*'
196
- # zip_file_path = '/a/sillytavern.zip'
197
  data_folder = '/root/SillyTavern' # 要压缩的目录
198
  zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
199
  metadata_file_path = '/a/dataset-metadata.json'
200
  last_uploaded_size = -1
201
 
 
202
  def update_last_uploaded_size(size):
203
  global last_uploaded_size
204
  last_uploaded_size = size
205
 
 
 
 
 
 
 
 
 
 
 
206
  def compress_folder():
207
  global last_uploaded_size # 声明使用全局变量
208
-
209
  # 清理并创建目录 /a
210
  if os.path.exists('/a'):
211
  subprocess.run(['rm', '-r', '/a/'])
212
-
213
  os.makedirs('/a', exist_ok=True)
214
-
215
  with lock: # 使用锁
216
- if os.path.exists(zip_file_path):
217
- print(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩。")
218
- return
219
-
220
- print('开始压缩数据')
221
- #result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder])
222
- # 7z a -tzip -mx=1 -mmt=2 /a/sillytavern.zip /sillytavern/*
223
- # tar -cvf - /sillytavern | pigz -p 6 -1 > /a/sillytavern.tar.gz
224
- try:
225
- result = subprocess.run(
226
- f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
227
- shell=True,
228
- check=True,
229
- stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
230
- stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
231
- )
232
- except subprocess.CalledProcessError as e:
233
- print(f"Command failed with return code {e.returncode}")
234
 
235
- print('重命名压缩后的文件')
236
- file_path = "/a/sillytavern.ctk"
237
- print(zip_file_path)
238
-
239
- subprocess.run(['mv', zip_file_path,file_path])
240
- if result.returncode != 0:
241
- print("压缩失败,请检查7z命令是否正确")
242
  return
243
 
244
- print(f"Data compressed into {file_path}")
245
-
246
- file_size = os.path.getsize(file_path) # 获取压缩包的大小
247
- print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2)
248
-
249
- # 判断是否大于800MB (800MB = 800 * 1024 * 1024 字节)
250
- if file_size < (400 * 1024 ** 2):
251
- print("文件小于800MB,不进行上传。")
252
- return
253
-
254
- if last_uploaded_size == -1 or file_size != last_uploaded_size:
255
- # 判断是否为首次运行或上次上传大小为0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  if last_uploaded_size == -1:
257
  print("首次运行,正在执行上传...")
258
- update_last_uploaded_size(file_size) # 更新为当前文件大小
259
 
260
  with open(metadata_file_path, 'w') as json_fid:
261
  json.dump(kaggle_metadata, json_fid)
262
- os.system("kaggle datasets version -m 'new version message' -p /a")
263
- #subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
264
- # kaggle datasets version -m 'new version message' -p /a
265
  last_uploaded_size = file_size
266
-
267
- elif file_size > last_uploaded_size:
268
- print(f"新文件 {zip_file_path} 大于上次上传的大小,正在执行上传...")
269
- update_last_uploaded_size(file_size) # 更新元数据中的最后一次上传大小
270
 
271
  with open(metadata_file_path, 'w') as json_fid:
272
  json.dump(kaggle_metadata, json_fid)
@@ -275,21 +276,19 @@ def compress_folder():
275
  last_uploaded_size = file_size
276
 
277
  else:
278
- print(f"新文件 {zip_file_path} 不大于上次上传的大小,跳过")
279
-
280
 
281
  def repeat_task():
282
  print('------打包线程启动-------------')
283
  while True:
284
  print('等待打包')
285
  time.sleep(18000)
286
- # compress_folder()
287
  print('------打包线程结束-------------')
 
 
288
 
289
 
290
- import os
291
- import subprocess
292
- import pexpect
293
 
294
  def generate_ssh_key():
295
  # 生成 SSH 密钥对,并捕获输出和错误信息
@@ -324,12 +323,24 @@ def copy_public_key_to_remote(host, port, user, password):
324
  # 生成 SSH 密钥对
325
  generate_ssh_key()
326
  os.system('chmod 600 ~/.ssh/id_rsa')
327
- # # 复制公钥到远程服务器
328
  copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
329
 
330
- def write_rsyncd_conf(path, port=7071):
 
 
 
 
 
 
 
 
 
 
 
331
  rsyncd_conf_content = f"""
332
  port = {port}
 
333
  [qilan]
334
  path = {path}
335
  comment = My rsync module
@@ -339,44 +350,19 @@ port = {port}
339
  with open('/etc/rsyncd.conf', 'w') as f:
340
  f.write(rsyncd_conf_content.strip())
341
  print(f"Successfully wrote to /etc/rsyncd.conf for module .")
 
 
 
 
342
 
343
- write_rsyncd_conf(data_folder)
344
- os.system("sudo rsync --daemon")
345
- os.system("ps aux | grep rsync")
346
-
347
- def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
348
- """创建一个带重试机制的请求会话"""
349
- session = session or requests.Session()
350
- retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
351
- adapter = HTTPAdapter(max_retries=retry)
352
- session.mount('http://', adapter)
353
- session.mount('https://', adapter)
354
- return session
355
-
356
  import os
357
  import time
358
  import requests
359
  import subprocess
360
  import logging
361
 
362
- import paramiko
363
-
364
- def check_ssh_connection(host, port, username, password):
365
- try:
366
- client = paramiko.SSHClient()
367
- # 允许连接到不在 known_hosts 中的主机
368
- client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
369
- # 尝试连接
370
- client.connect(hostname=host, port=port, username=username, password=password)
371
- client.close()
372
- return True
373
- except Exception as e:
374
- print(f"SSH 连接失败: {e}")
375
- return False
376
-
377
-
378
-
379
-
380
  # 配置日志
381
  logging.basicConfig(level=logging.INFO)
382
 
@@ -427,7 +413,6 @@ def check_api1():
427
  if "token" in response_json:
428
  print("检测到 token")
429
  try:
430
- print(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/")
431
  subprocess.run(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",shell=True, check=True)
432
  # break # 如果成功,跳出重试循环
433
  except subprocess.CalledProcessError as e:
@@ -452,13 +437,14 @@ def check_api1():
452
  time.sleep(5)
453
 
454
 
 
 
455
  def frp(configs, backstage):
456
  print('-----------FRP开始-------------')
457
  # 遍历所有配置并启动 FRP。
458
  for config_data, config_file_path in configs:
459
  with open(config_file_path, 'w') as config_file:
460
  config_file.write(config_data)
461
-
462
  # 启动 frpc 命令和参数。
463
  frpc_cmd=['/content/frp/frpc', '-c', config_file_path]
464
 
@@ -466,9 +452,8 @@ def frp(configs, backstage):
466
  subprocess.Popen(frpc_cmd)
467
  else:
468
  subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
469
-
470
  print('-----------FRP结束-------------')
471
-
472
  import requests
473
  import re
474
  from datetime import datetime, timedelta
@@ -548,9 +533,6 @@ def replace_info_in_file(file_path):
548
  except Exception as e:
549
  print(f"发生错误: {e}")
550
 
551
- import socket
552
- import subprocess
553
- import time
554
 
555
  def monitor_port():
556
  while True:
@@ -560,14 +542,20 @@ def monitor_port():
560
  print(f"端口 8000 正在使用中")
561
  else:
562
  print(f"端口 8000 未被使用")
563
- backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
564
- backup_thread.start()
 
 
 
 
 
 
 
 
565
  time.sleep(5) # 每5秒检查一次
566
  def Run_SillyTavern():
567
-
568
- # subprocess.run(f'node "server.js" "$@"', shell=True, check=True)
569
  try:
570
- os.chdir(data_folder)
571
  # 启动 Node.js 服务器,并将输出重定向到 /dev/null
572
  subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
573
  subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
@@ -576,9 +564,10 @@ def Run_SillyTavern():
576
  subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
577
  print("已尝试启动 server.js")
578
  except subprocess.CalledProcessError as e:
579
- print(f"Run_SillyTavern命令失败,返回码: {e.returncode}")
580
  except Exception as e: # 捕获所有其他异常
581
- print(f"Run_SillyTavern发生异常: {e}")
 
582
  def SillyTavern():
583
  print('-----------SillyTavern开始-------------')
584
  # 创建目录并写入 kaggle.json
@@ -593,161 +582,85 @@ def SillyTavern():
593
  os.system(f"rm -r /a /sillytavern /*.zi* {data_folder}")
594
  os.system(f"mkdir -p {data_folder}")
595
  os.chdir('/')
596
- print(f"开始下载 kaggle 数据集 {huggingface_name}/{huggingface_Data_name}")
597
-
598
- # 改进的下载逻辑
599
  download_n = 0
600
- max_retries = 5 # 修改为5次尝试
601
- download_success = False
602
-
603
- while download_n < max_retries:
604
- try:
605
- # 使用subprocess.run捕获命令的输出和错误
606
- result = subprocess.run(
607
- f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /",
608
- shell=True,
609
- check=False, # 不要在失败时抛出异常
610
- stdout=subprocess.PIPE,
611
- stderr=subprocess.PIPE
612
- )
613
-
614
- # 检查文件是否存在
615
- if os.path.exists(f'/{huggingface_Data_name}.zip'):
616
- print(f"{huggingface_Data_name}.zip 下载成功!")
617
- download_success = True
618
- break # 跳出循环
619
-
620
- # 输出错误信息
621
- print(f"下载尝试 {download_n+1}/{max_retries} 失败")
622
- if result.stderr:
623
- print(f"错误信息: {result.stderr.decode('utf-8', errors='replace')}")
624
-
625
- download_n += 1
626
-
627
- if download_n < max_retries:
628
- wait_time = 60 # 减少等待时间以加快失败后的切换
629
- print(f"等待 {wait_time} 秒后重试...")
630
- time.sleep(wait_time)
631
-
632
- except Exception as e:
633
- print(f"下载过程中发生错误: {str(e)}")
634
- download_n += 1
635
- if download_n < max_retries:
636
- print(f"等待 60 秒后重试...")
637
- time.sleep(60)
638
-
639
- # 检查文件是否存在,如果不存在则使用rsync同步
640
- if not download_success or not os.path.exists(f'/{huggingface_Data_name}.zip'):
641
- print(f"下载 {huggingface_Data_name}.zip 失败 {max_retries} 次,切换到rsync同步")
642
- os.system("mkdir -p /root/SillyTavern")
643
-
644
- # 添加rsync重试次数计数器
645
- rsync_retry_count = 0
646
- max_rsync_retries = 10
647
-
648
- while rsync_retry_count < max_rsync_retries:
649
- try:
650
- print(f"rsync同步尝试 {rsync_retry_count + 1}/{max_rsync_retries}")
651
- print("开始生成SSH密钥...")
652
- generate_ssh_key()
653
- print("复制SSH密钥到远程服务器...")
654
- copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
655
- print(f"开始从 {ssh_url}:{ssh_port} 同步数据到 {data_folder}")
656
- # 添加进度显示
657
- rsync_cmd = f"rsync -avz --progress --stats --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/"
658
- print(f"执行命令: {rsync_cmd}")
659
-
660
- # 设置超时
661
- result = subprocess.run(rsync_cmd, shell=True, check=True, timeout=1800) # 30分钟超时
662
- print("rsync同步完成")
663
- break # 同步成功,跳出循环
664
-
665
- except subprocess.TimeoutExpired:
666
- print(f"rsync同步超时,这是第 {rsync_retry_count + 1} 次尝试")
667
- rsync_retry_count += 1
668
-
669
- except subprocess.CalledProcessError as e:
670
- print(f"rsync同步失败: 返回码 {e.returncode}")
671
- if hasattr(e, 'stdout') and e.stdout:
672
- print(f"输出: {e.stdout}")
673
- if hasattr(e, 'stderr') and e.stderr:
674
- print(f"错误: {e.stderr}")
675
-
676
- rsync_retry_count += 1
677
-
678
- except Exception as e:
679
- print(f"rsync同步过程中发生未知错误: {str(e)}")
680
- rsync_retry_count += 1
681
-
682
- # 检查是否达到最大重试次数
683
- if rsync_retry_count >= max_rsync_retries:
684
- print(f"rsync同步失败达到最大重试次数 {max_rsync_retries},结束程序")
685
- sys.exit(1) # 使用非零退出码表示错误
686
-
687
- # 等待一段时间后重试
688
- wait_time = 30
689
- print(f"等待 {wait_time} 秒后重试...")
690
- time.sleep(wait_time)
691
  else:
 
692
  # 如果文件存在,可以继续执行后续代码
693
  print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
694
- # 解压文件
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695
  try:
696
- os.system("ls /")
697
- print("开始解压文件...")
698
- os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
699
- os.system("mv /sillytavern.tck sillytavern.tar.gz 2>/dev/null || true")
700
- os.system("mv /sillytavern.ctk sillytavern.tar.gz 2>/dev/null || true")
701
-
702
- # 检查tar.gz文件是否存在
703
- if os.path.exists("/sillytavern.tar.gz"):
704
- print("开始解压tar.gz文件...")
705
- os.system(f"tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
706
- print("tar.gz文件解压完成")
707
- else:
708
- print("警告: sillytavern.tar.gz文件不存在")
709
-
710
- os.chdir(data_folder)
711
- print('更新文件')
712
- os.system(f"ls {data_folder}")
713
- os.system("nvm install node")
714
- os.system("nvm use node")
715
- os.system("npm install -y")
716
-
717
- try:
718
- print("尝试启动SillyTavern...")
719
- subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
720
- except subprocess.CalledProcessError as e:
721
- print(f"启动失败: {e.returncode}")
722
- print(f"命令: {e.cmd}")
723
- if hasattr(e, 'output') and e.output:
724
- print(f"输出: {e.output}")
725
-
726
- os.system(f"ls {data_folder}")
727
-
728
- # 启动后台线程
729
- backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
730
- backup_thread.start()
731
- # 清理下载的文件
732
- print("清理临时文件...")
733
- os.system(f"rm -r /{huggingface_Data_name}.zip /sillytavern.tar.gz 2>/dev/null || true")
734
- except Exception as e:
735
- print(f"解压或启动过程中发生错误: {str(e)}")
736
-
737
- print('-----------SillyTavern结束-------------')
738
  threading.Thread(target=SillyTavern, daemon=True).start()
739
  time.sleep(60)
740
  check_api1()
741
 
 
 
 
 
 
 
 
 
 
 
 
742
  if os.path.exists(f'{data_folder}/start.sh'):
743
  replace_info_in_file(f'{data_folder}/public/login.html')
744
- # threading.Thread(target=repeat_task, daemon=True).start() #压缩备份
745
- backup_thread = threading.Thread(target=repeat_task, daemon=True)
746
  backup_thread.start()
747
  print("开始衔接")
748
  Service_status = True
749
  frp(configs, True)
750
-
751
  threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
752
  while True:
753
  if backup_thread.is_alive():
@@ -756,7 +669,7 @@ if os.path.exists(f'{data_folder}/start.sh'):
756
  print("备份线程已停止.")
757
  backup_thread = threading.Thread(target=repeat_task, daemon=True)
758
  backup_thread.start()
759
- break
760
  time.sleep(5)
761
 
762
  else:
 
1
+ ini_content = {"username":"ighlnvd551","key":"14dee8c2e790b386ca7a61e974537d66"}
2
  frp_url = '119.8.118.149'
3
  ssh_port = '7079'
4
  ssh_url = '43.135.135.22'
5
  st_url = f'http://{frp_url}:7077'
6
+ huggingface_name = 'ighlnvd551'
7
  huggingface_Data_name = 'qilan-st5'
8
  configs = [
9
  ("""
 
11
  server_addr = 47.237.156.222
12
  server_port = 7000
13
 
14
+ [safsa66]
15
  type = tcp
16
  local_ip = 127.0.0.1
17
  local_port = 8000
18
  remote_port = 7082
19
 
20
+ [sascb2f66]
21
  type = tcp
22
  local_ip = 127.0.0.1
23
  local_port = 22
 
32
  type = tcp
33
  local_ip = 127.0.0.1
34
  local_port = 8000
35
+ remote_port = 7076
36
  """, '/content/frp/frpc1.ini'),
37
+ ("""
38
+ [common]
39
+ server_addr = 47.237.78.158
40
+ server_port = 7000
41
+ [kjas6]
42
+ type = tcp
43
+ local_ip = 127.0.0.1
44
+ local_port = 8000
45
+ remote_port = 7075
46
+ """, '/content/frp/frpc2.ini'),
47
+ ("""
48
+ [common]
49
+ server_addr = 45.94.69.159
50
+ server_port = 7000
51
+ [kja1sh6]
52
+ type = tcp
53
+ local_ip = 127.0.0.1
54
+ local_port = 8000
55
+ remote_port = 7075
56
+ """, '/content/frp/frpc3.ini'),
57
+ ("""
58
+ [common]
59
+ server_addr = 43.128.135.88
60
+ server_port=7000
61
+ [kkji1mk6]
62
+ type=tcp
63
+ local_ip=127.0.0.1
64
+ local_port=8000
65
+ remote_port=7075
66
+ """, '/content/frp/frpc4.ini'),
67
  (f"""
68
  [common]
69
  server_addr = {ssh_url}
 
84
  import subprocess
85
  import os
86
  import sys
87
+ import configparser
88
  from IPython.display import clear_output
89
  import urllib.request
90
  from pathlib import Path
 
93
  import threading
94
  import time
95
  import pexpect
96
+ import socket
97
+ import time
98
  import glob # 导入 glob 模块
99
  from requests.adapters import HTTPAdapter
100
  from requests.packages.urllib3.util.retry import Retry
101
  os.system("rm -r /sync.sh")
102
  os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
103
  os.system("export LC_ALL=zh_CN.UTF-8")
104
+ # 创建 FRP 文件夹并下载 frpc 可执行文件。
105
  os.system("mkdir -p /content/frp")
106
  os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
107
  os.system("chmod +x /content/frp/frpc")
 
108
  # 更新软件包列表
109
  def is_installed(package):
110
  """Check if a package is installed."""
 
118
  def install_package(package):
119
  """Install a package using apt."""
120
  print(f"Installing {package}...")
121
+ os.system(f"sudo apt install {package} -y")
122
  def update():
123
  print('-----------更新软件包列表开始-------------')
124
  # os.system("sudo apt update")
 
131
 
132
  if not is_installed('npm'):
133
  install_package('npm')
134
+ # 安装 p7zip-full
135
+ os.system("sudo apt install p7zip-full -y")
136
+ os.system("pip install -U kaggle")
137
  os.system("pip uninstall -y kaggle > /dev/null 2>&1")
138
+ os.system("pip install kaggle==1.5.6 > /dev/null 2>&1")
139
+ # os.system("apt-get install inotify-tools")
140
+ os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
141
+ os.system("pip install pexpect")
142
+ os.system("pip install pytz")
143
+ os.system('apt-get install pigz')
144
+ os.system('apt-get install pv')
 
 
 
145
  print('-----------更新软件包列表结束-------------')
146
  update()
147
 
 
159
  print(f"结束frpc进程时出错: {e}")
160
  kill_frpc_processes()
161
 
162
+
163
  # SSH
164
  def run_command(command):
165
  try:
 
187
  ssh()
188
  clear_output()
189
 
190
+
 
 
 
 
191
 
192
  # 创建一个锁
193
  lock = threading.Lock()
 
 
194
  data_folder = '/root/SillyTavern' # 要压缩的目录
195
  zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
196
  metadata_file_path = '/a/dataset-metadata.json'
197
  last_uploaded_size = -1
198
 
199
+
200
  def update_last_uploaded_size(size):
201
  global last_uploaded_size
202
  last_uploaded_size = size
203
 
204
+ def get_folder_size(folder):
205
+ """使用 du 命令获取文件夹的总大小(字节数)"""
206
+ result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
207
+ if result.returncode == 0:
208
+ size = result.stdout.split()[0] # 获取大小
209
+ return int(size)
210
+ else:
211
+ print(f"Error calculating size: {result.stderr.decode()}")
212
+ return 0
213
+
214
  def compress_folder():
215
  global last_uploaded_size # 声明使用全局变量
 
216
  # 清理并创建目录 /a
217
  if os.path.exists('/a'):
218
  subprocess.run(['rm', '-r', '/a/'])
 
219
  os.makedirs('/a', exist_ok=True)
 
220
  with lock: # 使用锁
221
+ # 获取当前文件夹的大小
222
+ current_folder_size = get_folder_size(data_folder)
223
+ print(f"当前文件夹大小: {current_folder_size} 字节")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
+ # 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
226
+ if current_folder_size < (800 * 1024 ** 2):
227
+ print("文件夹小于800MB,不进行上传和压缩。")
 
 
 
 
228
  return
229
 
230
+ # 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
231
+ if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
232
+ print('开始压缩数据')
233
+ try:
234
+ # 执行压缩
235
+ result = subprocess.run(
236
+ f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
237
+ shell=True,
238
+ check=True,
239
+ stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
240
+ stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
241
+ )
242
+ except subprocess.CalledProcessError as e:
243
+ print(f"命令失败,返回代码: {e.returncode}")
244
+ return
245
+
246
+ print('压缩完成')
247
+ file_path = "/a/sillytavern.ctk"
248
+ subprocess.run(['mv', zip_file_path, file_path])
249
+ print(f"数据压缩为 {file_path}")
250
+
251
+ file_size = os.path.getsize(file_path) # 获取压缩包的大小
252
+ print('文件大小:', file_size)
253
+
254
+ if file_size < (800 * 1024 ** 2): # 判断压缩后的大小是否小于 800MB
255
+ print("压缩文件小于800MB,不进行上传。")
256
+ return
257
+
258
+ # 执行上传
259
  if last_uploaded_size == -1:
260
  print("首次运行,正在执行上传...")
261
+ update_last_uploaded_size(file_size)
262
 
263
  with open(metadata_file_path, 'w') as json_fid:
264
  json.dump(kaggle_metadata, json_fid)
265
+
266
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
 
267
  last_uploaded_size = file_size
268
+ else:
269
+ print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
270
+ update_last_uploaded_size(file_size)
 
271
 
272
  with open(metadata_file_path, 'w') as json_fid:
273
  json.dump(kaggle_metadata, json_fid)
 
276
  last_uploaded_size = file_size
277
 
278
  else:
279
+ print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")
 
280
 
281
  def repeat_task():
282
  print('------打包线程启动-------------')
283
  while True:
284
  print('等待打包')
285
  time.sleep(18000)
286
+ compress_folder()
287
  print('------打包线程结束-------------')
288
+ # repeat_task()
289
+ # compress_folder()
290
 
291
 
 
 
 
292
 
293
  def generate_ssh_key():
294
  # 生成 SSH 密钥对,并捕获输出和错误信息
 
323
  # 生成 SSH 密钥对
324
  generate_ssh_key()
325
  os.system('chmod 600 ~/.ssh/id_rsa')
326
+ # 复制公钥到远程服务器
327
  copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
328
 
329
+
330
+
331
+ def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
332
+ """创建一个带重试机制的请求会话"""
333
+ session = session or requests.Session()
334
+ retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
335
+ adapter = HTTPAdapter(max_retries=retry)
336
+ session.mount('http://', adapter)
337
+ session.mount('https://', adapter)
338
+ return session
339
+
340
+ def write_rsyncd_conf(path, port=7075):
341
  rsyncd_conf_content = f"""
342
  port = {port}
343
+
344
  [qilan]
345
  path = {path}
346
  comment = My rsync module
 
350
  with open('/etc/rsyncd.conf', 'w') as f:
351
  f.write(rsyncd_conf_content.strip())
352
  print(f"Successfully wrote to /etc/rsyncd.conf for module .")
353
+ os.system("sudo rsync --daemon")
354
+ os.system("sudo rsync --daemon")
355
+ os.system("sudo rsync --daemon")
356
+ os.system("sudo rsync --daemon")
357
 
358
+ # write_rsyncd_conf(data_folder)
359
+ # os.system("ps aux | grep rsync")
 
 
 
 
 
 
 
 
 
 
 
360
  import os
361
  import time
362
  import requests
363
  import subprocess
364
  import logging
365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  # 配置日志
367
  logging.basicConfig(level=logging.INFO)
368
 
 
413
  if "token" in response_json:
414
  print("检测到 token")
415
  try:
 
416
  subprocess.run(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",shell=True, check=True)
417
  # break # 如果成功,跳出重试循环
418
  except subprocess.CalledProcessError as e:
 
437
  time.sleep(5)
438
 
439
 
440
+
441
+
442
  def frp(configs, backstage):
443
  print('-----------FRP开始-------------')
444
  # 遍历所有配置并启动 FRP。
445
  for config_data, config_file_path in configs:
446
  with open(config_file_path, 'w') as config_file:
447
  config_file.write(config_data)
 
448
  # 启动 frpc 命令和参数。
449
  frpc_cmd=['/content/frp/frpc', '-c', config_file_path]
450
 
 
452
  subprocess.Popen(frpc_cmd)
453
  else:
454
  subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
 
455
  print('-----------FRP结束-------------')
456
+
457
  import requests
458
  import re
459
  from datetime import datetime, timedelta
 
533
  except Exception as e:
534
  print(f"发生错误: {e}")
535
 
 
 
 
536
 
537
  def monitor_port():
538
  while True:
 
542
  print(f"端口 8000 正在使用中")
543
  else:
544
  print(f"端口 8000 未被使用")
545
+ # 读取 config.ini 中的 monitor_port_enabled 配置项
546
+ config = configparser.ConfigParser()
547
+ config.read('/config.ini')
548
+ monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
549
+ if monitor_port_enabled:
550
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
551
+ backup_thread.start()
552
+ else:
553
+ print(f"monitor_port_enabled 为False跳过")
554
+
555
  time.sleep(5) # 每5秒检查一次
556
  def Run_SillyTavern():
557
+ os.chdir(data_folder)
 
558
  try:
 
559
  # 启动 Node.js 服务器,并将输出重定向到 /dev/null
560
  subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
561
  subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
 
564
  subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
565
  print("已尝试启动 server.js")
566
  except subprocess.CalledProcessError as e:
567
+ print(f"命令失败,返回码: {e.returncode}")
568
  except Exception as e: # 捕获所有其他异常
569
+ print(f"发生异常: {e}")
570
+
571
  def SillyTavern():
572
  print('-----------SillyTavern开始-------------')
573
  # 创建目录并写入 kaggle.json
 
582
  os.system(f"rm -r /a /sillytavern /*.zi* {data_folder}")
583
  os.system(f"mkdir -p {data_folder}")
584
  os.chdir('/')
585
+ print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
586
+ # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
 
587
  download_n = 0
588
+ while True:
589
+ # 执行下载命令
590
+ if download_n > 6:
591
+ break
592
+ os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
593
+ # 检查文件是否存在
594
+ if os.path.exists(f'/{huggingface_Data_name}.zip'):
595
+ print(f"{huggingface_Data_name}.zip 下载成功!")
596
+ break # 跳出循环
597
+ print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
598
+ download_n += 1
599
+ time.sleep(300) # 等待一段时间再重试(例如5秒
600
+ # os.system('kaggle datasets download xovale7506/sillytavern-data2')
601
+ # 检查文件是否存在
602
+ if not os.path.exists(f'/{huggingface_Data_name}.zip'):
603
+ print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
604
+ generate_ssh_key()
605
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
606
+ subprocess.run(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",shell=True, check=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
  else:
608
+
609
  # 如果文件存在,可以继续执行后续代码
610
  print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
611
+ # # 解压 sillytavern.zip
612
+ # os.system("rm *.zip")
613
+
614
+ os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
615
+ # os.system("mv /sillytavern.zip1 /sillytavern.zip")
616
+ # os.system("7z x /sillytavern.zip -o/sillytavern -y")
617
+ os.system("mv /sillytavern.tck sillytavern.tar.gz")
618
+ os.system("mv /sillytavern.ctk sillytavern.tar.gz")
619
+ os.system("ls /")
620
+ # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
621
+ os.system(f"tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
622
+ # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
623
+
624
+ print('更新文件')
625
+ # os.system('git pull --rebase --autostash')
626
+
627
+ os.chdir(data_folder)
628
+ os.system(f"ls {data_folder}")
629
+ os.system("nvm install node")
630
+ os.system("nvm use node")
631
+ os.system("npm install -y")
632
  try:
633
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
634
+ except subprocess.CalledProcessError as e:
635
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
636
+ print("Output:", e.output)
637
+ os.system(f"ls {data_folder}")
638
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
639
+ backup_thread.start()
640
+ os.system("rm -r /qilan-st2.zip /sillytavern.tar.gz")
641
+ print('-----------SillyTavern结束-------------')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  threading.Thread(target=SillyTavern, daemon=True).start()
643
  time.sleep(60)
644
  check_api1()
645
 
646
+
647
+ # 创建 ConfigParser 对象
648
+ config = configparser.ConfigParser()
649
+ # 添加一个 'general' 部分
650
+ config.add_section('general')
651
+ # 设置 'monitor_port_enabled' 选项的值为 True
652
+ config.set('general', 'monitor_port_enabled', 'True')
653
+ # 将配置写入到 'config.ini' 文件中
654
+ with open('/config.ini', 'w') as configfile:
655
+ config.write(configfile)
656
+
657
  if os.path.exists(f'{data_folder}/start.sh'):
658
  replace_info_in_file(f'{data_folder}/public/login.html')
659
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
 
660
  backup_thread.start()
661
  print("开始衔接")
662
  Service_status = True
663
  frp(configs, True)
 
664
  threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
665
  while True:
666
  if backup_thread.is_alive():
 
669
  print("备份线程已停止.")
670
  backup_thread = threading.Thread(target=repeat_task, daemon=True)
671
  backup_thread.start()
672
+ # break
673
  time.sleep(5)
674
 
675
  else: