Documentation
¶
Overview ¶
Package nas 是首页「NAS 概览」与设置页「NAS 监控」的数据层(首页 NAS 概览 H2):来源类型的注册表、地址与传输规则、 证书钉住、本机来源与采集器。
只依赖标准库、github.com/coder/websocket 与 internal/redact:读写数据库、解密密钥在 cmd(nas_wiring.go), 接口在 web(api_nas.go)。采集到的数据只在内存里:最新一份快照与最近 60 拍的历史,重启清空。
Index ¶
- Constants
- Variables
- func CheckTransport(k Kind, u *url.URL, sendsCredentials, ack bool) error
- func DecodeExtra(text string) (map[string]string, error)
- func EncodeExtra(extra map[string]string) (string, error)
- func Fingerprint(cert *x509.Certificate) string
- func HTTPClient(u *url.URL, pin string, timeout time.Duration) *http.Client
- func NormalizePin(pin string) string
- func ParseURL(kindName, raw string) (*url.URL, error)
- func RegisterKind(k Kind) (unregister func())
- func TLSConfig(host, pin string, roots *x509.CertPool) *tls.Config
- func Transport(u *url.URL, pin string, roots *x509.CertPool) *http.Transport
- func ValidPin(pin string) bool
- type Alert
- type Apps
- type AuthError
- type CPU
- type CertError
- type CertInfo
- type Collector
- func (c *Collector) Close(ctx context.Context) error
- func (c *Collector) List() []Status
- func (c *Collector) Reload(ctx context.Context, id string) error
- func (c *Collector) Retry(ctx context.Context, id string) (Status, error)
- func (c *Collector) Start(ctx context.Context)
- func (c *Collector) Stop(ctx context.Context) error
- type Config
- type Disk
- type ExtraSource
- type Facet
- type HistorySource
- type Kind
- type Local
- type Memory
- type Network
- type Pending
- type PendingKey
- type PlainRule
- type Pool
- type Sample
- type Snapshot
- type Source
- type SourceConfig
- type Status
- type System
- type TestInput
- type TestResult
Constants ¶
const ( StateOK = "ok" StateConnecting = "connecting" StateError = "error" StateAuthFailed = "auth_failed" StateCertUntrusted = "cert_untrusted" StateCertChanged = "cert_changed" StateDisabled = "disabled" StateUnsupported = "unsupported" )
来源的状态(Status.State)。
const ( FacetSystem = "system" FacetCPU = "cpu" FacetCPUTemp = "cpu_temp" FacetMemory = "memory" FacetNetwork = "network" FacetPools = "pools" FacetDisks = "disks" FacetAlerts = "alerts" FacetApps = "apps" )
快照里各类数据的键(Snapshot.Facets):界面据此写「这个来源读不到硬盘温度」,不把没有当成 0。
const ( FacetOK = "ok" // FacetUnsupported 是这个来源没有这类数据(本机读不到存储池、虚拟机没有 CPU 温度) FacetUnsupported = "unsupported" // FacetDenied 是账号没有读这类数据的权限 FacetDenied = "denied" // FacetError 是读的时候出错了(这一次) FacetError = "error" )
一类数据读没读到(Facet.Status)。
const ( DiskHDD = "hdd" DiskSSD = "ssd" DiskNVMe = "nvme" DiskUnknown = "unknown" )
硬盘的类型(Disk.Kind)。
const ( AlertCritical = "critical" AlertWarning = "warning" AlertInfo = "info" )
告警的级别(Alert.Level)。
const ( UsernameNone = "" UsernameOptional = "optional" UsernameRequired = "required" )
表单里用户名一栏(Kind.Username)。
const (
// HistoryLen 是内存里留几拍历史(30 秒一拍,约 30 分钟)
HistoryLen = 60
)
const KindFnOS = "fnos"
KindFnOS 是飞牛 fnOS 来源(实验性:只用假服务测过,没在真机上验证):飞牛网页用的 WebSocket 接口(飞牛没有公开它的 文档),用账号密码登录,开了两步验证的账号第一次测试时填验证码。登录得到的 token 与签名密钥加密存下,之后用它们连接, token 过期时用 longToken 换新的,都不行时才再用密码登录。
协议在 fnos_protocol.go,读哪些数据、怎么映射在 fnos_data.go。
const KindGlances = "glances"
KindGlances 是 Glances 来源:Glances 4.x 的 REST 接口(http(s)://主机:61208/api/4/<插件>)。Glances 是通用的系统监控, 群晖、飞牛、Unraid、OMV 等能跑 Docker 的 NAS 用官方镜像跑它就能接入。默认不开认证;开了时用 HTTP Basic, 用户名默认是 glances。
const KindSynology = "synology"
KindSynology 是群晖 DSM 来源(实验性:只用假服务测过,没在真机上验证):DSM 的 Web API(/webapi/*.cgi), 用账号密码登录,开了两步验证的账号第一次测试时填验证码,之后带设备令牌登录。
请求与回应照 py-synologydsm-api(Home Assistant 的群晖集成用它)与 Homarr 的群晖集成记录的格式写,没有搬它们的代码: 先用 SYNO.API.Info 查各接口的路径与版本,再用 SYNO.API.Auth 登录拿会话(sid),之后的请求都带上它。
const KindTrueNAS = "truenas"
KindTrueNAS 是 TrueNAS 来源:经 wss://主机/api/current 的 JSON-RPC 2.0(TrueNAS 25.04 起),用只读管理员账号的 API Key 登录,每条连接登录一次。证书不认时在握手阶段就断开、不发 Key;只收 https://(经 http 用过的 Key 会被 TrueNAS 吊销)。
const LocalID = "local"
LocalID 是本机来源在列表与设置里的编号(数据库里的来源是数字编号)。
const LocalKind = "local"
LocalKind 是本机来源的类型名。
const LocalSupported = true
LocalSupported 是这个平台能不能用本机来源(只有 Linux 有 /proc 与 /sys)。
const PendingTTL = 10 * time.Minute
PendingTTL 是测试连接产生的新凭据在内存里留多久(等用户点保存)。
Variables ¶
var ( // ErrAuth 是认证失败(具体原因见 *AuthError)。 ErrAuth = errors.New("认证失败") // ErrCertUntrusted 是证书链校验不过、也没有钉住的指纹(自签证书要在设置页确认)。 ErrCertUntrusted = errors.New("证书不受信任,要在「NAS 监控」里确认这张证书") // ErrCertChanged 是证书和钉住的那张不一样。 ErrCertChanged = errors.New("证书和信任的那张不一样(证书换了?)") // ErrUnsupported 是这个来源在这里用不了(本机来源只支持 Linux)。 ErrUnsupported = errors.New("本机来源只支持 Linux") )
var ErrNoLoop = errors.New("这个来源没有在采集(停用了或设置有问题),改好设置以后会自动重连")
ErrNoLoop 是这个来源没有在采集(停用了、设置有问题或这个版本不支持),「重新连接」没有用。
var ErrNotFound = errors.New("没有这个来源")
ErrNotFound 是没有这个来源。
var ErrPendingInvalid = errors.New("测试结果过期了,请再测一次")
ErrPendingInvalid 是保存时带的测试结果过期了、用过了,或者不是给这组地址与账号的。
var ErrPlainNeedsAck = errors.New("要用 http:// 连接并发送账号密码,先勾选「我知道账号密码会以明文经过局域网,可能被截获」,或者改用 https://")
ErrPlainNeedsAck 是要以明文(http://)发出凭据、而用户没有确认风险。
var FacetKeys = []string{FacetSystem, FacetCPU, FacetCPUTemp, FacetMemory, FacetNetwork, FacetPools, FacetDisks, FacetAlerts, FacetApps}
FacetKeys 是全部的键,按界面上的顺序。
Functions ¶
func CheckTransport ¶
CheckTransport 按这一次实际要发出的凭据校验传输(3.2.3):https:// 总可以;http:// 按这种来源的规则, sendsCredentials 是这次会不会发出账号、密码或令牌,ack 是用户这一次勾没勾明文风险。
func DecodeExtra ¶
DecodeExtra 解开 EncodeExtra 的结果(空串是没有)。
func EncodeExtra ¶
EncodeExtra 是来源的长期凭据(群晖的设备令牌、飞牛的 token)存进库里以前的样子:JSON 对象,没有时是空串。 加密由调用方做(cmd 的采集器写回与 web 的保存都经它,格式只有这一份)。
func Fingerprint ¶
func Fingerprint(cert *x509.Certificate) string
Fingerprint 是一张证书(DER)的 SHA-256,小写十六进制。
func HTTPClient ¶
HTTPClient 是连一个来源用的 HTTP 客户端:证书按 TLSConfig 校验、不走代理(NAS 在局域网里,环境变量里的代理是给 tracker 用的,不让 API Key 经过它),不跟随重定向(重定向可能把凭据带到别的主机),单次请求最多 timeout。
func NormalizePin ¶
NormalizePin 把用户或证书确认带来的指纹规范成小写十六进制(去掉冒号与空白)。
func ParseURL ¶
ParseURL 规范化一种来源的地址(保存与测试共用):去掉首尾空白与末尾的 /,只收 http(s);拒绝用户名密码、查询参数、# 与路径;主机名转成小写。只收 https:// 的来源拒绝 http://。传输上的要求(明文带凭据要确认)见 CheckTransport。
func RegisterKind ¶
func RegisterKind(k Kind) (unregister func())
RegisterKind 登记一种来源类型(各来源在自己文件的 init 里登记),返回撤销登记的函数(测试用)。 名字是 local 或已经登记过时 panic:这是写代码时的错误。
func TLSConfig ¶
TLSConfig 是连一个来源用的 TLS 设置:先按 roots(为空时是系统根证书)校验证书链与主机名;不通过时看叶证书的 SHA-256 是不是钉住的 pin;都不是时返回 *CertError。
校验写在 VerifyConnection 里,握手拿到证书就判:证书不认时连接在发出任何应用数据(含 API Key、密码)之前就断了。 为此关掉 crypto/tls 自己的链校验(InsecureSkipVerify),改成在这里做,不是跳过校验。
Types ¶
type Alert ¶
type Alert struct {
Level string `json:"level"`
Title string `json:"title"`
At *time.Time `json:"at,omitempty"`
}
Alert 是 NAS 自己的一条告警:At 是它发生的时间(来源没给时为空)。
type Apps ¶
type Apps struct {
Running int `json:"running"`
Total int `json:"total"`
Upgradable int `json:"upgradable"`
UpdatesUnknown bool `json:"updates_unknown,omitempty"`
}
Apps 是 NAS 上的应用(容器):运行中、共几个、可更新几个。UpdatesUnknown 为真是来源不知道哪些能更新(Glances 只看得到容器), 这时 Upgradable 不算数。
type CPU ¶
type CPU struct {
Percent float64 `json:"percent"`
IOWait *float64 `json:"iowait,omitempty"`
Load1 float64 `json:"load1"`
Load5 float64 `json:"load5"`
Load15 float64 `json:"load15"`
TempC *float64 `json:"temp_c,omitempty"`
}
CPU 是处理器:Percent 是占用百分比(0–100);IOWait 是 IO 等待的百分比、TempC 是温度,读不到时为空。
type CertError ¶
CertError 是握手时证书没通过:Changed 为真是钉住了指纹、但这张证书的指纹不一样;否则是系统根证书不认、也没有钉住。 errors.Is 认得 ErrCertChanged 与 ErrCertUntrusted。
type CertInfo ¶
type CertInfo struct {
SHA256 string `json:"sha256"`
Subject string `json:"subject"`
Issuer string `json:"issuer"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
DNSNames []string `json:"dns_names"`
}
CertInfo 是证书确认时给用户看的叶证书:SHA256 是整张证书(DER)的指纹,小写十六进制。
type Collector ¶
type Collector struct {
Load func(ctx context.Context) (Config, error)
SaveExtra func(ctx context.Context, id uint, revision int64, extra map[string]string) error
Factory func(cfg SourceConfig) (Source, error)
NewLocal func() Source
Now func() time.Time
Logf func(format string, args ...any)
// Light、Full、Timeout、Backoff 为零时用默认值(30 秒、5 分钟、10 秒、30 秒/1/2/5 分钟);测试里调小
Light, Full, Timeout time.Duration
Backoff []time.Duration
// contains filtered or unexported fields
}
Collector 定时采集各个来源:每个启用的来源一个循环,第一次完整采集,之后每 30 秒轻量采集、每 5 分钟完整采集, 结果合并成最新快照并留最近 60 拍的历史。网络等错误按 30 秒、1、2、5 分钟退避;认证失败、证书不受信任或换了以后 停住(熔断),直到这个来源的设置改了(Reload 带来新的 revision)或用户点「重新连接」(Retry,只试一次)。
Load 读全部设置(含停用的来源);SaveExtra 把来源刷新过的长期凭据写回(只在库里的 revision 没变时写); Factory 建一个来源(为空时按注册表的 Kind.New);NewLocal 建本机来源(为空时 NewLocalSource)。
func (*Collector) Reload ¶
Reload 在保存、删除来源或改了本机来源的开关以后调用:重新读设置,只重启 id 这一个来源(id 是 LocalID 或数字编号)。 设置没变(同一个 revision、开关一样)时什么也不做,数据与历史照旧。
func (*Collector) Retry ¶
Retry 立即试一次 id 这个来源(「重新连接」):等这一次试完(最多等到 ctx 结束),返回它现在的情况。 失败了照旧:熔断的继续停住,别的按退避重试。
type Config ¶
type Config struct {
LocalEnabled bool
Sources []SourceConfig
}
Config 是采集器要的全部设置:本机来源开没开,与数据库里的各个来源(含停用的,列表上照样显示)。
type Disk ¶
type Disk struct {
Name string `json:"name"`
Model string `json:"model"`
Kind string `json:"kind"`
Size uint64 `json:"size"`
TempC *float64 `json:"temp_c,omitempty"`
Pool string `json:"pool,omitempty"`
}
Disk 是一块硬盘:TempC 读不到时为空,Pool 是它所在的存储池(不在池里时为空)。
type ExtraSource ¶
type ExtraSource interface {
// TakeExtra 返回上一次调用以后刷新过的凭据;没有变化时为 nil。
TakeExtra() map[string]string
}
ExtraSource 是采集时会刷新长期凭据的来源(群晖的设备令牌、飞牛的 token):采集器每次采集以后取一次, 有变化时经 Collector.SaveExtra 写回数据库。
type HistorySource ¶
type HistorySource interface {
// TakeHistory 返回还没交出过的过去几拍;没有时为 nil。
TakeHistory() []Sample
}
HistorySource 是能补上过去几拍的来源(TrueNAS 的报表里有最近 30 分钟):采集器在每次采集成功以后取一次, 比历史里最早的一拍还早的那些放到最前面,首页的柱不用从一拍开始攒。
type Kind ¶
type Kind struct {
Name string
Label string
Experimental bool
Verified string
Username string
NeedsSecret func(username string) bool
Plain PlainRule
ParseURL func(u *url.URL) error
New func(cfg SourceConfig) (Source, error)
Test func(ctx context.Context, in TestInput) (*TestResult, error)
}
Kind 是一种来源类型。Username 是表单里用户名一栏(UsernameNone、Optional、Required);NeedsSecret 是填了这个用户名时 要不要密钥(为空表示总要);Plain 是 http:// 地址的规则;ParseURL 在通用规则之后再按这种来源检查地址(可为空)。 Verified 是实验性的类型在哪个版本的真机上验证过(例如「fnOS 1.2.1000」),没在真机上验证过时为空。
func (Kind) RequiresSecret ¶
RequiresSecret 是填了 username 时这种来源要不要密钥。
type Local ¶
type Local struct {
// Wait 是第一次采集时两次读 /proc/stat 之间的等待(测试里换掉,在里面改写假的 /proc/stat)
Wait func(ctx context.Context, d time.Duration) error
// contains filtered or unexported fields
}
Local 是本机来源:从 root 下的 /proc 与 /sys 读 pt-tools 所在主机的数据(Docker 里读到的是宿主机的 CPU、内存、 负载与运行时长)。root 在生产里是 /,测试里是放着假 /proc 的临时目录。
type Memory ¶
type Memory struct {
Total uint64 `json:"total"`
Used uint64 `json:"used"`
Available uint64 `json:"available"`
}
Memory 是内存(字节):Used = Total - Available。
type Network ¶
type Network struct {
RxBps uint64 `json:"rx_bps"`
TxBps uint64 `json:"tx_bps"`
Interfaces []string `json:"interfaces"`
}
Network 是各网卡合计的速度(字节/秒)与参与合计的网卡。
type Pending ¶
type Pending struct {
// Now 是现在的时间(测试里换掉)
Now func() time.Time
// contains filtered or unexported fields
}
Pending 是测试连接登录产生的新长期凭据(群晖的设备令牌、飞牛的 token 等)的暂存表:回应只给一个随机的 token, 不回明文;保存时凭 token 取出、加密写进库里。每份 10 分钟过期、只能用一次、只给绑定的那组目标用。
type PendingKey ¶
PendingKey 是一份暂存凭据绑定的目标:类型、规范化以后的地址、账号,以及来源编号(新建时是 0)。
type Pool ¶
type Pool struct {
Name string `json:"name"`
Status string `json:"status"`
Healthy *bool `json:"healthy,omitempty"`
Size uint64 `json:"size"`
Used uint64 `json:"used"`
Free uint64 `json:"free"`
Disks int `json:"disks"`
}
Pool 是一个存储池:Size、Used、Free 是可用容量(扣掉校验盘以后的,不是裸容量);Healthy 读不到时为空。
type Sample ¶
type Sample struct {
At time.Time `json:"at"`
CPU float64 `json:"cpu"`
Mem float64 `json:"mem"`
Rx uint64 `json:"rx"`
Tx uint64 `json:"tx"`
}
Sample 是历史的一拍:CPU 与 Mem 是百分比,Rx、Tx 是字节/秒。存储不进历史(存储卡画各池的分段条)。
type Snapshot ¶
type Snapshot struct {
At time.Time `json:"at"`
System System `json:"system"`
CPU CPU `json:"cpu"`
Memory Memory `json:"memory"`
Network Network `json:"network"`
Pools []Pool `json:"pools"`
Disks []Disk `json:"disks"`
Alerts []Alert `json:"alerts"`
Apps Apps `json:"apps"`
Facets map[string]Facet `json:"facets"`
}
Snapshot 是一个来源某一时刻的数据。轻量采集只更新 CPU、内存、网络与负载,存储池、硬盘、告警与应用沿用上一次完整采集的。
type Source ¶
Source 是一个 NAS 监控来源。full 为真时连存储池、硬盘、告警与应用一起取,否则只取 CPU、内存、网络与负载。 Collect 返回的错误按类分:*AuthError(errors.Is ErrAuth)、*CertError(ErrCertUntrusted 或 ErrCertChanged)、 ErrUnsupported,其余是网络、超时与协议错误。Close 断开来源持有的连接。
type SourceConfig ¶
type SourceConfig struct {
ID uint
Name string
Kind string
Enabled bool
URL string
Username string
Secret string
Extra map[string]string
PinSHA256 string
InsecureAck bool
Revision int64
Broken string
}
SourceConfig 是采集器看到的一个来源(密钥已经解密)。URL 是规范化以后的地址;Revision 每次保存加一; Broken 是这一行用不了的原因(例如密钥解不开):采集器不连它,只显示原因。
type Status ¶
type Status struct {
ID string
Name string
Kind string
Enabled bool
Experimental bool
URL string
HasSecret bool
PinSHA256 string
InsecureAck bool
State string
Message string
LastOKAt *time.Time
NextTryAt *time.Time
// FailingSince 是这次从什么时候开始出错(连着的时候为空):体检按它判断连不上多久了
FailingSince *time.Time
Snapshot *Snapshot
History []Sample
}
Status 是一个来源现在的情况(只读内存):State 见 State* 常量,Message 是给人看的原因(已去掉凭证), Snapshot 是最近一次成功采集合并出的数据(出错时还是上一份,界面写「这是 N 分钟前的数据」),History 是最近的几拍。
type System ¶
type System struct {
Hostname string `json:"hostname"`
Platform string `json:"platform"`
Version string `json:"version"`
Model string `json:"model"`
Cores int `json:"cores"`
UptimeSeconds int64 `json:"uptime_seconds"`
}
System 是主机信息:Platform 是系统(Linux、TrueNAS SCALE、DSM),Version 是它的版本(本机是内核版本),Model 是型号 (本机与读不到整机型号的来源写 CPU 型号)。
type TestInput ¶
type TestInput struct {
URL *url.URL
Username string
Secret string
Extra map[string]string
OTP string
PinSHA256 string
}
TestInput 是一次「测试连接」:URL 已经规范化;Extra 是库里的长期凭据(只在地址、账号没变时给); PinSHA256 是这一次要信任的证书指纹(空表示只按系统根证书校验);OTP 是用户填的验证码。
type TestResult ¶
TestResult 是测试连上以后读到的主机信息;Extra 是登录产生的新的长期凭据(没有时为空)。