system

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanupOldDiskCacheFiles

func CleanupOldDiskCacheFiles(maxAge time.Duration) error

CleanupOldDiskCacheFiles 清理旧的缓存文件 maxAge: 文件最大存活时间 注意:此函数只删除文件,不更新统计(因为无法知道每个文件的原始大小)

func CreateDiskCacheFile

func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)

CreateDiskCacheFile 创建磁盘缓存文件 cacheType: 缓存类型(body/file) 返回文件路径和文件句柄

func DecrementDiskFiles

func DecrementDiskFiles(size int64)

DecrementDiskFiles 减少磁盘文件计数

func DecrementMemoryBuffers

func DecrementMemoryBuffers(size int64)

DecrementMemoryBuffers 减少内存缓存计数

func EnsureDiskCacheDir

func EnsureDiskCacheDir() error

EnsureDiskCacheDir 确保缓存目录存在

func GetDiskCacheDir

func GetDiskCacheDir() string

GetDiskCacheDir 获取统一的磁盘缓存目录 注意:每次调用都会重新计算,以响应配置变化

func GetDiskCacheInfo

func GetDiskCacheInfo() (fileCount int, totalSize int64, err error)

GetDiskCacheInfo 获取磁盘缓存目录信息

func GetDiskCacheMaxSizeBytes

func GetDiskCacheMaxSizeBytes() int64

GetDiskCacheMaxSizeBytes 获取磁盘缓存最大大小(字节)

func GetDiskCachePath

func GetDiskCachePath() string

GetDiskCachePath 获取磁盘缓存目录

func GetDiskCacheThresholdBytes

func GetDiskCacheThresholdBytes() int64

GetDiskCacheThresholdBytes 获取磁盘缓存阈值(字节)

func IncDBReconnect

func IncDBReconnect()

func IncDependencyFail

func IncDependencyFail()

func IncFileIOError

func IncFileIOError()

func IncHTTP4xx

func IncHTTP4xx()

func IncHTTP5xx

func IncHTTP5xx()

func IncJWTVerifyFail

func IncJWTVerifyFail()

func IncPanic

func IncPanic()

func IncPreflightFail

func IncPreflightFail()

func IncSSLCertLoadFail

func IncSSLCertLoadFail()

func IncrementDiskCacheHits

func IncrementDiskCacheHits()

IncrementDiskCacheHits 增加磁盘缓存命中次数

func IncrementDiskFiles

func IncrementDiskFiles(size int64)

IncrementDiskFiles 增加磁盘文件计数

func IncrementMemoryBuffers

func IncrementMemoryBuffers(size int64)

IncrementMemoryBuffers 增加内存缓存计数

func IncrementMemoryCacheHits

func IncrementMemoryCacheHits()

IncrementMemoryCacheHits 增加内存缓存命中次数

func IsDiskCacheAvailable

func IsDiskCacheAvailable(requestSize int64) bool

IsDiskCacheAvailable 检查是否可以创建新的磁盘缓存

func IsDiskCacheEnabled

func IsDiskCacheEnabled() bool

IsDiskCacheEnabled 是否启用磁盘缓存

func Monitor

func Monitor()

Monitor 定时监控 CPU / 内存,超阈值则采样 profile。

设计要点:

  • 每轮采样失败不再 panic;记 warn 然后下一轮重试。
  • 阈值实时读取 PerformanceMonitorConfig,运维可通过 listener 调整。
  • CPU 采样窗口固定 10 s;heap dump 有冷却,避免磁盘被刷爆。
  • 文件以时间戳命名,便于排序。

func ReadDiskCacheFile

func ReadDiskCacheFile(filePath string) ([]byte, error)

ReadDiskCacheFile 读取磁盘缓存文件

func ReadDiskCacheFileString

func ReadDiskCacheFileString(filePath string) (string, error)

ReadDiskCacheFileString 读取磁盘缓存文件为字符串

func RecordRuntimeTrend

func RecordRuntimeTrend(p RuntimeTrendPoint)

RecordRuntimeTrend appends one sample to the in-memory ring and JSONL on disk. Callers should gate with ShouldSampleTrend() so the 5s system monitor does not over-sample; this function itself always records when invoked.

func RemoveDiskCacheFile

func RemoveDiskCacheFile(filePath string) error

RemoveDiskCacheFile 删除磁盘缓存文件

func ResetDiskCacheStats

func ResetDiskCacheStats()

ResetDiskCacheStats 重置命中统计信息(不重置当前使用量)

func ResetDiskCacheUsage

func ResetDiskCacheUsage()

ResetDiskCacheUsage 重置磁盘缓存使用量统计(用于清理缓存后)

func SafeSendBool

func SafeSendBool(ch chan bool, value bool) (closed bool)

func SafeSendString

func SafeSendString(ch chan string, value string) (closed bool)

func SafeSendStringTimeout

func SafeSendStringTimeout(ch chan string, value string, timeout int) (closed bool)

SafeSendStringTimeout send, return true, else return false

func SetDiskCacheConfig

func SetDiskCacheConfig(config DiskCacheConfig)

SetDiskCacheConfig 设置磁盘缓存配置

func SetDiskPathProvider

func SetDiskPathProvider(p DiskPathProvider)

SetDiskPathProvider registers a custom disk-path provider for monitoring.

func SetGaugeSetter

func SetGaugeSetter(s GaugeSetter)

SetGaugeSetter registers a custom gauge setter for Prometheus / metrics export.

func SetPProfDir

func SetPProfDir(dir string)

SetPProfDir 配置 pprof 文件落地目录。必须在 Monitor 启动前调用。 传空字符串则恢复默认值 "./pprof"。

func SetPerformanceMonitorConfig

func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)

SetPerformanceMonitorConfig 设置性能监控配置

func ShouldSampleTrend

func ShouldSampleTrend() bool

ShouldSampleTrend reports whether enough time has passed since the last trend sample.

func ShouldUseDiskCache

func ShouldUseDiskCache(dataSize int64) bool

ShouldUseDiskCache 判断是否应该使用磁盘缓存

func StartPyroScope

func StartPyroScope() error

StartPyroScope starts a Pyroscope profiling session using environment variables for configuration:

  • PYROSCOPE_URL (required; empty skips startup)
  • PYROSCOPE_APP_NAME (default "ling-base")
  • PYROSCOPE_BASIC_AUTH_USER
  • PYROSCOPE_BASIC_AUTH_PASSWORD
  • HOSTNAME (default "ling-base")
  • PYROSCOPE_MUTEX_RATE (default 5)
  • PYROSCOPE_BLOCK_RATE (default 5)

func StartSystemMonitor

func StartSystemMonitor()

StartSystemMonitor 启动系统监控

func SyncDiskCacheStats

func SyncDiskCacheStats()

SyncDiskCacheStats 从实际磁盘状态同步统计信息 用于修正统计与实际不符的情况

func SyncPrometheusRuntimeGauges

func SyncPrometheusRuntimeGauges()

SyncPrometheusRuntimeGauges pushes runtime stats into the registered gauge setter.

func TrendSampleInterval

func TrendSampleInterval() time.Duration

TrendSampleInterval returns the configured trend sample interval.

func ValidateURLWithFetchSetting

func ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) error

ValidateURLWithFetchSetting 使用FetchSetting配置验证URL

func WriteDiskCacheFile

func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)

WriteDiskCacheFile 写入数据到磁盘缓存文件 返回文件路径

func WriteDiskCacheFileString

func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)

WriteDiskCacheFileString 写入字符串到磁盘缓存文件

Types

type CPUSnapshot

type CPUSnapshot struct {
	UsagePercent  float64 `json:"usagePercent"`
	UserPercent   float64 `json:"userPercent"`
	SystemPercent float64 `json:"systemPercent"`
	IdlePercent   float64 `json:"idlePercent"`
	IowaitPercent float64 `json:"iowaitPercent"`
	NumCPU        int     `json:"numCpu"`
}

CPUSnapshot breaks down CPU usage.

type DiskCacheConfig

type DiskCacheConfig struct {
	// Enabled 是否启用磁盘缓存
	Enabled bool
	// ThresholdMB 触发磁盘缓存的请求体大小阈值(MB)
	ThresholdMB int
	// MaxSizeMB 磁盘缓存最大总大小(MB)
	MaxSizeMB int
	// Path 磁盘缓存目录
	Path string
}

DiskCacheConfig 磁盘缓存配置(由 performance_setting 包更新)

func GetDiskCacheConfig

func GetDiskCacheConfig() DiskCacheConfig

GetDiskCacheConfig 获取磁盘缓存配置

type DiskCacheStats

type DiskCacheStats struct {
	// 当前活跃的磁盘缓存文件数
	ActiveDiskFiles int64 `json:"active_disk_files"`
	// 当前磁盘缓存总大小(字节)
	CurrentDiskUsageBytes int64 `json:"current_disk_usage_bytes"`
	// 当前内存缓存数量
	ActiveMemoryBuffers int64 `json:"active_memory_buffers"`
	// 当前内存缓存总大小(字节)
	CurrentMemoryUsageBytes int64 `json:"current_memory_usage_bytes"`
	// 磁盘缓存命中次数
	DiskCacheHits int64 `json:"disk_cache_hits"`
	// 内存缓存命中次数
	MemoryCacheHits int64 `json:"memory_cache_hits"`
	// 磁盘缓存最大限制(字节)
	DiskCacheMaxBytes int64 `json:"disk_cache_max_bytes"`
	// 磁盘缓存阈值(字节)
	DiskCacheThresholdBytes int64 `json:"disk_cache_threshold_bytes"`
}

DiskCacheStats 磁盘缓存统计信息

func GetDiskCacheStats

func GetDiskCacheStats() DiskCacheStats

GetDiskCacheStats 获取缓存统计信息

type DiskCacheType

type DiskCacheType string

DiskCacheType 磁盘缓存类型

const (
	DiskCacheTypeBody DiskCacheType = "body" // 请求体缓存
	DiskCacheTypeFile DiskCacheType = "file" // 文件数据缓存
)

type DiskPathProvider

type DiskPathProvider func() []string

DiskPathProvider returns extra file-system paths to monitor for disk usage. Register a provider via SetDiskPathProvider to integrate with your application's configuration (log file, JWT key, SIP dir, SQLite DSN, etc.). The default provider returns the upload directory from the UPLOAD_DIR env variable (or constants.DefaultUploadDir when unset).

type DiskPathUsage

type DiskPathUsage struct {
	Path        string  `json:"path"`
	Total       uint64  `json:"total"`
	Used        uint64  `json:"used"`
	Free        uint64  `json:"free"`
	UsedPercent float64 `json:"usedPercent"`
	InodesTotal uint64  `json:"inodesTotal"`
	InodesFree  uint64  `json:"inodesFree"`
	InodesUsed  uint64  `json:"inodesUsed"`
}

DiskPathUsage is usage for one mounted path.

type DiskSpaceInfo

type DiskSpaceInfo struct {
	// 总空间(字节)
	Total uint64 `json:"total"`
	// 可用空间(字节)
	Free uint64 `json:"free"`
	// 已用空间(字节)
	Used uint64 `json:"used"`
	// 使用百分比
	UsedPercent float64 `json:"used_percent"`
}

DiskSpaceInfo 磁盘空间信息

func GetDiskSpaceInfo

func GetDiskSpaceInfo() DiskSpaceInfo

GetDiskSpaceInfo 获取缓存目录所在磁盘的空间信息 (Unix/Linux/macOS)

type GCSnapshot

type GCSnapshot struct {
	NumGC              uint32  `json:"numGC"`
	NumForcedGC        uint32  `json:"numForcedGC"`
	PauseTotalNs       uint64  `json:"pauseTotalNs"`
	PauseTotalMs       float64 `json:"pauseTotalMs"`
	RecentPauseAvgMs   float64 `json:"recentPauseAvgMs"`
	RecentPauseMaxMs   float64 `json:"recentPauseMaxMs"`
	RecentPauseSamples int     `json:"recentPauseSamples"`
	GCCPUFraction      float64 `json:"gcCpuFraction"`
	NextGC             uint64  `json:"nextGC"`
	LastGCUnixNano     int64   `json:"lastGCUnixNano"`
	GCPerMinute        float64 `json:"gcPerMinute"`
}

GCSnapshot summarizes recent GC STW pauses.

type GaugeSetter

type GaugeSetter func(name, help string, labels map[string]string, value float64)

GaugeSetter sets a named gauge value in an external metrics registry. Register an implementation via SetGaugeSetter to push runtime telemetry into Prometheus, OpenTelemetry, or any other backend. The default setter is a no-op.

Labels is a nilable map of label name → value (may be empty).

type GoroutineSnapshot

type GoroutineSnapshot struct {
	NumGoroutine    int            `json:"numGoroutine"`
	NumGoroutineMax int            `json:"numGoroutineMax"`
	NumThread       int            `json:"numThread"`
	NumCgoCall      int64          `json:"numCgoCall"`
	ByState         map[string]int `json:"byState"`
	LeakSuspect     bool           `json:"leakSuspect"`
}

GoroutineSnapshot captures goroutine / thread runtime counters.

type HostMemorySnapshot

type HostMemorySnapshot struct {
	Total       uint64  `json:"total"`
	Available   uint64  `json:"available"`
	Used        uint64  `json:"used"`
	UsedPercent float64 `json:"usedPercent"`
	SwapTotal   uint64  `json:"swapTotal"`
	SwapUsed    uint64  `json:"swapUsed"`
	SwapPercent float64 `json:"swapPercent"`
}

HostMemorySnapshot is OS-level memory including swap.

type HostSnapshot

type HostSnapshot struct {
	CPU     CPUSnapshot        `json:"cpu"`
	Load    LoadSnapshot       `json:"load"`
	Memory  HostMemorySnapshot `json:"memory"`
	Disks   []DiskPathUsage    `json:"disks"`
	Network NetSnapshot        `json:"network"`
	Process ProcessSnapshot    `json:"process"`
}

HostSnapshot aggregates host + process telemetry.

func CollectHostSnapshot

func CollectHostSnapshot() HostSnapshot

CollectHostSnapshot samples gopsutil host/process metrics.

type LoadSnapshot

type LoadSnapshot struct {
	Load1  float64 `json:"load1"`
	Load5  float64 `json:"load5"`
	Load15 float64 `json:"load15"`
}

LoadSnapshot is 1/5/15 minute load average.

type NetSnapshot

type NetSnapshot struct {
	BytesSent   uint64 `json:"bytesSent"`
	BytesRecv   uint64 `json:"bytesRecv"`
	PacketsSent uint64 `json:"packetsSent"`
	PacketsRecv uint64 `json:"packetsRecv"`
	DropIn      uint64 `json:"dropIn"`
	DropOut     uint64 `json:"dropOut"`
	ErrIn       uint64 `json:"errIn"`
	ErrOut      uint64 `json:"errOut"`
}

NetSnapshot is aggregate network IO since boot.

type OpsCounters

type OpsCounters struct {
	PanicTotal           uint64 `json:"panicTotal"`
	HTTP5xxTotal         uint64 `json:"http5xxTotal"`
	HTTP4xxTotal         uint64 `json:"http4xxTotal"`
	JWTVerifyFailTotal   uint64 `json:"jwtVerifyFailTotal"`
	DBReconnectTotal     uint64 `json:"dbReconnectTotal"`
	PreflightFailTotal   uint64 `json:"preflightFailTotal"`
	DependencyFailTotal  uint64 `json:"dependencyFailTotal"`
	FileIOErrorTotal     uint64 `json:"fileIoErrorTotal"`
	SSLCertLoadFailTotal uint64 `json:"sslCertLoadFailTotal"`
}

OpsCounters tracks process-wide error / anomaly counters for dashboards.

func GetOpsCounters

func GetOpsCounters() OpsCounters

type PerformanceMonitorConfig

type PerformanceMonitorConfig struct {
	Enabled         bool
	CPUThreshold    int
	MemoryThreshold int
	DiskThreshold   int
}

PerformanceMonitorConfig 性能监控配置

func GetPerformanceMonitorConfig

func GetPerformanceMonitorConfig() PerformanceMonitorConfig

GetPerformanceMonitorConfig 获取性能监控配置

type ProcessSnapshot

type ProcessSnapshot struct {
	PID            int32   `json:"pid"`
	RSS            uint64  `json:"rss"`
	VMS            uint64  `json:"vms"`
	CPUPercent     float64 `json:"cpuPercent"`
	OpenFDs        int32   `json:"openFds"`
	MaxFDs         uint64  `json:"maxFds"`
	NumThreads     int32   `json:"numThreads"`
	CreateTimeUnix int64   `json:"createTimeUnix"`
}

ProcessSnapshot is this process RSS/VMS/CPU/fds.

type RuntimeMemorySnapshot

type RuntimeMemorySnapshot struct {
	Alloc         uint64  `json:"alloc"`
	TotalAlloc    uint64  `json:"totalAlloc"`
	Sys           uint64  `json:"sys"`
	Lookups       uint64  `json:"lookups"`
	Mallocs       uint64  `json:"mallocs"`
	Frees         uint64  `json:"frees"`
	HeapAlloc     uint64  `json:"heapAlloc"`
	HeapSys       uint64  `json:"heapSys"`
	HeapIdle      uint64  `json:"heapIdle"`
	HeapInuse     uint64  `json:"heapInuse"`
	HeapReleased  uint64  `json:"heapReleased"`
	HeapObjects   uint64  `json:"heapObjects"`
	StackInuse    uint64  `json:"stackInuse"`
	StackSys      uint64  `json:"stackSys"`
	MSpanInuse    uint64  `json:"mSpanInuse"`
	MSpanSys      uint64  `json:"mSpanSys"`
	MCacheInuse   uint64  `json:"mCacheInuse"`
	MCacheSys     uint64  `json:"mCacheSys"`
	BuckHashSys   uint64  `json:"buckHashSys"`
	GCSys         uint64  `json:"gcSys"`
	OtherSys      uint64  `json:"otherSys"`
	NextGC        uint64  `json:"nextGC"`
	LastGC        uint64  `json:"lastGC"`
	PauseTotalNs  uint64  `json:"pauseTotalNs"`
	NumGC         uint32  `json:"numGC"`
	NumForcedGC   uint32  `json:"numForcedGC"`
	GCCPUFraction float64 `json:"gcCpuFraction"`
	EnableGC      bool    `json:"enableGC"`
}

RuntimeMemorySnapshot is the full runtime.MemStats export for ops dashboards.

type RuntimeSnapshot

type RuntimeSnapshot struct {
	GoVersion string                `json:"goVersion"`
	Memory    RuntimeMemorySnapshot `json:"memory"`
	GC        GCSnapshot            `json:"gc"`
	Goroutine GoroutineSnapshot     `json:"goroutine"`
}

RuntimeSnapshot bundles Go runtime telemetry.

func CollectRuntimeSnapshot

func CollectRuntimeSnapshot() RuntimeSnapshot

CollectRuntimeSnapshot reads MemStats and goroutine breakdown.

type RuntimeTrendPoint

type RuntimeTrendPoint struct {
	Ts          int64   `json:"ts"` // unix milliseconds
	HeapAlloc   uint64  `json:"heapAlloc"`
	HeapInuse   uint64  `json:"heapInuse"`
	HeapObjects uint64  `json:"heapObjects"`
	Sys         uint64  `json:"sys"`
	Goroutines  int     `json:"goroutines"`
	NumGC       uint32  `json:"numGC"`
	CPUUsage    float64 `json:"cpuUsage"`
	MemoryUsage float64 `json:"memoryUsage"`
	ProcessRSS  uint64  `json:"processRss,omitempty"`
}

RuntimeTrendPoint is one lightweight sample for leak/OOM trend charts.

type RuntimeTrendSnapshot

type RuntimeTrendSnapshot struct {
	IntervalSeconds int                 `json:"intervalSeconds"`
	PersistDir      string              `json:"persistDir"`
	Points          []RuntimeTrendPoint `json:"points"`
	Summary         RuntimeTrendSummary `json:"summary"`
}

RuntimeTrendSnapshot is returned by /system/status.

func GetRuntimeTrend

func GetRuntimeTrend(window string) RuntimeTrendSnapshot

GetRuntimeTrend returns points within the given window (e.g. 15m / 1h / 6h / 24h). Empty window defaults to 1h. Points are downsampled to maxTrendResponsePts.

type RuntimeTrendSummary

type RuntimeTrendSummary struct {
	SampleCount     int   `json:"sampleCount"`
	WindowMs        int64 `json:"windowMs"`
	HeapAllocDelta  int64 `json:"heapAllocDelta"`
	GoroutineDelta  int   `json:"goroutineDelta"`
	HeapAllocRising bool  `json:"heapAllocRising"`
	GoroutineRising bool  `json:"goroutineRising"`
	FirstTs         int64 `json:"firstTs,omitempty"`
	LastTs          int64 `json:"lastTs,omitempty"`
}

RuntimeTrendSummary is a coarse rising/falling signal for ops dashboards.

type SSRFProtection

type SSRFProtection struct {
	AllowPrivateIp         bool
	DomainFilterMode       bool     // true: 白名单, false: 黑名单
	DomainList             []string // domain format, e.g. example.com, *.example.com
	IpFilterMode           bool     // true: 白名单, false: 黑名单
	IpList                 []string // CIDR or single IP
	AllowedPorts           []int    // 允许的端口范围
	ApplyIPFilterForDomain bool     // 对域名启用IP过滤
}

SSRFProtection SSRF防护配置

func (*SSRFProtection) IsIPAccessAllowed

func (p *SSRFProtection) IsIPAccessAllowed(ip net.IP) bool

IsIPAccessAllowed 检查IP是否允许访问

func (*SSRFProtection) ValidateURL

func (p *SSRFProtection) ValidateURL(urlStr string) error

ValidateURL 验证URL是否安全

type SystemStatus

type SystemStatus struct {
	CPUUsage    float64
	MemoryUsage float64
	DiskUsage   float64
}

SystemStatus 系统状态信息

func GetSystemStatus

func GetSystemStatus() SystemStatus

GetSystemStatus 获取当前系统状态

Jump to

Keyboard shortcuts

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