Files
environment/install.sh
T
warren ca0757652e fix: seed api_keys on fresh install (X-API-Key auth) + momentry-proxy web-server plist + test.sh SPA auth model
- install.sh: seed api_keys row (key_hash = SHA-256 of demo key) — missing row
  caused 401 on every X-API-Key request after clean-install
- launchd/com.momentry.proxy.plist: serve via momentry-proxy binary
  (MOMENTRY_WEB_SERVER=true + TAURI_DIST_DIR) instead of serve_frontend.py
- test.sh: remote probes use X-API-Key (SPA auth model) instead of Bearer
  (proxy login returns UUID session token, core expects JWT/X-API-Key)
2026-11-09 05:03:27 +08:00

426 lines
15 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# Momentry 完整安裝腳本 - 含服務啟動與測試
# 用法: ./install.sh [--target-dir ~/momentry]
set -e
TARGET_DIR="${TARGET_DIR:-$HOME/momentry}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOG_FILE="$HOME/momentry_install_$(date +%Y%m%d_%H%M%S).log"
PG_BIN="/opt/homebrew/bin/psql"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log() { echo -e "${GREEN}[$(date +%H:%M:%S)]$NC $1" | tee -a "$LOG_FILE"; }
warn() { echo -e "${YELLOW}[WARN]$NC $1" | tee -a "$LOG_FILE"; }
err() { echo -e "${RED}[ERROR]$NC $1" | tee -a "$LOG_FILE"; }
step() { echo -e "\n${BLUE}═══════════════════════════════════════${NC}"; echo -e "${BLUE} $1${NC}"; echo -e "${BLUE}═══════════════════════════════════════${NC}"; }
pass() { echo -e " ${GREEN}✅ PASS${NC} $1" | tee -a "$LOG_FILE"; }
fail() { echo -e " ${RED}❌ FAIL${NC} $1" | tee -a "$LOG_FILE"; }
wait_for_port() {
local port=$1 name=$2 max_wait=${3:-15}
echo -n " 等待 $name (:$port)..."
for i in $(seq 1 $max_wait); do
if lsof -i :$port &>/dev/null; then
echo -e " ${GREEN}OK${NC} (${i}s)"
return 0
fi
sleep 1
echo -n "."
done
echo -e " ${RED}超時${NC}"
return 1
}
test_endpoint() {
local url=$1 name=$2 expected=${3:-"200"}
echo -n " 測試 $name..."
local http_code
http_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 "$url" 2>/dev/null)
if [ "$http_code" = "$expected" ]; then
pass "$name ($http_code)"
return 0
else
fail "$name (HTTP $http_code)"
return 1
fi
}
echo "╔══════════════════════════════════════════════════════════╗"
echo "║ Momentry 完整安裝程式 ║"
echo "║ $(date +%Y-%m-%d) ║"
echo "╚══════════════════════════════════════════════════════════╝"
# ── Step 1: 系統檢查 ──
step "[1/10] 系統檢查"
echo -n " CPU 架構: "
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
pass "Apple Silicon ($ARCH)"
else
err "需要 Apple Silicon,當前: $ARCH"
exit 1
fi
echo -n " Homebrew: "
if command -v brew &>/dev/null; then
pass "$(brew --version | head -1)"
else
err "請先安裝 Homebrew"
exit 1
fi
# ── Step 2: 建立目錄 ──
step "[2/10] 建立目錄"
for dir in bin tools/cli/rust/target/release processors config scripts dist etc logs output var/sftpgo/data/demo var/qdrant var/redis var/gitea; do
mkdir -p "$TARGET_DIR/$dir"
done
mkdir -p "$HOME/Library/LaunchAgents"
pass "目錄建立完成"
# ── Step 3: 啟動基礎設施 ──
step "[3/10] 啟動基礎設施服務"
echo -n " PostgreSQL: "
if brew services list 2>/dev/null | grep -q "postgresql.*started"; then
pass "已運行"
else
brew services start postgresql@18 2>/dev/null || brew services start postgresql 2>/dev/null || true
wait_for_port 5432 "PostgreSQL" 10 || warn "可能已運行"
fi
echo -n " Redis: "
if brew services list 2>/dev/null | grep -q "redis.*started"; then
pass "已運行"
else
brew services start redis 2>/dev/null || true
wait_for_port 6379 "Redis" 10 || warn "可能已運行"
fi
echo -n " Qdrant: "
if lsof -i :6333 &>/dev/null; then
pass "已運行"
else
# Check if qdrant binary exists
if [ -f "$HOME/opt_pgsql/bin/qdrant" ]; then
nohup "$HOME/opt_pgsql/bin/qdrant" > "$TARGET_DIR/logs/qdrant.log" 2>&1 &
wait_for_port 6333 "Qdrant" 10 || warn "啟動失敗"
else
warn "Qdrant 二進制不存在,跳過"
fi
fi
# ── Step 4: 初始化資料庫 ──
step "[4/10] 初始化資料庫"
echo -n " 建立資料庫: "
$PG_BIN -U "$(whoami)" -d postgres -c "CREATE DATABASE momentry;" 2>/dev/null && pass "momentry" || pass "momentry (已存在)"
$PG_BIN -U "$(whoami)" -d postgres -c "CREATE DATABASE sftpgo;" 2>/dev/null && pass "sftpgo" || pass "sftpgo (已存在)"
$PG_BIN -U "$(whoami)" -d postgres -c "CREATE DATABASE gitea;" 2>/dev/null && pass "gitea" || pass "gitea (已存在)"
echo ""
echo " 執行 Migrations:"
# pgvector extension (每個 DB 都要)
$PG_BIN -U "$(whoami)" -d momentry -c "CREATE EXTENSION IF NOT EXISTS vector;" 2>/dev/null || true
APPLIED=0
for sql in "$SCRIPT_DIR/sql/"*.sql; do
[ -f "$sql" ] || continue
name=$(basename "$sql" .sql)
# Check if already applied
if $PG_BIN -U "$(whoami)" -d momentry -t -c "SELECT 1 FROM schema_migrations WHERE version = '$name';" 2>/dev/null | grep -q 1; then
echo -n " ⏭️ $name (已執行)"
echo ""
continue
fi
echo -n " 📝 $name..."
if $PG_BIN -U "$(whoami)" -d momentry -f "$sql" >> "$LOG_FILE" 2>&1; then
echo -e " ${GREEN}OK${NC}"
APPLIED=$((APPLIED+1))
$PG_BIN -U "$(whoami)" -d momentry -c "INSERT INTO schema_migrations (version) VALUES ('$name') ON CONFLICT (version) DO NOTHING;" 2>/dev/null || true
else
echo -e " ${YELLOW}SKIP${NC} (可能已存在)"
fi
done
pass "$APPLIED 個新 migration 已執行"
# 建立核心表 (如果 migrations 沒有涵蓋)
echo ""
echo " 檢查核心表..."
TABLE_COUNT=$($PG_BIN -U "$(whoami)" -d momentry -t -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';" 2>/dev/null | tr -d ' ')
echo " 當前表數量: $TABLE_COUNT"
if [ "$TABLE_COUNT" -lt 30 ]; then
warn "表數量不足,建立核心表..."
$PG_BIN -U "$(whoami)" -d momentry -c "
CREATE TABLE IF NOT EXISTS videos (
id SERIAL PRIMARY KEY,
file_uuid VARCHAR(64) UNIQUE NOT NULL,
file_path TEXT NOT NULL,
file_name TEXT NOT NULL,
content_hash VARCHAR(64),
duration DOUBLE PRECISION,
width INTEGER,
height INTEGER,
fps DOUBLE PRECISION,
total_frames BIGINT DEFAULT 0,
file_size BIGINT,
probe_json JSONB,
status VARCHAR(20) DEFAULT 'registered',
processing_status VARCHAR(20) DEFAULT 'REGISTERED',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
completed_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(64) UNIQUE NOT NULL,
password_hash VARCHAR(256) NOT NULL,
name VARCHAR(255) DEFAULT '',
display_name VARCHAR(255) DEFAULT '',
role VARCHAR(20) NOT NULL DEFAULT 'user',
status VARCHAR(20) NOT NULL DEFAULT 'active',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
last_login TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS chunks (
id SERIAL PRIMARY KEY,
uuid VARCHAR(64) UNIQUE NOT NULL,
file_uuid VARCHAR(64) NOT NULL REFERENCES videos(file_uuid),
chunk_type VARCHAR(50) NOT NULL,
start_frame BIGINT,
end_frame BIGINT,
content TEXT,
speaker_id VARCHAR(50),
embedding vector(384),
metadata JSONB DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS monitor_jobs (
id SERIAL PRIMARY KEY,
uuid VARCHAR(64) UNIQUE NOT NULL,
file_uuid VARCHAR(64) REFERENCES videos(file_uuid),
status VARCHAR(20) DEFAULT 'pending',
processors TEXT[],
completed_processors TEXT[],
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS processor_results (
id SERIAL PRIMARY KEY,
file_uuid VARCHAR(64) NOT NULL REFERENCES videos(file_uuid),
processor_type VARCHAR(50) NOT NULL,
status VARCHAR(20) DEFAULT 'pending',
frames_count INTEGER DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(file_uuid, processor_type)
);
CREATE TABLE IF NOT EXISTS trace_profiles (
id SERIAL PRIMARY KEY,
trace_id VARCHAR(64) UNIQUE NOT NULL,
file_uuid VARCHAR(64) NOT NULL,
name VARCHAR(255) DEFAULT '',
identity_id INTEGER,
group_id BIGINT,
vlm_description TEXT,
vlm_description_localized TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
" 2>/dev/null || true
pass "核心表已建立"
fi
# 建立預設用戶
echo ""
echo " 建立預設用戶:"
$PG_BIN -U "$(whoami)" -d momentry -c "
INSERT INTO users (username, password_hash, name, display_name, role, status) VALUES
('demo', '\$2b\$12\$dummy_hash_for_demo_user', 'demo', 'Demo User', 'user', 'active'),
('admin', '\$2b\$12\$dummy_hash_for_admin_user', 'admin', 'Admin User', 'admin', 'active')
ON CONFLICT (username) DO NOTHING;
" 2>/dev/null || true
pass "demo 和 admin 用戶已建立"
# 建立預設 API Key(X-API-Key 認證用;key_hash = SHA-256 of key)
# 未種入此列會導致所有 X-API-Key 請求 401
$PG_BIN -U "$(whoami)" -d momentry -c "
INSERT INTO api_keys (key_id, key_hash, key_prefix, name, key_type, user_id, permissions, status)
SELECT 'muser_demo_key_32chars_abcdef1234567890',
'188601ba06ecda64873bedfd1176b4359fbbc0a54ac1b3650d73159efaf3a8ab',
'muser_de', 'Demo API Key', 'user',
(SELECT id FROM users WHERE username='demo'),
'{\"read\": true, \"write\": true}', 'active'
WHERE NOT EXISTS (SELECT 1 FROM api_keys WHERE key_id='muser_demo_key_32chars_abcdef1234567890');
" 2>/dev/null || true
pass "預設 API Key 已建立 (X-API-Key 認證)"
# ── Step 5: 部署二進制 ──
step "[5/10] 部署二進制"
COPIED=0
for src in "$SCRIPT_DIR/bin/"*; do
[ -f "$src" ] || continue
name=$(basename "$src")
dst="$TARGET_DIR/bin/$name"
if [ ! -f "$dst" ] || ! cmp -s "$src" "$dst"; then
cp "$src" "$dst"
chmod +x "$dst"
((COPIED++))
fi
done
# Symlinks
ln -sf /opt/homebrew/bin/ffmpeg "$TARGET_DIR/bin/ffmpeg" 2>/dev/null || true
ln -sf /opt/homebrew/bin/ffprobe "$TARGET_DIR/bin/ffprobe" 2>/dev/null || true
pass "$COPIED 個二進制已部署"
# ── Step 6: 部署 Rust tools ──
step "[6/10] 部署 Rust tools"
if [ -d "$SCRIPT_DIR/tools" ]; then
cp -r "$SCRIPT_DIR/tools"/* "$TARGET_DIR/" 2>/dev/null || true
find "$TARGET_DIR/tools/cli/rust/target/release/" -name "rust_*" -exec chmod +x {} \; 2>/dev/null || true
RUST_COUNT=$(ls "$TARGET_DIR/tools/cli/rust/target/release/" 2>/dev/null | wc -l | tr -d ' ')
pass "$RUST_COUNT 個 Rust binary 已部署"
fi
# ── Step 7: 部署 Processors ──
step "[7/10] 部署 Swift processors"
if [ -d "$SCRIPT_DIR/processors" ]; then
cp "$SCRIPT_DIR/processors/"* "$TARGET_DIR/processors/" 2>/dev/null || true
chmod +x "$TARGET_DIR/processors/"* 2>/dev/null || true
PROC_COUNT=$(ls "$TARGET_DIR/processors/" 2>/dev/null | wc -l | tr -d ' ')
pass "$PROC_COUNT 個 processor 已部署"
fi
# ── Step 8: 部署配置和前端 ──
step "[8/10] 部署配置和前端"
cp "$SCRIPT_DIR/config/"* "$TARGET_DIR/config/" 2>/dev/null || true
cp "$SCRIPT_DIR/etc/"* "$TARGET_DIR/etc/" 2>/dev/null || true
cp -r "$SCRIPT_DIR/dist/"* "$TARGET_DIR/dist/" 2>/dev/null || true
# 更新路徑
USER="$(whoami)"
for f in "$TARGET_DIR/config/"*.json "$TARGET_DIR/config/"*.env "$TARGET_DIR/etc/"*; do
[ -f "$f" ] || continue
sed -i '' "s|/Users/accusys|/Users/$USER|g" "$f" 2>/dev/null || true
done
if [ -d "$TARGET_DIR/launchd" ]; then
for f in "$TARGET_DIR/launchd/"*.plist; do
[ -f "$f" ] || continue
sed -i '' "s|/Users/accusys|/Users/$USER|g" "$f" 2>/dev/null || true
done
fi
pass "配置和前端已部署"
# ── Step 9: 部署並啟動服務 ──
step "[9/10] 部署並啟動服務"
# 複製 launchd plists
cp "$SCRIPT_DIR/launchd/"*.plist "$HOME/Library/LaunchAgents/" 2>/dev/null || true
PLIST_COUNT=$(ls "$HOME/Library/LaunchAgents/com.momentry."*.plist 2>/dev/null | wc -l | tr -d ' ')
pass "$PLIST_COUNT 個服務定義已部署"
echo ""
echo " 啟動服務 (依序):"
# 定義服務啟動順序
SERVICES=(
"com.momentry.server:momentry server:3002"
"com.momentry.worker:momentry worker:"
"com.momentry.proxy:serve_frontend.py:8888"
"com.momentry.markbase:markbase-core:11438"
"com.momentry.llm:llama-server:8080"
"com.momentry.embedding:embeddinggemma:11436"
"com.momentry.markbaseengine:markbaseengine:8082"
"com.momentry.sftpgo:sftpgo:8081"
)
for svc_info in "${SERVICES[@]}"; do
IFS=':' read -r label process port <<< "$svc_info"
plist="$HOME/Library/LaunchAgents/$label.plist"
if [ -f "$plist" ]; then
echo -n " 啟動 $label..."
launchctl bootout "gui/$(id -u)/$label" 2>/dev/null || true
sleep 1
launchctl bootstrap "gui/$(id -u)/$label" "$plist" 2>/dev/null
if [ -n "$port" ]; then
wait_for_port "$port" "$label" 10 || warn "啟動可能失敗"
else
echo -e " ${GREEN}OK${NC}"
fi
fi
done
# 特殊處理 serve_frontend.py
if [ -f "$TARGET_DIR/bin/serve_frontend.py" ]; then
echo -n " 啟動 serve_frontend.py..."
pkill -f "serve_frontend.py" 2>/dev/null || true
sleep 1
nohup python3 "$TARGET_DIR/bin/serve_frontend.py" 8888 > "$TARGET_DIR/logs/proxy.log" 2>&1 &
wait_for_port 8888 "frontend" 5 || warn "啟動失敗"
fi
# ── Step 10: 最終測試 ──
step "[10/10] 最終測試"
echo ""
echo " 服務檢查:"
test_endpoint "http://127.0.0.1:3002/api/v1/health" "API Server" "200" || warn "server 未就緒"
sleep 2
echo ""
echo " 前端檢查:"
RESP=$(curl -s --max-time 3 "http://127.0.0.1:8888/" 2>/dev/null)
if echo "$RESP" | grep -q "DOCTYPE\|html"; then
pass "前端正常"
else
fail "前端異常"
fi
echo ""
echo " 登入檢查:"
RESP=$(curl -s --max-time 5 -X POST "http://127.0.0.1:8888/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{"username":"demo","password":"demo123"}' 2>/dev/null)
if echo "$RESP" | grep -q '"success":true'; then
pass "登入正常 (demo/demo123)"
else
fail "登入失敗"
fi
echo ""
echo " 外部 HTTPS 檢查:"
RESP=$(curl -s --max-time 5 -k "https://nextorage.momentry.ddns.net/" 2>/dev/null)
if echo "$RESP" | grep -q "DOCTYPE\|html"; then
pass "HTTPS 正常"
else
warn "HTTPS 可能未配置"
fi
# ── 完成 ──
echo ""
echo "╔══════════════════════════════════════════════════════════╗"
echo "║ 安裝完成! ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo ""
echo "服務端口:"
echo " API Server: http://localhost:3002"
echo " Frontend: http://localhost:8888"
echo " MarkBase: http://localhost:11438"
echo " External HTTPS: https://nextorage.momentry.ddns.net"
echo ""
echo "預設帳號: demo / demo123"
echo ""
echo "日誌: $LOG_FILE"