Files
auto-stock/Jenkinsfile
shuim b4a1fc79ab feat: 멀티테넌트 1단계 — 사용자별 KIS 계좌·포트폴리오·수동매매 (MULTI_TENANT_ENABLED 기본 OFF)
설계: docs/multi_tenant_design.md / 검수: docs/multi_tenant_phase1_review.md (High 0, MT=False 배포 가능)

데이터·인프라
- user_kis_credentials(Fernet 암호화, PBKDF2 키 파생, key_version), stock_bans_v2 신설,
  portfolio/trade_history/active_trades/trade_journals/trading_sessions 등 user_id nullable 추가
- alembic 0009~0011(idempotent, legacy owner 백필). main.py 기동 시 portfolio.user_id 스키마 검사(H1)
- Jenkinsfile: DB Migration 을 Deploy 앞으로, alembic 이력 없으면 stamp 0008 후 upgrade(N1)
- bootstrap: users 비어 있으면 BOOTSTRAP_ADMIN_* 로 관리자 시드 + .env KIS 자격증명 이관 + 백필(SAVEPOINT)

백엔드
- core/crypto.py, core/tenant_auth.py(get_current_user — 비활성 사용자 401, API 키→legacy owner,
  deny_non_owner_session_when_mt), core/dt_utils.py
- services/tenant: context, kis_pool, registry(UserContextRegistry, 락 최소화·복호화 to_thread), risk_factory
- KoreaInvestmentAPI.for_user(사용자별 인스턴스, 토큰캐시 users/{id}/, 시세는 공용 위임)
- trade_executor.safe_place_order_v2(사용자별 락/세마포어, legacy ctx 는 기존 키)
- mdd_manager/loss_tracker _v2 + ban_until tz-aware/naive 경계 정규화(레거시 경로 버그 포함 수정)
- db_worker: payload user_id 옵션 필터, upsert_stock_ban_v2, legacy ActiveTrade 조회 LIMIT 1
- API: /account/credentials(등록·마스킹조회·삭제·연결테스트·자동매매), /auth/admin/tenant/*,
  /portfolio/v2(조회·요약·sync·buy·sell), /trades/v2(+pending). PortfolioResponse Optional 수정

프론트
- /account 내 계좌 설정, useTenantMode(세션=v2 / API키=legacy, 미확정 시 쿼리·버튼 비활성),
  계좌 미등록 인라인 안내, v2 매수/매도/거래이력 분기

테스트: tests/integration(격리 Postgres, KIS 전면 mock) 20 passed / 1 xfailed(0012 이전 제약)
2단계(스케줄러 사용자화·legacy 라우터 격리) 전까지 MULTI_TENANT_ENABLED=True 전환 금지

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 10:26:51 +09:00

142 lines
5.1 KiB
Groovy

pipeline {
agent any
environment {
DEPLOY_DIR = '/volume1/docker/autostock'
ENV_FILE = "${DEPLOY_DIR}/.env"
// Dockerfile 의 pip/npm 캐시 마운트(RUN --mount=type=cache)를 쓰려면 BuildKit 필요
DOCKER_BUILDKIT = '1'
COMPOSE_DOCKER_CLI_BUILD = '1'
}
options {
timeout(time: 30, unit: 'MINUTES')
disableConcurrentBuilds()
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Validate') {
steps {
sh '''
echo "=== Syntax Check ==="
python3 -c "
import ast, pathlib
errors = []
for f in pathlib.Path('backend/app').rglob('*.py'):
try:
ast.parse(f.read_text())
except SyntaxError as e:
errors.append(f'{f}: {e}')
for f in pathlib.Path('mcp-server').glob('*.py'):
try:
ast.parse(f.read_text())
except SyntaxError as e:
errors.append(f'{f}: {e}')
if errors:
print('\\n'.join(errors))
exit(1)
print('All files OK')
"
'''
}
}
stage('Sync & Build') {
steps {
sh """
echo "=== Syncing source to deploy directory ==="
mkdir -p ${DEPLOY_DIR}
# .env 존재 확인
if [ ! -f "${ENV_FILE}" ]; then
echo "WARNING: ${ENV_FILE} not found. Creating template..."
cp deploy/setup-nas.sh ${DEPLOY_DIR}/ 2>/dev/null || true
fi
# 소스 동기화 (backend, mcp-server, frontend, docker-compose.yml, docker/)
cp docker-compose.yml ${DEPLOY_DIR}/
cp -r docker/ ${DEPLOY_DIR}/ 2>/dev/null || true
rsync -a --delete backend/ ${DEPLOY_DIR}/backend/ || cp -r backend/ ${DEPLOY_DIR}/backend/
rsync -a --delete mcp-server/ ${DEPLOY_DIR}/mcp-server/ || cp -r mcp-server/ ${DEPLOY_DIR}/mcp-server/
rsync -a --delete frontend/ ${DEPLOY_DIR}/frontend/ || cp -r frontend/ ${DEPLOY_DIR}/frontend/
echo "=== Building Docker Images ==="
cd ${DEPLOY_DIR}
docker-compose build backend mcp-server frontend
"""
}
}
// H1: 마이그레이션은 반드시 Deploy(백엔드 재기동) 이전에 끝나야 한다.
// `create_all()`은 신규 테이블만 생성하고 기존 테이블 컬럼 추가는 하지 않으므로,
// 새 이미지를 먼저 올리면(구 스키마 + 신규 컬럼을 매핑하는 신규 코드) 레거시 경로
// 전체가 UndefinedColumnError로 실패한다. 마이그레이션 실패 시 파이프라인을 중단한다
// (기존 backend 컨테이너는 아직 중지 전이라 서비스 영향 없음).
stage('DB Migration') {
steps {
sh """
cd ${DEPLOY_DIR}
# N1: create_all 전용으로 운영돼 alembic_version 이 비어 있으면 upgrade head 가
# 0001 부터 실행돼 기존 컬럼과 충돌한다. 이력이 없으면 현 스키마(users 테이블까지
# create_all 로 존재) 기준인 0008 로 stamp 한 뒤 0009+ 만 적용한다.
CURRENT=\$(docker-compose run --rm --no-deps backend alembic current 2>/dev/null | grep -oE '^[0-9a-f]{4,}' || true)
if [ -z "\$CURRENT" ]; then
echo "alembic 이력 없음 → stamp 0008"
docker-compose run --rm --no-deps backend alembic stamp 0008
else
echo "alembic current: \$CURRENT"
fi
docker-compose run --rm --no-deps backend alembic upgrade head
"""
}
}
stage('Deploy') {
steps {
sh """
cd ${DEPLOY_DIR}
echo "=== Rolling Deploy (앱만 재시작, DB/Redis 유지) ==="
docker-compose stop backend mcp-server frontend 2>/dev/null || true
docker-compose up -d
echo "=== Waiting for health check ==="
sleep 15
for i in 1 2 3 4 5; do
if curl -sf http://localhost:8000/health > /dev/null 2>&1; then
echo "Backend is healthy!"
break
fi
echo "Waiting for backend... (\$i/5)"
sleep 5
done
docker-compose ps
"""
}
}
}
post {
success {
echo 'Deployment successful!'
}
failure {
echo 'Deployment failed!'
sh """
cd ${DEPLOY_DIR} 2>/dev/null && docker-compose logs --tail=30 backend mcp-server 2>/dev/null || true
"""
}
always {
cleanWs()
}
}
}