#!/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