---
document_type: "reference_doc"
service: "MOMENTRY_CORE"
title: "Momentry 系統服務安裝與管理指南"
date: "2026-03-18"
version: "V1.0"
status: "active"
owner: "Warren"
created_by: "OpenCode"
tags:
  - "momentry"
  - "系統服務安裝與管理指南"
ai_query_hints:
  - "查詢 Momentry 系統服務安裝與管理指南 的內容"
  - "Momentry 系統服務安裝與管理指南 的主要目的是什麼？"
  - "如何操作或實施 Momentry 系統服務安裝與管理指南？"
---

# Momentry 系統服務安裝與管理指南

| 項目 | 內容 |
|------|------|
| 建立者 | Warren |
| 建立時間 | 2026-03-18 |
| 更新時間 | 2026-03-25 |
| 文件版本 | V1.2 |

---

## 版本歷史

| 版本 | 日期 | 目的 | 操作人 | 工具/模型 |
|------|------|------|--------|-----------|
| V1.0 | 2026-03-18 | 創建文件 | Warren | OpenCode / MiniMax M2.5 |
| V1.1 | 2026-03-24 | 更新所有服務 plist 狀態，統一使用自定義 plist | OpenCode | OpenCode / big-pickle |
| V1.2 | 2026-03-25 | 新增 Momentry Playground、Job Worker 說明 | OpenCode | OpenCode / GLM-5 |

---

## 概述

本文檔記錄 momentry 系統所需的所有服務，包括安裝步驟、健康檢查和管理命令。

**重要**: 請勿使用 `brew services` 命令管理服務，否則可能導致 .plist 檔案還原為預設狀態，造成系統異常。請使用 `launchctl` 命令進行管理。

**2026-03-24 更新**: 所有服務已統一使用自定義 plist，存在於 `/Library/LaunchDaemons/` 目錄。Reboot 後會自動啟動。

---

## 服務清單

| 服務名稱 | 安裝方式 | 用途 | 狀態 |
|----------|----------|------|-------|
| PostgreSQL | 自定義 plist | 影片元資料儲存 | ✅ 正常 |
| Redis | 自定義 plist | 快取與工作佇列 | ✅ 正常 |
| Ollama | 自定義 plist | 本地 LLM 推論 | ✅ 正常 |
| Caddy | 自定義 plist | 網頁伺服器 | ✅ 正常 |
| Gitea | 自定義 plist | Git 服務 | ✅ 正常 |
| Gitea MCP Server | 自定義 plist | Gitea MCP 整合 | ✅ 正常 |
| Grafana | Homebrew | 監控儀表板 | ⚠️ Homebrew |
| Kafka | 手動安裝 | 訊息佇列 (可選) | ⚠️ 未遷移 |
| MariaDB | 自定義 plist | 資料庫 (可選) | ✅ 正常 |
| Netdata | Homebrew | 系統監控 | ⚠️ Homebrew |
| PHP | 自定義 plist | Web 後端 | ✅ 正常 |
| Prometheus | Homebrew | 指標收集 | ⚠️ Homebrew |
| SeaweedFS | 手動安裝 | 分散式儲存 (可選) | ⚠️ 未遷移 |
| SFTPGo | 自定義 plist | SFTP 服務 | ✅ 正常 |
| n8n | 自定義 plist | 工作流自動化 | ✅ 正常 |
| n8n Worker | 自定義 plist | 工作流 Worker | ✅ 正常 |
| MongoDB | 自定義 plist | 文件資料庫 | ✅ 正常 |
| Qdrant | 自定義 plist | 向量資料庫 | ✅ 正常 |
| Momentry API | 自定義 plist | 影片管理 API | ✅ 正常 |
| Momentry Playground | CLI | 開發測試用二進位 | ✅ 正常 |
| RustDesk HBBR | 自定義 plist | 遠端桌面橋接 | ✅ 正常 |
| RustDesk HBBS | 自定義 plist | 遠端桌面服務器 | ✅ 正常 |

---

## Momentry 服務說明

### Momentry API vs Momentry Playground

| 項目 | Momentry API | Momentry Playground |
|------|--------------|---------------------|
| 用途 | 生產環境 | 開發/測試環境 |
| Port | 3002 | 3003 |
| Redis Prefix | `momentry:` | `momentry_dev:` |
| 環境變數 | `.env` | `.env.development` |
| 啟動命令 | `cargo run --bin momentry -- server` | `cargo run --bin momentry_playground -- server` |

### Job Worker

Job Worker 是 Momentry Core 的背景處理系統，負責執行影片處理任務。

**架構**:
- 輪詢 `monitor_jobs` 表取得待處理任務
- 最多同時執行 2 個 processor（可透過環境變數調整）
- 更新 `processor_results` 表記錄每個處理器狀態

**環境變數**:
| 變數 | 預設值 | 說明 |
|------|--------|------|
| `MOMENTRY_MAX_CONCURRENT` | 2 | 最大並行處理器數 |
| `MOMENTRY_POLL_INTERVAL` | 5 | 輪詢間隔（秒） |
| `MOMENTRY_WORKER_ENABLED` | true | 是否啟用 Worker |

**狀態監控**:
```bash
# 查看待處理工作
psql -U accusys -d momentry -c "SELECT * FROM monitor_jobs WHERE status = 'pending';"

# 查看執行中工作
psql -U accusys -d momentry -c "SELECT * FROM monitor_jobs WHERE status = 'running';"

# 查看處理器狀態
psql -U accusys -d momentry -c "SELECT * FROM processor_results WHERE job_id = <job_id>;"
```

---

## 服務健康檢查結果 (2026-03-24)

### ✅ 正常運行的服務

| 服務 | 版本 | Port | 測試命令 | 結果 |
|------|------|------|----------|------|
| **PostgreSQL** | 18.1 | 5432 | `pg_isready -h 127.0.0.1 -p 5432` | ✅ 接受連線 |
| **Redis** | 7.4.x | 6379 | `redis-cli -a accusys ping` | ✅ PONG |
| **MongoDB** | 8.2.6 | 27017 | `mongosh --eval "db.adminCommand('ping')"` | ✅ { ok: 1 } |
| **Ollama** | - | 11434 | `curl -s http://localhost:11434/api/tags` | ✅ 模型可用 |
| **n8n** | 2.12.3 | 5678/5681/5682 | `curl -s http://localhost:5678/healthz` | ✅ {"status":"ok"} |
| **n8n Worker** | 2.12.3 | 5681/5690/5691 | - | ✅ 運行中 |
| **Momentry API** | 0.1.0 | 3002 | `curl -s http://localhost:3002/health` | ✅ OK |
| **Momentry Playground** | 0.1.0 | 3003 | `curl -s http://localhost:3003/health` | ✅ OK (開發環境) |
| **Qdrant** | 1.17.0 | 6333 | `curl -s http://localhost:6333/` | ✅ 版本資訊 |
| **Caddy** | 2.10.x | 443 | `curl -sI https://momentry.ddns.net` | ✅ HTTP 200 |
| **SFTPGo** | 2.7.x | 8080 | `curl -s http://localhost:8080/sftpgo/` | ✅ JSON 響應 |
| **Gitea** | - | 3000 | `curl -s http://localhost:3000/` | ✅ HTML 響應 |
| **Gitea MCP** | - | 8787 | `curl -s http://localhost:8787/` | ✅ 運行中 |
| **MariaDB** | 12.1.x | 3306 | `mariadb -u root -e "SELECT 1;"` | ✅ 正常 |
| **PHP-FPM** | 8.5.x | 9000 | `ps aux \| grep php-fpm` | ✅ 運行中 |

### ⚠️ 需要配置的服務

| 服務 | 問題 | 解決方案 |
|------|------|----------|
| Grafana | 使用 Homebrew | 考慮遷移到自定義 plist |
| Prometheus | 使用 Homebrew | 考慮遷移到自定義 plist |
| Kafka | 未遷移 | 可選服務 |
| SeaweedFS | 未遷移 | 可選服務 |
| Netdata | 使用 Homebrew | 考慮遷移到自定義 plist |

### ⚠️ Homebrew 管理的服務 (建議遷移)

| 服務 | 風險 |
|------|------|
| homebrew.mxcl.grafana | Reboot 後可能自動啟動但使用預設設定 |
| homebrew.mxcl.prometheus | Reboot 後可能自動啟動但使用預設設定 |
| homebrew.mxcl.openwebui | 需要確認是否需要 |
| homebrew.mxcl.kafka | 需要確認是否需要 |
| homebrew.mxcl.seaweedfs | 需要確認是否需要 |
| homebrew.mxcl.netdata | 需要確認是否需要 |
| homebrew.mxcl.ddclient | 動態 DNS，可能需要 |
| homebrew.mxcl.shadowsocks-rust | VPN，可能需要 |

### MCP Servers (2026-03-24)

| Server | 安裝方式 | 路徑 | 狀態 |
|--------|----------|------|------|
| gitea | Homebrew | /opt/homebrew/bin/gitea-mcp-server | ✅ Connected |
| n8n | NPM | /opt/homebrew/bin/mcp-n8n | ✅ Connected |
| postgres | NPM | /opt/homebrew/bin/mcp-server-postgres | ✅ Connected |
| redis | NPM | /opt/homebrew/bin/mcp-server-redis | ✅ Connected |
| mongodb | NPM | /opt/homebrew/bin/mongodb-mcp-server | ✅ Connected |
| qdrant | Python | /opt/homebrew/bin/mcp-server-qdrant | ✅ Connected |
| filesystem | NPM | /opt/homebrew/bin/mcp-server-filesystem | ✅ Connected |
| sentry | NPM | /opt/homebrew/bin/sentry-mcp | ⏳ Pending Config |
| context7 | NPM | /opt/homebrew/bin/context7-mcp | ✅ Connected |
| playwright | NPM | /opt/homebrew/bin/playwright-mcp | ✅ Connected |

**配置文件**: `~/.config/opencode/opencode.json`

**驗證命令**:
```bash
opencode mcp ls
```

**詳細文檔**: [OpenCode MCP 安裝指南](./OPENCODE_MCP_INSTALL.md)

### 測試腳本

```bash
#!/bin/bash
# services_health_check.sh

echo "=== Momentry 服務健康檢查 ==="
echo ""

# PostgreSQL
pg_isready -h 127.0.0.1 -p 5432 -U accusys > /dev/null 2>&1 && echo "✅ PostgreSQL" || echo "❌ PostgreSQL"

# Redis
redis-cli -a accusys ping > /dev/null 2>&1 && echo "✅ Redis" || echo "❌ Redis"

# MongoDB
mongosh --quiet --eval "db.adminCommand('ping')" > /dev/null 2>&1 && echo "✅ MongoDB" || echo "❌ MongoDB"

# Ollama
curl -s http://localhost:11434/api/tags > /dev/null 2>&1 && echo "✅ Ollama" || echo "❌ Ollama"

# n8n
curl -s http://localhost:5678/ > /dev/null 2>&1 && echo "✅ n8n" || echo "❌ n8n"

# Momentry API
curl -s http://localhost:3002/health > /dev/null 2>&1 && echo "✅ Momentry API" || echo "❌ Momentry API"

# Qdrant
curl -s http://localhost:6333/ > /dev/null 2>&1 && echo "✅ Qdrant" || echo "❌ Qdrant"

# Caddy
curl -sI https://momentry.ddns.net > /dev/null 2>&1 && echo "✅ Caddy" || echo "❌ Caddy"

# SFTPGo
curl -s http://localhost:8080/api/v2/healthz > /dev/null 2>&1 && echo "✅ SFTPGo" || echo "⚠️ SFTPGo (需配置)"
```

---

---

## 必要服務 (Momentry 核心)

### 1. PostgreSQL

#### 安裝
```bash
# 檢查是否已安裝
brew list postgresql@18 2>/dev/null || echo "Not installed"

# 安裝 PostgreSQL 18
brew install postgresql@18
```

#### 資料目錄
```
/Users/accusys/momentry/var/postgresql
```

**重要**: 確保使用統一的資料目錄，避免與 homebrew plist 衝突。

#### 開機自動啟動
```bash
# 建立 plist 檔案
sudo tee /Library/LaunchDaemons/com.momentry.postgresql.plist > /dev/null <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.momentry.postgresql</string>
    <key>UserName</key>
    <string>accusys</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>LC_ALL</key>
        <string>en_US.UTF-8</string>
    </dict>
    <key>WorkingDirectory</key>
    <string>/Users/accusys/momentry/var/postgresql</string>
    <key>ProgramArguments</key>
    <array>
        <string>/opt/homebrew/opt/postgresql@18/bin/postgres</string>
        <string>-D</string>
        <string>/Users/accusys/momentry/var/postgresql</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/Users/accusys/momentry/log/postgresql.error.log</string>
    <key>StandardOutPath</key>
    <string>/Users/accusys/momentry/log/postgresql.log</string>
</dict>
</plist>
EOF

# 載入服務
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.postgresql.plist
```

#### 管理命令
```bash
# 啟動
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.postgresql.plist

# 停止
sudo launchctl bootout system/com.momentry.postgresql.plist

# 重新載入
sudo launchctl bootout system/com.momentry.postgresql.plist
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.postgresql.plist

# 查看狀態
launchctl list | grep com.momentry.postgresql
```

#### 健康檢查
```bash
# 方法 1: 使用 pg_isready
pg_isready -h localhost -p 5432 -U accusys

# 方法 2: 連線測試
PGPASSWORD=n8n1234 psql -h localhost -U n8n -d n8n -c "SELECT 1;"

# 方法 3: 檢查程序
pgrep -a postgres

# 方法 4: 檢查資料庫
PGPASSWORD=n8n1234 psql -h localhost -U n8n -d n8n -c "SELECT COUNT(*) FROM workflow_entity;"
```

---

### 2. Redis

#### 安裝
```bash
# 檢查是否已安裝
brew list redis 2>/dev/null || echo "Not installed"

# 安裝 Redis
brew install redis
```

#### 設定密碼
```bash
# 編輯 Redis 設定檔
vim /opt/homebrew/etc/redis.conf

# 找到 requirepass 行，修改為:
requirepass accusys

# 或使用環境變數方式啟動
```

#### 開機自動啟動
```bash
# 建立 plist 檔案
sudo tee /Library/LaunchDaemons/com.momentry.redis.plist > /dev/null <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.momentry.redis</string>
    <key>UserName</key>
    <string>accusys</string>
    <key>WorkingDirectory</key>
    <string>/Users/accusys/momentry/var/redis</string>
    <key>ProgramArguments</key>
    <array>
        <string>/opt/homebrew/opt/redis/bin/redis-server</string>
        <string>/opt/homebrew/etc/redis.conf</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>REDIS_PASSWORD</key>
        <string>accusys</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/accusys/momentry/log/redis.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/accusys/momentry/log/redis.error.log</string>
</dict>
</plist>
EOF

# 載入服務
sudo launchctl load /Library/LaunchDaemons/com.momentry.redis.plist
```

#### 管理命令
```bash
# 啟動
sudo launchctl load /Library/LaunchDaemons/com.momentry.redis.plist

# 停止
sudo launchctl unload /Library/LaunchDaemons/com.momentry.redis.plist

# 重啟
sudo launchctl unload /Library/LaunchDaemons/com.momentry.redis.plist
sudo launchctl load /Library/LaunchDaemons/com.momentry.redis.plist

# 查看狀態
launchctl list | grep com.momentry.redis

# 查看日誌
tail -f /Users/accusys/momentry/log/redis.log
tail -f /Users/accusys/momentry/log/redis.error.log
```

#### 健康檢查
```bash
# 方法 1: 使用 redis-cli ping
redis-cli -a accusys ping

# 輸出應為: PONG

# 方法 2: 檢查密碼認證
redis-cli -a accusys AUTH accusys

# 方法 3: 檢查程序
pgrep -f redis-server

# 方法 4: 檢查連線數
redis-cli -a accusys INFO clients
```

---

### 3. Ollama

#### 安裝
```bash
# 檢查是否已安裝
which ollama || echo "Not installed"

# 安裝 Ollama
brew install ollama
```

#### 模型下載
```bash
# 下載 Mistral (LLM)
ollama pull mistral:latest

# 下載 Embedding 模型
ollama pull nomic-embed-text:latest

# 驗證模型
ollama list
```

#### 開機自動啟動
```bash
# 建立 plist 檔案
sudo tee /Library/LaunchDaemons/com.momentry.ollama.plist > /dev/null <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.momentry.ollama</string>
    <key>UserName</key>
    <string>accusys</string>
    <key>WorkingDirectory</key>
    <string>/Users/accusys/momentry/var/ollama</string>
    <key>ProgramArguments</key>
    <array>
        <string>/opt/homebrew/bin/ollama</string>
        <string>serve</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>OLLAMA_HOST</key>
        <string>0.0.0.0:11434</string>
        <key>OLLAMA_MODELS</key>
        <string>/Users/accusys/momentry/var/ollama/models</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/accusys/momentry/log/ollama.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/accusys/momentry/log/ollama.error.log</string>
</dict>
</plist>
EOF

# 載入服務
sudo launchctl load /Library/LaunchDaemons/com.momentry.ollama.plist
```

#### 管理命令
```bash
# 啟動
sudo launchctl load /Library/LaunchDaemons/com.momentry.ollama.plist

# 停止
sudo launchctl unload /Library/LaunchDaemons/com.momentry.ollama.plist

# 重啟
sudo launchctl unload /Library/LaunchDaemons/com.momentry.ollama.plist
sudo launchctl load /Library/LaunchDaemons/com.momentry.ollama.plist

# 查看狀態
launchctl list | grep com.momentry.ollama

# 查看日誌
tail -f /Users/accusys/momentry/log/ollama.log
tail -f /Users/accusys/momentry/log/ollama.error.log
```

#### 健康檢查
```bash
# 方法 1: API 測試
curl -s http://localhost:11434/api/tags | jq '.models[].name'

# 方法 2: 檢查程序
pgrep -f ollama

# 方法 3: 列出模型
ollama list
```

---

### 4. n8n (工作流自動化)

#### 安裝
```bash
# 檢查是否已安裝
which n8n || echo "Not installed"

# 安裝 n8n
brew install n8n
```

#### 開機自動啟動
```bash
# 複製 plist 到 LaunchDaemons 目錄
sudo cp /Users/accusys/momentry_core_0.1/momentry_runtime/plist/com.momentry.n8n.main.plist /Library/LaunchDaemons/
sudo cp /Users/accusys/momentry_core_0.1/momentry_runtime/plist/com.momentry.n8n.worker.plist /Library/LaunchDaemons/

# 載入服務
sudo launchctl load /Library/LaunchDaemons/com.momentry.n8n.main.plist
sudo launchctl load /Library/LaunchDaemons/com.momentry.n8n.worker.plist
```

#### 管理命令
```bash
# 啟動
sudo launchctl load /Library/LaunchDaemons/com.momentry.n8n.main.plist
sudo launchctl load /Library/LaunchDaemons/com.momentry.n8n.worker.plist

# 停止
sudo launchctl unload /Library/LaunchDaemons/com.momentry.n8n.main.plist
sudo launchctl unload /Library/LaunchDaemons/com.momentry.n8n.worker.plist
```

#### 健康檢查
```bash
# 方法 1: API 測試
curl -s http://localhost:5678/

# 方法 2: 檢查程序
ps aux | grep n8n | grep -v grep

# 方法 3: 檢查端口
lsof -i :5678
lsof -i :5679
```

---

## 可選服務

### 4. Caddy (網頁伺服器)

```bash
# 安裝
brew install caddy

# 開機啟動
cp /opt/homebrew.mxcl.caddy.plist /Library/LaunchDaemons/
sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.caddy.plist

# 健康檢查
curl -s https://localhost:2019/config/ | head -5
```

### 5. Grafana (監控)

```bash
# 安裝
brew install grafana

# 開機啟動
cp /opt/homebrew.mxcl.grafana.plist ~/Library/LaunchAgents/
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.grafana.plist

# 健康檢查
curl -s http://localhost:3000/api/health | jq '.'
```

### 6. Prometheus (監控)

```bash
# 安裝
brew install prometheus

# 開機啟動
cp /opt/homebrew.mxcl.prometheus.plist ~/Library/LaunchAgents/
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.prometheus.plist

# 健康檢查
curl -s http://localhost:9090/-/healthy
```

### 7. Netdata (系統監控)

```bash
# 安裝
brew install netdata

# 開機啟動
sudo brew services start netdata

# 健康檢查
curl -s http://localhost:19999/api/v1/info | jq '.version'
```

---

## 統一健康檢查腳本

建立 `/Users/accusys/momentry_core_0.1/scripts/health_check.sh`:

```bash
#!/bin/bash

# Momentry 系統健康檢查腳本

echo "========================================"
echo "Momentry 系統健康檢查"
echo "========================================"
echo ""

# 顏色定義
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

check_service() {
    local name=$1
    local check_cmd=$2
    
    if eval "$check_cmd" > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} $name"
        return 0
    else
        echo -e "${RED}✗${NC} $name"
        return 1
    fi
}

total=0
passed=0

# 1. PostgreSQL
total=$((total + 1))
check_service "PostgreSQL (localhost:5432)" "pg_isready -h localhost -p 5432 -U accusys" && passed=$((passed + 1))

# 2. Redis
total=$((total + 1))
check_service "Redis (localhost:6379)" "redis-cli -a accusys ping" && passed=$((passed + 1))

# 3. Ollama
total=$((total + 1))
check_service "Ollama (localhost:11434)" "curl -s http://localhost:11434/api/tags > /dev/null" && passed=$((passed + 1))

# 4. n8n
total=$((total + 1))
check_service "n8n (localhost:5678)" "curl -s http://localhost:5678/ > /dev/null" && passed=$((passed + 1))

# 5. Grafana (如果安裝)
if command -v grafana-server > /dev/null 2>&1; then
    total=$((total + 1))
    check_service "Grafana (localhost:3000)" "curl -s http://localhost:3000/api/health > /dev/null" && passed=$((passed + 1))
fi

# 6. Prometheus (如果安裝)
if command -v prometheus > /dev/null 2>&1; then
    total=$((total + 1))
    check_service "Prometheus (localhost:9090)" "curl -s http://localhost:9090/-/healthy > /dev/null" && passed=$((passed + 1))
fi

# 7. Netdata (如果安裝)
if command -v netdata > /dev/null 2>&1; then
    total=$((total + 1))
    check_service "Netdata (localhost:19999)" "curl -s http://localhost:19999/api/v1/info > /dev/null" && passed=$((passed + 1))
fi

echo ""
echo "========================================"
echo "結果: $passed/$total 服務正常"
echo "========================================"

if [ $passed -eq $total ]; then
    exit 0
else
    exit 1
fi
```

使用方式:
```bash
chmod +x scripts/health_check.sh
./scripts/health_check.sh
```

---

## 服務管理速查表

### 啟動服務 (使用 launchctl bootstrap)
```bash
# 所有服務
for plist in /Library/LaunchDaemons/com.momentry.*.plist; do
    sudo launchctl bootstrap system "$plist"
done

# PostgreSQL
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.postgresql.plist

# Redis, Ollama, Qdrant
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.redis.plist
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.ollama.plist
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.qdrant.plist

# n8n (main + worker)
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.n8n.main.plist
sudo launchctl bootstrap system /Library/LaunchDaemons/com.momentry.n8n.worker.plist
```

### 停止服務 (使用 launchctl bootout)
```bash
# 所有 Momentry 服務
for svc in $(launchctl list | grep com.momentry | awk '{print $3}'); do
    sudo launchctl bootout system/$svc 2>/dev/null
done

# PostgreSQL
sudo launchctl bootout system/com.momentry.postgresql.plist

# Redis, Ollama, Qdrant
sudo launchctl bootout system/com.momentry.redis.plist
sudo launchctl bootout system/com.momentry.ollama.plist
sudo launchctl bootout system/com.momentry.qdrant.plist

# n8n
sudo launchctl bootout system/com.momentry.n8n.main.plist
sudo launchctl bootout system/com.momentry.n8n.worker.plist
```

### 查詢服務狀態
```bash
# 查看所有 Momentry 服務
launchctl list | grep com.momentry

# 查看特定服務
launchctl list | grep com.momentry.postgresql
launchctl list | grep com.momentry.n8n
```

---

## 故障排除

### PostgreSQL 問題

```bash
# 查看日誌
tail -f /opt/homebrew/var/postgresql@18/logfile

# 重新初始化
pg_ctl -D /opt/homebrew/var/postgresql@18 stop
rm -rf /opt/homebrew/var/postgresql@18
initdb -D /opt/homebrew/var/postgresql@18

# 重建資料庫
dropdb momentry
createdb -U accusys momentry
```

### Redis 問題

```bash
# 查看日誌
tail -f /opt/homebrew/var/log/redis.log

# 測試連線
redis-cli -a accusys DEBUG SLEEP 1

# 重新整理 ACL
redis-cli -a accusys FLUSHALL
```

### Ollama 問題

```bash
# 查看日誌
tail -f ~/.ollama/logs/server.log

# 重新下載模型
ollama pull mistral:latest
ollama pull nomic-embed-text:latest

# 檢查 GPU 使用情況
ollama list
```

---

## 自動化腳本

建立 `/Users/accusys/momentry_core_0.1/scripts/service_manager.sh`:

```bash
#!/bin/bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLIST_DIR="$SCRIPT_DIR/../momentry_runtime/plist"

action=${1:-start}
service=${2:-all}

start_postgresql() {
    echo "Starting PostgreSQL..."
    sudo launchctl load /Library/LaunchDaemons/com.momentry.postgresql.plist 2>/dev/null || \
        echo "PostgreSQL plist not found, skipping..."
}

start_redis() {
    echo "Starting Redis..."
    launchctl load ~/Library/LaunchAgents/com.momentry.redis.plist 2>/dev/null || \
        echo "Redis plist not found, skipping..."
}

start_ollama() {
    echo "Starting Ollama..."
    launchctl load ~/Library/LaunchAgents/com.momentry.ollama.plist 2>/dev/null || \
        echo "Ollama plist not found, skipping..."
}

stop_postgresql() {
    echo "Stopping PostgreSQL..."
    sudo launchctl unload /Library/LaunchDaemons/com.momentry.postgresql.plist 2>/dev/null || true
}

stop_redis() {
    echo "Stopping Redis..."
    launchctl unload ~/Library/LaunchAgents/com.momentry.redis.plist 2>/dev/null || true
}

stop_ollama() {
    echo "Stopping Ollama..."
    launchctl unload ~/Library/LaunchAgents/com.momentry.ollama.plist 2>/dev/null || true
}

case $action in
    start)
        case $service in
            all)
                start_postgresql
                start_redis
                start_ollama
                ;;
            postgresql|pgsql|pg)
                start_postgresql
                ;;
            redis)
                start_redis
                ;;
            ollama)
                start_ollama
                ;;
            *)
                echo "Unknown service: $service"
                exit 1
                ;;
        esac
        ;;
    stop)
        case $service in
            all)
                stop_ollama
                stop_redis
                stop_postgresql
                ;;
            postgresql|pgsql|pg)
                stop_postgresql
                ;;
            redis)
                stop_redis
                ;;
            ollama)
                stop_ollama
                ;;
            *)
                echo "Unknown service: $service"
                exit 1
                ;;
        esac
        ;;
    restart)
        $0 stop $service
        sleep 2
        $0 start $service
        ;;
    status)
        echo "Service Status:"
        echo "==============="
        launchctl list | grep -E "(postgres|redis|ollama)" || echo "No services found"
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status} [service]"
        echo "Services: all, postgresql, redis, ollama"
        exit 1
        ;;
esac
```

---

## 服務快速參照

### Port 對照表

| Port | 服務 | 說明 |
|------|------|------|
| 11434 | Ollama | LLM API |
| 19999 | Netdata | 系統監控 |
| 2019 | Caddy | 管理 API |
| 21115-21119 | RustDesk | 遠端桌面 |
| 27017 | MongoDB | 文件資料庫 |
| 3000 | Gitea | Git 服務 |
| 3001 | Grafana | 監控儀表板 |
| 3002 | Momentry API | Rust API 伺服器 (生產環境) |
| 3003 | Momentry Playground | Rust API 伺服器 (開發環境) |
| 3306 | MariaDB | MySQL 相容資料庫 |
| 4096 | OpenCode | CLI 工具 |
| 5000-7000 | ControlCenter | 控制中心 |
| 5678 | n8n | 工作流自動化 (Main) |
| 5681 | n8n | Worker HTTP |
| 5682 | n8n | Worker Health Check |
| 5690 | n8n | Task Broker |
| 5691 | n8n | Runner Health |
| 6333-6334 | Qdrant | 向量資料庫 |
| 6379 | Redis | 快取/佇列 |
| 8080 | SFTPGo | HTTP/WebDAV |
| 8081 | Trunk | 轉發服務 |
| 8082 | SeaweedFS | Master |
| 8090 | SFTPGo | WebDAV |
| 8333 | SeaweedFS | Volume |
| 8388 | Shadowsocks | VPN |
| 8888 | SeaweedFS | Filer |
| 9000 | PHP-FPM | PHP 處理器 |
| 9090 | Prometheus | 指標收集 |
| 9092-9093 | Kafka | 訊息佇列 |
| 9333 | SeaweedFS | Volume |
| 18082 | SeaweedFS | Volume |
| 18333 | SeaweedFS | Volume |
| 18888 | SeaweedFS | Filer |
| 19333 | SeaweedFS | Volume |

## Caddy 反向代理 URL 對照表

| URL | 內部服務 | 說明 |
|-----|----------|------|
| `n8n.momentry.ddns.net` | :5678 | n8n 工作流自動化 |
| `wp.momentry.ddns.net` | :9000 | WordPress 網站 |
| `seaweed.momentry.ddns.net` | :8888 | SeaweedFS Filer |
| `sftpgo.momentry.ddns.net` | :8080 | SFTPGo HTTP |
| `webdav.momentry.ddns.net` | :8090 | SFTPGo WebDAV |
| `qdrant.momentry.ddns.net` | :6333 | Qdrant 向量資料庫 |
| `gitea.momentry.ddns.net` | :3000 | Gitea Git 服務 |
| `chat.momentry.ddns.net` | :8085 | Open WebUI |
| `netdata.momentry.ddns.net` | :19999 | Netdata 監控 |
| `grafana.momentry.ddns.net` | :3001 | Grafana 儀表板 |
| `router5.momentry.ddns.net` | 192.168.5.1:80 | Router 5 |
| `router110.momentry.ddns.net` | 192.168.110.1:80 | Router 110 |
| `router0.momentry.ddns.net/admin/*` | 192.168.0.1:80 | Router 0 |
| `truenas.momentry.ddns.net` | 192.168.0.219:80 | TrueNAS |
| `:3200` | :3002 | Momentry Dashboard + API |

**Caddy 管理**: https://localhost:2019/

---

## 目錄對照表

### /Users/accusys/momentry/var/

| 目錄 | 服務 | 說明 |
|------|------|------|
| `caddy/` | Caddy | 資料目錄 |
| `gitea/` | Gitea | Git 資料庫 |
| `mariadb/` | MariaDB | 資料庫檔案 |
| `mongodb/` | MongoDB | 文件資料庫 (自定義 plist) |
| `n8n/` | n8n | 工作流資料 |
| `ollama/` | Ollama | 模型快取 |
| `php/` | PHP | FastCGI 進程 |
| `postgresql/` | PostgreSQL | 主資料庫 (自定義 plist) |
| `qdrant/` | Qdrant | 向量資料庫 |
| `redis/` | Redis | 持久化檔案 |
| `rustdesk/` | RustDesk | ID 資料庫 |
| `sftpgo/` | SFTPGo | 使用者資料 |
| `sftpgo_backup/` | SFTPGo | 備份 |

### /opt/homebrew/var/ (Homebrew 管理)

| 目錄 | 服務 | 說明 |
|------|------|------|
| `mongodb/` | MongoDB | (舊) 文件資料庫 |
| `postgresql@18/` | PostgreSQL | (舊) 主資料庫 |

### /Users/accusys/momentry/etc/

| 目錄 | 服務 | 說明 |
|------|------|------|
| `caddy/` | Caddy | 配置 |
| `gitea/` | Gitea | 配置 |
| `php/` | PHP | 配置 |
| `sftpgo/` | SFTPGo | 配置 |

### /Users/accusys/momentry/log/

| 檔案 | 服務 | 說明 |
|------|------|------|
| `backup.log` | Backup | 備份日誌 |
| `redis.log` | Redis | 執行日誌 |
| `redis.error.log` | Redis | 錯誤日誌 |
| `ollama.log` | Ollama | 執行日誌 |
| `ollama.error.log` | Ollama | 錯誤日誌 |

### /Users/accusys/momentry/backup/

| 目錄 | 說明 |
|------|------|
| `daily/` | 每日備份 |
| `weekly/` | 每週備份 |
| `monthly/` | 每月備份 |

---

## 附錄: 服務版本對應表

| 服務 | 版本 | Port | 使用者 | plist 位置 | 資料目錄 |
|------|------|------|--------|-------------|----------|
| PostgreSQL | 18.1 | 5432 | accusys | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/postgresql |
| Redis | 7.4.x | 6379 | accusys | /Library/LaunchDaemons/ | /opt/homebrew/var/redis |
| Ollama | 0.13.5 | 11434 | accusys | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/ollama/models |
| n8n | 2.12.3 | 5678/5681 | accusys | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/n8n |
| Node.js (n8n) | 22.22.1 | - | - | /opt/homebrew/opt/node@22/ | - |
| Python (Momentry) | 3.11.14 | - | - | venv/bin/python | - |
| Caddy | 2.10.x | 2019/443 | root | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/caddy |
| Gitea | - | 3000 | accusys | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/gitea |
| Gitea MCP | - | 8787 | accusys | /Library/LaunchDaemons/ | - |
| SFTPGo | 2.7.x | 8080/2022 | accusys | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/sftpgo |
| Qdrant | 1.17.0 | 6333 | accusys | /Library/LaunchDaemons/ | /Users/accusys/.local/share/qdrant |
| MongoDB | 8.2.6 | 27017 | root | /Library/LaunchDaemons/ | /opt/homebrew/var/mongodb |
| MariaDB | 12.1.x | 3306 | accusys | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/mariadb |
| RustDesk HBBR | - | 21115 | accusys | /Library/LaunchDaemons/ | - |
| RustDesk HBBS | - | 21115-21119 | accusys | /Library/LaunchDaemons/ | /Users/accusys/momentry/var/rustdesk |
| PHP | 8.5.x | 9000 | - | /Library/LaunchDaemons/ | - |
| Momentry API | 0.1.0 | 3002 | accusys | /Library/LaunchDaemons/ | - |
| Momentry Playground | 0.1.0 | 3003 | accusys | - | - |

---

## 重要密碼與金鑰

| 服務 | 用途 | 預設值 |
|------|------|--------|
| **PostgreSQL** | 連線密碼 (accusys) | `accusys` |
| **Redis** | 認證密碼 | `accusys` |
| **Qdrant** | API Key | `Test3200Test3200Test3200` |
| **n8n** | 資料庫密碼 | `n8n` (PostgreSQL) |
| **SFTPGo** | 安裝碼 | `Test3200Test3200` |
| **SFTPGo** | DB 密碼 | `sftpgo_pass_2026` |
| **Momentry API** | 資料庫 | `postgres://accusys:accusys@127.0.0.1:5432/momentry` |
