diff --git a/docs/swagger.json b/docs/swagger.json index 755cac111f7..32693788d3e 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -27011,6 +27011,32 @@ } } }, + "github_com_Tencent_WeKnora_internal_im.RuntimeStatus": { + "type": "object", + "properties": { + "active": { + "type": "integer" + }, + "available": { + "type": "boolean" + }, + "pending": { + "type": "integer" + }, + "queue_limit": { + "type": "integer" + }, + "rejected": { + "type": "integer" + }, + "timed_out": { + "type": "integer" + }, + "workers": { + "type": "integer" + } + } + }, "github_com_Tencent_WeKnora_internal_infrastructure_chunker.DocProfile": { "type": "object", "properties": { @@ -41832,6 +41858,150 @@ } } }, + "internal_handler.OperationsBackup": { + "type": "object", + "properties": { + "available": { + "type": "boolean" + }, + "completed_at": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "snapshot_count": { + "type": "integer" + }, + "stale": { + "type": "boolean" + } + } + }, + "internal_handler.OperationsDisk": { + "type": "object", + "properties": { + "available": { + "type": "boolean" + }, + "available_bytes": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "total_bytes": { + "type": "integer" + }, + "used_percent": { + "type": "number" + } + } + }, + "internal_handler.OperationsHost": { + "type": "object", + "properties": { + "cpu_count": { + "type": "integer" + }, + "load_1m": { + "type": "number" + }, + "memory_available_bytes": { + "type": "integer" + }, + "memory_total_bytes": { + "type": "integer" + } + } + }, + "internal_handler.OperationsLog": { + "type": "object", + "properties": { + "bytes": { + "type": "integer" + }, + "health": { + "type": "string" + }, + "max_files": { + "type": "string" + }, + "max_size": { + "type": "string" + }, + "name": { + "type": "string" + }, + "status": { + "type": "string" + } + } + }, + "internal_handler.OperationsService": { + "type": "object", + "properties": { + "active": { + "type": "string" + }, + "available": { + "type": "boolean" + }, + "exit_status": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "result": { + "type": "string" + }, + "running_required": { + "type": "boolean" + } + } + }, + "internal_handler.OperationsStatus": { + "type": "object", + "properties": { + "available": { + "type": "boolean" + }, + "backups": { + "type": "array", + "items": { + "$ref": "#/definitions/internal_handler.OperationsBackup" + } + }, + "collected_at": { + "type": "integer" + }, + "disks": { + "type": "array", + "items": { + "$ref": "#/definitions/internal_handler.OperationsDisk" + } + }, + "host": { + "$ref": "#/definitions/internal_handler.OperationsHost" + }, + "logs": { + "type": "array", + "items": { + "$ref": "#/definitions/internal_handler.OperationsLog" + } + }, + "services": { + "type": "array", + "items": { + "$ref": "#/definitions/internal_handler.OperationsService" + } + }, + "stale": { + "type": "boolean" + } + } + }, "internal_handler.PageResponse": { "type": "object", "properties": { @@ -42581,6 +42751,9 @@ "type": "boolean", "x-agent": true }, + "im": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_im.RuntimeStatus" + }, "model_limiter_available": { "type": "boolean", "x-agent": true @@ -42596,6 +42769,9 @@ "type": "boolean", "x-agent": true }, + "operations": { + "$ref": "#/definitions/internal_handler.OperationsStatus" + }, "parse_concurrency": { "description": "compatibility alias for upstream_concurrency", "type": "integer" diff --git a/docs/swagger.yaml b/docs/swagger.yaml index fd2023114ac..4cd3dbd451e 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1059,6 +1059,23 @@ definitions: updated_at: type: string type: object + github_com_Tencent_WeKnora_internal_im.RuntimeStatus: + properties: + active: + type: integer + available: + type: boolean + pending: + type: integer + queue_limit: + type: integer + rejected: + type: integer + timed_out: + type: integer + workers: + type: integer + type: object github_com_Tencent_WeKnora_internal_infrastructure_chunker.DocProfile: properties: all_caps_short_line_count: @@ -12753,6 +12770,100 @@ definitions: - kb_id - knowledge_ids type: object + internal_handler.OperationsBackup: + properties: + available: + type: boolean + completed_at: + type: integer + name: + type: string + snapshot_count: + type: integer + stale: + type: boolean + type: object + internal_handler.OperationsDisk: + properties: + available: + type: boolean + available_bytes: + type: integer + name: + type: string + total_bytes: + type: integer + used_percent: + type: number + type: object + internal_handler.OperationsHost: + properties: + cpu_count: + type: integer + load_1m: + type: number + memory_available_bytes: + type: integer + memory_total_bytes: + type: integer + type: object + internal_handler.OperationsLog: + properties: + bytes: + type: integer + health: + type: string + max_files: + type: string + max_size: + type: string + name: + type: string + status: + type: string + type: object + internal_handler.OperationsService: + properties: + active: + type: string + available: + type: boolean + exit_status: + type: integer + name: + type: string + result: + type: string + running_required: + type: boolean + type: object + internal_handler.OperationsStatus: + properties: + available: + type: boolean + backups: + items: + $ref: '#/definitions/internal_handler.OperationsBackup' + type: array + collected_at: + type: integer + disks: + items: + $ref: '#/definitions/internal_handler.OperationsDisk' + type: array + host: + $ref: '#/definitions/internal_handler.OperationsHost' + logs: + items: + $ref: '#/definitions/internal_handler.OperationsLog' + type: array + services: + items: + $ref: '#/definitions/internal_handler.OperationsService' + type: array + stale: + type: boolean + type: object internal_handler.PageResponse: properties: data: {} @@ -13294,6 +13405,8 @@ definitions: available: type: boolean x-agent: true + im: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_im.RuntimeStatus' model_limiter_available: type: boolean x-agent: true @@ -13305,6 +13418,8 @@ definitions: models_error: type: boolean x-agent: true + operations: + $ref: '#/definitions/internal_handler.OperationsStatus' parse_concurrency: description: compatibility alias for upstream_concurrency type: integer diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index c3a16d2a190..07aa1d5246c 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -636,6 +636,26 @@ export interface ModelRuntimeStat { limit: number } +export interface IMRuntimeStatus { + available: boolean + workers: number + queue_limit: number + pending: number + active: number + rejected: number + timed_out: number +} +export interface OperationsStatus { + available: boolean + stale: boolean + collected_at?: number + host?: { cpu_count?: number; load_1m?: number; memory_total_bytes?: number; memory_available_bytes?: number } + disks?: { name: string; available: boolean; used_percent?: number; available_bytes?: number; total_bytes?: number }[] + backups?: { name: string; available: boolean; snapshot_count: number; completed_at?: number; stale: boolean }[] + logs?: { name: string; bytes?: number; max_size?: string; max_files?: string; status?: string; health?: string }[] + services?: { name: string; available: boolean; result?: string; active?: string; exit_status?: number; running_required: boolean }[] +} + /** * Runtime queue dashboard payload. `available` is false in Lite mode * (no Redis/asynq) — render an "unavailable in this deployment" state @@ -644,6 +664,8 @@ export interface ModelRuntimeStat { * server heartbeats. */ export interface RuntimeQueuesResponse { + operations?: OperationsStatus + im?: IMRuntimeStatus available: boolean upstream_concurrency: number parse_concurrency: number diff --git a/frontend/src/i18n/locales/en-US/system.ts b/frontend/src/i18n/locales/en-US/system.ts index 3917f80577f..3a497206746 100644 --- a/frontend/src/i18n/locales/en-US/system.ts +++ b/frontend/src/i18n/locales/en-US/system.ts @@ -108,6 +108,33 @@ export default { networkError: 'Network error, please try again later' }, globalSettings: { + operations: { + title: "Operations", + eyebrow: "PLATFORM OPERATIONS", + im: "Messaging requests", + processing: "Processing", + waiting: "Queued", + instanceScope: "Current instance only", + memory: "Available memory", + total: "Total memory", + cpu: "CPU", + load: "1-minute load", + available: "Available", + notConnected: "Configure the optional host collector to view host status.", + stale: "Host data is over 10 minutes old. Check the collector.", + backups: "Local backups", + snapshots: "Snapshots", + unknown: "Unknown", + overdue: "Over 26 hours old", + recent: "Recently completed", + logs: "Container log size", + retentionUnknown: "Retention limit not reported", + services: "Services and scheduled jobs", + normal: "Normal", + failed: "Check required", + running: "Running", + notUpdated: "Not collected", + }, title: 'System Settings', description: 'Platform-wide runtime configuration. Saves take effect immediately for every workspace. Visible and editable by system administrators only.', loading: 'Loading...', diff --git a/frontend/src/i18n/locales/ja-JP/system.ts b/frontend/src/i18n/locales/ja-JP/system.ts index 8cb488afa3f..89dd41be4fd 100644 --- a/frontend/src/i18n/locales/ja-JP/system.ts +++ b/frontend/src/i18n/locales/ja-JP/system.ts @@ -108,6 +108,33 @@ export default { networkError: 'ネットワークエラーです。しばらくしてから再試行してください' }, globalSettings: { + operations: { + title: "運用状況", + eyebrow: "PLATFORM OPERATIONS", + im: "メッセージ処理", + processing: "処理中", + waiting: "待機中", + instanceScope: "現在のインスタンスのみ", + memory: "利用可能メモリ", + total: "合計メモリ", + cpu: "CPU", + load: "1分間の負荷", + available: "利用可能", + notConnected: "ホストの状態を表示するには収集サービスを設定してください。", + stale: "ホストデータは10分以上更新されていません。収集サービスを確認してください。", + backups: "ローカルバックアップ", + snapshots: "スナップショット", + unknown: "不明", + overdue: "26時間以上経過", + recent: "最近完了", + logs: "コンテナログ容量", + retentionUnknown: "保持上限が未報告", + services: "サービスと定期実行", + normal: "正常", + failed: "確認が必要", + running: "実行中", + notUpdated: "未収集", + }, title: 'システム設定', description: 'プラットフォーム全体のランタイム設定です。保存するとすべてのワークスペースに即座に反映されます。システム管理者のみが表示・編集できます。', loading: '読み込み中...', diff --git a/frontend/src/i18n/locales/ko-KR/system.ts b/frontend/src/i18n/locales/ko-KR/system.ts index e2ff40490e1..914c5c6cd36 100644 --- a/frontend/src/i18n/locales/ko-KR/system.ts +++ b/frontend/src/i18n/locales/ko-KR/system.ts @@ -104,6 +104,33 @@ export default { graphDatabaseEngineDescription: '현재 사용 중인 그래프 데이터베이스 엔진', unknown: '알 수 없음', globalSettings: { + operations: { + title: "운영 상태", + eyebrow: "PLATFORM OPERATIONS", + im: "메시지 요청", + processing: "처리 중", + waiting: "대기 중", + instanceScope: "현재 인스턴스만 집계", + memory: "사용 가능한 메모리", + total: "전체 메모리", + cpu: "CPU", + load: "1분 부하", + available: "사용 가능", + notConnected: "호스트 상태를 보려면 선택적 수집기를 설정하세요.", + stale: "호스트 데이터가 10분 이상 갱신되지 않았습니다. 수집기를 확인하세요.", + backups: "로컬 백업", + snapshots: "스냅샷", + unknown: "알 수 없음", + overdue: "26시간 초과", + recent: "최근 완료", + logs: "컨테이너 로그 크기", + retentionUnknown: "보관 한도 미보고", + services: "서비스 및 예약 작업", + normal: "정상", + failed: "확인 필요", + running: "실행 중", + notUpdated: "수집되지 않음", + }, title: '시스템 설정', description: '플랫폼 전역 런타임 설정입니다. 저장하면 모든 워크스페이스에 즉시 적용됩니다. 시스템 관리자만 보고 수정할 수 있습니다.', loading: '로딩 중...', diff --git a/frontend/src/i18n/locales/ru-RU/system.ts b/frontend/src/i18n/locales/ru-RU/system.ts index 65a1f877c7c..fdb328d17f3 100644 --- a/frontend/src/i18n/locales/ru-RU/system.ts +++ b/frontend/src/i18n/locales/ru-RU/system.ts @@ -104,6 +104,33 @@ export default { graphDatabaseEngineDescription: 'Используемый в настоящее время движок графовой базы данных', unknown: 'Неизвестно', globalSettings: { + operations: { + title: "Состояние системы", + eyebrow: "PLATFORM OPERATIONS", + im: "Запросы сообщений", + processing: "Обработка", + waiting: "В очереди", + instanceScope: "Только текущий экземпляр", + memory: "Доступная память", + total: "Всего памяти", + cpu: "CPU", + load: "Нагрузка за минуту", + available: "Доступно", + notConnected: "Настройте сборщик для просмотра состояния хоста.", + stale: "Данные хоста не обновлялись более 10 минут. Проверьте сборщик.", + backups: "Локальные резервные копии", + snapshots: "Снимки", + unknown: "Неизвестно", + overdue: "Более 26 часов", + recent: "Недавно завершено", + logs: "Размер логов контейнеров", + retentionUnknown: "Лимит хранения не указан", + services: "Службы и задания", + normal: "Норма", + failed: "Требуется проверка", + running: "Работает", + notUpdated: "Нет данных", + }, title: 'Системные настройки', description: 'Настройки платформы, применяемые в режиме реального времени. Изменения сразу действуют для всех пространств. Доступны только системным администраторам.', loading: 'Загрузка...', diff --git a/frontend/src/i18n/locales/zh-CN/system.ts b/frontend/src/i18n/locales/zh-CN/system.ts index a6ec20be5b3..992a0935508 100644 --- a/frontend/src/i18n/locales/zh-CN/system.ts +++ b/frontend/src/i18n/locales/zh-CN/system.ts @@ -104,6 +104,33 @@ export default { graphDatabaseEngineDescription: '当前使用的图数据库引擎', unknown: '未知', globalSettings: { + operations: { + title: "运行保障", + eyebrow: "PLATFORM OPERATIONS", + im: "即时问答", + processing: "正在处理", + waiting: "排队", + instanceScope: "仅统计当前实例", + memory: "可用内存", + total: "总内存", + cpu: "处理器", + load: "1分钟负载", + available: "可用空间", + notConnected: "尚未接入可选主机采集器,请配置采集服务。", + stale: "主机数据已超过10分钟未更新,请检查采集服务。", + backups: "本机备份", + snapshots: "快照数", + unknown: "未知", + overdue: "超过26小时", + recent: "近期完成", + logs: "容器日志容量", + retentionUnknown: "未报告保留上限", + services: "服务与定时任务", + normal: "正常", + failed: "需检查", + running: "运行中", + notUpdated: "尚未采集", + }, title: '系统设置', description: '平台级运行时配置,保存后立即对所有空间生效。仅系统管理员可见可改。', loading: '加载中...', diff --git a/frontend/src/i18n/locales/zh-TW/system.ts b/frontend/src/i18n/locales/zh-TW/system.ts index 044e366f2ef..0f65c4082df 100644 --- a/frontend/src/i18n/locales/zh-TW/system.ts +++ b/frontend/src/i18n/locales/zh-TW/system.ts @@ -104,6 +104,33 @@ export default { graphDatabaseEngineDescription: '當前使用的圖資料庫引擎', unknown: '未知', globalSettings: { + operations: { + title: "執行保障", + eyebrow: "PLATFORM OPERATIONS", + im: "即時問答", + processing: "處理中", + waiting: "排隊", + instanceScope: "僅統計目前執行個體", + memory: "可用記憶體", + total: "總記憶體", + cpu: "處理器", + load: "1分鐘負載", + available: "可用空間", + notConnected: "尚未連接選用主機收集器,請設定收集服務。", + stale: "主機資料超過10分鐘未更新,請檢查收集服務。", + backups: "本機備份", + snapshots: "快照數", + unknown: "未知", + overdue: "超過26小時", + recent: "近期完成", + logs: "容器日誌容量", + retentionUnknown: "未回報保留上限", + services: "服務與排程工作", + normal: "正常", + failed: "需檢查", + running: "執行中", + notUpdated: "尚未收集", + }, title: '系統設定', description: '平台級運行時設定,儲存後立即對所有空間生效。僅系統管理員可見可改。', loading: '載入中...', diff --git a/frontend/src/views/system/OperationsOverview.vue b/frontend/src/views/system/OperationsOverview.vue new file mode 100644 index 00000000000..44900d33d2b --- /dev/null +++ b/frontend/src/views/system/OperationsOverview.vue @@ -0,0 +1,148 @@ + + + + + diff --git a/frontend/src/views/system/RuntimeQueues.vue b/frontend/src/views/system/RuntimeQueues.vue index e9b052b3846..f0ff2579d98 100644 --- a/frontend/src/views/system/RuntimeQueues.vue +++ b/frontend/src/views/system/RuntimeQueues.vue @@ -45,6 +45,7 @@ />
+
@@ -526,6 +527,7 @@ import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue' import { useI18n } from 'vue-i18n' import { MessagePlugin } from 'tdesign-vue-next' +import OperationsOverview from './OperationsOverview.vue' import SettingDrawer from '@/components/settings/SettingDrawer.vue' import DocumentProgress from './DocumentProgress.vue' import { mergeRuntimeTaskPage } from './runtimeTaskPagination' @@ -535,6 +537,8 @@ import { mutateRuntimeTask, purgeArchivedRuntimeTasks, type ModelRuntimeStat, + type OperationsStatus, + type IMRuntimeStatus, type QueueStat, type RuntimeTask, type RuntimeTaskAction, @@ -546,6 +550,8 @@ const { t, te, locale } = useI18n() const POLL_INTERVAL_MS = 5000 +const operations = ref() +const imStatus = ref() const queues = ref([]) const pools = ref([]) const models = ref([]) @@ -926,6 +932,8 @@ async function load(showSpinner: boolean) { if (showSpinner) loading.value = true try { const resp = await getRuntimeQueues() + operations.value = resp.operations + imStatus.value = resp.im available.value = resp.available pools.value = resp.pools || [] queues.value = resp.queues || [] diff --git a/internal/container/container.go b/internal/container/container.go index 61f79bba40e..93670f503c3 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -803,6 +803,7 @@ func BuildContainer(container *dig.Container) *dig.Container { logger.Debugf(ctx, "[Container] Registering IM integration...") must(container.Provide(imPkg.NewService)) must(container.Invoke(registerIMService)) + must(container.Invoke(func(s *imPkg.Service, h *handler.SystemHandler) { h.BindIMRuntime(s) })) must(container.Provide(handler.NewIMHandler)) must(container.Provide(handler.NewEmbedChannelHandler)) must(container.Provide(handler.NewMCPEndpointHandler)) diff --git a/internal/handler/operations_status.go b/internal/handler/operations_status.go new file mode 100644 index 00000000000..efd387ab25b --- /dev/null +++ b/internal/handler/operations_status.go @@ -0,0 +1,101 @@ +package handler + +import ( + "encoding/json" + "io" + "os" + "time" + + "github.com/Tencent/WeKnora/internal/im" +) + +// OperationsHost uses optional fields so missing host metrics remain unknown. +type OperationsHost struct { + CPUCount *int `json:"cpu_count,omitempty"` + Load1m *float64 `json:"load_1m,omitempty"` + MemoryTotalBytes *uint64 `json:"memory_total_bytes,omitempty"` + MemoryAvailableBytes *uint64 `json:"memory_available_bytes,omitempty"` +} + +// OperationsDisk keeps availability explicit to distinguish a missing mount from zero usage. +type OperationsDisk struct { + Name string `json:"name"` + Available bool `json:"available"` + UsedPercent *float64 `json:"used_percent,omitempty"` + AvailableBytes *uint64 `json:"available_bytes,omitempty"` + TotalBytes *uint64 `json:"total_bytes,omitempty"` +} + +// OperationsBackup separates completion from availability so incomplete snapshots cannot appear healthy. +type OperationsBackup struct { + Name string `json:"name"` + Available bool `json:"available"` + SnapshotCount uint64 `json:"snapshot_count"` + CompletedAt *int64 `json:"completed_at,omitempty"` + Stale bool `json:"stale"` +} + +// OperationsLog uses optional sizes because remote log drivers may not expose local files. +type OperationsLog struct { + Name string `json:"name"` + Bytes *uint64 `json:"bytes,omitempty"` + MaxSize string `json:"max_size,omitempty"` + MaxFiles string `json:"max_files,omitempty"` + Status string `json:"status,omitempty"` + Health string `json:"health,omitempty"` +} + +// OperationsService distinguishes scheduled jobs from services that must remain active. +type OperationsService struct { + Name string `json:"name"` + Available bool `json:"available"` + Result string `json:"result,omitempty"` + Active string `json:"active,omitempty"` + ExitStatus *int `json:"exit_status,omitempty"` + RunningRequired bool `json:"running_required"` +} + +// OperationsStatus contains aggregate telemetry from an optional external collector. +type OperationsStatus struct { + Available bool `json:"available"` + Stale bool `json:"stale"` + CollectedAt int64 `json:"collected_at,omitempty"` + Host *OperationsHost `json:"host,omitempty"` + Disks []OperationsDisk `json:"disks,omitempty"` + Backups []OperationsBackup `json:"backups,omitempty"` + Logs []OperationsLog `json:"logs,omitempty"` + Services []OperationsService `json:"services,omitempty"` +} + +func readOperationsStatus(path string, now time.Time) OperationsStatus { + if path == "" { + return OperationsStatus{} + } + // Reject pipes/devices before opening: this request must not wait for a producer. + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() > 128*1024 { + return OperationsStatus{} + } + f, err := os.Open(path) + if err != nil { + return OperationsStatus{} + } + defer func() { + // Closing a read-only sample cannot affect the already buffered telemetry. + _ = f.Close() + }() + b, err := io.ReadAll(io.LimitReader(f, 128*1024+1)) + var status OperationsStatus + if err != nil || len(b) > 128*1024 || json.Unmarshal(b, &status) != nil || + status.CollectedAt <= 0 || status.CollectedAt > now.Unix()+60 { + return OperationsStatus{} + } + status.Available = true + status.Stale = now.Unix()-status.CollectedAt > 600 + return status +} + +// BindIMRuntime connects the independent IM queue to the administrator dashboard. +func (h *SystemHandler) BindIMRuntime(service *im.Service) { + h.imRuntime = service.RuntimeStatus +} diff --git a/internal/handler/operations_status_test.go b/internal/handler/operations_status_test.go new file mode 100644 index 00000000000..42e63d27591 --- /dev/null +++ b/internal/handler/operations_status_test.go @@ -0,0 +1,92 @@ +package handler + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/im" + "github.com/gin-gonic/gin" +) + +func TestOperationsStatusUnknownAndStale(t *testing.T) { + now := time.Unix(2000, 0) + p := filepath.Join(t.TempDir(), "status.json") + if readOperationsStatus(p, now).Available { + t.Fatal("missing sample must be unknown") + } + for _, bad := range []string{ + `{}`, + `{"collected_at":3000}`, + `broken`, + `{"collected_at":1900,"host":{"cpu_count":"bad"}}`, + `{"collected_at":1900,"host":{"memory_total_bytes":-1}}`, + strings.Repeat("x", 128*1024+1), + } { + if err := os.WriteFile(p, []byte(bad), 0o600); err != nil { + t.Fatal(err) + } + if readOperationsStatus(p, now).Available { + t.Fatal("invalid sample must be unknown") + } + } + if err := os.WriteFile(p, []byte(`{"collected_at":1300,"disks":[]}`), 0o600); err != nil { + t.Fatal(err) + } + s := readOperationsStatus(p, now) + if !s.Available || !s.Stale { + t.Fatal("old collector sample must be visibly stale") + } + if err := os.WriteFile(p, []byte(`{"collected_at":1900,"disks":[]}`), 0o600); err != nil { + t.Fatal(err) + } + s = readOperationsStatus(p, now) + if !s.Available || s.Stale { + t.Fatal("recent sample should be available") + } +} + +func TestOperationsStatusRejectsDirectoryAndEmptyPath(t *testing.T) { + now := time.Now() + for _, path := range []string{"", t.TempDir()} { + if readOperationsStatus(path, now).Available { + t.Fatalf("unexpected availability for %q", path) + } + } +} + +func TestGetRuntimeQueuesIncludesOperationsWithoutAsynq(t *testing.T) { + gin.SetMode(gin.TestMode) + path := filepath.Join(t.TempDir(), "status.json") + sample := fmt.Sprintf(`{"collected_at":%d,"host":{"cpu_count":2},"secret":"not exported"}`, time.Now().Unix()) + if err := os.WriteFile(path, []byte(sample), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("WEKNORA_OPERATIONS_STATUS_FILE", path) + h := &SystemHandler{ + imRuntime: func() im.RuntimeStatus { + return im.RuntimeStatus{Available: true, Workers: 5, Pending: 2, Active: 1} + }, + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/system/admin/runtime/queues", nil) + h.GetRuntimeQueues(ctx) + var result RuntimeQueuesResponse + if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + if recorder.Code != http.StatusOK || result.Available || !result.Operations.Available || + result.IM == nil || result.IM.Pending != 2 || result.IM.Workers != 5 { + t.Fatalf("unexpected runtime response: %s", recorder.Body.String()) + } + if strings.Contains(recorder.Body.String(), "secret") { + t.Fatal("unknown collector fields must not be exposed") + } +} diff --git a/internal/handler/system.go b/internal/handler/system.go index e2d73686268..5e1848d8860 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -21,6 +21,7 @@ import ( "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/database" apperrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/im" "github.com/Tencent/WeKnora/internal/infrastructure/docparser" "github.com/Tencent/WeKnora/internal/logger" modellimiter "github.com/Tencent/WeKnora/internal/models/limiter" @@ -38,6 +39,7 @@ type runtimeKnowledgeCanceller interface { // SystemHandler handles system-related requests type SystemHandler struct { + imRuntime func() im.RuntimeStatus documentProgress *service.DocumentProgressService cfg *config.Config neo4jDriver neo4j.Driver @@ -1862,6 +1864,8 @@ type RuntimeWorkerPool struct { } type RuntimeQueuesResponse struct { + Operations OperationsStatus `json:"operations"` + IM *im.RuntimeStatus `json:"im,omitempty"` QueuesError bool `json:"queues_error" extensions:"x-agent"` WorkersError bool `json:"workers_error" extensions:"x-agent"` ModelsError bool `json:"models_error" extensions:"x-agent"` @@ -1992,6 +1996,11 @@ func (h *SystemHandler) GetRuntimeQueues(c *gin.Context) { if modelErr != nil { logger.Errorf(ctx, "get model concurrency stats failed: %v", modelErr) } + resp.Operations = readOperationsStatus(os.Getenv("WEKNORA_OPERATIONS_STATUS_FILE"), time.Now()) + if h.imRuntime != nil { + status := h.imRuntime() + resp.IM = &status + } resp.ModelsError = modelErr != nil resp.ModelLimiterAvailable = modelSupported resp.Models = modelStats diff --git a/internal/im/runtime_status.go b/internal/im/runtime_status.go new file mode 100644 index 00000000000..2ce1cecb7b0 --- /dev/null +++ b/internal/im/runtime_status.go @@ -0,0 +1,29 @@ +package im + +// RuntimeStatus reports the current process IM queue, independently of Asynq. +type RuntimeStatus struct { + Available bool `json:"available"` + Workers int `json:"workers"` + QueueLimit int `json:"queue_limit"` + Pending int `json:"pending"` + Active int64 `json:"active"` + Rejected int64 `json:"rejected"` + TimedOut int64 `json:"timed_out"` +} + +// RuntimeStatus keeps disabled queues unavailable rather than reporting misleading zero capacity. +func (s *Service) RuntimeStatus() RuntimeStatus { + if s == nil || s.qaQueue == nil { + return RuntimeStatus{} + } + m := s.qaQueue.Metrics() + return RuntimeStatus{ + Available: true, + Workers: s.qaQueue.workers, + QueueLimit: s.qaQueue.maxSize, + Pending: m.Depth, + Active: m.ActiveWorkers, + Rejected: m.TotalRejected, + TimedOut: m.TotalTimeout, + } +} diff --git a/internal/im/runtime_status_test.go b/internal/im/runtime_status_test.go new file mode 100644 index 00000000000..9bf4cb4d2ec --- /dev/null +++ b/internal/im/runtime_status_test.go @@ -0,0 +1,26 @@ +package im + +import "testing" + +func TestRuntimeStatusUnavailable(t *testing.T) { + var service *Service + if service.RuntimeStatus().Available { + t.Fatal("nil service must be unavailable") + } + if (&Service{}).RuntimeStatus().Available { + t.Fatal("disabled queue must be unavailable") + } +} + +func TestRuntimeStatusReportsLocalQueue(t *testing.T) { + q := newQAQueue(5, 50, 3, 0, nil, nil) + q.queue = []*qaRequest{{}, {}} + q.activeWorkers.Store(3) + q.totalRejected.Store(7) + q.totalTimeout.Store(11) + status := (&Service{qaQueue: q}).RuntimeStatus() + if !status.Available || status.Workers != 5 || status.QueueLimit != 50 || status.Pending != 2 || + status.Active != 3 || status.Rejected != 7 || status.TimedOut != 11 { + t.Fatalf("unexpected local queue metrics: %+v", status) + } +} diff --git a/scripts/monitoring/README.md b/scripts/monitoring/README.md new file mode 100644 index 00000000000..8d7f127af66 --- /dev/null +++ b/scripts/monitoring/README.md @@ -0,0 +1,68 @@ +# Optional runtime operations overview + +Settings → System Administration → Task Queues now includes an operations overview. +The existing SystemAdmin endpoint reports IM active workers, queue depth, configured +local capacity, and rejection/timeout counters. These are current-process metrics, +independent of the Redis global IM limit and provider-account concurrency. +Disabled IM queues show unknown values. + +Host metrics come from an optional external JSON file. Without a collector, the +IM card still works and host values remain unknown. Samples older than 10 minutes +are visibly stale. The backend accepts regular files up to 128 KiB, rejects invalid +types/timestamps, and never invokes Docker or systemd. + +## Collector (Linux, Python 3 standard library) + +```sh +python3 scripts/monitoring/collect-status.py \ + --output /var/lib/weknora/monitoring/status.json \ + --disk / --disk /srv/weknora \ + --container WeKnora-app \ + --backup WeKnora=/srv/backups/weknora \ + --service weknora-backup.service \ + --running-service weknora.service +``` + +Selection options are repeatable and optional. By default only memory, CPU, load, +and the root filesystem are sampled. Schedule the command every two minutes with +your host scheduler. Docker/log access is needed only by the collector. Container +failures are isolated; rotated local logs are included in byte totals. Remote log +drivers can have unknown size/retention. Only metadata and byte counts are exported; +no environment variables, log text, or backup contents are returned. The collector +does not change retention, restart services, or perform backups. + +The optional backup convention is `DIRECTORY/latest` pointing to a direct snapshot +child containing `COMPLETE`. Its mtime is the completion time. Missing, incomplete, +outside-directory, and future-dated markers remain unknown. Completion older than +26 hours is overdue. Snapshot count is a directory count and does not verify a +backup or restore. `--service` allows an inactive successful scheduled job; +`--running-service` also requires an active service. Missing units remain unknown. + +Mount the directory read-only (a single-file mount retains the old inode after +atomic sample replacement): + +```yaml +services: + app: + environment: + WEKNORA_OPERATIONS_STATUS_FILE: /run/weknora-monitoring/status.json + volumes: + - /var/lib/weknora/monitoring:/run/weknora-monitoring:ro +``` + +For native deployments, set the environment variable to the readable JSON path. +Protect the directory from untrusted writes. In multi-instance setups, mount the +intended host sample for each instance. Host freshness is independent of live IM +numbers. Removing the environment variable disables host telemetry. + +## Verification + +```sh +python3 -m unittest discover -s scripts/monitoring -p 'test_*.py' +go test -race ./internal/im ./internal/handler ./internal/router -run 'Runtime|Operations' -count=1 +cd frontend && npm run type-check && npm run check-i18n +``` + +Check normal/stale/missing samples and disabled IM as SystemAdmin. Ordinary members +and anonymous requests retain the existing 403/401 behavior. No scheduling changes, +schema migrations, or new production dependencies are introduced. diff --git a/scripts/monitoring/collect-status.py b/scripts/monitoring/collect-status.py new file mode 100644 index 00000000000..429e995839a --- /dev/null +++ b/scripts/monitoring/collect-status.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Export optional aggregate host metrics for the administrator runtime page.""" +import argparse +import json +import os +import pathlib +import subprocess +import tempfile +import time + + +def command(args): + return subprocess.run(args, capture_output=True, text=True, timeout=10, check=True).stdout + + +def disk(path): + try: + stat = os.statvfs(path) + used = (stat.f_blocks - stat.f_bfree) * stat.f_frsize + available = stat.f_bavail * stat.f_frsize + return {"name": path, "available": True, "total_bytes": stat.f_blocks * stat.f_frsize, + "available_bytes": available, "used_percent": round(100 * used / (used + available), 1) if used + available else 0} + except OSError: + return {"name": path, "available": False} + + +def backup(name, directory, now): + root = pathlib.Path(directory) + result = {"name": name, "available": False, "snapshot_count": 0} + try: + result["snapshot_count"] = sum(p.is_dir() and not p.is_symlink() for p in root.iterdir()) + latest = (root / "latest").resolve(strict=True) + if latest.parent != root.resolve() or not (latest / "COMPLETE").is_file(): + return result + completed = int((latest / "COMPLETE").stat().st_mtime) + if completed > now + 60: + return result + result.update(available=True, completed_at=completed, stale=now - completed > 26 * 3600) + except (OSError, RuntimeError): + pass + return result + + +def service(unit, running_required): + try: + data = dict(line.split("=", 1) for line in command([ + "systemctl", "show", unit, "-p", "LoadState", "-p", "ActiveState", "-p", "Result", "-p", "ExecMainStatus" + ]).splitlines() if "=" in line) + if data.get("LoadState") != "loaded": + return {"name": unit, "available": False} + return {"name": unit, "available": True, "active": data.get("ActiveState"), + "result": data.get("Result"), "exit_status": int(data["ExecMainStatus"]), "running_required": running_required} + except (OSError, ValueError, KeyError, subprocess.SubprocessError): + return {"name": unit, "available": False} + + +def container_log(name): + try: + container = json.loads(command(["docker", "inspect", "--", name]))[0] + log_path = container.get("LogPath") + size = None + if log_path: + path = pathlib.Path(log_path) + if path.is_file(): + # Include rotated siblings; never read log contents. + size = sum(p.stat().st_size for p in [path, *path.parent.glob(path.name + ".*")] if p.is_file()) + options = container["HostConfig"].get("LogConfig", {}).get("Config", {}) + return {"name": name, "bytes": size, "max_size": options.get("max-size"), "max_files": options.get("max-file"), + "status": container["State"].get("Status"), "health": container["State"].get("Health", {}).get("Status")} + except (OSError, ValueError, KeyError, IndexError, subprocess.SubprocessError): + return {"name": name} + + +def collect(disks=None, backups=None, containers=None, services=None, running_services=None): + now = int(time.time()) + memory = {} + try: + for line in pathlib.Path("/proc/meminfo").read_text().splitlines(): + key, value = line.split(":", 1) + if key in ("MemTotal", "MemAvailable"): + memory[key] = int(value.split()[0]) * 1024 + except (OSError, ValueError): + pass + host = {"cpu_count": os.cpu_count(), "load_1m": os.getloadavg()[0], + "memory_total_bytes": memory.get("MemTotal"), "memory_available_bytes": memory.get("MemAvailable")} + return {"collected_at": now, "host": host, "disks": [disk(p) for p in (disks or ["/"])], + "backups": [backup(name, path, now) for name, path in (backups or [])], + "logs": [container_log(name) for name in (containers or [])], + "services": [service(unit, False) for unit in (services or [])] + + [service(unit, True) for unit in (running_services or [])]} + + +def write_atomic(path, status): + target = pathlib.Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + fd, temp = tempfile.mkstemp(prefix=".status-", dir=target.parent) + try: + with os.fdopen(fd, "w") as output: + json.dump(status, output, ensure_ascii=False, allow_nan=False) + output.flush() + os.fsync(output.fileno()) + os.chmod(temp, 0o644) + os.replace(temp, target) + finally: + if os.path.exists(temp): + os.unlink(temp) + + +def backup_arg(value): + name, sep, path = value.partition("=") + if not sep or not name or not path: + raise argparse.ArgumentTypeError("expected NAME=DIRECTORY") + return name, path + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True) + parser.add_argument("--disk", action="append") + parser.add_argument("--backup", type=backup_arg, action="append") + parser.add_argument("--container", action="append") + parser.add_argument("--service", action="append", help="Completed scheduled job; inactive is allowed") + parser.add_argument("--running-service", action="append", help="Service that must remain active") + args = parser.parse_args() + write_atomic(args.output, collect(args.disk, args.backup, args.container, args.service, args.running_service)) diff --git a/scripts/monitoring/test_collect_status.py b/scripts/monitoring/test_collect_status.py new file mode 100644 index 00000000000..8d19596580b --- /dev/null +++ b/scripts/monitoring/test_collect_status.py @@ -0,0 +1,68 @@ +import importlib.util +import json +import os +import pathlib +import tempfile +import time +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location("collector", pathlib.Path(__file__).with_name("collect-status.py")) +collector = importlib.util.module_from_spec(spec) +spec.loader.exec_module(collector) + + +class CollectorTest(unittest.TestCase): + def test_backup_marker_and_boundary(self): + now = int(time.time()) + with tempfile.TemporaryDirectory() as directory, tempfile.TemporaryDirectory() as outside: + root = pathlib.Path(directory) + snapshot = root / "snapshot" + snapshot.mkdir() + (root / "latest").symlink_to(snapshot) + self.assertFalse(collector.backup("test", directory, now)["available"]) + marker = snapshot / "COMPLETE" + marker.touch() + self.assertTrue(collector.backup("test", directory, now)["available"]) + os.utime(marker, (now - 27 * 3600, now - 27 * 3600)) + self.assertTrue(collector.backup("test", directory, now)["stale"]) + os.utime(marker, (now + 120, now + 120)) + self.assertFalse(collector.backup("test", directory, now)["available"]) + (root / "latest").unlink() + (root / "latest").symlink_to(outside) + (pathlib.Path(outside) / "COMPLETE").touch() + self.assertFalse(collector.backup("test", directory, now)["available"]) + + def test_missing_service_remains_unknown(self): + with patch.object(collector, "command", return_value="LoadState=not-found\nActiveState=inactive\nResult=success\nExecMainStatus=0"): + self.assertFalse(collector.service("missing.service", False)["available"]) + + def test_collection_failures_remain_unknown(self): + with patch.object(collector, "command", side_effect=OSError("unavailable")): + result = collector.collect(services=["job.service"], containers=["app"]) + self.assertFalse(result["services"][0]["available"]) + self.assertNotIn("status", result["logs"][0]) + + def test_container_failures_are_independent_and_rotations_counted(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "log.json" + path.write_bytes(b"123") + pathlib.Path(str(path) + ".1").write_bytes(b"4567") + data = [{"LogPath": str(path), "HostConfig": {"LogConfig": {"Config": {"max-size": "20m"}}}, "State": {"Status": "running"}}] + with patch.object(collector, "command", side_effect=[OSError("missing"), json.dumps(data)]): + result = collector.collect(containers=["missing", "app"]) + self.assertNotIn("status", result["logs"][0]) + self.assertEqual(result["logs"][1]["bytes"], 7) + self.assertEqual(result["logs"][1]["status"], "running") + + def test_atomic_write_replaces_complete_sample(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "status.json" + collector.write_atomic(path, {"collected_at": 10}) + collector.write_atomic(path, {"collected_at": 20}) + self.assertEqual(json.loads(path.read_text()), {"collected_at": 20}) + self.assertEqual(list(path.parent.glob(".status-*")), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/website-docs/04-api/02-api-system.md b/website-docs/04-api/02-api-system.md index 8e671cee230..99e134773e3 100644 --- a/website-docs/04-api/02-api-system.md +++ b/website-docs/04-api/02-api-system.md @@ -237,12 +237,14 @@ curl -X DELETE $BASE/api/v1/system/admin/settings/default_storage_quota -H "Auth 用途:asynq 队列深度与并发状态(Lite 模式返回 `available:false`;平台 key 需 `system_runtime_read|manage`)。 -响应:200 `{"available",upstream_concurrency,parse_concurrency,wiki_concurrency,pools,queues,model_limiter_available,models,timestamp}` +响应:200 `{"available",upstream_concurrency,parse_concurrency,wiki_concurrency,pools,queues,model_limiter_available,models,im,operations,timestamp}` ```bash curl $BASE/api/v1/system/admin/runtime/queues -H "Authorization: Bearer $TOKEN" ``` +`im` 返回当前实例的即时问答槽位与排队数;未启用队列时 `im.available:false`。`operations` 为可选主机采集数据,包含容量、备份时效、日志容量和服务状态。未配置或无有效样本时 `operations.available:false`,超过 10 分钟的样本返回 `operations.stale:true`。两者独立于 asynq 的 `available` 状态。采集器和只读挂载配置见 [运行概览配置](../../scripts/monitoring/README.md)。 + ### GET /api/v1/system/admin/runtime/queues/:queue/tasks 用途:队列任务列表。查询参数:`state`(`pending/active/scheduled/retry/archived/completed`)、`cursor`、`page_size`(默认 20,上限 100)。 diff --git a/website-docs/public/screenshots/runtime-operations-overview.jpg b/website-docs/public/screenshots/runtime-operations-overview.jpg new file mode 100644 index 00000000000..1ce78a30478 Binary files /dev/null and b/website-docs/public/screenshots/runtime-operations-overview.jpg differ