1. 日常运维
司空 2 私有化FAQ
  • V2.0 已知问题与解决方案
    • 安装部署
      • 【部署安装】部署阶段提示SWAP状态已启用
      • 【部署安装】系统依赖包安装预演失败
      • 【部署安装】检测到1.x版本残留项是否可以继续
      • 【部署安装】系统依赖包无法只新增安装
      • 【部署安装】集群底座安装停滞或K3s等待超时
      • 【部署安装】SSH断开后如何断点续装
      • 【部署安装】Ubuntu22.04如何将内网IP配置为静态地址
      • 【部署安装】大疆官网安装包下载失败
      • 【部署安装】部署页面提示进度连接已断开
      • 【部署安装】KylinSecOS指纹文件生成失败
    • 日常运维
      • 【日常运维】高程导入卡在“处理中”或启用失败:状态核对与快速恢复
      • 【日常运维】高程导入卡在“处理中”或启用失败:按现象排查
      • 【日常运维】如何将HTTP访问切换为HTTPS
      • 【日常运维】系统时钟偏差过大如何校时
      • 【日常运维】定位部署目录及查看或重置AIO密码
      • 【日常运维】如何重启司空服务
      • 【日常运维】2.0常用运维命令与脚本
      • 【日常运维】K3s垃圾回收清理镜像后如何恢复
    • 网络连接
      • 【网络连接】集群上行或下行流量短时增高
      • 【网络连接】配置4G白名单后设备仍无法连接
      • 【网络连接】云服务器部署后直播黑屏或异常
    • 升级维护
      • 【升级维护】主控节点升级时提示当前节点不是控制节点
      • 【升级维护】硬链接快照失败并提示invalid-cross-device-link
  • V1.5 已知问题与解决方案
    • 部署与升级问题
      • 【通用】在管理后台上传安装包失败
    • 配置问题
      • 【通用】修改内部/外部IP导致建模量测相关功能不可用
  • 历史已知问题与方案
    • 部署相关
      • 高程数据导入报错 tif_slices"does not exist 问题
      • 解决没有NTP服务可用的问题
      • 机场媒体文件无法上传问题
      • 关于司空2平台调用RTK标定接口进行RTK标定未成功问题
      • 配置OAuth后,三方账号导入管理账户无权限为游客
      • 通过Amazon Cognito 身份平台用户登录白屏问题
      • 司空私有化平台无法修改设备绑定码问题
      • 登录司空平台报异常,且网络显示未连接问题
      • 司空平台删除模型文件后服务器对应文件还是存在问题
      • 司空私有化服务器重启后部分容器无法自动启动问题
      • 司空私有化系admin 账号提示没有权限问题
      • 部署司空报错HTTP 403解决方案
      • 司空服务异常报错 CodeMeter Licence Server not found Error 101 或者 Failure reason: CmContainer Entry not found, Error 200
      • codemeter启动/导入许可证异常处理
      • 修改env配置文件portainer密码未生效
      • FH2-V1.3高程数据导入报错 map_element_file_details doesnot exist
      • 司空页面报错服务器异常无法访问(容器全部运行正常)
      • 司空部署过程中tas-service/minio等容器报错退出致部署失败问题
      • 司空配置sync文件同步时报错:tls: failed to verify certificate: x509: certificate signed by unknown authority (*url.Error)
      • 部署司空的过程中报错error mounting "/etc/localtime" to rootfs at "/etc/localtime
      • 司空页面点击设备管理页面报错 “初始化设备列表失败”
      • 司空大日志文件截取方法
    • 网络相关
      • 司空私有化内外网混合部署下的网络打通
      • 防火墙端口放开策略说明
      • 机场到司空私有化网络情况测试方法
    • 媒体相关
      • 设备上传媒体文件完成,但是在平台找不到对应的媒体文件
      • 开启MQTT桥接后,机场上传媒体到司空 2 的进度卡住不动
    • 地图相关
      • 离线地图部署各种问题解答
      • 在私有化安装部署中使用在线地图
      • 高程数据导入成功但是地图上不显示高程红色框问题
      • 发布地图显示成功,但地图服务map-server-gl报错了-panic: runtime error: invalid memory address or nil pointer dereference
    • 直播相关
      • 直播黑屏黑屏问题+直播报错超时问题
      • 司空私有化Webrtc 直播端口8000修改后,直播黑屏没有数据流问题
      • 虚拟驾驶舱直播报错213030问题
      • 飞机直播报错213030
      • 司空私有化点开项目或驾驶舱页面报“网络异常”错误
      • 司空页面点击设备直播报错“设备端运行异常(错误码400)”
    • 建模相关
      • 司空页面建模报错问题
      • 客户环境建模报错-已存在重建任务,请等待或取消进行的任务
      • 建模报错 “未找到有效的云端重建证书”
      • 上传模型文件或建模98%报异常问题解决
      • 物模型获取API中rainfall字段枚举对应的具体雨量值
    • 设备相关
      • 设备上云报超时问题
      • 飞机显示离线且poilt2报错101
      • 关于地形障碍物同步报错问题
      • 一体机在线设备扩容步骤
      • 司空下发任务报错:云端与机场通信异常319005
    • License证书
      • 部署司空2报codemeter的License相关错误解决
      • 司空私有化license v1.0升级v1.1
      • 4G私有化服务器升级到最新版本教程
      • license文件locked问题,获取CodeMeter服务日志方法
      • 许可证更新后设备上线异常
    • 二次开发相关
      • 司空2私有版的组织秘钥如何获取?
      • 司空2私有版的组织密钥是不是所有用户都是一样?
      • 通过curl命令访问/openapi/v0.1/flight-task/{task_uuid}/media,点击响应中的url连接提示没有权限
      • 物模型获取API中rainfall字段枚举对应的具体雨量值
      • 如何获取司空2前端PaaS组件的demo文件
      • 前端组件demo下载说明
      • PaaS SDK
        • 用户使用直播sdk初始化失败
        • 用户使用Nginx服务端部署SDK,无法识别/加载WASM文件
        • 用户调用SDK获取设备列表识别,错误拉取到html页面
        • 运行demo文件依赖的config.json中的字段值怎么填
        • 后台集成直播操控sdk后应用出现fatal error崩溃
        • 飞机已经开始直播,但是SDK没有触发推送直播码流数据回调
        • SDK会目前支持哪些开发语言和操作系统
        • 通过「直播操控SDK」获取直播码流,推送到流媒体服务器中,播放视频出现卡顿和模糊
        • 通过SDK远程控制无人机拍照报错,日志提示:“拍照失败,错误码: -6”
        • 目前SDK支持获取设备的哪些osd信息,osd的推送频率是怎样的
        • 在通过SDK远程控制负载或者无人机动作的时候,是否需要获取控制权
        • 使用SDK操控无人机拍照,照片信息中的拍摄时间比下发拍照指令的时间早2s
        • SDK上报的”liveview_world _region“ osd包含的字段信息及其含义是什么
        • 接入SDK后报错:Java.lang.unsatisfiedLinkError:void com.dji.flighthubsdk.generated.flighthubsdkJNI.swig_moduta_init()
        • 运行SDK demo报错:”[Networklmpl]http error status_code: 403“
        • SDK初始化完成后getDroneInstance时报错:SDK not initialized
        • 无人机osd中的height和elevation字段分别代表什么意思
        • 如何通过SDK判断无人机是否是返航状态
        • 通过 SDK getIs_online() 定频获取在线设备列表提示“获取设备列表失败:ERROR_OPERATION_FAILED”
        • 通过 SDK 收到的无人机和机场的新设备接入通知都是机场的sn
        • SDK 已经支持环绕飞行,DJI 那些无人机型号支持环绕飞行
        • javacript前端直播播放器拉取ZLM的直播流提示错误
        • 消息通知SDK配置websocket连接地址后,建立连接失败
        • 如何异步等待websocket连接建立
        • 如何管理多个设备的通知事件
        • 同一个SN存在多个订阅者,消息是如何分发的,是广播模式吗
        • SDK的消息频率设置没生效,设置频率是30秒,消息推送还是1秒1次
        • 飞行任务状态变更事件通知中是否支持获取无人机的SN
        • 是否支持websocket连接健康检查,判断当前连接是否正常
        • 司空 2 私有版切换为https访问后,SDK报错:server's cert didn't look good
        • SDK的websocket连接断开后在OnClose回调中重连报错
        • SDK的websocket连接断开后重新建立连接后,会继续触发OnOpen回调吗
        • 接入SDK后无法收到事件的消息通知
        • 接入SDK后运行时报错:”无法加载JNI库:在jar包中找不到库文件:/lib/windows/x86_64/1ibcrypto.so.3“
        • SDK程序运行报错:Errorcode:NotificationcenterErrorcode_SubscribeError
        • SDK获取的飞行任务状态status的枚举值是什么
        • 如何获取上云 API 2 默认组织的id和token
      • 飞行记录PaaS组件
        • window.FH2 报错为 undefined
        • 运行飞行记录组件demo.html但地图区域未加载
        • 飞行记录组件只加载了一部分界面
        • 飞行任务完成后,在组件中没有关联显示任务的视频录制回放,但是在媒体库中有
      • 航线PaaS组件
        • 通过航线创建组件创建航线提示“文件已删除”
        • 航点航线全局设置面板消失+模糊
        • 刷新网页后航线组件无法加载
        • 地图渲染错误:cesium render Error Cannott read properties of undefined(reading origin)
        • 地图右下角控件(底图切换)点击无反应
        • 航线Paas组件的全局*号样式会影响客户项目本身的样式
        • 航线预览时地图回中时的中心点是什么
        • PaaS组件是否支持切换英文
        • 司空2私有版切换为https访问后,PaaS组件报错
        • 点击航线预览回中显示,画面并没有出现完整航线
      • 驾驶舱PaaS组件
        • 无法进入驾驶舱,浏览器控制台报错,prjId为空
        • 在红外镜头直播情况下如何修改调色盘
        • 在html中动态加载的paas.js文件,导致paas-core文件未正常引入
        • 集成驾驶舱组件后存在文字图标显示位置不对的问题
        • 前端集成驾驶舱组件后地图部分没有正常显示
        • 在驾驶舱内拍摄4K分辨率视频,实际在媒体库看到的视频还是1080P
        • 在驾驶舱组件中操控无人机起飞后无法查看直播
      • OpenAPI
        • 司空2私有版开启直播API能否支持返回RTMP拉流地址
        • /openapi/v0.1/flight-task/{task_uuid} GET API 报200500错误码
        • /openapi/v0.1/flight-task/{task_uuid}/media GET API 报200500错误码
        • 通过curl命令访问/openapi/v0.1/flight-task/{task_uuid}/media,点击响应中的url连接提示没有权限
        • /openapi/v0.9/media/api/v1/workspaces/{proj_uuid}/files GET API返回的create_at是不是媒体的拍摄时间
        • 航线任务的暂停、恢复和终止返航可以通过哪个API实现
        • 在无人机飞行过程中,如何切换直播镜头为红外镜头
        • 通过flight-commands下发camera_look_at指令返回228406错误码
        • 是否有API能支持设置无人机的home点
        • 通过payload-command API下发camera_look_at指令,报500错误
        • 怎么通过API查询指点飞行或者一键起飞任务过程中产生的媒体文件
        • 无人机在飞行过程中的媒体文件怎么开启边飞边传
        • 如何通过API查询到司空 2 组织的设备绑定码
        • 怎么通过API查询航线任务产生的媒体文件
        • 哪些设备支持照片空中回传功能
        • 下发一键起飞指令成功,但是无人机没有飞起来,提示错误码:328051
        • 通过 API 下发返航指令报210113错误码
        • 如果通过 API 根据航线文件夹筛选文件夹
        • 通过 API 下发返航指令返回212018错误码
        • 如何通过 API 远程控制机场开关舱盖
        • 如何通过 API 触发断点续飞任务
        • 如何通过 API 设置无人机的返航预留电量
        • 如果通过 API 控制无人机负载录制视频
        • 如何获取司空 2 AI 巡逻航线任务过程中的告警信息
        • 司空 2 的蛙跳任务如何保证在无人机降落时另一台机场满足降落条件?
        • 如果通过 API 下发一键起飞任务?
        • 如何通过无人机OSD判断是否触发了避障
        • 司空私有版在运行一段时间后,有部分容器始终处于restarting状态
        • 创建航线任务后,提示 319008 错误码
        • 给Dock 3 下发航线任务后,无人机拍照的像素只有1200万,可以拍4800万像素吗
      • 设备管理PaaS组件
    • DJI Inside设备
      • DJI Inside设备媒体文件上传问题
    • 私有化4G增强图传相关
      • 私有化4G增强图传排障流程图
      • 4G私有化服务器第一次登录protainer 需要密码
      • 4G仲裁成功但是图传增强服务不可用问题
      • 4G私有化服务器license locked后如何处理
      • 4G私有化服务部署时本地IP地址无法配置上错误
    • 漏洞相关
      • 司空私有化Node-exporter容器30815端口漏洞修复
    • 上云 API 2
      • 安装部署
        • 部署安装成功后无法创建组织
      • 设备上云
      • 前端组件
      • SDK
  1. 日常运维

【日常运维】高程导入卡在“处理中”或启用失败:状态核对与快速恢复

文档编号维护人内容版本号
2026113016corin高程导入卡住时的状态核对、分流和脚本导入2.x
本文用于快速判断并恢复,需要逐项排查的见《按现象排查》:【日常运维】高程导入卡在“处理中”或启用失败:按现象排查。

问题现象:#

导入高程长时间显示“处理中”。
页面弹出红色错误提示,或提示高程启用失败。
后台任务已经结束,页面还停在“处理中”。
导入容器长时间等待,或者起不来。

问题原因:#

页面显示“处理中”,未必是导入还在进行,也可能是 Web 客户端页面状态没更新。
大地图导入耗时过长而超时,或 MinIO 空间不足。
源数据还在下载、解压、上传,或任务执行失败、结果状态写回异常。
镜像、配置、数据库或存储有问题。

一、刷新页面并判断问题类型#

在 AIO 的“底图服务 → 高程设置”页面,按 F5 进行刷新。
如果状态从处理中,变为显示“已启用”、没有红色错误提示,说明导入完成了,不用再发起一次。反之显示“处理中”或启用失败的,在 K3s 控制面节点执行下面的命令,再对照表格找到对应的处理方法。

命令与解读#

看 Job 及任务状态。列表里看不到状态的,执行 sudo k3s kubectl -n flighthub2 describe job <Job名称>,<Job名称> 取下一条命令输出里的 jobName。
看高程记录的 status(含义见下表)和 jobName;是 3(失败)时,再看 errMsg(失败原因)。
列出状态不是 Running / Completed 的 Pod,用于初筛。导入任务刚创建时会短暂显示 Init:数字/数字,属于正常初始化,一直不变才算异常。
看静态 MinIO 的磁盘使用情况,Use% 接近 100% 说明空间不足。
高程记录的 status:
状态值含义
0已启用
1已停用
2处理中
3失败
分流表(“对应章节”标注《按现象排查》的,在另一篇文档):
序号现象或检查结果下一步对应章节
1导入已经跑了 2 小时以上(V2.0)确认原流程已结束,改用脚本导入「二、使用脚本导入高程」
2静态 MinIO 的 Use% 接近 100%结合写入报错确认空间不足后,改用脚本导入「二、使用脚本导入高程」
3Job 是 Complete,高程记录的 status 还是 2查看导入日志和管理服务日志《按现象排查》「一、Job 已完成,高程仍显示处理中」
4Job 列表为空,高程记录的 status 还是 2查看管理服务状态和日志《按现象排查》「二、找不到 Job,高程仍显示处理中」
5Job 是 Failed找到最先失败的容器《按现象排查》「三、导入 Job 失败」
6Pod 一直 Pending,或容器起不来查看 Pod 事件,按事件处理《按现象排查》「四、Pod 长时间等待或容器无法启动」
7Pod 是 Init:Error、Init:CrashLoopBackOff、Error,或日志里能看出某个阶段报错按阶段查看日志,按报错处理《按现象排查》「五、导入容器报错」
8高程记录的 status 是 3,或故障原因已处理、要重新导入确认原流程已结束,复位后重新导入《按现象排查》「六、复位并重新导入高程」
9按以上方法处理后仍未解决,或都不符合联系技术支持「三、仍未解决时联系技术支持」

二、使用脚本导入高程#

导入超过 2 小时,或静态 MinIO 空间不足时,用脚本处理。这个脚本走直接导入流程,大包导入会快一些。静态 MinIO 空间不够、存储又支持在线扩容时,会自动申请扩容。
脚本:(行数900+,点击可以折叠)
import-elevation
#!/usr/bin/env bash
# Read-only diagnostics. Only the selected output directory is written.
set -u
set -o pipefail
umask 077
export LC_ALL=C
export S_TIME_FORMAT=ISO
VERSION=1.2.2
MODE=${1:-help}
[[ $# -gt 0 ]] && shift
SINCE='30 minutes ago'
UNTIL=now
OUT=/var/tmp
NS=flighthub2
INTERVAL=5
DURATION=600
POD_LOGS=0
MAX_PODS=20
PACKAGE=''
LIMIT=$((5 * 1024 * 1024))
PROM_URL=''
PROM_INSTANCE=''
PROM_JOB=''
PROM_STEP=45
PROM_AUTH=''
PROM_CA=''
PROM_READY=0
PROM_RESERVE_KB=0
usage() {
  cat <<'HELP'
司空 Ubuntu 服务器环境收集脚本(含可选 Prometheus 历史采集)
用法:bash fh2-diagnose.sh collect|watch|discover [参数]

模式:
collect            收集当前环境、指定时段日志及已有 sar 历史负载
watch              先收集环境,再持续采样,结束后补采期间的系统/服务日志
discover           只读发现 Prometheus 地址和当前节点目标,仅打印提示,不采集、不写文件

参数:
--since TIME       历史开始时间,默认最近 30 分钟
--until TIME       历史结束时间,默认当前时间(不严格限制 Pod 日志)
--output DIR       输出父目录,必须已存在且可写,默认 /var/tmp
--namespace NAME   Kubernetes 命名空间,默认 flighthub2
--pod-logs         额外收集 Pod 业务日志,默认关闭,开启前确认允许采集
--max-pods N       最多采集日志的 Pod 数,范围 1~100,默认 20
--package FILE     检查本地升级包的校验值和目录,不解压、不执行
--interval N       watch 目标采样间隔,单位秒,范围 2~3600,默认 5
--duration N       watch 持续时间,单位秒,范围 2~86400,默认 600
--prometheus-url URL       可选 http/https 地址,可含路径前缀;不允许认证信息、query、fragment
--prometheus-instance VALUE 可选 instance 精确匹配;省略查询所有实例并提示
--prometheus-job VALUE     可选 job 精确匹配;省略不限制 job
--prometheus-step N        query_range 步长秒,15~3600,默认 45
--prometheus-auth-file FILE 可选 curl header 文件;普通文件、600、root 或当前用户所有且可读
--prometheus-ca-file FILE  可选可读 PEM CA 文件;不跳过 TLS 校验
--help, -h         显示本帮助

示例:
sudo bash fh2-diagnose.sh discover
sudo bash fh2-diagnose.sh collect
sudo bash fh2-diagnose.sh collect --since "2026-11-16 17:20:00" --until "2026-11-16 17:40:00" --pod-logs
sudo bash fh2-diagnose.sh watch --interval 5 --duration 1200
sudo bash fh2-diagnose.sh collect --prometheus-url https://monitor.example/prometheus --prometheus-instance server:9100

注意:时间默认按服务器本地时区解释,也可明确指定 UTC 或时区偏移。
历史时段最多 31 天,watch 理论采样次数最多 2000 次。
启用 Prometheus 时请求点数 floor((end-start)/step)+1 不得超过 2000。
默认步长 45 秒,与当前一体机 node-exporter 抓取间隔一致;查询 25 小时及以上时请增大步长。
查询步长不是原始采样频率;其他服务器的采样间隔不同时可用 --prometheus-step 指定。
Prometheus 使用原 --since/--until 窗口;watch 不改变该历史窗口。
rate 指标为 5 分钟平均,需开始时间之前已有数据,不是瞬时负载。
collect/watch 不提供 URL 时先发现并打印候选命令,不自动选择、不采集 Prometheus 历史指标;基础采集继续。
发现仅查询 Kubernetes/K3s Service 和候选地址的当前 node_uname_info,最多 12 个地址、总限时约 45 秒。
列出的是所有当前 node_exporter 节点目标,不证明目标属于本机,也不保证有请求时段的历史数据。
发现不使用认证文件,不扫描端口、不尝试 loopback、不转发端口、不安装依赖、不修改服务、不读取 Secrets。
discover 不严格要求 root;建议 sudo 以便读取 K3s 集群信息。发现依赖 python3、curl 和 kubectl 或 k3s。
缺少 curl/python3 时仅跳过 Prometheus;基础采集继续。认证内容不得放在命令参数中。
历史负载必须此前已记录,不能事后还原;发送结果前须人工检查敏感信息。
依赖:Bash 4+、GNU date、timeout、head、sed、df、du、tar、mktemp、awk、wc、hostname。
HELP
}
die() { printf '[错误] %s\n' "$*" >&2; exit 1; }

# One embedded standard-library helper; only discovery prints sanitized URLs/labels, never server errors.
prom_python() {
  python3 - "$@" <<'PY'
import csv
import datetime
import io
import ipaddress
import json
import math
import os
import queue
import selectors
import shlex
import shutil
import signal
import socket
import stat
import subprocess
import sys
import threading
import time
import unicodedata
import urllib.parse

LIMIT = 5 * 1024 * 1024
BUDGET = 256 * 1024 * 1024
MIN_FREE = 600 * 1024 * 1024
HEADER = ['timestamp_utc', 'metric', 'unit', 'labels_json', 'value']

def discover(script):
  def display(value):
      return ''.join(c if not unicodedata.category(c).startswith('C') and c not in '\u2028\u2029'
                     else '\\u%04x' % ord(c) for c in str(value))

  print('[发现] 本机主机名:' + display(socket.gethostname()), flush=True)
  print('[提示] 以下为所有当前 node_exporter 节点目标;instance 可以是主机名而非 IP。请人工核对本机,不自动选择。')
  print('[提示] 仅查询当前 node_uname_info,不保证历史数据;只发现 Kubernetes/K3s Service,不尝试 loopback。')
  deadline = time.monotonic() + 45

  def bounded(args, seconds):
      end = min(deadline, time.monotonic() + seconds)
      if time.monotonic() >= end:
          raise TimeoutError()
      # No output files or kubectl disk cache; cap pipes even for chunked HTTP responses.
      proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
                              start_new_session=True)
      chunks = []
      size = 0
      try:
          with selectors.DefaultSelector() as reader:
              reader.register(proc.stdout, selectors.EVENT_READ)
              while reader.get_map():
                  remaining = end - time.monotonic()
                  if remaining <= 0:
                      raise TimeoutError()
                  for key, _ in reader.select(min(remaining, 0.1)):
                      data = os.read(key.fd, 65536)
                      if not data:
                          reader.unregister(key.fileobj)
                          continue
                      size += len(data)
                      if size > LIMIT:
                          raise ValueError('response limit')
                      chunks.append(data)
          rc = proc.wait(timeout=max(0.001, end - time.monotonic()))
          if rc:
              raise ValueError('command failed')
          return b''.join(chunks)
      finally:
          # Also stop descendants that might retain the pipe after their parent exits.
          try:
              os.killpg(proc.pid, signal.SIGKILL)
          except ProcessLookupError:
              pass
          proc.stdout.close()
          try:
              proc.wait(timeout=0.5)
          except subprocess.TimeoutExpired:
              pass

  if not shutil.which('curl'):
      print('[跳过] 未找到 curl,无法验证 Prometheus;基础采集不受影响。')
      return
  commands = []
  if shutil.which('kubectl'):
      commands.append(['kubectl'])
  if shutil.which('k3s'):
      commands.append(['k3s', 'kubectl'])
  if not commands:
      print('[跳过] 未找到 kubectl 或 k3s;请手动提供 --prometheus-url。')
      return
  services = None
  for command in commands:
      try:
          obj = json.loads(bounded(command + ['--cache-dir=/dev/null', '--request-timeout=8s',
                                             'get', 'svc', '-A', '-o', 'json'], 10))
          if not isinstance(obj, dict) or not isinstance(obj.get('items'), list):
              raise ValueError()
          services = obj['items']
          break
      except (OSError, ValueError, subprocess.TimeoutExpired, TimeoutError):
          print('[提示] ' + ' '.join(command) + ' 只读 Service 查询失败、超时或响应超过 5 MiB;检查权限/集群连接。')
  if services is None:
      print('[跳过] 无法读取集群 Service;建议 sudo 访问 K3s,或手动提供 --prometheus-url。')
      return
  candidates = []
  for svc in services:
      if not isinstance(svc, dict):
          continue
      meta, spec = svc.get('metadata', {}), svc.get('spec', {})
      if not isinstance(meta, dict) or not isinstance(spec, dict):
          continue
      name, namespace, labels = meta.get('name', ''), meta.get('namespace', ''), meta.get('labels', {})
      if not isinstance(name, str) or not isinstance(namespace, str) or not isinstance(labels, dict):
          continue
      if 'prometheus' not in (name + ' ' + ' '.join(str(k) + '=' + str(v) for k, v in labels.items())).lower():
          continue
      if spec.get('type') == 'ExternalName':
          continue
      try:
          # Only literal ClusterIPs from Service metadata, never arbitrary URLs/hosts from labels.
          address = str(ipaddress.ip_address(spec.get('clusterIP', '')))
      except ValueError:
          continue
      host = '[' + address + ']' if ':' in address else address
      ports = spec.get('ports', [])
      if not isinstance(ports, list):
          continue
      for port in ports:
          if not isinstance(port, dict) or port.get('protocol', 'TCP') != 'TCP':
              continue
          number, port_name = port.get('port'), str(port.get('name', '')).lower()
          if not isinstance(number, int) or isinstance(number, bool) or not 1 <= number <= 65535:
              continue
          if number != 9090 and 'prometheus' not in port_name:
              continue
          candidates.append((namespace != 'monitoring', namespace, name, 'http://' + host + ':' + str(number)))
  candidates.sort()
  unique = []
  seen = set()
  for _, namespace, name, url in candidates:
      if url not in seen:
          seen.add(url)
          unique.append((namespace, name, url))
  if not unique:
      print('[无匹配] 没有可用的 Prometheus ClusterIP Service/端口;请手动提供 --prometheus-url。')
      return
  if len(unique) > 12:
      print('[提示] 候选超过 12 个,仅验证前 12 个(monitoring 命名空间优先)。')
  found = False
  for namespace, name, url in unique[:12]:
      if time.monotonic() >= deadline:
          print('[跳过] 达到发现总限时,剩余候选未验证。')
          break
      print('[候选] ' + display(namespace + '/' + name) + ' ' + url, flush=True)
      try:
          raw = bounded(['curl', '-q', '--silent', '--show-error', '--fail', '--noproxy', '*',
                         '--proto', '=http', '--connect-timeout', '2', '--max-time', '5',
                         '--max-filesize', str(LIMIT), '--get', '--data-urlencode',
                         'query=node_uname_info', '--url', url + '/api/v1/query'], 6)
          obj = json.loads(raw)
          if (not isinstance(obj, dict) or obj.get('status') != 'success' or
                  not isinstance(obj.get('data'), dict) or obj['data'].get('resultType') != 'vector' or
                  not isinstance(obj['data'].get('result'), list)):
              raise ValueError()
          identities = set()
          for item in obj['data']['result']:
              metric = item.get('metric') if isinstance(item, dict) else None
              if not isinstance(metric, dict) or metric.get('__name__') != 'node_uname_info':
                  continue
              identity = tuple(metric.get(k, '') for k in ('instance', 'job', 'nodename'))
              if all(isinstance(v, str) for v in identity):
                  identities.add(identity)
          if not identities:
              print('[无节点指标] 当前 node_uname_info 为空或不包含有效节点身份。')
              continue
          for instance, job, nodename in sorted(identities):
              found = True
              print('[节点] instance=' + display(instance) + ' job=' + display(job) + ' nodename=' + display(nodename))
              try:
                  validate(url, instance, job, '', '')
                  if not instance or not job:
                      raise ValueError()
                  args = ['sudo', 'bash', os.path.abspath(script), 'collect', '--prometheus-url', url,
                          '--prometheus-instance', instance, '--prometheus-job', job]
                  if any(display(arg) != arg for arg in args):
                      raise ValueError()
                  print('[命令] ' + ' '.join(shlex.quote(arg) for arg in args))
              except ValueError:
                  print('[提示] 身份缺少 instance/job 或含不安全字符,未生成命令;请人工核对。')
      except (OSError, ValueError, subprocess.TimeoutExpired, TimeoutError):
          print('[不可用] 地址不可达、HTTP/API 失败、超时或响应无效/超过 5 MiB;未使用认证。')
  if not found:
      print('[无可用目标] 未验证到当前节点指标;请手动检查 Prometheus 地址和 node_exporter。')
  print('[提示] 未选择任何地址或实例,未采集历史指标。需要采集时请人工执行对应命令,可调整 --since/--until。')

def open_auth(path):
  fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
  try:
      s = os.fstat(fd)
      if (not stat.S_ISREG(s.st_mode) or stat.S_IMODE(s.st_mode) != 0o600 or
              s.st_uid not in (0, os.geteuid())):
          raise ValueError('Auth file must be readable, regular, mode 600 and owned by root/current user')
      return fd
  except Exception:
      os.close(fd)
      raise

def validate(url, instance, job, auth, ca):
  if any(unicodedata.category(c) in ('Cc', 'Cs') for c in instance + job):
      raise ValueError('Prometheus label values must not contain controls or Unicode surrogates')
  if any(len(s) > 4096 for s in (url, instance, job)):
      raise ValueError('Prometheus URL/label value exceeds 4096 characters')
  if url:
      p = urllib.parse.urlsplit(url)
      decoded = urllib.parse.unquote(url)
      if (p.scheme not in ('http', 'https') or not p.hostname or
              p.username is not None or p.password is not None or '@' in p.netloc or
              '?' in url or '#' in url or '\\' in decoded or
              any(c.isspace() or unicodedata.category(c) == 'Cc' for c in decoded)):
          raise ValueError('Invalid Prometheus URL: use http/https without credentials, query or fragment')
      if p.port is not None and not 1 <= p.port <= 65535:
          raise ValueError('Invalid Prometheus URL port')
  if auth:
      os.close(open_auth(auth))
  if ca:
      if not os.path.isfile(ca) or not os.access(ca, os.R_OK):
          raise ValueError('CA file must be a readable PEM file')
      with open(ca, 'rb') as f:
          pem = f.read(LIMIT + 1)
      if len(pem) > LIMIT or b'-----BEGIN CERTIFICATE-----' not in pem or b'-----END CERTIFICATE-----' not in pem:
          raise ValueError('CA file must contain PEM certificates and be at most 5 MiB')

def plan(instance, job):
  filters = []
  for key, value in (('instance', instance), ('job', job)):
      if value:
          # Go/PromQL does not accept JSON surrogate-pair escapes for non-BMP characters.
          filters.append(key + '=' + json.dumps(value, ensure_ascii=False))
  def metric(name, *extra):
      terms = filters + list(extra)
      return name + ('{' + ','.join(terms) + '}' if terms else '')
  fs = ('fstype!~"autofs|binfmt_misc|bpf|cgroup2?|configfs|debugfs|devpts|devtmpfs|fusectl|hugetlbfs|mqueue|nsfs|overlay|proc|pstore|ramfs|securityfs|squashfs|sysfs|tmpfs|tracefs"',)
  size = metric('node_filesystem_size_bytes', *fs)
  return [
      ('node_load1', 'load', metric('node_load1')),
      ('node_load5', 'load', metric('node_load5')),
      ('node_load15', 'load', metric('node_load15')),
      ('cpu_usage_percent', 'percent', '100*(1-avg by(instance,job)(rate(' + metric('node_cpu_seconds_total', 'mode="idle"') + '[5m])))'),
      ('iowait_percent', 'percent', '100*avg by(instance,job)(rate(' + metric('node_cpu_seconds_total', 'mode="iowait"') + '[5m]))'),
      ('memory_used_percent', 'percent', '100*(1-' + metric('node_memory_MemAvailable_bytes') + '/' + metric('node_memory_MemTotal_bytes') + ')'),
      ('available_bytes', 'bytes', metric('node_memory_MemAvailable_bytes')),
      ('swap_used_bytes', 'bytes', metric('node_memory_SwapTotal_bytes') + '-' + metric('node_memory_SwapFree_bytes')),
      ('filesystem_usage_percent', 'percent', '(100*(1-' + metric('node_filesystem_avail_bytes', *fs) + '/' + size + ')) and (' + size + '>0)'),
      ('disk_read_bytes_per_second', 'bytes/second', 'rate(' + metric('node_disk_read_bytes_total') + '[5m])'),
      ('disk_write_bytes_per_second', 'bytes/second', 'rate(' + metric('node_disk_written_bytes_total') + '[5m])'),
      ('disk_io_busy_percent', 'percent', '100*rate(' + metric('node_disk_io_time_seconds_total') + '[5m])'),
      ('network_receive_bytes_per_second', 'bytes/second', 'rate(' + metric('node_network_receive_bytes_total', 'device!="lo"') + '[5m])'),
      ('network_transmit_bytes_per_second', 'bytes/second', 'rate(' + metric('node_network_transmit_bytes_total', 'device!="lo"') + '[5m])'),
      ('up', '0/1', metric('up')),
  ]

def room(root):
  used = 0
  for base, dirs, files in os.walk(root, followlinks=False):
      for path in [base] + [os.path.join(base, n) for n in files + dirs]:
          s = os.stat(path, follow_symlinks=False)
          used += getattr(s, 'st_blocks', (s.st_size + 4095) // 4096 * 8) * 512
  return min(BUDGET - used, shutil.disk_usage(root).free - MIN_FREE) - 65536

def fetch(root, name, unit, query, url, start, end, step, auth, ca):
  dest = os.path.join(root, 'prometheus')
  csv_path = os.path.join(dest, name + '.csv')
  with open(csv_path, 'w', encoding='utf-8', newline='') as f:
      csv.writer(f).writerow(HEADER)
  # Reserve worst-case bounded response + CSV + private stderr, without enlarging the base budget.
  if room(root) < 12 * 1024 * 1024:
      return ('skipped_budget', 0, 0, '000', 0)
  # collect/watch can run for hours after preflight; do not trust stale auth/CA permissions.
  validate(url, '', '', '', ca)
  response = os.path.join(dest, name + '.response.txt')
  errors = os.path.join(dest, name + '.curl-error.txt')
  args = ['curl', '-q', '--silent', '--show-error', '--proto', '=http,https',
          '--connect-timeout', '5', '--max-time', '30', '--max-filesize', str(LIMIT),
          '--get', '--data-urlencode', 'query=' + query, '--data-urlencode', 'start=' + start,
          '--data-urlencode', 'end=' + end, '--data-urlencode', 'step=' + step,
          '--output', '-', '--write-out', '\n%{http_code}']
  if ca:
      args += ['--cacert', os.path.abspath(ca)]
  args += ['--url', url.rstrip('/') + '/api/v1/query_range']
  # Bounded pipe readers also cover chunked responses and old curl versions that ignore max-filesize.
  auth_descriptor = open_auth(auth) if auth else None
  try:
      if auth_descriptor is not None:
          # Pin the verified inode: replacing the original path must not change the headers curl reads.
          args += ['--header', '@/proc/self/fd/' + str(auth_descriptor)]
      proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                              pass_fds=(auth_descriptor,) if auth_descriptor is not None else ())
  finally:
      if auth_descriptor is not None:
          os.close(auth_descriptor)
  chunks = queue.Queue(maxsize=8)
  def read_pipe(pipe, stream):
      try:
          while True:
              data = pipe.read(65536)
              if not data:
                  break
              chunks.put((stream, data))
      finally:
          pipe.close()
          chunks.put((stream, None))
  for stream, pipe in enumerate((proc.stdout, proc.stderr)):
      threading.Thread(target=read_pipe, args=(pipe, stream), daemon=True).start()
  total = 0
  err_bytes = 0
  closed = 0
  capped = False
  timed_out = False
  deadline = time.monotonic() + 35
  with open(response, 'wb') as out, open(errors, 'wb') as err:
      while closed < 2:
          if time.monotonic() > deadline and not timed_out:
              timed_out = True
              proc.kill()
          try:
              stream, data = chunks.get(timeout=0.1)
          except queue.Empty:
              continue
          if data is None:
              closed += 1
              continue
          if capped or timed_out:
              continue
          remaining = LIMIT - total
          take = min(len(data), remaining, 65536 - err_bytes if stream else len(data))
          if take:
              (err if stream else out).write(data[:take])
              total += take
              if stream:
                  err_bytes += take
          if len(data) > take:
              capped = True
              proc.kill()
  rc = proc.wait(timeout=5)
  if capped or timed_out:
      return ('response_limit' if capped else 'timeout', 0, 0, '000', rc)
  with open(response, 'rb') as f:
      payload, sep, code = f.read(LIMIT).rpartition(b'\n')
  http = code.decode('ascii') if sep and len(code) == 3 and code.isdigit() else '000'
  if rc:
      return ('curl_failed', 0, 0, http, rc)
  if http != '200':
      return ('http_failed', 0, 0, http, rc)
  try:
      obj = json.loads(payload)
      if not isinstance(obj, dict):
          raise ValueError()
      if obj.get('status') == 'error':
          return ('api_error', 0, 0, http, rc)
      data = obj.get('data')
      if obj.get('status') != 'success' or not isinstance(data, dict) or data.get('resultType') != 'matrix':
          raise ValueError()
      series = data.get('result')
      if not isinstance(series, list):
          raise ValueError()
      for item in series:
          if not isinstance(item, dict) or not isinstance(item.get('metric'), dict) or not isinstance(item.get('values'), list):
              raise ValueError()
          if any(not isinstance(k, str) or not isinstance(v, str) for k, v in item['metric'].items()):
              raise ValueError()
          if len(item['values']) > 2000:
              raise ValueError()
          for pair in item['values']:
              if (not isinstance(pair, list) or len(pair) != 2 or
                      isinstance(pair[0], bool) or not isinstance(pair[0], (int, float)) or
                      not math.isfinite(pair[0]) or isinstance(pair[1], bool) or
                      not isinstance(pair[1], (str, int, float))):
                  raise ValueError()
              datetime.datetime.fromtimestamp(pair[0], datetime.timezone.utc)
  except (ValueError, TypeError, OverflowError, OSError):
      return ('invalid_json', 0, 0, http, rc)
  # Strip only curl's numeric status trailer. Successful JSON, including labels, stays private and unmasked.
  with open(response, 'r+b') as f:
      f.truncate(len(payload))
  os.replace(response, os.path.join(dest, name + '.json'))
  allowance = min(LIMIT, room(root))
  written = 0
  rows = 0
  outcome = 'ok'
  buffer = io.StringIO(newline='')
  writer = csv.writer(buffer)
  with open(csv_path, 'wb') as f:
      writer.writerow(HEADER)
      encoded = buffer.getvalue().encode('utf-8')
      f.write(encoded)
      written += len(encoded)
      for item in series:
          labels = json.dumps(item['metric'], ensure_ascii=True, sort_keys=True, separators=(',', ':'))
          for timestamp, value in item['values']:
              buffer.seek(0)
              buffer.truncate(0)
              utc = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc).isoformat().replace('+00:00', 'Z')
              writer.writerow([utc, name, unit, labels, value])
              encoded = buffer.getvalue().encode('utf-8')
              if written + len(encoded) > allowance or shutil.disk_usage(root).free - len(encoded) < MIN_FREE:
                  outcome = 'csv_limit'
                  break
              f.write(encoded)
              written += len(encoded)
              rows += 1
          if outcome != 'ok':
              break
  if outcome == 'ok' and rows == 0:
      outcome = 'no_data'
  return (outcome, rows, len(series), http, rc)

try:
  action = sys.argv[1]
  if action == 'validate':
      validate(*sys.argv[2:])
  elif action == 'discover':
      discover(sys.argv[2])
  elif action == 'init':
      root, url, instance, job, start, end, step, from_time, to_time = sys.argv[2:]
      dest = os.path.join(root, 'prometheus')
      os.mkdir(dest, 0o700)
      with open(os.path.join(dest, 'queries.tsv'), 'w', encoding='utf-8', newline='') as f:
          w = csv.writer(f, delimiter='\t', lineterminator='\n', quoting=csv.QUOTE_NONE, quotechar=None)
          w.writerow(['name', 'unit', 'PromQL'])
          w.writerows(plan(instance, job))
      with open(os.path.join(dest, 'query-status.tsv'), 'w', encoding='utf-8') as f:
          f.write('name\toutcome\trows\tseries\thttp_status\tcurl_exit\n')
      with open(os.path.join(dest, 'README.txt'), 'w', encoding='utf-8') as f:
          f.write('Prometheus retained node_exporter history (read-only HTTP API)\n')
          f.write('Address: ' + url + '\nInstance exact: ' + json.dumps(instance) + '\nJob exact: ' + json.dumps(job) + '\n')
          f.write('Requested history: ' + from_time + ' to ' + to_time + '\n')
          f.write('Epoch start/end: ' + start + ' / ' + end + '\nStep seconds: ' + step + '\nCSV timestamps: UTC (Z). Watch does not change the requested history window.\n')
          f.write('Instance omitted: all instances. Job omitted: all jobs. up is ALL targets when both are omitted, not only node_exporter.\n')
          f.write('load1/5/15: load averages. CPU: non-idle percent, averaged per instance/job. iowait: averaged CPU waiting percent.\n')
          f.write('Memory used: 100*(1-available/total); available: bytes. Swap used: total-free bytes.\n')
          f.write('Filesystem: 100*(1-avail/size), pseudo filesystems excluded, size<=0 excluded (no data, not infinity).\n')
          f.write('Disk read/write: bytes/s; disk busy: 100*I/O time rate, per device, may exceed 100. Network: bytes/s per device excluding lo. up: scrape success 0/1.\n')
          f.write('All rate(...[5m]) values are FIVE-MINUTE AVERAGES, not instantaneous; retained samples before start are required.\n')
          f.write('No missing values are filled with zero. NaN/Inf and nonnumeric sample strings are preserved in CSV.\n')
          f.write('no_data: empty successful result/no samples; node_exporter may be absent, filtered out, expired, or not recorded. No cAdvisor/plugins/custom metric guessing.\n')
          f.write('Failures are nonfatal; empty CSV header accompanies API/HTTP errors. csv_limit means partial CSV. response_limit means response not parsed.\n')
          f.write('Total collection budget: 256 MiB; minimum free space: 600 MiB. Each curl output and CSV capped at 5 MiB.\n')
          f.write('Successful JSON/CSV labels and private .response.txt/.curl-error.txt may contain sensitive data: MANUALLY REVIEW BEFORE SHARING.\n')
          f.write('Auth/CA input files are never copied into the bundle. No redirects, insecure TLS, remote_write, service changes or Grafana login.\n')
          if url.startswith('http://'):
              f.write('WARNING: HTTP is unencrypted; any authentication headers travel in plaintext. Prefer HTTPS.\n')
  elif action == 'query':
      print('\t'.join(str(v) for v in fetch(*sys.argv[2:])))
  else:
      raise ValueError('Unknown internal Prometheus action')
except Exception:
  # Do not disclose exception text: it can contain credentials, labels or a response body.
  if len(sys.argv) > 1 and sys.argv[1] == 'query':
      print('local_failed\t0\t0\t000\t0')
  elif len(sys.argv) > 1 and sys.argv[1] == 'discover':
      print('[跳过] Prometheus 发现失败;请手动提供地址,基础采集不受影响。', file=sys.stderr)
  else:
      print('Prometheus validation/setup failed; check URL, label controls and local file permissions/PEM format.', file=sys.stderr)
      sys.exit(1)
PY
}

[[ $MODE == help || $MODE == --help || $MODE == -h ]] && { usage; exit 0; }
[[ $MODE == collect || $MODE == watch || $MODE == discover ]] || { usage; exit 1; }
while [[ $# -gt 0 ]]; do
  case $1 in
      --help|-h) usage; exit 0 ;;
      --pod-logs) POD_LOGS=1; shift ;;
      --since|--until|--output|--namespace|--interval|--duration|--max-pods|--package|--prometheus-url|--prometheus-instance|--prometheus-job|--prometheus-step|--prometheus-auth-file|--prometheus-ca-file)
          [[ $# -ge 2 && -n $2 ]] || die "Missing value for $1"
          case $1 in
              --since) SINCE=$2 ;; --until) UNTIL=$2 ;; --output) OUT=$2 ;;
              --namespace) NS=$2 ;; --interval) INTERVAL=$2 ;; --duration) DURATION=$2 ;;
              --max-pods) MAX_PODS=$2 ;; --package) PACKAGE=$2 ;;
              --prometheus-url) PROM_URL=$2 ;; --prometheus-instance) PROM_INSTANCE=$2 ;;
              --prometheus-job) PROM_JOB=$2 ;; --prometheus-step) PROM_STEP=$2 ;;
              --prometheus-auth-file) PROM_AUTH=$2 ;; --prometheus-ca-file) PROM_CA=$2 ;;
          esac
          shift 2 ;;
      *) die 'Unknown argument (use --help)' ;;
  esac
done
if [[ $MODE == discover || -z $PROM_URL ]]; then
  printf '[提示] Prometheus 只读发现 v%s;只打印候选和命令,不自动启用历史采集。\n' "$VERSION"
  if command -v python3 >/dev/null 2>&1; then
      prom_python discover "${BASH_SOURCE[0]}"
  else
      printf '[跳过] 未找到 python3,无法发现 Prometheus;基础采集不受影响。\n'
  fi
  [[ $MODE != discover ]] || exit 0
fi
[[ ${BASH_VERSINFO[0]} -ge 4 ]] || die 'Bash 4+ required'
for tool in date timeout head sed df du tar mktemp awk wc hostname; do
  command -v "$tool" >/dev/null 2>&1 || die "Required tool missing: $tool"
done
for value in "$INTERVAL" "$DURATION" "$MAX_PODS" "$PROM_STEP"; do
  [[ $value =~ ^[1-9][0-9]{0,5}$ ]] || die 'Numeric options must be positive decimal integers'
done
(( INTERVAL >= 2 && INTERVAL <= 3600 )) || die 'interval must be 2..3600'
(( DURATION >= 2 && DURATION <= 86400 )) || die 'duration must be 2..86400'
(( MAX_PODS <= 100 )) || die 'max-pods must be 1..100'
(( PROM_STEP >= 15 && PROM_STEP <= 3600 )) || die 'prometheus-step must be 15..3600'
(( (DURATION + INTERVAL - 1) / INTERVAL <= 2000 )) || die 'Too many watch samples (maximum 2000)'
[[ $NS =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ && ${#NS} -le 63 ]] || die 'Invalid namespace'
START=$(date -d "$SINCE" +%s 2>/dev/null) || die 'Invalid since time'
END=$(date -d "$UNTIL" +%s 2>/dev/null) || die 'Invalid until time'
(( END >= START && END - START <= 31 * 86400 )) || die 'Time range must be ordered and no longer than 31 days'
FROM=$(date -d "@$START" '+%Y-%m-%d %H:%M:%S %z')
TO=$(date -d "@$END" '+%Y-%m-%d %H:%M:%S %z')
if [[ -n $PROM_URL ]]; then
  (( (END - START) / PROM_STEP + 1 <= 2000 )) || die 'Too many Prometheus points per series (maximum 2000); increase step or shorten time range'
  if command -v python3 >/dev/null 2>&1; then
      prom_python validate "$PROM_URL" "$PROM_INSTANCE" "$PROM_JOB" "$PROM_AUTH" "$PROM_CA" || die 'Invalid Prometheus options'
      if command -v curl >/dev/null 2>&1; then
          PROM_READY=1
          PROM_RESERVE_KB=32768
      fi
  fi
fi
[[ -d $OUT && -w $OUT ]] || die 'Output parent must exist and be writable'
[[ -z $PACKAGE || -f $PACKAGE ]] || die 'Package is not a local regular file'
free_kb=$(df -Pk "$OUT" | awk 'END {print $4}')
[[ $free_kb =~ ^[0-9]+$ ]] && (( free_kb >= 1048576 )) || die 'At least 1 GiB free output space required'
ROOT=$(mktemp -d "$OUT/fh2-diag-$(date +%Y%m%d-%H%M%S)-XXXXXX") || die 'Cannot create output directory'
STATUS=$ROOT/status.tsv
printf 'time\tfile\tresult\n' > "$STATUS" || die 'Cannot write status file'
progress() {
  local label
  case $2 in
      os.txt) label='操作系统版本' ;; kernel.txt) label='内核版本' ;;
      time.txt) label='服务器时间和时区' ;; uptime.txt) label='运行时长和平均负载' ;;
      cpu.txt) label='CPU 配置' ;; memory.txt|watch/*-memory.txt) label='内存和 Swap' ;;
      disks.txt) label='磁盘和分区' ;; space.txt) label='磁盘空间' ;; inodes.txt) label='inode 使用量' ;;
      processes.txt|watch/*-processes.txt) label='进程资源占用' ;; gpu.txt) label='GPU 状态' ;;
      addresses.txt) label='网卡 IP 和网段' ;; routes.txt) label='路由表' ;; dns.txt) label='DNS 配置' ;;
      listeners.txt) label='监听端口' ;; connections-summary.txt) label='连接概要' ;;
      ufw.txt|nft.txt|iptables.txt) label='本机防火墙规则' ;;
      failed-services.txt|services.txt) label='系统服务状态' ;; sysstat-timer.txt) label='sar 定时采集状态' ;;
      kernel-history.txt|watch-kernel-events.txt) label='内核日志' ;;
      system-warnings-history.txt|watch-system-warnings.txt) label='系统告警日志' ;;
      journal-*.txt|watch-journal-*.txt) label='系统服务日志' ;;
      k3s-version.txt) label='K3s 版本' ;; nodes.txt|node-conditions.txt) label='集群节点状态' ;;
      pods.txt|pod-state.txt) label='Pod 和容器状态' ;; workloads.txt) label='工作负载状态' ;;
      k8s-services.txt) label='Kubernetes Service' ;; events.txt) label='Kubernetes 事件' ;;
      top-nodes-current.txt|top-pods-current.txt) label='集群当前 CPU 和内存' ;;
      pod-logs/*.txt) label='Pod 日志' ;; pod-log-list) label='Pod 日志采集名单' ;;
      history/sar-*.txt) label='sar 历史负载' ;;
      package-hash.txt) label='升级包 SHA-256' ;; package-list.txt) label='升级包文件清单' ;;
      watch/*-vmstat.txt) label='CPU 和系统活动采样' ;; watch/*-io.txt) label='磁盘 I/O 采样' ;;
      watch/*-net.txt) label='网卡收发计数' ;; *) label=$2 ;;
  esac
  printf '[%s] %s (%s)\n' "$1" "$label" "$2"
}
note() {
  printf '%s\t%s\t%s\n' "$(date -Is)" "$1" "$2" >> "$STATUS" || die 'Cannot write status file'
  case $2 in
      OK) progress '完成' "$1" ;;
      'SKIPPED: tool unavailable') progress '跳过:未安装所需工具' "$1" ;;
      SKIPPED*)
          case $1 in
              sar) printf '[跳过] 未安装 sar,不能读取已有历史负载。\n' ;;
              kubernetes) printf '[跳过] 未找到 kubectl 或 k3s,无法采集集群信息。\n' ;;
              prometheus) printf '[跳过] Prometheus 历史采集未启用、缺少工具或预算不足;详见 status.tsv。\n' ;;
              *) progress '跳过:详情见 status.tsv' "$1" ;;
          esac ;;
      TRUNCATED*) progress '截断:达到输出上限' "$1" ;;
      'PARTIAL/FAILED:'*) progress '失败或超时:查看对应结果文件' "$1" ;;
      'NO VERIFIED SAR DATA:'*) progress '缺失:没有可用的历史负载记录' "$1" ;;
      *)
          case $1 in
              permissions) printf '[提示] 当前不是 root,部分信息可能无法采集。\n' ;;
              history) printf '[提示] 请求结束时间在服务器当前时间之后,请核对时区和故障时间。\n' ;;
              watch) printf '[采样结束或停止] 具体轮次和原因见 status.tsv。\n' ;;
              pod-logs) printf '[提示] Pod 日志为受限尾部记录,不保证覆盖整个故障时段。\n' ;;
              historical-monitoring) printf '[提示] 仅在显式指定地址时查询 Prometheus;不自动查询 atop 或启用历史监控。\n' ;;
              package) printf '[提示] 升级包仅校验和列目录,不执行升级。\n' ;;
              *) progress '记录:详情见 status.tsv' "$1" ;;
          esac ;;
  esac
}
printf '[开始] 司空环境收集脚本 v%s,模式:%s\n' "$VERSION" "$MODE"
printf '[时间] 历史采集窗口:%s 至 %s(服务器时区)\n' "$FROM" "$TO"
printf '[目录] %s\n' "$ROOT"
space_ok() {
  local free used
  free=$(df -Pk "$ROOT" | awk 'END {print $4}')
  used=$(du -sk "$ROOT" | awk '{print $1}')
  [[ $free =~ ^[0-9]+$ && $used =~ ^[0-9]+$ ]] && (( free >= 614400 + PROM_RESERVE_KB && used < 262144 - PROM_RESERVE_KB ))
}

# Best-effort text masking is not a substitute for manual review of attachments.
redact() {
  sed -E \
      -e 's#(://[^ /:@]+:)[^@ /]+@#\1[REDACTED]@#g' \
      -e 's#([Bb]earer[[:space:]]+)[A-Za-z0-9._~+/=-]+#\1[REDACTED]#g' \
      -e 's#((password|passwd|token|secret|access_key|authorization)[A-Za-z_]*[" ]*[:=][" ]*)[^ ,"\t}]+#\1[REDACTED]#Ig'
}
run() {
  local file=$1 seconds=$2 rc bytes code
  local -a pipe_codes
  shift 2
  if ! space_ok; then
      note "$file" 'SKIPPED: 256 MiB total budget/reservation reached or less than 600 MiB free space'
      return 0
  fi
  if ! command -v "$1" >/dev/null 2>&1; then
      printf 'Unavailable tool: %s\n' "$1" > "$ROOT/$file" || die 'Cannot write result file'
      note "$file" 'SKIPPED: tool unavailable'
      return 0
  fi
  progress '开始' "$file"
  printf 'Collected at: %s\n' "$(date -Is)" > "$ROOT/$file" || die 'Cannot write result file'
  timeout --signal=TERM --kill-after=5s "${seconds}s" "$@" 2>&1 |
      head -c "$LIMIT" | redact >> "$ROOT/$file"
  pipe_codes=("${PIPESTATUS[@]}")
  (( pipe_codes[2] == 0 )) || die "Masking/output write failed; partial results retained: $ROOT"
  rc=0
  for code in "${pipe_codes[@]}"; do (( code != 0 )) && rc=$code; done
  bytes=$(wc -c < "$ROOT/$file")
  if (( bytes >= LIMIT )); then
      note "$file" "TRUNCATED: 5 MiB cap; pipeline exit=$rc"
  elif (( rc != 0 )); then
      note "$file" "PARTIAL/FAILED: pipeline exit=$rc (124=timeout); see file"
  else
      note "$file" OK
  fi
  # Optional failures never prevent collection of independent evidence.
  return 0
}
collect_prometheus() {
  local name unit query result outcome rows series http rc
  if [[ -z $PROM_URL ]]; then
      note prometheus 'SKIPPED: no --prometheus-url supplied; discovery hints only, no automatic selection or historical query'
      return 0
  fi
  if (( ! PROM_READY )); then
      note prometheus 'SKIPPED: curl or python3 unavailable; base collection continues'
      return 0
  fi
  if ! space_ok; then
      # Release the base reservation so Prometheus can use it, still under the same total cap.
      PROM_RESERVE_KB=0
      if ! space_ok; then
          note prometheus 'SKIPPED: total budget or free-space limit reached'
          return 0
      fi
  fi
  PROM_RESERVE_KB=0
  prom_python init "$ROOT" "$PROM_URL" "$PROM_INSTANCE" "$PROM_JOB" "$START" "$END" "$PROM_STEP" "$FROM" "$TO" || {
      note prometheus 'PARTIAL/FAILED: local plan/README setup failed'
      return 0
  }
  [[ -n $PROM_INSTANCE ]] || printf '[提示] 未指定 Prometheus instance,将查询所有实例;结果可能较大。\n'
  [[ -n $PROM_INSTANCE || -n $PROM_JOB ]] || printf '[提示] up 查询所有 job/instance 的目标,不仅限 node_exporter。\n'
  printf '[提示] Prometheus 使用上述原历史窗口;rate 为 5 分钟平均,开始前需已有数据。\n'
  while IFS=$'\t' read -r name unit query; do
      [[ $name == name ]] && continue
      printf '[开始] Prometheus 指标:%s\n' "$name"
      result=$(prom_python query "$ROOT" "$name" "$unit" "$query" "$PROM_URL" "$START" "$END" "$PROM_STEP" "$PROM_AUTH" "$PROM_CA")
      IFS=$'\t' read -r outcome rows series http rc <<< "$result"
      case $outcome in
          ok|no_data|api_error|http_failed|curl_failed|invalid_json|response_limit|csv_limit|timeout|skipped_budget|local_failed) ;;
          *) outcome=local_failed; rows=0; series=0; http=000; rc=0 ;;
      esac
      printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$name" "$outcome" "$rows" "$series" "$http" "$rc" >> "$ROOT/prometheus/query-status.tsv" || die 'Cannot write Prometheus status'
      case $outcome in
          ok) printf '[完成] Prometheus 指标:%s,CSV 行数:%s\n' "$name" "$rows" ;;
          no_data) printf '[无数据] Prometheus 指标:%s;可能未安装 node_exporter、未记录、过滤不匹配或已过期,不补零。\n' "$name" ;;
          skipped_budget) printf '[跳过] Prometheus 指标:%s,达到预算或空闲空间底线。\n' "$name" ;;
          *) printf '[失败或截断] Prometheus 指标:%s,状态:%s;基础采集结果保留。\n' "$name" "$outcome" ;;
      esac
      note "prometheus/$name" "$outcome; rows=$rows; series=$series; http=$http; curl_exit=$rc"
  done < "$ROOT/prometheus/queries.tsv"
}
printf 'FH2 diagnostics %s\nMode: %s\nHost: %s\nStarted: %s\nUID: %s\nTimezone: %s\nRequested history: %s to %s\n' \
  "$VERSION" "$MODE" "$(hostname)" "$(date -Is)" "$EUID" "$(date '+%Z %z')" "$FROM" "$TO" > "$ROOT/summary.txt"
printf '\nCurrent snapshots are NOT historical fault-time metrics.\nHistorical metrics require previously enabled retention.\nLogs may contain personal data or secrets despite masking. REVIEW BEFORE SHARING.\nNo Secrets, kubeconfig, process environments or full deployment configurations are collected.\n' >> "$ROOT/summary.txt"
(( EUID == 0 )) || note permissions 'Non-root: some collectors may fail or return incomplete data'
(( END <= $(date +%s) )) || note history 'Requested end time is in the future'
trap 'note interrupted "Collection interrupted; partial directory retained"; printf "[中断] 已保留部分结果:%s\n" "$ROOT"; exit 130' INT TERM

run os.txt 15 cat /etc/os-release
run kernel.txt 15 uname -a
run time.txt 15 timedatectl
run uptime.txt 15 uptime
run cpu.txt 15 lscpu
run memory.txt 15 free -h
run disks.txt 15 lsblk -o NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT
run space.txt 15 df -hT
run inodes.txt 15 df -hi
run processes.txt 15 ps -eo pid,ppid,comm,pcpu,pmem,rss,stat --sort=-rss
run gpu.txt 20 nvidia-smi --query-gpu=name,driver_version,memory.total,memory.used,utilization.gpu,temperature.gpu --format=csv
run addresses.txt 15 ip -br address
run routes.txt 15 ip route show table all
run dns.txt 15 resolvectl status
run listeners.txt 15 ss -lntup
run connections-summary.txt 15 ss -s
run ufw.txt 15 ufw status verbose
run nft.txt 20 nft list ruleset
run iptables.txt 20 iptables-save
run failed-services.txt 15 systemctl --failed --no-pager
run services.txt 20 systemctl list-units --all --type=service --no-pager
run sysstat-timer.txt 15 systemctl status sysstat-collect.timer --no-pager
# Epoch timestamps avoid systemd timezone parsing differences.
run kernel-history.txt 30 journalctl _TRANSPORT=kernel --since "@$START" --until "@$END" --no-pager -o short-iso
run system-warnings-history.txt 30 journalctl --since "@$START" --until "@$END" -p warning --no-pager -o short-iso
for unit in k3s k3s-agent flighthub2-mgmt flighthub2-diag; do
  run "journal-$unit.txt" 30 journalctl -u "$unit" --since "@$START" --until "@$END" --no-pager -o short-iso
done

KUBE=()
if command -v kubectl >/dev/null 2>&1; then KUBE=(kubectl "--cache-dir=$ROOT/kube-cache")
elif command -v k3s >/dev/null 2>&1; then KUBE=(k3s kubectl "--cache-dir=$ROOT/kube-cache")
fi
run k3s-version.txt 15 k3s --version
if (( ${#KUBE[@]} )); then
  run nodes.txt 30 "${KUBE[@]}" --request-timeout=20s get nodes -o wide
  run node-conditions.txt 30 "${KUBE[@]}" --request-timeout=20s get nodes -o 'custom-columns=NAME:.metadata.name,CONDITIONS:.status.conditions[*].type,VALUES:.status.conditions[*].status'
  run pods.txt 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" get pods -o wide
  run pod-state.txt 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" get pods -o 'custom-columns=POD:.metadata.name,CONTAINER:.status.containerStatuses[*].name,RESTARTS:.status.containerStatuses[*].restartCount,LAST_REASON:.status.containerStatuses[*].lastState.terminated.reason,WAITING:.status.containerStatuses[*].state.waiting.reason,IMAGE:.spec.containers[*].image'
  run workloads.txt 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" get deployments,statefulsets,daemonsets
  run k8s-services.txt 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" get services -o wide
  run events.txt 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" get events --sort-by=.metadata.creationTimestamp
  run top-nodes-current.txt 30 "${KUBE[@]}" --request-timeout=20s top nodes
  run top-pods-current.txt 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" top pods --containers
  if (( POD_LOGS )); then
      mkdir "$ROOT/pod-logs" || die 'Cannot create pod log directory'
      progress '开始' pod-log-list
      pods=$(timeout --kill-after=5s 25s "${KUBE[@]}" --request-timeout=20s -n "$NS" get pods -o name 2> "$ROOT/pod-list-error.txt")
      rc=$?
      note pod-log-list "exit=$rc; first $MAX_PODS pods only; each current/previous file capped at 5 MiB"
      count=0
      while IFS= read -r pod; do
          [[ $pod =~ ^pod/[a-z0-9.-]+$ ]] || continue
          (( count >= MAX_PODS )) && break
          count=$((count + 1))
          run "pod-logs/${pod#pod/}-current.txt" 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" logs "$pod" --all-containers=true --prefix=true --timestamps=true --since-time="$(date -u -d "@$START" +%Y-%m-%dT%H:%M:%SZ)" --tail=3000 --limit-bytes="$LIMIT"
          run "pod-logs/${pod#pod/}-previous.txt" 30 "${KUBE[@]}" --request-timeout=20s -n "$NS" logs "$pod" --all-containers=true --prefix=true --previous=true --timestamps=true --since-time="$(date -u -d "@$START" +%Y-%m-%dT%H:%M:%SZ)" --tail=3000 --limit-bytes="$LIMIT"
      done <<< "$pods"
      note pod-logs 'Limited per-container tail, not a complete time-window export. No until filter; may include AFTER end. Rotation/removed Pods may make older records unavailable.'
  fi
else
  note kubernetes 'SKIPPED: kubectl and k3s unavailable'
fi

# saDD is ambiguous across months: verify the date stored inside before using it.
mkdir "$ROOT/history" || die 'Cannot create history directory'
if command -v sar >/dev/null 2>&1; then
  printf '[开始] 检查指定时段已有的 sar 历史记录。\n'
  day=$(date -d "@$START" +%F)
  last=$(date -d "@$END" +%F)
  while :; do
      found=0
      for base in /var/log/sysstat /var/log/sa; do
          for name in "sa${day//-/}" "sa${day:8:2}"; do
              path=$base/$name
              [[ -r $path ]] || continue
              header=$(timeout --kill-after=5s 5s sar -u -f "$path" 2>/dev/null | head -n 1)
              if [[ $header != *"$day"* && $header != *"${day:5:2}/${day:8:2}/${day:0:4}"* ]]; then
                  note "history/$day" "SKIPPED ambiguous archive date: $path"
                  continue
              fi
              s=00:00:00; e=23:59:59
              [[ $day == $(date -d "@$START" +%F) ]] && s=$(date -d "@$START" +%T)
              [[ $day == "$last" ]] && e=$(date -d "@$END" +%T)
              run "history/sar-$day.txt" 30 sar -A -f "$path" -s "$s" -e "$e"
              found=1
              break
          done
          (( found )) && break
      done
      (( found )) || note "history/$day" 'NO VERIFIED SAR DATA: not recorded, unavailable, date mismatch or expired'
      [[ $day == "$last" ]] && break
      day=$(date -d "$day +1 day" +%F)
  done
else
  note sar 'SKIPPED: sysstat/sar not installed; historical load cannot be reconstructed'
fi
note historical-monitoring 'Prometheus is queried only with an explicit URL after base collection; atop is not auto-queried. Historical monitoring is not enabled.'
if [[ -n $PACKAGE ]]; then
  run package-hash.txt 300 sha256sum "$PACKAGE"
  run package-list.txt 60 tar -tf "$PACKAGE"
  note package 'Archive only listed/hashed; absence of K3s in an incremental package does NOT prove corruption'
fi

if [[ $MODE == watch ]]; then
  mkdir "$ROOT/watch" || die 'Cannot create watch directory'
  deadline=$(( $(date +%s) + DURATION ))
  count=0
  printf '\nWatch begins: %s; duration=%s seconds; interval=%s seconds; no CPU/GPU stress test.\n' "$(date -Is)" "$DURATION" "$INTERVAL" >> "$ROOT/summary.txt"
  printf '[实时采样] 现在可以复现问题。目标间隔 %s 秒,持续 %s 秒。\n' "$INTERVAL" "$DURATION"
  while (( $(date +%s) < deadline && count < 2000 )); do
      if ! space_ok; then
          note watch 'STOPPED: output budget/space limit reached or disk check failed'
          break
      fi
      count=$((count + 1))
      printf '[采样] 第 %s 轮,时间:%s\n' "$count" "$(date -Is)"
      sample_start=$(date +%s)
      prefix="watch/$(printf '%04d' "$count")"
      run "$prefix-memory.txt" 5 free -m
      run "$prefix-vmstat.txt" 5 vmstat 1 2
      run "$prefix-io.txt" 5 iostat -dx 1 2
      run "$prefix-processes.txt" 5 ps -eo pid,ppid,comm,pcpu,pmem,rss,stat --sort=-pcpu
      run "$prefix-net.txt" 5 ip -s link
      remaining=$((deadline - $(date +%s)))
      wait_s=$((sample_start + INTERVAL - $(date +%s)))
      (( wait_s > remaining )) && wait_s=$remaining
      (( wait_s > 0 )) && sleep "$wait_s"
  done
  note watch "Finished $count samples; interval is a target, slow commands can extend it; process CPU from ps is lifetime average"
  WATCH_FROM="@$((deadline - DURATION))"
  run watch-kernel-events.txt 30 journalctl _TRANSPORT=kernel --since "$WATCH_FROM" --no-pager -o short-iso
  run watch-system-warnings.txt 30 journalctl --since "$WATCH_FROM" -p warning --no-pager -o short-iso
  for unit in k3s k3s-agent flighthub2-mgmt flighthub2-diag; do
      run "watch-journal-$unit.txt" 30 journalctl -u "$unit" --since "$WATCH_FROM" --no-pager -o short-iso
  done
fi
collect_prometheus
printf '\nFinished: %s\nReview status.tsv for missing, failed and truncated data.\n' "$(date -Is)" >> "$ROOT/summary.txt"
# Keep the archive in the private directory, not at a predictable /var/tmp path.
ARCHIVE=$ROOT/bundle.tar.gz
free_kb=$(df -Pk "$ROOT" | awk 'END {print $4}')
used_kb=$(du -sk "$ROOT" | awk '{print $1}')
[[ $free_kb =~ ^[0-9]+$ && $used_kb =~ ^[0-9]+$ ]] && (( free_kb > used_kb + 102400 )) || die "Insufficient packaging space; results retained: $ROOT"
: > "$ARCHIVE" || die 'Cannot create archive'
printf '[打包] 正在生成压缩包:%s\n' "$ARCHIVE"
if timeout --kill-after=5s 300s tar --exclude='./bundle.tar.gz' -czf "$ARCHIVE" -C "$ROOT" .; then
  chmod 600 "$ARCHIVE"
  printf '[结束] 本次采集流程已完成,缺项和失败信息请查看 status.tsv。\n诊断目录:%s\n压缩包:%s\n发送前请人工检查并脱敏。\n' "$ROOT" "$ARCHIVE"
else
  printf '[打包失败] 可能存在不完整压缩包;采集结果已保留:%s\n' "$ROOT" >&2
  exit 1
fi

执行前确认#

1.
脚本执行期间会占用服务器资源,不要安排在作业期间,放到业务低峰期做。
2.
脚本会以 ZIP 文件名新建一条高程记录,启用新高程、停用其他已启用的记录,还会把高程存储桶设为匿名下载。执行前确认现场能接受,并确认现有高程数据已有备份。
3.
在存放高程 ZIP 的集群节点上跑,导入任务会调度到该节点。需要 Python3、kubectl 和集群操作权限。
4.
节点内存要够:/dev/shm 可用空间不小于高程包解压后大小的 3 倍,可用内存不小于 6 倍(下限分别为 1 GiB、2 GiB),用 df -h /dev/shm、free -h 查看。不满足时,脚本在改动前退出。
5.
高程包为 ZIP,路径为 terrain/global_ellipsoid/,含 layer.json 和 .terrain 瓦片(EPSG:4326、quantized-mesh-1.0)。不符合时,脚本在校验阶段退出,不会修改现场。
6.
脚本只支持使用集群本地存储(Longhorn)的部署。自动扩容需要存储支持在线扩容(不停服务直接增加容量),不支持时脚本会提示错误并停止,需要联系技术支持处理。
7.
旧记录还卡在“处理中”的,先确认原来的导入任务和管理服务的处理都已结束(方法见《按现象排查》「六、复位并重新导入高程」的步骤 1),再在“底图服务 → 高程设置”页面把它停用,确认变成“已停用”后跑脚本;不停用的话,脚本要等上传、解压完才会报错退出。
8.
不要用“删除”代替“停用”,删除会把原上传包一起清掉。

执行并等待完成#

把 import-elevation 换成实际的脚本文件名,在脚本所在目录执行;<高程包.zip的绝对路径> 填本地高程 ZIP 文件的完整绝对路径,脚本只接收这一个参数:
chmod +x 在首次执行时赋予可执行权限;sudo -v 先验证 sudo 密码,避免后台运行时卡在密码输入;nohup … & 让脚本在后台运行,SSH 断开后不会中断,日志写入 elevation-import.log。
查看进度,按 Ctrl+C 退出查看,不影响脚本运行:
导入任务最长运行 7500 秒(约 2 小时 5 分),源包上传最长 15 分钟,超时即失败。
脚本运行期间,不要在页面对高程做启用、停用或删除操作。

验证结果#

1.
跑完后看两处:日志里有 enabled and readable;司空页面显示“已启用”,没有红色错误提示。
2.
脚本失败就把 elevation-import.log 留下来联系技术支持,不建议反复跑脚本,可能并不解决问题。
3.
脚本被中断的,可能残留导入锁和“处理中”记录,重复运行会失败,同样联系技术支持。
4.
脚本导入的问题以 elevation-import.log 为准,不要套用《按现象排查》里的任务名、Pod 名、容器名。
5.
脚本运行期间会加锁,避免同时执行多次;拿不准的先联系技术支持。

三、仍未解决时联系技术支持#

已按上述各节处理但问题仍在的,联系技术支持时请一并提供:
1.
基本背景:导入开始的时间、已等待的总耗时,以及高程包的大致数据量。
2.
自检命令输出:「一、刷新页面并判断问题类型」中 4 条命令的完整终端输出。
3.
关键日志:
使用页面导入的:对应 Pod 的 import 容器日志(logs $POD -c import --tail=300)及管理服务日志。
使用脚本导入的:elevation-import.log 的完整内容。
发送前遮盖密码、Token 等敏感信息。
修改于 2026-11-30 08:42:42
上一页
【部署安装】KylinSecOS指纹文件生成失败
下一页
【日常运维】高程导入卡在“处理中”或启用失败:按现象排查
Built with