Compare commits
1 Commits
feat/kie-q
...
d2325f3102
| Author | SHA1 | Date | |
|---|---|---|---|
| d2325f3102 |
@@ -2,15 +2,14 @@
|
|||||||
|
|
||||||
# --- Model (compose) ---
|
# --- Model (compose) ---
|
||||||
GPU_DEVICE=0 # index hoặc UUID card, như `docker run --gpus device=0`
|
GPU_DEVICE=0 # index hoặc UUID card, như `docker run --gpus device=0`
|
||||||
KIE_MODEL_DIR=./qwen35-4b-model # mkdir -p qwen35-4b-model; tar -xf qwen35-4b-weights.tar -C qwen35-4b-model
|
CHANDRA_MODEL_DIR=/path/to/chandra-dla-v2 # thư mục weights trên host
|
||||||
|
KIE_MODEL_DIR=/path/to/Qwen3.5-4B # snapshot HF đã bung (không để symlink trỏ ra ngoài)
|
||||||
GPU_UTIL=0.55 # chandra; GPU_UTIL + KIE_GPU_UTIL < phần card còn trống
|
GPU_UTIL=0.55 # chandra; GPU_UTIL + KIE_GPU_UTIL < phần card còn trống
|
||||||
KIE_GPU_UTIL=0.3
|
KIE_GPU_UTIL=0.3
|
||||||
MAX_MODEL_LEN=32768 # chandra; cấu hình cũ 98304 cần thêm KV cache GPU
|
|
||||||
MAX_NUM_SEQS=128
|
|
||||||
MAX_BATCHED_TOKENS=65536
|
|
||||||
PORT=9222
|
PORT=9222
|
||||||
KIE_PORT=9224
|
KIE_PORT=9224
|
||||||
# IMAGE_TAG=chandra-dla-api:v2-20260906-024126
|
# IMAGE_TAG=chandra-dla-api:v2-20260906-024126
|
||||||
|
# KIE_IMAGE=vllm/vllm-openai:v0.23.0
|
||||||
# APP_IMAGE=idp-parsing-service:0.2.0
|
# APP_IMAGE=idp-parsing-service:0.2.0
|
||||||
|
|
||||||
# --- HDFS native (worker) ---
|
# --- HDFS native (worker) ---
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,7 +4,6 @@ __pycache__/
|
|||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
export/
|
export/
|
||||||
qwen35-4b-model/
|
|
||||||
idp_parsing_service.egg-info/
|
idp_parsing_service.egg-info/
|
||||||
build/
|
build/
|
||||||
chandra-dla-api-v2-20260906-024126.tar
|
chandra-dla-api-v2-20260906-024126.tar
|
||||||
|
|||||||
89
SERVICE.md
89
SERVICE.md
@@ -133,70 +133,15 @@ Một file `docker-compose.yaml` dựng đủ 4 container trên **một host, m
|
|||||||
| Service | Container | Việc | Cổng |
|
| Service | Container | Việc | Cổng |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `chandra` | `chandra-ocr` | DLA/OCR từng trang (vLLM, image `IMAGE_TAG`) | `PORT` (9222) |
|
| `chandra` | `chandra-ocr` | DLA/OCR từng trang (vLLM, image `IMAGE_TAG`) | `PORT` (9222) |
|
||||||
| `kie` | `qwen-kie` | Bóc trường Qwen3.5-4B (cùng image vLLM với Chandra) | `KIE_PORT` (9224) |
|
| `kie` | `qwen-kie` | Bóc trường Qwen3.5-4B (vLLM, image `KIE_IMAGE`) | `KIE_PORT` (9224) |
|
||||||
| `api` | `idp-api` | HTTP API (image build từ `Dockerfile`) | `IDP_PORT` (8001) |
|
| `api` | `idp-api` | HTTP API (image build từ `Dockerfile`) | `IDP_PORT` (8001) |
|
||||||
| `worker` | `idp-worker` | Hàng đợi trang, KIE, finalize, callback, tải PDF từ HDFS | — |
|
| `worker` | `idp-worker` | Hàng đợi trang, KIE, finalize, callback, tải PDF từ HDFS | — |
|
||||||
|
|
||||||
Image `chandra-dla-api:v2-20260906-024126` đã chứa vLLM 0.23.0 và weight Chandra.
|
|
||||||
Service `kie` cũng dùng image này, nhưng mount weight Qwen3.5-4B từ host lên `/model`.
|
|
||||||
Vì `qwen35-4b-weights.tar` đã được tải lên server riêng, thư mục dự án mang đi
|
|
||||||
không chứa 8.8 GB weight. `deploy-offline.sh` sẽ kiểm tra SHA-256 và giải nén
|
|
||||||
archive trên server vào `qwen35-4b-model/`. Thư mục dự án có sẵn archive image
|
|
||||||
API trong `export/` và file `.env`; hai mục này bị Git bỏ qua, vì vậy hãy chuyển
|
|
||||||
**cả thư mục trên đĩa** (ví dụ bằng `rsync`), không chỉ `git clone`.
|
|
||||||
|
|
||||||
Trước khi chạy, kiểm tra `.env`, đặc biệt `KIE_MODEL_DIR=./qwen35-4b-model`, GPU,
|
|
||||||
API key và `HDFS_NATIVE_DIR`. Gói HDFS native không có trong thư mục dự án: server
|
|
||||||
phải có thư mục `/root/idp-portable/native-hdfs` (hoặc chỉnh `HDFS_NATIVE_DIR` trong
|
|
||||||
`.env`) chứa `bin/hdfs`, `conf/krb5.conf` và keytab.
|
|
||||||
Nếu `chandra-ocr` đang chạy từ compose cũ, dừng stack cũ trước khi khởi động
|
|
||||||
compose mới để giải phóng tên container và cổng 9222.
|
|
||||||
|
|
||||||
Sau khi chuyển thư mục, chạy một lệnh trên server (thay đường dẫn bằng vị trí
|
|
||||||
archive Qwen đã upload):
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash deploy-offline.sh /duong/dan/qwen35-4b-weights.tar
|
cp .env.example .env # sửa đường dẫn weights, GPU, HDFS, khóa; chmod 600 .env
|
||||||
```
|
docker compose up -d --build # máy không có mạng: xem mục offline bên dưới
|
||||||
|
docker compose ps # chandra/kie healthy thì worker mới khởi động
|
||||||
Script nạp image API từ `export/`, giải nén Qwen nếu cần, rồi chạy Compose với
|
docker compose logs -f worker
|
||||||
`--wait` để chỉ báo thành công khi cả bốn container healthy. Mặc định chờ tối đa
|
|
||||||
30 phút cho hai model tải lên GPU; có thể đổi bằng `DEPLOY_WAIT_SECONDS`. Các lần
|
|
||||||
sau có thể chạy trực tiếp `docker compose up -d --no-build --pull never --wait`.
|
|
||||||
|
|
||||||
Cả bốn service dùng `restart: unless-stopped`: Docker tự khởi động lại container
|
|
||||||
khi tiến trình chính thoát hoặc daemon khởi động lại. API có healthcheck kiểm tra
|
|
||||||
HTTP và SQLite; worker kiểm tra SQLite cùng HDFS client/keytab; hai model kiểm tra
|
|
||||||
`/health`. Healthcheck chuyển trạng thái sang `unhealthy` nhưng Docker Compose
|
|
||||||
**không tự restart container chỉ vì unhealthy**. Nếu service bị treo mà tiến trình
|
|
||||||
chưa thoát, cần cảnh báo/giám sát bên ngoài. Worker sẽ thoát nếu một luồng xử lý
|
|
||||||
chết bất thường để Docker có thể khởi động lại container. Job đang chạy được lưu
|
|
||||||
trong SQLite và thử lại sau khi lease hết hạn (`IDP_LEASE_SECONDS`, mặc định 1800 giây).
|
|
||||||
|
|
||||||
Nếu server có mạng và muốn build lại image API từ source, sau khi Qwen đã giải
|
|
||||||
nén thì dùng:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
Nếu muốn tự giải nén Qwen trước khi chạy Compose, dùng:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Chạy trong thư mục parsing-service; archive có thể nằm ở nơi khác trên server.
|
|
||||||
echo '65efebd5f15f4db7dac8053bedbb8f38a75d1ac1c11b410db7691d308802bd13 /duong/dan/qwen35-4b-weights.tar' | sha256sum -c -
|
|
||||||
mkdir -p qwen35-4b-model
|
|
||||||
tar -xf /duong/dan/qwen35-4b-weights.tar -C qwen35-4b-model
|
|
||||||
test -f qwen35-4b-model/config.json
|
|
||||||
test -f qwen35-4b-model/model.safetensors.index.json
|
|
||||||
```
|
|
||||||
|
|
||||||
Sau khi chạy Compose:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose ps # chandra/kie healthy thì worker mới khởi động
|
|
||||||
curl -f http://127.0.0.1:9222/health
|
|
||||||
curl -f http://127.0.0.1:9224/health
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`.env` vừa cấp biến cho compose vừa là env của `api`/`worker`, nên các biến `IDP_*`
|
`.env` vừa cấp biến cho compose vừa là env của `api`/`worker`, nên các biến `IDP_*`
|
||||||
@@ -205,9 +150,8 @@ giữ nguyên như khi chạy `run-api.sh`/`run-worker.sh`. Những biến riên
|
|||||||
- `GPU_DEVICE`: index hoặc UUID card (như `docker run --gpus device=0`). Hai model
|
- `GPU_DEVICE`: index hoặc UUID card (như `docker run --gpus device=0`). Hai model
|
||||||
chia card bằng `GPU_UTIL` (0.55) và `KIE_GPU_UTIL` (0.3), thực đo ~80% card H200;
|
chia card bằng `GPU_UTIL` (0.55) và `KIE_GPU_UTIL` (0.3), thực đo ~80% card H200;
|
||||||
`kie` chỉ khởi động sau khi `chandra` healthy để hai vLLM không đo bộ nhớ cùng lúc.
|
`kie` chỉ khởi động sau khi `chandra` healthy để hai vLLM không đo bộ nhớ cùng lúc.
|
||||||
- `KIE_MODEL_DIR`: thư mục weight Qwen trên host, mount chỉ đọc vào `/model` của
|
- `CHANDRA_MODEL_DIR`, `KIE_MODEL_DIR`: thư mục weights trên host, mount chỉ đọc vào
|
||||||
container `kie`. Thư mục giải nén từ `qwen35-4b-weights.tar` không chứa symlink
|
`/model`. Weights Qwen là snapshot HF đã bung, không để symlink trỏ ra ngoài thư mục.
|
||||||
ra ngoài. Chandra dùng weight đã nhúng trong image, không cần mount từ host.
|
|
||||||
- `HDFS_NATIVE_DIR`: thư mục `native-hdfs` của gói portable (Java, Hadoop client,
|
- `HDFS_NATIVE_DIR`: thư mục `native-hdfs` của gói portable (Java, Hadoop client,
|
||||||
`conf/krb5.conf`, keytab), mount chỉ đọc vào worker ở `/opt/native-hdfs`; image
|
`conf/krb5.conf`, keytab), mount chỉ đọc vào worker ở `/opt/native-hdfs`; image
|
||||||
đã có `kinit`. Chỉ cần khi `IDP_STORAGE=hdfs_cli`.
|
đã có `kinit`. Chỉ cần khi `IDP_STORAGE=hdfs_cli`.
|
||||||
@@ -218,16 +162,19 @@ giữ nguyên như khi chạy `run-api.sh`/`run-worker.sh`. Những biến riên
|
|||||||
và phân giải namenode/KDC theo `/etc/hosts` của host, y như khi chạy bằng script.
|
và phân giải namenode/KDC theo `/etc/hosts` của host, y như khi chạy bằng script.
|
||||||
Kiểm tra HDFS trong container: `docker compose exec worker hdfs dfs -ls /`.
|
Kiểm tra HDFS trong container: `docker compose exec worker hdfs dfs -ls /`.
|
||||||
|
|
||||||
Máy đích không có Internet: `build` service API cần mạng (base `python:3.11-slim`, apt,
|
Máy đích không có Internet: `build` cần mạng (base `python:3.11-slim`, apt, PyPI),
|
||||||
PyPI), nên build ở máy có mạng rồi mang image sang. Máy đích cần hai image:
|
nên build ở máy có mạng rồi mang image sang. Cả 3 image phải có sẵn trên máy đích,
|
||||||
`idp-parsing-service:0.2.0` (đã đóng trong `export/`) và
|
thiếu cái nào compose sẽ cố pull và lỗi.
|
||||||
`chandra-dla-api:v2-20260906-024126` (đã mang sang trước đó), cộng với thư mục
|
|
||||||
`qwen35-4b-weights.tar` đã upload riêng trên server.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Nếu không dùng deploy-offline.sh, nạp image API từ thư mục dự án:
|
# máy có mạng
|
||||||
cd export && sha256sum -c idp-parsing-service-0.2.0.tar.gz.sha256 && cd ..
|
docker compose build api
|
||||||
docker load -i export/idp-parsing-service-0.2.0.tar.gz
|
docker save idp-parsing-service:0.2.0 | gzip > idp-parsing-service-0.2.0.tar.gz
|
||||||
|
docker save vllm/vllm-openai:v0.23.0 | gzip > vllm-openai-v0.23.0.tar.gz # nếu máy đích chưa có
|
||||||
|
# máy đích (image chandra-dla-api đã load từ trước)
|
||||||
|
docker load -i idp-parsing-service-0.2.0.tar.gz
|
||||||
|
docker load -i vllm-openai-v0.23.0.tar.gz
|
||||||
|
docker images | grep -E 'idp-parsing-service|vllm-openai|chandra-dla-api'
|
||||||
docker compose up -d --no-build --pull never
|
docker compose up -d --no-build --pull never
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Run all services on a server that already has the Chandra image loaded.
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
cd "${ROOT}"
|
|
||||||
|
|
||||||
test -f .env || { echo "Missing .env (copy and configure .env.example)" >&2; exit 1; }
|
|
||||||
MODEL_DIR="${ROOT}/qwen35-4b-model"
|
|
||||||
ARCHIVE="${1:-${KIE_WEIGHTS_ARCHIVE:-${ROOT}/qwen35-4b-weights.tar}}"
|
|
||||||
EXPECTED_SHA256="65efebd5f15f4db7dac8053bedbb8f38a75d1ac1c11b410db7691d308802bd13"
|
|
||||||
|
|
||||||
if [[ ! -d "${MODEL_DIR}" ]]; then
|
|
||||||
test -f "${ARCHIVE}" || { echo "Missing Qwen archive: ${ARCHIVE}" >&2; exit 1; }
|
|
||||||
actual_sha256="$(sha256sum "${ARCHIVE}" | cut -d ' ' -f 1)"
|
|
||||||
[[ "${actual_sha256}" == "${EXPECTED_SHA256}" ]] || {
|
|
||||||
echo "Qwen archive checksum mismatch: ${ARCHIVE}" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
staging_dir="$(mktemp -d "${ROOT}/.qwen35-stage.XXXXXX")"
|
|
||||||
cleanup() { rm -rf -- "${staging_dir}"; }
|
|
||||||
trap cleanup EXIT
|
|
||||||
tar -xf "${ARCHIVE}" -C "${staging_dir}"
|
|
||||||
for required in config.json model.safetensors.index.json \
|
|
||||||
model.safetensors-00001-of-00002.safetensors \
|
|
||||||
model.safetensors-00002-of-00002.safetensors; do
|
|
||||||
test -s "${staging_dir}/${required}" || { echo "Missing Qwen file: ${required}" >&2; exit 1; }
|
|
||||||
done
|
|
||||||
mv -- "${staging_dir}" "${MODEL_DIR}"
|
|
||||||
trap - EXIT
|
|
||||||
fi
|
|
||||||
|
|
||||||
for required in config.json model.safetensors.index.json \
|
|
||||||
model.safetensors-00001-of-00002.safetensors \
|
|
||||||
model.safetensors-00002-of-00002.safetensors; do
|
|
||||||
test -s "${MODEL_DIR}/${required}" || { echo "Missing Qwen file: ${MODEL_DIR}/${required}" >&2; exit 1; }
|
|
||||||
done
|
|
||||||
|
|
||||||
(cd export && sha256sum -c idp-parsing-service-0.2.0.tar.gz.sha256)
|
|
||||||
docker load -i export/idp-parsing-service-0.2.0.tar.gz
|
|
||||||
docker compose config --quiet
|
|
||||||
docker compose config --images | sort -u | while IFS= read -r image; do
|
|
||||||
docker image inspect "${image}" >/dev/null || { echo "Missing Docker image: ${image}" >&2; exit 1; }
|
|
||||||
done
|
|
||||||
if ! docker compose up -d --no-build --pull never --wait \
|
|
||||||
--wait-timeout "${DEPLOY_WAIT_SECONDS:-1800}"; then
|
|
||||||
docker compose ps
|
|
||||||
echo "Deployment did not reach healthy state; inspect docker compose logs" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
docker compose ps
|
|
||||||
@@ -11,8 +11,6 @@
|
|||||||
# namenode/KDC phân giải theo /etc/hosts của host.
|
# namenode/KDC phân giải theo /etc/hosts của host.
|
||||||
# kie chỉ khởi động sau khi chandra healthy để hai vLLM không đo bộ nhớ GPU cùng lúc;
|
# kie chỉ khởi động sau khi chandra healthy để hai vLLM không đo bộ nhớ GPU cùng lúc;
|
||||||
# worker đợi cả hai model healthy mới nhận trang.
|
# worker đợi cả hai model healthy mới nhận trang.
|
||||||
# Chandra đọc weight nhúng sẵn trong image tại /model. Qwen đọc weight đã giải nén
|
|
||||||
# từ qwen35-4b-weights.tar tại KIE_MODEL_DIR, dùng cùng image làm runtime vLLM.
|
|
||||||
|
|
||||||
x-gpu: &gpu
|
x-gpu: &gpu
|
||||||
resources:
|
resources:
|
||||||
@@ -22,8 +20,6 @@ x-gpu: &gpu
|
|||||||
device_ids: ["${GPU_DEVICE:-0}"] # như `docker run --gpus device=0`
|
device_ids: ["${GPU_DEVICE:-0}"] # như `docker run --gpus device=0`
|
||||||
capabilities: [gpu]
|
capabilities: [gpu]
|
||||||
|
|
||||||
x-vllm-image: &vllm-image ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
|
|
||||||
|
|
||||||
x-vllm-env: &vllm-env
|
x-vllm-env: &vllm-env
|
||||||
HF_HUB_OFFLINE: "1"
|
HF_HUB_OFFLINE: "1"
|
||||||
TRANSFORMERS_OFFLINE: "1"
|
TRANSFORMERS_OFFLINE: "1"
|
||||||
@@ -45,8 +41,7 @@ x-app: &app
|
|||||||
|
|
||||||
services:
|
services:
|
||||||
chandra:
|
chandra:
|
||||||
image: *vllm-image
|
image: ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
|
||||||
pull_policy: never
|
|
||||||
container_name: chandra-ocr
|
container_name: chandra-ocr
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
deploy: *gpu
|
deploy: *gpu
|
||||||
@@ -55,6 +50,8 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "${PORT:-9222}:8000"
|
- "${PORT:-9222}:8000"
|
||||||
environment: *vllm-env
|
environment: *vllm-env
|
||||||
|
volumes:
|
||||||
|
- ${CHANDRA_MODEL_DIR:?dat CHANDRA_MODEL_DIR trong .env}:/model:ro
|
||||||
command:
|
command:
|
||||||
- --model=/model
|
- --model=/model
|
||||||
- --served-model-name=chandra
|
- --served-model-name=chandra
|
||||||
@@ -72,9 +69,7 @@ services:
|
|||||||
healthcheck: *health
|
healthcheck: *health
|
||||||
|
|
||||||
kie:
|
kie:
|
||||||
# Dùng runtime vLLM đã có trong image Chandra; mount Qwen đè lên /model.
|
image: ${KIE_IMAGE:-vllm/vllm-openai:v0.23.0}
|
||||||
image: *vllm-image
|
|
||||||
pull_policy: never
|
|
||||||
container_name: qwen-kie
|
container_name: qwen-kie
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -87,12 +82,7 @@ services:
|
|||||||
- "${KIE_PORT:-9224}:8000"
|
- "${KIE_PORT:-9224}:8000"
|
||||||
environment: *vllm-env
|
environment: *vllm-env
|
||||||
volumes:
|
volumes:
|
||||||
- type: bind
|
- ${KIE_MODEL_DIR:?dat KIE_MODEL_DIR trong .env}:/model:ro
|
||||||
source: ${KIE_MODEL_DIR:?dat KIE_MODEL_DIR trong .env}
|
|
||||||
target: /model
|
|
||||||
read_only: true
|
|
||||||
bind:
|
|
||||||
create_host_path: false
|
|
||||||
command:
|
command:
|
||||||
- --model=/model
|
- --model=/model
|
||||||
- --served-model-name=qwen3.5-4b
|
- --served-model-name=qwen3.5-4b
|
||||||
@@ -101,7 +91,6 @@ services:
|
|||||||
- --dtype=bfloat16
|
- --dtype=bfloat16
|
||||||
- --max-model-len=32768
|
- --max-model-len=32768
|
||||||
- --max-num-seqs=16
|
- --max-num-seqs=16
|
||||||
- --max-num-batched-tokens=8192
|
|
||||||
- --gpu-memory-utilization=${KIE_GPU_UTIL:-0.3}
|
- --gpu-memory-utilization=${KIE_GPU_UTIL:-0.3}
|
||||||
- --enable-prefix-caching
|
- --enable-prefix-caching
|
||||||
- --seed=42
|
- --seed=42
|
||||||
@@ -120,12 +109,6 @@ services:
|
|||||||
# Cùng đường dẫn trong và ngoài container; SQLite phải nằm trên đĩa local, không NFS.
|
# Cùng đường dẫn trong và ngoài container; SQLite phải nằm trên đĩa local, không NFS.
|
||||||
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
|
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
|
||||||
command: ["uvicorn", "idp_service.api:app", "--host=${IDP_HOST:-0.0.0.0}", "--port=${IDP_PORT:-8001}"]
|
command: ["uvicorn", "idp_service.api:app", "--host=${IDP_HOST:-0.0.0.0}", "--port=${IDP_PORT:-8001}"]
|
||||||
healthcheck:
|
|
||||||
test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:${IDP_PORT:-8001}/readyz', timeout=3)\""]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 3
|
|
||||||
start_period: 30s
|
|
||||||
|
|
||||||
worker:
|
worker:
|
||||||
<<: *app
|
<<: *app
|
||||||
@@ -143,16 +126,5 @@ services:
|
|||||||
HDFS_KEYTAB: /opt/native-hdfs/conf/searchengine.headless.keytab
|
HDFS_KEYTAB: /opt/native-hdfs/conf/searchengine.headless.keytab
|
||||||
volumes:
|
volumes:
|
||||||
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
|
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
|
||||||
- type: bind
|
- ${HDFS_NATIVE_DIR:-./native-hdfs}:/opt/native-hdfs:ro
|
||||||
source: ${HDFS_NATIVE_DIR:?dat HDFS_NATIVE_DIR trong .env}
|
|
||||||
target: /opt/native-hdfs
|
|
||||||
read_only: true
|
|
||||||
bind:
|
|
||||||
create_host_path: false
|
|
||||||
command: ["python", "-m", "idp_service.worker"]
|
command: ["python", "-m", "idp_service.worker"]
|
||||||
healthcheck:
|
|
||||||
test: ["CMD-SHELL", "python -c \"import os, shutil, sqlite3; from idp_service.config import Settings; s=Settings(); db=sqlite3.connect(str(s.db_path), timeout=3); db.execute('SELECT 1'); db.close(); assert s.storage != 'hdfs_cli' or (shutil.which('hdfs') and os.access(os.environ.get('HDFS_KEYTAB', ''), os.R_OK))\""]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 3
|
|
||||||
start_period: 30s
|
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import sqlite3
|
|||||||
import time
|
import time
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Lock
|
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
|
||||||
@@ -15,9 +14,6 @@ def retry_delay(attempt: int) -> int:
|
|||||||
class Store:
|
class Store:
|
||||||
def __init__(self, path: Path):
|
def __init__(self, path: Path):
|
||||||
self.path = path
|
self.path = path
|
||||||
# Worker threads share this Store. Serialize their write transactions so
|
|
||||||
# idle queue polling does not make dozens of SQLite writers contend.
|
|
||||||
self._tx_lock = Lock()
|
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
self.init()
|
self.init()
|
||||||
|
|
||||||
@@ -85,20 +81,19 @@ class Store:
|
|||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def tx(self):
|
def tx(self):
|
||||||
with self._tx_lock:
|
db = self.connect()
|
||||||
db = self.connect()
|
try:
|
||||||
try:
|
db.execute("BEGIN IMMEDIATE")
|
||||||
db.execute("BEGIN IMMEDIATE")
|
yield db
|
||||||
yield db
|
db.execute("COMMIT")
|
||||||
db.execute("COMMIT")
|
except BaseException:
|
||||||
except BaseException:
|
# BEGIN IMMEDIATE hết busy_timeout thì chưa có transaction: ROLLBACK lúc đó
|
||||||
# BEGIN IMMEDIATE hết busy_timeout thì chưa có transaction: ROLLBACK lúc đó
|
# sẽ ném "no transaction is active" và che mất lỗi "database is locked" gốc.
|
||||||
# sẽ ném "no transaction is active" và che mất lỗi "database is locked" gốc.
|
if db.in_transaction:
|
||||||
if db.in_transaction:
|
db.execute("ROLLBACK")
|
||||||
db.execute("ROLLBACK")
|
raise
|
||||||
raise
|
finally:
|
||||||
finally:
|
db.close()
|
||||||
db.close()
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def as_dict(row):
|
def as_dict(row):
|
||||||
|
|||||||
@@ -249,12 +249,9 @@ class Worker:
|
|||||||
self.callback(job)
|
self.callback(job)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def loop(self, step, monitor_threads=()):
|
def loop(self, step):
|
||||||
"""Lỗi tạm thời (SQLite locked, HDFS chập chờn) chỉ log rồi thử lại, không được giết luồng."""
|
"""Lỗi tạm thời (SQLite locked, HDFS chập chờn) chỉ log rồi thử lại, không được giết luồng."""
|
||||||
while not self.stop.is_set():
|
while not self.stop.is_set():
|
||||||
dead = [thread.name for thread in monitor_threads if not thread.is_alive()]
|
|
||||||
if dead:
|
|
||||||
raise RuntimeError(f"Worker threads stopped unexpectedly: {', '.join(dead)}")
|
|
||||||
try:
|
try:
|
||||||
if step():
|
if step():
|
||||||
continue
|
continue
|
||||||
@@ -284,7 +281,7 @@ class Worker:
|
|||||||
log.info("Worker started with %s OCR threads and %s callback threads",
|
log.info("Worker started with %s OCR threads and %s callback threads",
|
||||||
self.settings.ocr_workers, self.settings.callback_workers)
|
self.settings.ocr_workers, self.settings.callback_workers)
|
||||||
try:
|
try:
|
||||||
self.loop(self.coordinator_once, threads)
|
self.loop(self.coordinator_once)
|
||||||
finally:
|
finally:
|
||||||
self.stop.set()
|
self.stop.set()
|
||||||
for thread in threads:
|
for thread in threads:
|
||||||
|
|||||||
@@ -406,63 +406,6 @@ def test_locked_database_surfaces_and_does_not_kill_worker_thread(tmp_path, monk
|
|||||||
blocker.execute("ROLLBACK")
|
blocker.execute("ROLLBACK")
|
||||||
|
|
||||||
|
|
||||||
def test_worker_store_serializes_write_transactions(tmp_path, monkeypatch):
|
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
store = Store(settings_for(tmp_path).db_path)
|
|
||||||
monkeypatch.setattr(store, "connect", lambda: sqlite3.connect(store.path, timeout=0.05,
|
|
||||||
isolation_level=None))
|
|
||||||
first_entered = Event()
|
|
||||||
release_first = Event()
|
|
||||||
second_started = Event()
|
|
||||||
second_done = Event()
|
|
||||||
errors = []
|
|
||||||
|
|
||||||
def first_writer():
|
|
||||||
try:
|
|
||||||
with store.tx():
|
|
||||||
first_entered.set()
|
|
||||||
release_first.wait(2)
|
|
||||||
except Exception as exc:
|
|
||||||
errors.append(exc)
|
|
||||||
|
|
||||||
def second_writer():
|
|
||||||
second_started.set()
|
|
||||||
try:
|
|
||||||
store.claim_page(1800, 2)
|
|
||||||
except Exception as exc:
|
|
||||||
errors.append(exc)
|
|
||||||
finally:
|
|
||||||
second_done.set()
|
|
||||||
|
|
||||||
first = Thread(target=first_writer)
|
|
||||||
second = Thread(target=second_writer)
|
|
||||||
first.start()
|
|
||||||
try:
|
|
||||||
assert first_entered.wait(2)
|
|
||||||
second.start()
|
|
||||||
assert second_started.wait(2)
|
|
||||||
assert not second_done.wait(0.1)
|
|
||||||
finally:
|
|
||||||
release_first.set()
|
|
||||||
first.join(2)
|
|
||||||
if second.ident is not None:
|
|
||||||
second.join(2)
|
|
||||||
assert second_done.is_set()
|
|
||||||
assert not errors
|
|
||||||
|
|
||||||
|
|
||||||
def test_worker_main_loop_exits_when_processing_thread_stops(tmp_path):
|
|
||||||
worker = Worker(settings_for(tmp_path))
|
|
||||||
dead_thread = Thread(name="dead-ocr")
|
|
||||||
try:
|
|
||||||
worker.loop(lambda: False, [dead_thread])
|
|
||||||
except RuntimeError as exc:
|
|
||||||
assert "dead-ocr" in str(exc)
|
|
||||||
else:
|
|
||||||
raise AssertionError("Worker must exit so Docker can restart it")
|
|
||||||
|
|
||||||
|
|
||||||
def test_real_http_ocr_and_callback(tmp_path):
|
def test_real_http_ocr_and_callback(tmp_path):
|
||||||
callbacks = []
|
callbacks = []
|
||||||
auth_headers = []
|
auth_headers = []
|
||||||
@@ -650,3 +593,4 @@ def test_voffice_decryption_rejects_wrong_key(tmp_path):
|
|||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise AssertionError("Invalid encrypted document was accepted")
|
raise AssertionError("Invalid encrypted document was accepted")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user