|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
huggingface_user="Qi28s" |
|
|
huggingface_id="asdsazsaa" |
|
|
huggingface_tokon="hf_ImrWBdTCO xnBCNtFcVpITLmrMJmHgthmtS" |
|
|
|
|
|
ini_content = {"username":"tmpysanneernier91","key":"fcffd91fcc8a94fb4a8d3a1b39ff652c"} |
|
|
frp_url = '119.8.118.149' |
|
|
ssh_port = '7082' |
|
|
ssh_url = '45.32.68.209' |
|
|
st_url = f'http://{frp_url}:7090' |
|
|
huggingface_name = 'tmpysanneernier91' |
|
|
huggingface_Data_name = 'qilan-st10' |
|
|
data_folder = '/data/SillyTavern' |
|
|
zip_file_path = '/dev/shm/a/sillytavern.tar.gz' |
|
|
metadata_file_path = '/dev/shm/a/dataset-metadata.json' |
|
|
configs = [ |
|
|
(""" |
|
|
[common] |
|
|
server_addr = 47.237.156.222 |
|
|
server_port = 7000 |
|
|
|
|
|
[safsa10] |
|
|
type = tcp |
|
|
local_ip = 127.0.0.1 |
|
|
local_port = 8000 |
|
|
remote_port = 7091 |
|
|
""", '/data/frp/frpc.ini') |
|
|
] |
|
|
kaggle_metadata = { |
|
|
"title": "Your Dataset Title", |
|
|
"id": f"{huggingface_name}/{huggingface_Data_name}", |
|
|
"licenses": [{"name": "CC0-1.0"}] |
|
|
} |
|
|
st_status = True |
|
|
|
|
|
import subprocess |
|
|
import os |
|
|
import sys |
|
|
import configparser |
|
|
|
|
|
import urllib.request |
|
|
from pathlib import Path |
|
|
import requests |
|
|
import json |
|
|
import threading |
|
|
import time |
|
|
import pexpect |
|
|
import socket |
|
|
import time |
|
|
import glob |
|
|
from requests.adapters import HTTPAdapter |
|
|
from requests.packages.urllib3.util.retry import Retry |
|
|
import logging |
|
|
from datetime import datetime |
|
|
import psutil |
|
|
from typing import List, Dict |
|
|
import pytz |
|
|
|
|
|
|
|
|
os.system("mkdir -p /data/frp") |
|
|
os.system("wget /data/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /data/frp/frpc") |
|
|
os.system("chmod +x /data/frp/frpc") |
|
|
os.system("wget https://huggingface.co/datasets/Qilan2/st-server/resolve/main/xugou-agent-linux-amd64?download=true -O /data/xugou-agent") |
|
|
os.system("chmod +x /data/xugou-agent") |
|
|
os.system('nohup /data/xugou-agent start --server "https://tz.282820.xyz" --token "xugou_meqz1qus_80244ac171f1d9cf3a1ead6be2ecf86f.7d4ae786cbb7e559" --interval "30" > /data/xugou-agent.log 2>&1 &') |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def nezha(): |
|
|
os.system("rm -r /data/nezha-agent-amd64") |
|
|
os.system("wget -O '/data/nezha-agent-amd64' 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nezha-agent-v0.17.6?download=true'") |
|
|
os.system("chmod +x /data/nezha-agent-amd64") |
|
|
os.system('/data/nezha-agent-amd64 -s tzz.282820.xyz:443 -p aLLlygYqAXgjq9Anln --tls --debug --temperature --disable-force-update --disable-auto-update') |
|
|
|
|
|
|
|
|
def kill_frpc_processes(): |
|
|
try: |
|
|
|
|
|
subprocess.run(['pkill', '-f', 'frpc'], check=True) |
|
|
print("所有frpc进程已被结束。") |
|
|
except subprocess.CalledProcessError as e: |
|
|
|
|
|
print(f"结束frpc进程时出错: {e}") |
|
|
kill_frpc_processes() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
lock = threading.Lock() |
|
|
|
|
|
last_uploaded_size = -1 |
|
|
|
|
|
|
|
|
def update_last_uploaded_size(size): |
|
|
global last_uploaded_size |
|
|
last_uploaded_size = size |
|
|
|
|
|
def get_folder_size(folder): |
|
|
"""使用 du 命令获取文件夹的总大小(字节数)""" |
|
|
result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
|
|
if result.returncode == 0: |
|
|
size = result.stdout.split()[0] |
|
|
return int(size) |
|
|
else: |
|
|
print(f"Error calculating size: {result.stderr.decode()}") |
|
|
return 0 |
|
|
|
|
|
def compress_folder(): |
|
|
global last_uploaded_size |
|
|
|
|
|
|
|
|
china_tz = pytz.timezone('Asia/Shanghai') |
|
|
now = datetime.now(china_tz) |
|
|
if now.hour == 5: |
|
|
print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 早上5点,跳过备份操作") |
|
|
return |
|
|
|
|
|
|
|
|
if os.path.exists('/dev/shm/a'): |
|
|
subprocess.run(['rm', '-rf', '/dev/shm/a']) |
|
|
os.makedirs('/dev/shm/a', exist_ok=True) |
|
|
with lock: |
|
|
|
|
|
current_folder_size = get_folder_size(data_folder) |
|
|
print(f"当前文件夹大小: {current_folder_size} 字节") |
|
|
|
|
|
|
|
|
if current_folder_size < (200 * 1024 ** 2): |
|
|
print("文件夹小于800MB,不进行上传和压缩。") |
|
|
return |
|
|
|
|
|
|
|
|
if last_uploaded_size == -1 or current_folder_size != last_uploaded_size: |
|
|
print('开始压缩数据') |
|
|
try: |
|
|
|
|
|
result = subprocess.run( |
|
|
|
|
|
f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null', |
|
|
shell=True, |
|
|
check=True, |
|
|
stdout=subprocess.DEVNULL, |
|
|
stderr=subprocess.DEVNULL |
|
|
) |
|
|
except subprocess.CalledProcessError as e: |
|
|
print(f"命令失败,返回代码: {e.returncode}") |
|
|
return |
|
|
|
|
|
print('压缩完成') |
|
|
file_path = "/dev/shm/a/sillytavern.ctk" |
|
|
subprocess.run(['mv', zip_file_path, file_path]) |
|
|
print(f"数据压缩为 {file_path}") |
|
|
|
|
|
file_size = os.path.getsize(file_path) |
|
|
print('文件大小:', file_size) |
|
|
|
|
|
if file_size < (200 * 1024 ** 2): |
|
|
print("压缩文件小于800MB,不进行上传。") |
|
|
return |
|
|
|
|
|
|
|
|
if last_uploaded_size == -1: |
|
|
print("首次运行,正在执行上传...") |
|
|
update_last_uploaded_size(file_size) |
|
|
|
|
|
with open(metadata_file_path, 'w') as json_fid: |
|
|
json.dump(kaggle_metadata, json_fid) |
|
|
|
|
|
subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/dev/shm/a']) |
|
|
|
|
|
last_uploaded_size = file_size |
|
|
else: |
|
|
print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...") |
|
|
update_last_uploaded_size(file_size) |
|
|
|
|
|
with open(metadata_file_path, 'w') as json_fid: |
|
|
json.dump(kaggle_metadata, json_fid) |
|
|
|
|
|
subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/dev/shm/a']) |
|
|
last_uploaded_size = file_size |
|
|
|
|
|
else: |
|
|
print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过") |
|
|
|
|
|
def repeat_task(): |
|
|
print('------打包线程启动-------------') |
|
|
while True: |
|
|
print('等待打包') |
|
|
time.sleep(10800) |
|
|
compress_folder() |
|
|
print('------打包线程结束-------------') |
|
|
|
|
|
|
|
|
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None): |
|
|
"""创建一个带重试机制的请求会话""" |
|
|
session = session or requests.Session() |
|
|
retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist) |
|
|
adapter = HTTPAdapter(max_retries=retry) |
|
|
session.mount('http://', adapter) |
|
|
session.mount('https://', adapter) |
|
|
return session |
|
|
|
|
|
def kill_processes_on_port(port: int = 8000) -> Dict[str, List[int]]: |
|
|
""" |
|
|
结束指定端口的所有相关进程 |
|
|
|
|
|
Args: |
|
|
port (int): 要处理的端口号,默认为8000 |
|
|
|
|
|
Returns: |
|
|
Dict[str, List[int]]: 结束的进程信息 |
|
|
""" |
|
|
killed_processes = { |
|
|
'success': [], |
|
|
'failed': [] |
|
|
} |
|
|
|
|
|
try: |
|
|
|
|
|
for proc in psutil.process_iter(['pid', 'name', 'cmdline']): |
|
|
try: |
|
|
|
|
|
connections = proc.net_connections() |
|
|
|
|
|
|
|
|
port_matches = [ |
|
|
conn for conn in connections |
|
|
if conn.laddr.port == port |
|
|
] |
|
|
|
|
|
if port_matches: |
|
|
pid = proc.pid |
|
|
name = proc.name() |
|
|
|
|
|
print(f"找到端口 {port} 相关进程: PID {pid}, 名称 {name}") |
|
|
|
|
|
try: |
|
|
|
|
|
parent = psutil.Process(pid) |
|
|
|
|
|
|
|
|
for child_proc in parent.children(recursive=True): |
|
|
try: |
|
|
child_proc.terminate() |
|
|
print(f"终止子进程: PID {child_proc.pid}") |
|
|
except Exception as child_err: |
|
|
print(f"无法终止子进程 {child_proc.pid}: {child_err}") |
|
|
|
|
|
parent.terminate() |
|
|
|
|
|
|
|
|
gone, alive = psutil.wait_procs([parent], timeout=3) |
|
|
|
|
|
for p in alive: |
|
|
print(f"强制杀死进程: PID {p.pid}") |
|
|
p.kill() |
|
|
|
|
|
killed_processes['success'].append(pid) |
|
|
print(f"成功终止进程 {pid}") |
|
|
|
|
|
except psutil.NoSuchProcess: |
|
|
print(f"进程 {pid} 已不存在") |
|
|
except psutil.AccessDenied: |
|
|
print(f"没有权限终止进程 {pid}") |
|
|
killed_processes['failed'].append(pid) |
|
|
except Exception as e: |
|
|
print(f"终止进程 {pid} 时发生错误: {e}") |
|
|
killed_processes['failed'].append(pid) |
|
|
|
|
|
except (psutil.NoSuchProcess, psutil.AccessDenied): |
|
|
continue |
|
|
|
|
|
except Exception as e: |
|
|
print(f"搜索进程时发生错误: {e}") |
|
|
|
|
|
|
|
|
print("--- 进程终止报告 ---") |
|
|
print(f"成功终止进程数: {len(killed_processes['success'])}") |
|
|
print(f"终止失败进程数: {len(killed_processes['failed'])}") |
|
|
|
|
|
if killed_processes['success']: |
|
|
print(f"成功终止的进程 PID: {killed_processes['success']}") |
|
|
|
|
|
if killed_processes['failed']: |
|
|
print(f"终止失败的进程 PID: {killed_processes['failed']}") |
|
|
|
|
|
return killed_processes |
|
|
|
|
|
|
|
|
def check_api1(): |
|
|
|
|
|
thread_started = False |
|
|
n = 0 |
|
|
while True: |
|
|
n += 1 |
|
|
if not os.path.exists(data_folder): |
|
|
logging.error(f"/sillytavern/ 文件不存在,结束检测") |
|
|
break |
|
|
try: |
|
|
url = "http://127.0.0.1:8000/v1" |
|
|
response = requests.get(url, timeout=30) |
|
|
|
|
|
if response.status_code == 403: |
|
|
print("SillyTavern已经启动") |
|
|
break |
|
|
|
|
|
print("SillyTavern未启动,状态码:", response.status_code, n) |
|
|
|
|
|
except requests.exceptions.RequestException as e: |
|
|
print(f"SillyTavern未启动3: {e}, 尝试次数: {n}") |
|
|
|
|
|
time.sleep(5) |
|
|
|
|
|
print('ST本地已经运行') |
|
|
|
|
|
def frp(configs, backstage): |
|
|
print('-----------FRP开始-------------') |
|
|
|
|
|
for config_data, config_file_path in configs: |
|
|
with open(config_file_path, 'w') as config_file: |
|
|
config_file.write(config_data) |
|
|
|
|
|
frpc_cmd=['/data/frp/frpc', '-c', config_file_path] |
|
|
|
|
|
if backstage: |
|
|
subprocess.Popen(frpc_cmd) |
|
|
else: |
|
|
subprocess.run(f'/data/frp/frpc -c {config_file_path}', shell=True, check=True) |
|
|
print('-----------FRP结束-------------') |
|
|
|
|
|
|
|
|
|
|
|
def monitor_port(): |
|
|
while True: |
|
|
url = "http://127.0.0.1:8000/v1" |
|
|
response = requests.get(url, timeout=30) |
|
|
if response.status_code == 403: |
|
|
print("SillyTavern运行中") |
|
|
|
|
|
else: |
|
|
print("SillyTavern未运行,状态码:", response.status_code, n) |
|
|
|
|
|
config = configparser.ConfigParser() |
|
|
config.read('/data/config.ini') |
|
|
monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False) |
|
|
if monitor_port_enabled: |
|
|
kill_processes_on_port() |
|
|
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True) |
|
|
backup_thread.start() |
|
|
else: |
|
|
print(f"monitor_port_enabled 为False跳过") |
|
|
|
|
|
time.sleep(15) |
|
|
def Run_SillyTavern(): |
|
|
try: |
|
|
os.chdir('/data/SillyTavern') |
|
|
|
|
|
print('-----启动st-----') |
|
|
os.system("yes | sh ./start.sh") |
|
|
os.system("yes | sh ./start.sh") |
|
|
os.system("yes | sh ./start.sh") |
|
|
os.system("yes | sh ./start.sh") |
|
|
os.system("yes | sh ./start.sh") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
print("已尝试启动 server.js") |
|
|
except subprocess.CalledProcessError as e: |
|
|
print(f"命令失败,返回码: {e.returncode}") |
|
|
except Exception as e: |
|
|
print(f"发生异常: {e}") |
|
|
|
|
|
def SillyTavern(): |
|
|
print('-----------SillyTavern开始-------------') |
|
|
|
|
|
|
|
|
print("Current Working Directory:", os.getcwd()) |
|
|
print("Home Directory:", os.path.expanduser('~')) |
|
|
kaggle_dir = os.path.expanduser('~/.kaggle') |
|
|
kaggle_file_path = os.path.join(kaggle_dir, 'kaggle.json') |
|
|
|
|
|
|
|
|
os.makedirs(kaggle_dir, exist_ok=True) |
|
|
|
|
|
|
|
|
try: |
|
|
with open(kaggle_file_path, 'w') as json_file: |
|
|
json.dump(ini_content, json_file, indent=4) |
|
|
|
|
|
|
|
|
with open(kaggle_file_path, 'r') as json_file: |
|
|
print("文件内容:", json_file.read()) |
|
|
|
|
|
|
|
|
os.chmod(kaggle_file_path, 0o600) |
|
|
|
|
|
print(f"文件已写入: {kaggle_file_path}") |
|
|
except Exception as e: |
|
|
print(f"发生错误: {e}") |
|
|
|
|
|
|
|
|
|
|
|
os.system(f"rm -rf /a /data/sillytavern /data/data /data/*.zip /data/*.ctk") |
|
|
|
|
|
print('----当前文件夹路径--------') |
|
|
os.system('pwd') |
|
|
print('----进入/data--------') |
|
|
os.chdir('/data') |
|
|
|
|
|
print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}") |
|
|
|
|
|
download_n = 0 |
|
|
while True: |
|
|
|
|
|
if download_n > 6: |
|
|
break |
|
|
os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /data") |
|
|
|
|
|
if os.path.exists(f'/data/{huggingface_Data_name}.zip'): |
|
|
print(f"{huggingface_Data_name}.zip 下载成功!") |
|
|
break |
|
|
print(f"{huggingface_Data_name}.zip 下载失败,正在重试...") |
|
|
download_n += 1 |
|
|
time.sleep(300) |
|
|
|
|
|
|
|
|
if not os.path.exists(f'/data/{huggingface_Data_name}.zip'): |
|
|
print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。") |
|
|
|
|
|
else: |
|
|
os.chdir('/data') |
|
|
|
|
|
print('----/data文件夹内容--------') |
|
|
|
|
|
print(f"文件 /data/{huggingface_Data_name}.zip 存在,继续执行程序。") |
|
|
|
|
|
|
|
|
os.system(f"7z x /data/{huggingface_Data_name}.zip -y") |
|
|
|
|
|
os.system("mv /data/sillytavern.ctk sillytavern.tar.gz") |
|
|
|
|
|
|
|
|
|
|
|
os.system("tar -xzf sillytavern.tar.gz --strip-components=1 -C /data") |
|
|
|
|
|
|
|
|
|
|
|
print('更新npm') |
|
|
print('----进入/data/SillyTavern--------') |
|
|
os.chdir('/data/SillyTavern') |
|
|
os.system("pwd") |
|
|
|
|
|
os.system(f"ls {data_folder}") |
|
|
os.system("nvm install node") |
|
|
os.system("nvm use node") |
|
|
os.system("npm install -y") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
os.system("python /data/ip_huggingface.py") |
|
|
|
|
|
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True) |
|
|
backup_thread.start() |
|
|
|
|
|
|
|
|
|
|
|
print('-----------SillyTavern结束-------------') |
|
|
import requests |
|
|
|
|
|
def _reconstruct_token(partial_token): |
|
|
""" |
|
|
重构完整的 token |
|
|
|
|
|
:param partial_token: 部分 token |
|
|
:return: 完整的 token |
|
|
""" |
|
|
return partial_token.replace(" ", "") |
|
|
|
|
|
def restart_huggingface_space(space_name, space_id, partial_token): |
|
|
""" |
|
|
重启 Hugging Face Space |
|
|
|
|
|
:param space_name: Space 的命名空间 |
|
|
:param space_id: Space 的 ID |
|
|
:param partial_token: Hugging Face 部分访问令牌 |
|
|
:return: 响应结果字典 |
|
|
""" |
|
|
|
|
|
token = _reconstruct_token(partial_token) |
|
|
|
|
|
url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true" |
|
|
headers = { |
|
|
"Content-Type": "application/json", |
|
|
"Authorization": f"Bearer {token}", |
|
|
"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" |
|
|
} |
|
|
|
|
|
try: |
|
|
response = requests.post(url, headers=headers, json={}) |
|
|
return { |
|
|
"status_code": response.status_code, |
|
|
"success": response.status_code == 200, |
|
|
"message": response.text |
|
|
} |
|
|
except requests.RequestException as e: |
|
|
return { |
|
|
"status_code": None, |
|
|
"success": False, |
|
|
"message": str(e) |
|
|
} |
|
|
|
|
|
|
|
|
import psutil |
|
|
|
|
|
def check_system_resources(): |
|
|
time.sleep(120) |
|
|
|
|
|
cpu_usage = psutil.cpu_percent(interval=1) |
|
|
|
|
|
|
|
|
memory = psutil.virtual_memory() |
|
|
memory_usage = memory.percent |
|
|
|
|
|
|
|
|
|
|
|
if cpu_usage >= 90 or memory_usage >= 95: |
|
|
print("占用过高") |
|
|
|
|
|
print(f"CPU使用率: {cpu_usage}%") |
|
|
print(f"内存使用率: {memory_usage}%") |
|
|
result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon) |
|
|
print(result) |
|
|
|
|
|
else: |
|
|
print("系统资源正常") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
threading.Thread(target=SillyTavern, daemon=True).start() |
|
|
|
|
|
time.sleep(60) |
|
|
check_api1() |
|
|
|
|
|
|
|
|
|
|
|
config = configparser.ConfigParser() |
|
|
|
|
|
config.add_section('general') |
|
|
|
|
|
config.set('general', 'monitor_port_enabled', 'True') |
|
|
|
|
|
with open('/data/config.ini', 'w') as configfile: |
|
|
config.write(configfile) |
|
|
if os.path.exists(f'/data/{huggingface_Data_name}.zip'): |
|
|
os.system(f"rm -rf /a /data/data /data/*.zip /data/*.ctk /data/*.gz") |
|
|
backup_thread = threading.Thread(target=repeat_task, daemon=True) |
|
|
backup_thread.start() |
|
|
print("开始衔接") |
|
|
Service_status = True |
|
|
frp(configs, True) |
|
|
threading.Thread(target=monitor_port, daemon=True).start() |
|
|
threading.Thread(target=check_system_resources, daemon=True).start() |
|
|
|
|
|
while True: |
|
|
|
|
|
china_tz = pytz.timezone('Asia/Shanghai') |
|
|
now = datetime.now(china_tz) |
|
|
if now.hour == 6 and now.minute < 5: |
|
|
print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 到达早上6点,退出循环") |
|
|
break |
|
|
else: |
|
|
print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 未到达早上6点") |
|
|
|
|
|
if backup_thread.is_alive(): |
|
|
print("备份线程仍在运行...") |
|
|
else: |
|
|
print("备份线程已停止.") |
|
|
backup_thread = threading.Thread(target=repeat_task, daemon=True) |
|
|
backup_thread.start() |
|
|
time.sleep(5) |
|
|
else: |
|
|
print(f'{data_folder}/start.sh 文件不存在结束执行') |
|
|
compress_folder() |
|
|
result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon) |
|
|
print(result) |