fix: 给 soffice 加超时(120s)机制、worker 自动回收超时 running 任务,避免任务挂死阻塞队列

This commit is contained in:
sophie committed 2026-05-29 11:37:02 +08:00
1 parent 1d72018eb7
commit 0eb577df1a
11 files changed
+379 -88

No files matched your search

+16 -28
View File
@@ -1,47 +1,35 @@
"""
backend/edkb_system/skills/doc_to_pdf.py
文件用途:将 Word 文档转换为 PDF,供后续 PDF 解析链路使用
说明:
- Windows 优先走 Word COM(word_bridge);
- Linux/容器环境走 LibreOffice,转换超时由 soffice_util 统一控制。
"""
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from edkb_system.contracts import Context
from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice
from edkb_system.skills.word_bridge import convert_with_word
def _find_soffice() -> str | None:
candidates = [
os.environ.get("EDKB_SOFFICE"),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
for c in candidates:
if not c:
continue
if c == "soffice":
return c
if Path(c).exists():
return c
return None
def _convert_with_word(path: Path, out_dir: Path) -> Path:
output = out_dir / f"{path.stem}.pdf"
return convert_with_word(path.resolve(), output.resolve(), 17)
def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path:
"""通过 soffice 转 PDF;超时抛出 RuntimeError。"""
output = out_dir / f"{path.stem}.pdf"
cmd = [
proc = convert_with_soffice(
soffice,
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
convert_to="pdf",
source_path=path,
out_dir=out_dir,
)
if proc.returncode != 0:
stderr = (proc.stderr or "").strip() or "no stderr"
raise RuntimeError(
@@ -66,7 +54,7 @@ def run(input_data: dict, context: Context) -> dict:
except Exception as exc:
errors.append(f"word: {exc}")
soffice = _find_soffice()
soffice = find_soffice()
if soffice:
try:
pdf = _convert_with_soffice(file_path, out_dir, soffice)
+18 -17
View File
@@ -14,6 +14,7 @@ import xml.etree.ElementTree as ET
from pathlib import Path
from edkb_system.contracts import Block, Context
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
from edkb_system.skills.word_bridge import convert_with_word
@@ -1583,6 +1584,11 @@ def _convert_doc_with_word(path: Path, out_dir: Path) -> Path:
def _convert_doc_to_docx(path: Path, out_dir: Path) -> Path:
"""
将 .doc 转为 .docx。
Windows 优先 Word COM;Linux/容器走 soffice_util(带 EDKB_SOFFICE_TIMEOUT_SEC 超时)。
"""
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.docx"
force_reconvert = str(
@@ -1606,29 +1612,24 @@ def _convert_doc_to_docx(path: Path, out_dir: Path) -> Path:
except Exception as exc:
errors.append(f"Word COM conversion failed: {exc}")
soffice_candidates = [
os.environ.get("EDKB_SOFFICE"),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
for soffice in soffice_candidates:
# 非 Windows:依次尝试 soffice 候选路径,单次转换受 soffice_util 超时保护
soffice_candidates_list = soffice_candidates()
for soffice in soffice_candidates_list:
if not soffice:
continue
cmd = [
soffice,
"--headless",
"--convert-to",
"docx",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
proc = convert_with_soffice(
soffice,
convert_to="docx",
source_path=path,
out_dir=out_dir,
)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
continue
except RuntimeError as exc:
errors.append(str(exc))
continue
if proc.returncode == 0 and output.exists():
return output
+19 -22
View File
@@ -1,44 +1,41 @@
"""
backend/edkb_system/skills/loader_excel.py
文件用途:加载 Excel 表格为结构化数据
说明:
- .xls 旧格式先经 soffice_util 转为 .xlsx,再走 openpyxl 解析。
"""
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from openpyxl import load_workbook
from edkb_system.contracts import Context
def _soffice_candidates() -> list[str]:
return [
os.environ.get("EDKB_SOFFICE", "").strip(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
"""将 .xls 转为 .xlsx;soffice 调用带超时,见 EDKB_SOFFICE_TIMEOUT_SEC。"""
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.xlsx"
errors: list[str] = []
for soffice in _soffice_candidates():
for soffice in soffice_candidates():
if not soffice:
continue
cmd = [
soffice,
"--headless",
"--convert-to",
"xlsx",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
proc = convert_with_soffice(
soffice,
convert_to="xlsx",
source_path=path,
out_dir=out_dir,
)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
continue
except RuntimeError as exc:
errors.append(str(exc))
continue
if proc.returncode == 0 and output.exists():
return output
stderr = (proc.stderr or "").strip()
+16 -20
View File
@@ -4,10 +4,10 @@ import base64
import hashlib
import io
import re
import subprocess
from pathlib import Path
from edkb_system.contracts import Block, Context
from edkb_system.skills.soffice_util import convert_with_soffice
def _to_data_uri(blob: bytes, content_type: str) -> str:
@@ -15,17 +15,14 @@ def _to_data_uri(blob: bytes, content_type: str) -> str:
def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path:
"""将 .ppt 转为 .pptx;soffice 超时由 soffice_util 控制。"""
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
proc = convert_with_soffice(
"soffice",
"--headless",
"--convert-to",
"pptx",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
convert_to="pptx",
source_path=path,
out_dir=out_dir,
)
if proc.returncode != 0:
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
output = out_dir / f"{path.stem}.pptx"
@@ -35,20 +32,19 @@ def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path:
def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None:
"""将演示文稿转为 PDF;失败或超时返回 None,由上层选择其它解析路径。"""
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"soffice",
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
proc = convert_with_soffice(
"soffice",
convert_to="pdf",
source_path=path,
out_dir=out_dir,
)
except FileNotFoundError:
return None
except RuntimeError:
return None
if proc.returncode != 0:
return None
output = out_dir / f"{path.stem}.pdf"
@@ -0,0 +1,92 @@
"""
backend/edkb_system/skills/soffice_util.py
文件用途:LibreOffice(soffice)转换统一封装
说明:
- 为 loader_docx / doc_to_pdf / loader_excel / loader_pptx 等技能提供带超时的 soffice 调用;
- 避免单个 Office 文档转换卡死导致 kb-worker 长期阻塞;
- 超时阈值通过环境变量 EDKB_SOFFICE_TIMEOUT_SEC 配置(默认 120 秒)。
"""
from __future__ import annotations
import os
import subprocess
from pathlib import Path
def soffice_timeout_sec() -> int:
"""读取 soffice 子进程超时秒数,最小 10 秒。"""
raw = str(os.environ.get("EDKB_SOFFICE_TIMEOUT_SEC", "120")).strip()
try:
value = int(raw)
except ValueError:
value = 120
return max(value, 10)
def soffice_candidates() -> list[str]:
"""返回 soffice 可执行文件候选路径(环境变量优先,其次 Windows 默认安装路径)。"""
return [
os.environ.get("EDKB_SOFFICE", "").strip(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
def find_soffice() -> str | None:
"""返回第一个可用的 soffice 路径;PATH 中的 `soffice` 不做存在性探测。"""
for candidate in soffice_candidates():
if not candidate:
continue
if candidate == "soffice":
return candidate
if Path(candidate).exists():
return candidate
return None
def run_soffice(cmd: list[str]) -> subprocess.CompletedProcess[str]:
"""
执行 soffice 命令并强制超时。
超时时抛出 RuntimeError,供上层清洗任务识别为失败而非无限等待。
"""
timeout = soffice_timeout_sec()
try:
return subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
)
except subprocess.TimeoutExpired as exc:
label = Path(cmd[-2]).name if len(cmd) >= 2 else "soffice"
raise RuntimeError(
f"soffice timed out after {timeout}s: {label}"
) from exc
def convert_with_soffice(
soffice: str,
*,
convert_to: str,
source_path: Path,
out_dir: Path,
) -> subprocess.CompletedProcess[str]:
"""
以 headless 模式调用 soffice 做格式转换。
:param convert_to: 目标格式,如 docx / pdf / xlsx / pptx
"""
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
soffice,
"--headless",
"--convert-to",
convert_to,
str(source_path),
"--outdir",
str(out_dir),
]
return run_soffice(cmd)