Skip to content

Commit 39de892

Browse files
committed
add Docker Client API地址
1 parent ac94196 commit 39de892

File tree

7 files changed

+127
-117
lines changed

7 files changed

+127
-117
lines changed

app/api/endpoints/plugin.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -395,10 +395,6 @@ def save_plugin_folders(folders: dict, _: schemas.TokenPayload = Depends(get_cur
395395
"""
396396
try:
397397
SystemConfigOper().set(SystemConfigKey.PluginFolders, folders)
398-
399-
# 验证保存结果
400-
saved_result = SystemConfigOper().get(SystemConfigKey.PluginFolders)
401-
402398
return schemas.Response(success=True)
403399
except Exception as e:
404400
logger.error(f"[文件夹API] 保存文件夹配置失败: {str(e)}")

app/api/endpoints/system.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@
3636
from app.utils.crypto import HashUtils
3737
from app.utils.http import RequestUtils
3838
from app.utils.security import SecurityUtils
39-
from app.utils.system import SystemUtils
4039
from app.utils.url import UrlUtils
40+
from helper.system import SystemHelper
4141
from version import APP_VERSION
4242

4343
router = APIRouter()
@@ -474,12 +474,12 @@ def restart_system(_: User = Depends(get_current_active_superuser)):
474474
"""
475475
重启系统(仅管理员)
476476
"""
477-
if not SystemUtils.can_restart():
477+
if not SystemHelper.can_restart():
478478
return schemas.Response(success=False, message="当前运行环境不支持重启操作!")
479479
# 标识停止事件
480480
global_vars.stop_system()
481481
# 执行重启
482-
ret, msg = SystemUtils.restart()
482+
ret, msg = SystemHelper.restart()
483483
return schemas.Response(success=ret, message=msg)
484484

485485

app/chain/system.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from app.utils.http import RequestUtils
1111
from app.utils.singleton import Singleton
1212
from app.utils.system import SystemUtils
13+
from helper.system import SystemHelper
1314
from version import FRONTEND_VERSION, APP_VERSION
1415

1516

@@ -45,7 +46,8 @@ def restart(self, channel: MessageChannel, userid: Union[int, str], source: Opti
4546
"channel": channel.value,
4647
"userid": userid
4748
}, self._restart_file)
48-
SystemUtils.restart()
49+
# 重启
50+
SystemHelper.restart()
4951

5052
def __get_version_message(self) -> str:
5153
"""

app/core/config.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,8 @@ class Config:
280280
TOKENIZED_SEARCH: bool = False
281281
# 为指定默认字幕添加.default后缀
282282
DEFAULT_SUB: Optional[str] = "zh-cn"
283+
# Docker Client API地址
284+
DOCKER_CLIENT_API: Optional[str] = "tcp://127.0.0.1:38379"
283285

284286

285287
class Settings(BaseSettings, ConfigModel, LogConfigModel):

app/helper/resource.py

Lines changed: 68 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from app.utils.singleton import Singleton
99
from app.utils.string import StringUtils
1010
from app.utils.system import SystemUtils
11+
from helper.system import SystemHelper
1112

1213

1314
class ResourceHelper(metaclass=Singleton):
@@ -32,80 +33,80 @@ def check(self):
3233
检测是否有更新,如有则下载安装
3334
"""
3435
if not settings.AUTO_UPDATE_RESOURCE:
35-
return
36+
return None
3637
if SystemUtils.is_frozen():
37-
return
38+
return None
3839
logger.info("开始检测资源包版本...")
3940
res = RequestUtils(proxies=self.proxies, headers=settings.GITHUB_HEADERS, timeout=10).get_res(self._repo)
4041
if res:
4142
try:
4243
resource_info = json.loads(res.text)
44+
online_version = resource_info.get("version")
45+
if online_version:
46+
logger.info(f"最新资源包版本:v{online_version}")
47+
# 需要更新的资源包
48+
need_updates = {}
49+
# 资源明细
50+
resources: dict = resource_info.get("resources") or {}
51+
for rname, resource in resources.items():
52+
rtype = resource.get("type")
53+
platform = resource.get("platform")
54+
target = resource.get("target")
55+
version = resource.get("version")
56+
# 判断平台
57+
if platform and platform != SystemUtils.platform():
58+
continue
59+
# 判断版本号
60+
if rtype == "auth":
61+
# 站点认证资源
62+
local_version = self.siteshelper.auth_version
63+
elif rtype == "sites":
64+
# 站点索引资源
65+
local_version = self.siteshelper.indexer_version
66+
else:
67+
continue
68+
if StringUtils.compare_version(version, ">", local_version):
69+
logger.info(f"{rname} 资源包有更新,最新版本:v{version}")
70+
else:
71+
continue
72+
# 需要安装
73+
need_updates[rname] = target
74+
if need_updates:
75+
# 下载文件信息列表
76+
r = RequestUtils(proxies=settings.PROXY, headers=settings.GITHUB_HEADERS,
77+
timeout=30).get_res(self._files_api)
78+
if r and not r.ok:
79+
return None, f"连接仓库失败:{r.status_code} - {r.reason}"
80+
elif not r:
81+
return None, "连接仓库失败"
82+
files_info = r.json()
83+
for item in files_info:
84+
save_path = need_updates.get(item.get("name"))
85+
if not save_path:
86+
continue
87+
if item.get("download_url"):
88+
logger.info(f"开始更新资源文件:{item.get('name')} ...")
89+
download_url = f"{settings.GITHUB_PROXY}{item.get('download_url')}"
90+
# 下载资源文件
91+
res = RequestUtils(proxies=self.proxies, headers=settings.GITHUB_HEADERS,
92+
timeout=180).get_res(download_url)
93+
if not res:
94+
logger.error(f"文件 {item.get('name')} 下载失败!")
95+
elif res.status_code != 200:
96+
logger.error(f"下载文件 {item.get('name')} 失败:{res.status_code} - {res.reason}")
97+
# 创建插件文件夹
98+
file_path = self._base_dir / save_path / item.get("name")
99+
if not file_path.parent.exists():
100+
file_path.parent.mkdir(parents=True, exist_ok=True)
101+
# 写入文件
102+
file_path.write_bytes(res.content)
103+
logger.info("资源包更新完成,开始重启服务...")
104+
SystemHelper.restart()
105+
else:
106+
logger.info("所有资源已最新,无需更新")
43107
except json.JSONDecodeError:
44108
logger.error("资源包仓库数据解析失败!")
45-
return
109+
return None
46110
else:
47111
logger.warn("无法连接资源包仓库!")
48-
return
49-
online_version = resource_info.get("version")
50-
if online_version:
51-
logger.info(f"最新资源包版本:v{online_version}")
52-
# 需要更新的资源包
53-
need_updates = {}
54-
# 资源明细
55-
resources: dict = resource_info.get("resources") or {}
56-
for rname, resource in resources.items():
57-
rtype = resource.get("type")
58-
platform = resource.get("platform")
59-
target = resource.get("target")
60-
version = resource.get("version")
61-
# 判断平台
62-
if platform and platform != SystemUtils.platform():
63-
continue
64-
# 判断版本号
65-
if rtype == "auth":
66-
# 站点认证资源
67-
local_version = self.siteshelper.auth_version
68-
elif rtype == "sites":
69-
# 站点索引资源
70-
local_version = self.siteshelper.indexer_version
71-
else:
72-
continue
73-
if StringUtils.compare_version(version, ">", local_version):
74-
logger.info(f"{rname} 资源包有更新,最新版本:v{version}")
75-
else:
76-
continue
77-
# 需要安装
78-
need_updates[rname] = target
79-
if need_updates:
80-
# 下载文件信息列表
81-
r = RequestUtils(proxies=settings.PROXY, headers=settings.GITHUB_HEADERS,
82-
timeout=30).get_res(self._files_api)
83-
if r and not r.ok:
84-
return None, f"连接仓库失败:{r.status_code} - {r.reason}"
85-
elif not r:
86-
return None, "连接仓库失败"
87-
files_info = r.json()
88-
for item in files_info:
89-
save_path = need_updates.get(item.get("name"))
90-
if not save_path:
91-
continue
92-
if item.get("download_url"):
93-
logger.info(f"开始更新资源文件:{item.get('name')} ...")
94-
download_url = f"{settings.GITHUB_PROXY}{item.get('download_url')}"
95-
# 下载资源文件
96-
res = RequestUtils(proxies=self.proxies, headers=settings.GITHUB_HEADERS,
97-
timeout=180).get_res(download_url)
98-
if not res:
99-
logger.error(f"文件 {item.get('name')} 下载失败!")
100-
elif res.status_code != 200:
101-
logger.error(f"下载文件 {item.get('name')} 失败:{res.status_code} - {res.reason}")
102-
# 创建插件文件夹
103-
file_path = self._base_dir / save_path / item.get("name")
104-
if not file_path.parent.exists():
105-
file_path.parent.mkdir(parents=True, exist_ok=True)
106-
# 写入文件
107-
file_path.write_bytes(res.content)
108-
logger.info("资源包更新完成,开始重启服务...")
109-
SystemUtils.restart()
110-
else:
111-
logger.info("所有资源已最新,无需更新")
112+
return None

app/helper/system.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from pathlib import Path
2+
from typing import Tuple
3+
4+
import docker
5+
6+
from app.core.config import settings
7+
from app.utils.system import SystemUtils
8+
9+
10+
class SystemHelper:
11+
12+
@staticmethod
13+
def can_restart() -> bool:
14+
"""
15+
判断是否可以内部重启
16+
"""
17+
return Path("/var/run/docker.sock").exists()
18+
19+
@staticmethod
20+
def restart() -> Tuple[bool, str]:
21+
"""
22+
执行Docker重启操作
23+
"""
24+
if not SystemUtils.is_docker():
25+
return False, "非Docker环境,无法重启!"
26+
try:
27+
# 创建 Docker 客户端
28+
client = docker.DockerClient(base_url=settings.DOCKER_CLIENT_API)
29+
# 获取当前容器的 ID
30+
container_id = None
31+
with open('/proc/self/mountinfo', 'r') as f:
32+
data = f.read()
33+
index_resolv_conf = data.find("resolv.conf")
34+
if index_resolv_conf != -1:
35+
index_second_slash = data.rfind("/", 0, index_resolv_conf)
36+
index_first_slash = data.rfind("/", 0, index_second_slash) + 1
37+
container_id = data[index_first_slash:index_second_slash]
38+
if len(container_id) < 20:
39+
index_resolv_conf = data.find("/sys/fs/cgroup/devices")
40+
if index_resolv_conf != -1:
41+
index_second_slash = data.rfind(" ", 0, index_resolv_conf)
42+
index_first_slash = data.rfind("/", 0, index_second_slash) + 1
43+
container_id = data[index_first_slash:index_second_slash]
44+
if not container_id:
45+
return False, "获取容器ID失败!"
46+
# 重启当前容器
47+
client.containers.get(container_id.strip()).restart()
48+
return True, ""
49+
except Exception as err:
50+
print(str(err))
51+
return False, f"重启时发生错误:{str(err)}"

app/utils/system.py

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from pathlib import Path
1212
from typing import List, Optional, Tuple, Union
1313

14-
import docker
1514
import psutil
1615

1716
from app import schemas
@@ -439,47 +438,6 @@ def memory_usage() -> List[int]:
439438
"""
440439
return [psutil.virtual_memory().used, int(psutil.virtual_memory().percent)]
441440

442-
@staticmethod
443-
def can_restart() -> bool:
444-
"""
445-
判断是否可以内部重启
446-
"""
447-
return Path("/var/run/docker.sock").exists()
448-
449-
@staticmethod
450-
def restart() -> Tuple[bool, str]:
451-
"""
452-
执行Docker重启操作
453-
"""
454-
if not SystemUtils.is_docker():
455-
return False, "非Docker环境,无法重启!"
456-
try:
457-
# 创建 Docker 客户端
458-
client = docker.DockerClient(base_url='tcp://127.0.0.1:38379')
459-
# 获取当前容器的 ID
460-
container_id = None
461-
with open('/proc/self/mountinfo', 'r') as f:
462-
data = f.read()
463-
index_resolv_conf = data.find("resolv.conf")
464-
if index_resolv_conf != -1:
465-
index_second_slash = data.rfind("/", 0, index_resolv_conf)
466-
index_first_slash = data.rfind("/", 0, index_second_slash) + 1
467-
container_id = data[index_first_slash:index_second_slash]
468-
if len(container_id) < 20:
469-
index_resolv_conf = data.find("/sys/fs/cgroup/devices")
470-
if index_resolv_conf != -1:
471-
index_second_slash = data.rfind(" ", 0, index_resolv_conf)
472-
index_first_slash = data.rfind("/", 0, index_second_slash) + 1
473-
container_id = data[index_first_slash:index_second_slash]
474-
if not container_id:
475-
return False, "获取容器ID失败!"
476-
# 重启当前容器
477-
client.containers.get(container_id.strip()).restart()
478-
return True, ""
479-
except Exception as err:
480-
print(str(err))
481-
return False, f"重启时发生错误:{str(err)}"
482-
483441
@staticmethod
484442
def is_hardlink(src: Path, dest: Path) -> bool:
485443
"""

0 commit comments

Comments
 (0)