Qilan2 commited on
Commit
fb571c0
·
verified ·
1 Parent(s): 460b3ca

Create server10.py

Browse files
Files changed (1) hide show
  1. server10.py +431 -0
server10.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ini_content = {"username":"tmpysanneernier91","key":"fcffd91fcc8a94fb4a8d3a1b39ff652c"}
2
+ frp_url = '119.8.118.149'
3
+ ssh_port = '7082'
4
+ ssh_url = '45.32.68.209'
5
+ st_url = f'http://{frp_url}:7082'
6
+ huggingface_name = 'tmpysanneernier91'
7
+ huggingface_Data_name = 'qilan-st10'
8
+ data_folder = '/data/SillyTavern' # 要压缩的目录
9
+ zip_file_path = '/dev/shm/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
10
+ metadata_file_path = '/dev/shm/a/dataset-metadata.json'
11
+ configs = [
12
+ ("""
13
+ [common]
14
+ server_addr = 47.237.156.222
15
+ server_port = 7000
16
+
17
+ [safsa10]
18
+ type = tcp
19
+ local_ip = 127.0.0.1
20
+ local_port = 8000
21
+ remote_port = 7091
22
+ """, '/data/frp/frpc.ini'),
23
+ (f"""
24
+ [common]
25
+ server_addr = {frp_url}
26
+ server_port = 7000
27
+ token = qilan
28
+ [1kkjmk99]
29
+ type = tcp
30
+ local_ip = 127.0.0.1
31
+ local_port = 8000
32
+ remote_port = 7082
33
+ """, '/data/frp/frpc1.ini'),
34
+ ("""
35
+ [common]
36
+ server_addr = 43.134.75.213
37
+ server_port = 7000
38
+ [2kjas9]
39
+ type = tcp
40
+ local_ip = 127.0.0.1
41
+ local_port = 8000
42
+ remote_port = 7079
43
+ """, '/data/frp/frpc2.ini'),
44
+ ("""
45
+ [common]
46
+ server_addr = 8.210.217.27
47
+ server_port = 7000
48
+ [3kja1sh9]
49
+ type = tcp
50
+ local_ip = 127.0.0.1
51
+ local_port = 8000
52
+ remote_port = 7079
53
+ """, '/data/frp/frpc3.ini'),
54
+ ("""
55
+ [common]
56
+ server_addr = 45.32.68.209
57
+ server_port=7000
58
+ [4kkji1mk9]
59
+ type=tcp
60
+ local_ip=127.0.0.1
61
+ local_port=8000
62
+ remote_port=7079
63
+ """, '/data/frp/frpc4.ini'),
64
+ (f"""
65
+ [common]
66
+ server_addr = {ssh_url}
67
+ server_port=7000
68
+ [5kkji1mk99]
69
+ type=tcp
70
+ local_ip=127.0.0.1
71
+ local_port=22
72
+ remote_port={ssh_port}
73
+ """, '/data/frp/frpc5.ini')
74
+ ]
75
+ kaggle_metadata = {
76
+ "title": "Your Dataset Title",
77
+ "id": f"{huggingface_name}/{huggingface_Data_name}",
78
+ "licenses": [{"name": "CC0-1.0"}]
79
+ }
80
+ st_status = True
81
+ import subprocess
82
+ import os
83
+ import sys
84
+ import configparser
85
+ from IPython.display import clear_output
86
+ import urllib.request
87
+ from pathlib import Path
88
+ import requests
89
+ import json
90
+ import threading
91
+ import time
92
+ import pexpect
93
+ import socket
94
+ import time
95
+ import glob # 导入 glob 模块
96
+ from requests.adapters import HTTPAdapter
97
+ from requests.packages.urllib3.util.retry import Retry
98
+ import logging
99
+ os.system("rm -r /sync.sh")
100
+ os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh" )
101
+ os.system("export LC_ALL=zh_CN.UTF-8")
102
+ # 创建 FRP 文件夹并下载 frpc 可执行文件。
103
+ os.system("mkdir -p /data/frp")
104
+ os.system("wget /data/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /data/frp/frpc")
105
+ os.system("chmod +x /data/frp/frpc")
106
+
107
+
108
+
109
+ def kill_frpc_processes():
110
+ try:
111
+ # 使用pkill命令结束所有frpc进程
112
+ subprocess.run(['pkill', '-f', 'frpc'], check=True)
113
+ print("所有frpc进程已被结束。")
114
+ except subprocess.CalledProcessError as e:
115
+ # 如果pkill命令失败,打印错误信息
116
+ print(f"结束frpc进程时出错: {e}")
117
+ kill_frpc_processes()
118
+
119
+
120
+
121
+
122
+
123
+ # 创建一个锁
124
+ lock = threading.Lock()
125
+
126
+ last_uploaded_size = -1
127
+
128
+
129
+ def update_last_uploaded_size(size):
130
+ global last_uploaded_size
131
+ last_uploaded_size = size
132
+
133
+ def get_folder_size(folder):
134
+ """使用 du 命令获取文件夹的总大小(字节数)"""
135
+ result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
136
+ if result.returncode == 0:
137
+ size = result.stdout.split()[0] # 获取大小
138
+ return int(size)
139
+ else:
140
+ print(f"Error calculating size: {result.stderr.decode()}")
141
+ return 0
142
+
143
+ def compress_folder():
144
+ global last_uploaded_size # 声明使用全局变量
145
+ # 清理并创建目录 /a
146
+ if os.path.exists('/dev/shm/a'):
147
+ subprocess.run(['rm', '-rf', '/dev/shm/a'])
148
+ os.makedirs('/dev/shm/a', exist_ok=True)
149
+ with lock: # 使用锁
150
+ # 获取当前文件夹的大小
151
+ current_folder_size = get_folder_size(data_folder)
152
+ print(f"当前文件夹大小: {current_folder_size} 字节")
153
+
154
+ # 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
155
+ if current_folder_size < (800 * 1024 ** 2):
156
+ print("文件夹小于800MB,不进行上传和压缩。")
157
+ return
158
+
159
+ # 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
160
+ if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
161
+ print('开始压缩数据')
162
+ try:
163
+ # 执行压缩
164
+ result = subprocess.run(
165
+ f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
166
+ shell=True,
167
+ check=True,
168
+ stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
169
+ stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
170
+ )
171
+ except subprocess.CalledProcessError as e:
172
+ print(f"命令失败,返回代码: {e.returncode}")
173
+ return
174
+
175
+ print('压缩完成')
176
+ file_path = "/dev/shm/a/sillytavern.ctk"
177
+ subprocess.run(['mv', zip_file_path, file_path])
178
+ print(f"数据压缩为 {file_path}")
179
+
180
+ file_size = os.path.getsize(file_path) # 获取压缩包的大小
181
+ print('文件大小:', file_size)
182
+
183
+ if file_size < (800 * 1024 ** 2): # 判断压缩后的大小是否小于 800MB
184
+ print("压缩文件小于800MB,不进行上传。")
185
+ return
186
+
187
+ # 执行上传
188
+ if last_uploaded_size == -1:
189
+ print("首次运行,正在执行上传...")
190
+ update_last_uploaded_size(file_size)
191
+
192
+ with open(metadata_file_path, 'w') as json_fid:
193
+ json.dump(kaggle_metadata, json_fid)
194
+
195
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/dev/shm/a'])
196
+ #kaggle datasets version -m 'new version message' -p /dev/shm/a
197
+ last_uploaded_size = file_size
198
+ else:
199
+ print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
200
+ update_last_uploaded_size(file_size)
201
+
202
+ with open(metadata_file_path, 'w') as json_fid:
203
+ json.dump(kaggle_metadata, json_fid)
204
+
205
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/dev/shm/a'])
206
+ last_uploaded_size = file_size
207
+
208
+ else:
209
+ print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")
210
+
211
+ def repeat_task():
212
+ print('------打包线程启动-------------')
213
+ while True:
214
+ print('等待打包')
215
+ time.sleep(18000)
216
+ compress_folder()
217
+ print('------打包线程结束-------------')
218
+
219
+
220
+ def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
221
+ """创建一个带重试机制的请求会话"""
222
+ session = session or requests.Session()
223
+ retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
224
+ adapter = HTTPAdapter(max_retries=retry)
225
+ session.mount('http://', adapter)
226
+ session.mount('https://', adapter)
227
+ return session
228
+
229
+
230
+
231
+ def check_api1():
232
+ # 第一次检查 SillyTavern 是否启动
233
+ thread_started = False
234
+ n = 0
235
+ while True:
236
+ n += 1
237
+ if not os.path.exists(data_folder):
238
+ logging.error(f"/sillytavern/ 文件不存在,结束检测")
239
+ break
240
+ try:
241
+ url = "http://127.0.0.1:8000/v1"
242
+ response = requests.get(url, timeout=30)
243
+
244
+ if response.status_code == 403:
245
+ print("SillyTavern已经启动")
246
+ break
247
+
248
+ print("SillyTavern未启动,状态码:", response.status_code, n)
249
+
250
+ except requests.exceptions.RequestException as e:
251
+ print(f"SillyTavern未启动3: {e}, 尝试次数: {n}")
252
+
253
+ time.sleep(5)
254
+
255
+ print('ST本地已经运行')
256
+
257
+ def frp(configs, backstage):
258
+ print('-----------FRP开始-------------')
259
+ # 遍历所有配置并启动 FRP。
260
+ for config_data, config_file_path in configs:
261
+ with open(config_file_path, 'w') as config_file:
262
+ config_file.write(config_data)
263
+ # 启动 frpc 命令和参数。
264
+ frpc_cmd=['/data/frp/frpc', '-c', config_file_path]
265
+
266
+ if backstage:
267
+ subprocess.Popen(frpc_cmd)
268
+ else:
269
+ subprocess.run(f'/data/frp/frpc -c {config_file_path}', shell=True, check=True)
270
+ print('-----------FRP结束-------------')
271
+
272
+
273
+
274
+ def monitor_port():
275
+ while True:
276
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
277
+ result = sock.connect_ex(('localhost', 8000))
278
+ if result == 0:
279
+ print(f"端口 8000 正在使用中")
280
+ else:
281
+ print(f"端口 8000 未被使用")
282
+ # 读取 config.ini 中的 monitor_port_enabled 配置项
283
+ config = configparser.ConfigParser()
284
+ config.read('/data/config.ini')
285
+ monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
286
+ if monitor_port_enabled:
287
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
288
+ backup_thread.start()
289
+ else:
290
+ print(f"monitor_port_enabled 为False跳过")
291
+
292
+ time.sleep(5) # 每5秒检查一次
293
+ def Run_SillyTavern():
294
+ os.chdir(data_folder)
295
+ try:
296
+ # 启动 Node.js 服务器,并将输出重定向到 /dev/null
297
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
298
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
299
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
300
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
301
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
302
+
303
+ print("已尝试启动 server.js")
304
+ except subprocess.CalledProcessError as e:
305
+ print(f"命令失败,返回码: {e.returncode}")
306
+ except Exception as e: # 捕获所有其他异常
307
+ print(f"发生异常: {e}")
308
+
309
+ def SillyTavern():
310
+ print('-----------SillyTavern开始-------------')
311
+ # 创建目录并写入 kaggle.json
312
+
313
+
314
+ # 打印当前工作目录和用户主目录
315
+ print("Current Working Directory:", os.getcwd())
316
+ print("Home Directory:", os.path.expanduser('~'))
317
+ kaggle_dir = os.path.expanduser('~/.kaggle')
318
+ kaggle_file_path = os.path.join(kaggle_dir, 'kaggle.json')
319
+
320
+ # 确保目录存在
321
+ os.makedirs(kaggle_dir, exist_ok=True)
322
+
323
+ # 显式写入并验证
324
+ try:
325
+ with open(kaggle_file_path, 'w') as json_file:
326
+ json.dump(ini_content, json_file, indent=4)
327
+
328
+ # 验证文件内容
329
+ with open(kaggle_file_path, 'r') as json_file:
330
+ print("文件内容:", json_file.read())
331
+
332
+ # 设置权限
333
+ os.chmod(kaggle_file_path, 0o600)
334
+
335
+ print(f"文件已写入: {kaggle_file_path}")
336
+ except Exception as e:
337
+ print(f"发生错误: {e}")
338
+
339
+
340
+
341
+ os.system(f"rm -rf /a /data/sillytavern /data/data /data/*.zip /data/*.ctk")
342
+ # os.system(f"mkdir -p {data_folder}")
343
+ os.chdir('/data')
344
+ os.system("ls")
345
+ print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
346
+ # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
347
+ download_n = 0
348
+ while True:
349
+ # 执行下载命令
350
+ if download_n > 6:
351
+ break
352
+ os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /data")
353
+ # 检查文件是否存在
354
+ if os.path.exists(f'/data/{huggingface_Data_name}.zip'):
355
+ print(f"{huggingface_Data_name}.zip 下载成功!")
356
+ break # 跳出循环
357
+ print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
358
+ download_n += 1
359
+ time.sleep(300) # 等待一段时间再重试(例如5秒
360
+ # os.system('kaggle datasets download xovale7506/sillytavern-data2')
361
+ # 检查文件是否存在
362
+ if not os.path.exists(f'/data/{huggingface_Data_name}.zip'):
363
+ print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
364
+
365
+ else:
366
+
367
+ # 如果文件存在,可以继续执行后续代码
368
+ print(f"文件 /data/{huggingface_Data_name}.zip 存在,继续执行程序。")
369
+ # # 解压 sillytavern.zip
370
+ # os.system("rm *.zip")
371
+ os.system(f"7z x /data/{huggingface_Data_name}.zip -y")
372
+ os.system("mv /data/sillytavern.tck sillytavern.tar.gz")
373
+ os.system("mv /data/sillytavern.ctk sillytavern.tar.gz")
374
+ os.system("ls /data")
375
+ # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
376
+ os.system(f"tar -xvpf /data/sillytavern.tar.gz -C /data --use-compress-program=pigz > /dev/null")
377
+ # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
378
+ os.system("mv /data/data/SillyTavern /data/SillyTavern")
379
+
380
+ print('更新文件')
381
+ os.chdir('/data/SillyTavern')
382
+ os.system(f"ls {data_folder}")
383
+ os.system("nvm install node")
384
+ os.system("nvm use node")
385
+ os.system("npm install -y")
386
+ try:
387
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
388
+ except subprocess.CalledProcessError as e:
389
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
390
+ print("Output:", e.output)
391
+ os.system(f"ls {data_folder}")
392
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
393
+ backup_thread.start()
394
+ # os.system(f"rm -rf /a /data/sillytavern /data/data /data/*.zip /data/*.ctk")
395
+
396
+ print('-----------SillyTavern结束-------------')
397
+ threading.Thread(target=SillyTavern, daemon=True).start()
398
+ # SillyTavern()
399
+ time.sleep(60)
400
+ check_api1()
401
+
402
+ compress_folder()
403
+ # 创建 ConfigParser 对象
404
+ config = configparser.ConfigParser()
405
+ # 添加一个 'general' 部分
406
+ config.add_section('general')
407
+ # 设置 'monitor_port_enabled' 选项的值为 True
408
+ config.set('general', 'monitor_port_enabled', 'True')
409
+ # 将配置写入到 'config.ini' 文件中
410
+ with open('/data/config.ini', 'w') as configfile:
411
+ config.write(configfile)
412
+ if os.path.exists(f'/data/{huggingface_Data_name}.zip'):
413
+ os.system(f"rm -rf /a /data/data /data/*.zip /data/*.ctk /data/*.gz")
414
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
415
+ backup_thread.start()
416
+ print("开始衔接")
417
+ Service_status = True
418
+ frp(configs, True)
419
+ threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
420
+ while True:
421
+ if backup_thread.is_alive():
422
+ print("备份线程仍在运行...")
423
+ else:
424
+ print("备份线程已停止.")
425
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)
426
+ backup_thread.start()
427
+ # break
428
+ time.sleep(5)
429
+ else:
430
+ print(f'{data_folder}/start.sh 文件不存在结束执行')
431
+ compress_folder()