record

package
v2.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package record 实现终端会话的**客户端侧**记录:终端上显示什么就记录什么。

设计要点:

  • 记录只写在运行终端的主机本地(Agent 数据目录),服务端数据库与审计日志永不保存终端内容(INV-M4);
  • 记录的是 PTY 的输出字节流(包含 shell 对键入内容的回显),外加窗口尺寸变化与时间标记; 没有独立的按键流,也不做口令屏蔽——关闭回显的口令输入自然不会出现,显示出来的一切都会被记录;
  • 写盘走异步队列,任何磁盘问题(写满、权限、变慢)都只会让记录出现「缺口」,绝不影响终端本身;
  • 文件按 1 MiB 分段,封存后的分段在后台压缩;单会话滚动配额、整机配额、保留期与低磁盘保护均可配置。

文件布局(目录 0700、文件 0600):

<Dir>/sessions/<sid>/meta.json        会话元数据(创建时写入,结束时更新)
<Dir>/sessions/<sid>/index.jsonl      追加式日志:分段起止、压缩、清理与缺口
<Dir>/sessions/<sid>/seg-000001.rec   原始分段(封存后被压缩为 .rec.gz)

Index

Constants

View Source
const (

	// MaxEventPayload 是单个事件净荷的上限;更长的输出会被切成多个事件。
	MaxEventPayload = 32 << 10

	// MaxPageBytes 是单次读取返回的字节上限。
	MaxPageBytes = 48 << 10
)
View Source
const (
	KindOutput byte = 1 // 终端显示的输出字节(含 shell 对键入内容的回显)
	KindResize byte = 2 // 窗口尺寸变化:rows u16 BE + cols u16 BE
	KindMark   byte = 3 // 标记:JSON(见 Mark)
)

事件类别。

View Source
const (
	MarkSeg = "seg" // 分段起点:带绝对时间与当前窗口尺寸
	MarkGap = "gap" // 缺口:这一段时间内的输出没有被记录
	MarkEnd = "end" // 会话结束
)

标记类型(Mark.T)。

View Source
const (
	GapBacklog    = "backlog"     // 写盘跟不上,队列溢出
	GapDiskLow    = "disk_low"    // 磁盘剩余空间低于保护线
	GapWriteError = "write_error" // 写文件失败
	GapPolicyOff  = "policy_off"  // 服务端策略临时关闭了录制
)

缺口原因(Mark.Reason / 会话状态)。

View Source
const (
	DefaultSegmentBytes = 1 << 20
	DefaultSessionBytes = 64 << 20
	DefaultHostBytes    = 512 << 20
	DefaultRetention    = 30 * 24 * time.Hour
	DefaultMinFree      = 1 << 30
)

默认容量与保留策略(均可通过 Options 调整)。

View Source
const (
	StateOn        = "on"        // 正在录制
	StatePaused    = "paused"    // 暂停:磁盘不足或服务端策略临时关闭,恢复后会补缺口标记
	StateError     = "error"     // 写文件失败,重试中
	StateOff       = "off"       // 服务端策略关闭了录制,本会话没有录
	StateVeto      = "veto"      // 本机以 --no-record 一票否决
	StateIncognito = "incognito" // 创建会话时选择了无痕
)

会话的录制状态(SessionInfo.Rec)。

Variables

View Source
var ErrNotFound = errors.New("record: not found")

ErrNotFound 表示没有这个会话的记录(从未录制、已被清理或已过保留期)。

Functions

func AppendEvent

func AppendEvent(dst []byte, kind byte, dtMS uint64, payload []byte) []byte

AppendEvent 把一个事件编码追加到 dst:kind(1) | dt uvarint | len uvarint | 净荷。

func DecodeResize

func DecodeResize(p []byte) (rows, cols uint16, ok bool)

DecodeResize 解出 KindResize 事件的净荷。

func ValidSID

func ValidSID(sid string) bool

ValidSID 判断会话 ID 是否合法(128 位小写十六进制)。路径拼接前必须校验,杜绝目录穿越。

Types

type Event

type Event struct {
	Kind    byte
	DT      uint64 // 距上一个事件的毫秒数(分段内第一个事件为 0)
	Payload []byte
}

Event 是解码后的一个事件。

func DecodeEvent

func DecodeEvent(data []byte) (Event, int, error)

DecodeEvent 从 data 开头解出一个完整事件,返回事件与消耗的字节数。 数据不足一个完整事件时返回 errShortEvent(写入中的分段尾部属于正常情况)。

func DecodeEvents

func DecodeEvents(data []byte) ([]Event, int, error)

DecodeEvents 尽可能多地解出完整事件,返回事件列表与消耗的字节数;遇到损坏数据返回错误。

type Info

type Info struct {
	SID          string    `json:"sid"`
	Name         string    `json:"name,omitempty"`
	Shell        string    `json:"shell,omitempty"`
	CreatedMS    int64     `json:"created_ms"`
	EndedMS      int64     `json:"ended_ms,omitempty"`
	EndedReason  string    `json:"ended_reason,omitempty"`
	ExitCode     *int      `json:"exit_code,omitempty"`
	Signal       string    `json:"signal,omitempty"`
	Rows         uint16    `json:"rows,omitempty"` // 会话创建时的窗口尺寸
	Cols         uint16    `json:"cols,omitempty"`
	FirstMS      int64     `json:"first_ms,omitempty"`
	LastMS       int64     `json:"last_ms,omitempty"`
	RawBytes     int64     `json:"raw_bytes"`
	DiskBytes    int64     `json:"disk_bytes"`
	DroppedBytes int64     `json:"dropped_bytes,omitempty"` // 因配额被清理或因缺口丢失的字节数
	Gap          bool      `json:"gap,omitempty"`           // 记录不完整(开头被清理或中途有缺口)
	Head         bool      `json:"head,omitempty"`          // 最早的分段不是第 1 段:更早内容已被清理
	Segments     []SegInfo `json:"segments"`
}

Info 是一个会话记录的索引信息(不含任何终端内容)。

type Mark

type Mark struct {
	T      string `json:"t"`
	Seq    uint32 `json:"seq,omitempty"`    // seg:分段序号
	T0     int64  `json:"t0,omitempty"`     // seg:分段起点的绝对时间(Unix 毫秒)
	Rows   uint16 `json:"rows,omitempty"`   // seg:此刻的窗口尺寸
	Cols   uint16 `json:"cols,omitempty"`   // seg:此刻的窗口尺寸
	Reason string `json:"reason,omitempty"` // gap:原因;end:结束原因
	Bytes  int64  `json:"bytes,omitempty"`  // gap:丢失的输出字节数(尽力统计)
	Code   *int   `json:"code,omitempty"`   // end:退出码
	Signal string `json:"signal,omitempty"` // end:终止信号
}

Mark 是 KindMark 事件的 JSON 净荷。

func DecodeMark

func DecodeMark(p []byte) (Mark, bool)

DecodeMark 解出 KindMark 事件的净荷。

type Meta

type Meta struct {
	V           int    `json:"v"`
	SID         string `json:"sid"`
	Name        string `json:"name,omitempty"`
	Shell       string `json:"shell,omitempty"`
	CreatedMS   int64  `json:"created_ms"`
	Rows        uint16 `json:"rows,omitempty"`
	Cols        uint16 `json:"cols,omitempty"`
	EndedMS     int64  `json:"ended_ms,omitempty"`
	EndedReason string `json:"ended_reason,omitempty"`
	ExitCode    *int   `json:"exit_code,omitempty"`
	Signal      string `json:"signal,omitempty"`

	// Incognito 只是 Begin 的输入:无痕会话根本不会落盘,所以不写入文件。
	Incognito bool `json:"-"`
}

Meta 是 meta.json 的内容。

type Options

type Options struct {
	// Dir 是记录根目录(通常是 <数据目录>/records)。
	Dir string
	// Disabled 是本机一票否决:不录制任何会话(已有记录仍可读取,直到过期)。
	Disabled bool

	SegmentBytes int64         // 分段大小,默认 1 MiB
	SessionBytes int64         // 单会话保留的原始字节上限,默认 64 MiB(滚动,丢弃最旧分段)
	SessionLines int64         // 单会话至少保留最近多少行输出(按换行符计;超出后滚动丢弃最旧分段,实际多保留不超过一个分段);0 = 不限制(默认)
	HostBytes    int64         // 整机磁盘占用上限,默认 512 MiB
	Retention    time.Duration // 会话结束后的保留期,默认 30 天
	MinFree      int64         // 磁盘剩余空间低于此值停止录制,默认 1 GiB;负数表示关闭保护
	QueueBytes   int64         // 每会话异步队列的字节上限,默认 4 MiB
	FlushEvery   time.Duration // 缓冲刷盘间隔,默认 250 ms
	GCInterval   time.Duration // 保留期与配额清理的周期,默认 10 分钟
	NoCompress   bool          // 关闭后台压缩(测试用)

	// RecoverReason 是启动时对「上次未正常收尾」的会话写入的结束原因,默认 holder_exit。
	RecoverReason string
	// DeferRecover 为 true 时 Open 不做启动恢复,由调用方在弄清每个会话的结束原因之后调用 Recover。
	DeferRecover bool

	Now       func() time.Time
	FreeSpace func(dir string) (uint64, error)
	// Harden 在目录创建之后收紧访问权限(Windows 上设置 ACL);Unix 上目录权限已是 0700。
	Harden func(dir string) error
	Logf   func(format string, args ...any)
}

Options 是记录存储的配置。零值字段取默认值。

type Page

type Page struct {
	Data    []byte `json:"-"`
	Seg     uint32 `json:"seg"` // 本页数据实际起点所在分段
	Off     uint32 `json:"off"` // 本页数据在该分段(解压后,含 4 字节文件头)内的偏移
	NextSeg uint32 `json:"next_seg"`
	NextOff uint32 `json:"next_off"`
	// EOF 表示已读到当前记录的末尾(会话仍在运行时之后可能还有新数据)。
	EOF bool `json:"eof"`
	// Skipped 表示请求的起点已被清理,数据从最早保留的分段开头开始。
	Skipped bool `json:"skipped,omitempty"`
}

Page 是一次读取的结果:若干个完整事件的原始编码(与分段文件里的编码完全一致)。

type Policy

type Policy struct {
	Off           bool
	RetentionDays int
	SessionBytes  int64
	SessionLines  int64
	HostBytes     int64
}

Policy 是服务端下发的录制策略:只能比本机配置更严格——可以关闭、缩短保留、降低配额, 永远不能强制开启或放宽。

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Reader 是记录目录的只读视图:不启动任何后台任务,也不会修改任何文件。 Agent 进程用它读取守护进程写下的记录(守护进程停止时历史记录仍可读取)。

func NewReader

func NewReader(dir string) *Reader

NewReader 打开记录根目录(与 Options.Dir 相同)的只读视图。

func (*Reader) Info

func (r *Reader) Info(sid string) (*Info, error)

Info 返回会话记录的索引信息。

func (*Reader) List

func (r *Reader) List() []*Info

List 返回全部会话记录的索引信息(按创建时间升序)。

func (*Reader) Read

func (r *Reader) Read(sid string, seg, off uint32, max int) (*Page, error)

Read 读取一页记录内容,见 readPage。

type SegInfo

type SegInfo struct {
	Seq  uint32 `json:"seq"`
	T0   int64  `json:"t0"`             // 起点(Unix 毫秒)
	T1   int64  `json:"t1,omitempty"`   // 终点(Unix 毫秒)
	Raw  int64  `json:"raw"`            // 解压后的字节数
	Disk int64  `json:"disk"`           // 实际占用的磁盘字节数
	Rows uint16 `json:"rows,omitempty"` // 分段起点处的窗口尺寸
	Cols uint16 `json:"cols,omitempty"`
	Gz   bool   `json:"gz,omitempty"`
}

SegInfo 描述一个仍保留的分段。

type Stats

type Stats struct {
	State    string // on | paused | error
	Reason   string // 暂停 / 出错的原因(Gap* 常量)
	Raw      int64  // 当前保留的原始字节数(含正在写的分段)
	FirstMS  int64  // 最早保留内容的时间(Unix 毫秒)
	LastMS   int64  // 最近一次写入的时间
	Gap      bool   // 记录不完整
	Dropped  int64  // 累计丢失 / 被清理的字节数
	Segments int
}

Stats 是一个会话录制状态的快照(原子读取,可在持有其他锁时调用)。

func (Stats) String

func (s Stats) String() string

String 便于日志与测试。

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store 管理一台主机上的全部会话记录。

func Open

func Open(o Options) (*Store, error)

Open 打开(必要时创建)记录存储:收紧目录权限、收尾上次遗留的会话、启动后台压缩与清理。

func (*Store) Begin

func (s *Store) Begin(m Meta) (w *Writer, state string)

Begin 为新会话开始录制。返回的 Writer 可能为 nil(nil 的 Writer 上所有方法都是无操作), 此时 state 说明原因:veto(本机否决)/ off(服务端策略关闭)/ incognito(无痕)/ error(目录不可写)。

func (*Store) Close

func (s *Store) Close()

Close 收尾仍在录制的会话并停止后台任务。

func (*Store) Delete

func (s *Store) Delete(sid string) error

Delete 删除一个已结束会话的全部记录;仍在录制的会话不可删除。

func (*Store) Disabled

func (s *Store) Disabled() bool

Disabled 报告本机是否以一票否决关闭了录制。

func (*Store) Info

func (s *Store) Info(sid string) (*Info, error)

Info 返回会话记录的索引信息;会话仍在录制时先刷盘,让结果包含最新内容。

func (*Store) List

func (s *Store) List() []*Info

List 返回全部会话记录的索引信息(按创建时间升序)。

func (*Store) Read

func (s *Store) Read(sid string, seg, off uint32, max int) (*Page, error)

Read 读取一页记录内容,见 readPage。

func (*Store) Reader

func (s *Store) Reader() *Reader

Reader 返回只读视图。

func (*Store) Recover

func (s *Store) Recover(reasonFor func(sid string) string)

Recover 收尾上次没有正常结束的会话(进程被杀、断电):补上结束时间与原因,使其进入保留期计时。 reasonFor 可按会话给出更精确的结束原因(例如主机重启);返回空串或为 nil 时取 Options.RecoverReason。

func (*Store) SessionDir

func (s *Store) SessionDir(sid string) string

SessionDir 返回会话记录目录(不检查是否存在)。sid 必须通过 ValidSID。

func (*Store) SessionLineLimit

func (s *Store) SessionLineLimit() int64

SessionLineLimit 是生效的单会话行数上限:本机配置与服务端策略都为正时取较小者,只有一方为正时取那一方, 都没设则为 0(不限制)。服务端只能收紧、不能放宽——本机设了上限,策略再大也不会让它变松。

func (*Store) SetPolicy

func (s *Store) SetPolicy(p Policy)

SetPolicy 应用服务端策略。关闭录制会让正在录制的会话暂停(之后恢复时补缺口标记); 配额与保留期变严会立即触发一次清理。

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer 把一个会话的终端显示内容异步写入记录。

所有写入方法都是非阻塞的:队列满时丢弃并在记录里留下「缺口」标记;磁盘错误只会让记录暂停, 绝不会向调用方(PTY 读循环)传播。*Writer 为 nil 时全部方法都是无操作。

func (*Writer) End

func (w *Writer) End(code *int, signal, reason string)

End 结束录制:写入结束标记、封存最后一个分段、在 meta.json 里记下结束时间与原因。 最多等待数秒,写协程卡住也不会拖住调用方。

func (*Writer) Flush

func (w *Writer) Flush()

Flush 等待已入队的事件写入并刷盘(读取进行中会话的记录前调用,让读者看到最新内容)。

func (*Writer) Output

func (w *Writer) Output(p []byte)

Output 记录一段终端输出。p 会被复制,调用方可以立即复用。

func (*Writer) Resize

func (w *Writer) Resize(rows, cols uint16)

Resize 记录窗口尺寸变化。

func (*Writer) SetName

func (w *Writer) SetName(name string)

SetName 更新会话名称(写入 meta.json)。

func (*Writer) Stats

func (w *Writer) Stats() Stats

Stats 返回当前录制状态。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL