mirror of
https://github.com/fankes/komari-agent.git
synced 2026-02-04 12:17:30 +08:00
Compare commits
18 Commits
e8835d135a
...
c22aecbf1d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c22aecbf1d | ||
|
|
7079b5d26b | ||
|
|
5c12b5c570 | ||
|
|
9e6d354117 | ||
|
|
a4fc402efa | ||
|
|
9eb31277b7 | ||
|
|
3abca7cf9d | ||
|
|
aab157a7bb | ||
|
|
75442886c0 | ||
|
|
5d573cfb1a | ||
|
|
256a6db04e | ||
|
|
fed087b123 | ||
|
|
ddb069791f | ||
|
|
ea0a5089bf | ||
|
|
c59781dfb3 | ||
|
|
a9d191d6c3 | ||
|
|
7071fa746b | ||
|
|
1547184903 |
54
cmd/checkMem.go
Normal file
54
cmd/checkMem.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var CheckMemCmd = &cobra.Command{
|
||||
Use: "check-mem",
|
||||
Short: "Check memory usage",
|
||||
Long: `Check memory usage`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
log.Println("--- Memory Check ---")
|
||||
|
||||
// Print raw /proc/meminfo if on Linux
|
||||
if info, err := monitoring.ReadProcMeminfo(); err == nil {
|
||||
log.Println("--- /proc/meminfo ---")
|
||||
log.Printf("MemTotal: %d MiB", info.MemTotal/1024/1024)
|
||||
log.Printf("MemFree: %d MiB", info.MemFree/1024/1024)
|
||||
log.Printf("MemAvailable: %d MiB", info.MemAvailable/1024/1024)
|
||||
log.Printf("Buffers: %d MiB", info.Buffers/1024/1024)
|
||||
log.Printf("Cached: %d MiB", info.Cached/1024/1024)
|
||||
log.Printf("SwapTotal: %d MiB", info.SwapTotal/1024/1024)
|
||||
log.Printf("SwapFree: %d MiB", info.SwapFree/1024/1024)
|
||||
log.Printf("SwapCached: %d MiB", info.SwapCached/1024/1024)
|
||||
log.Printf("Shmem: %d MiB", info.Shmem/1024/1024)
|
||||
log.Printf("SReclaimable: %d MiB", info.SReclaimable/1024/1024)
|
||||
log.Printf("Zswap: %d MiB", info.Zswap/1024/1024)
|
||||
log.Printf("Zswapped: %d MiB", info.Zswapped/1024/1024)
|
||||
log.Println("---------------------")
|
||||
}
|
||||
|
||||
printRamInfo := func(info monitoring.RamInfo) {
|
||||
log.Printf("[%s] Total: %d bytes (%d MiB), Used: %d bytes (%d MiB)",
|
||||
info.Mode,
|
||||
info.Total, info.Total/(1024*1024),
|
||||
info.Used, info.Used/(1024*1024),
|
||||
)
|
||||
}
|
||||
|
||||
printRamInfo(monitoring.GetMemHtopLike())
|
||||
printRamInfo(monitoring.GetMemGopsutil())
|
||||
printRamInfo(monitoring.CallFree())
|
||||
|
||||
log.Println("--- Current Configured ---")
|
||||
printRamInfo(monitoring.Ram())
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(CheckMemCmd)
|
||||
}
|
||||
@@ -19,6 +19,7 @@ type Config struct {
|
||||
CFAccessClientID string `json:"cf_access_client_id" env:"AGENT_CF_ACCESS_CLIENT_ID"` // Cloudflare Access Client ID
|
||||
CFAccessClientSecret string `json:"cf_access_client_secret" env:"AGENT_CF_ACCESS_CLIENT_SECRET"` // Cloudflare Access Client Secret
|
||||
MemoryIncludeCache bool `json:"memory_include_cache" env:"AGENT_MEMORY_INCLUDE_CACHE"` // 包括缓存/缓冲区的内存使用情况
|
||||
MemoryReportRawUsed bool `json:"memory_report_raw_used" env:"AGENT_MEMORY_REPORT_RAW_USED"` // 使用原始内存使用情况报告
|
||||
CustomDNS string `json:"custom_dns" env:"AGENT_CUSTOM_DNS"` // 使用的自定义DNS服务器
|
||||
EnableGPU bool `json:"enable_gpu" env:"AGENT_ENABLE_GPU"` // 启用详细GPU监控
|
||||
ShowWarning bool `json:"show_warning" env:"AGENT_SHOW_WARNING"` // Windows 上显示安全警告,作为子进程运行一次
|
||||
@@ -26,6 +27,7 @@ type Config struct {
|
||||
CustomIpv6 string `json:"custom_ipv6" env:"AGENT_CUSTOM_IPV6"` // 自定义 IPv6 地址
|
||||
GetIpAddrFromNic bool `json:"get_ip_addr_from_nic" env:"AGENT_GET_IP_ADDR_FROM_NIC"` // 从网卡获取IP地址
|
||||
ConfigFile string `json:"config_file" env:"AGENT_CONFIG_FILE"` // JSON配置文件路径
|
||||
|
||||
}
|
||||
|
||||
var GlobalConfig = &Config{}
|
||||
|
||||
@@ -169,6 +169,7 @@ func init() {
|
||||
RootCmd.PersistentFlags().StringVar(&flags.CFAccessClientID, "cf-access-client-id", "", "Cloudflare Access Client ID")
|
||||
RootCmd.PersistentFlags().StringVar(&flags.CFAccessClientSecret, "cf-access-client-secret", "", "Cloudflare Access Client Secret")
|
||||
RootCmd.PersistentFlags().BoolVar(&flags.MemoryIncludeCache, "memory-include-cache", false, "Include cache/buffer in memory usage")
|
||||
RootCmd.PersistentFlags().BoolVar(&flags.MemoryReportRawUsed, "memory-exclude-bcf", false, "Use \"raminfo.Used = v.Total - v.Free - v.Buffers - v.Cached\" calculation for memory usage")
|
||||
RootCmd.PersistentFlags().StringVar(&flags.CustomDNS, "custom-dns", "", "Custom DNS server to use (e.g. 8.8.8.8, 114.114.114.114). By default, the program uses the system DNS resolver.")
|
||||
RootCmd.PersistentFlags().BoolVar(&flags.EnableGPU, "gpu", false, "Enable detailed GPU monitoring (usage, memory, multi-GPU support)")
|
||||
RootCmd.PersistentFlags().BoolVar(&flags.ShowWarning, "show-warning", false, "Show security warning on Windows, run once as a subprocess")
|
||||
|
||||
41
install.sh
41
install.sh
@@ -157,6 +157,10 @@ uninstall_previous() {
|
||||
/etc/init.d/${service_name} stop
|
||||
/etc/init.d/${service_name} disable
|
||||
rm -f "/etc/init.d/${service_name}"
|
||||
elif command -v initctl >/dev/null 2>&1 && [ -f "/etc/init/${service_name}.conf" ]; then
|
||||
log_info "Stopping and removing existing upstart service..."
|
||||
initctl stop ${service_name}
|
||||
rm -f "/etc/init/${service_name}.conf"
|
||||
elif [ "$os_name" = "darwin" ] && command -v launchctl >/dev/null 2>&1; then
|
||||
# macOS launchd service - check both system and user locations
|
||||
system_plist="/Library/LaunchDaemons/com.komari.${service_name}.plist"
|
||||
@@ -401,6 +405,12 @@ detect_init_system() {
|
||||
echo "openrc"
|
||||
return
|
||||
fi
|
||||
|
||||
# check for Upstart (CentOS 6)
|
||||
if command -v initctl >/dev/null 2>&1 && [ -d /etc/init ]; then
|
||||
echo "upstart"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "unknown"
|
||||
}
|
||||
@@ -597,6 +607,37 @@ EOF
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
elif [ "$init_system" = "upstart" ]; then
|
||||
# Upstart service configuration
|
||||
log_info "Using upstart for service management"
|
||||
service_file="/etc/init/${service_name}.conf"
|
||||
cat > "$service_file" << EOF
|
||||
# KOMARI Agent
|
||||
description "Komari Agent Service"
|
||||
|
||||
chdir ${target_dir}
|
||||
start on filesystem or runlevel [2345]
|
||||
stop on runlevel [!2345]
|
||||
|
||||
respawn
|
||||
respawn limit 10 5
|
||||
umask 022
|
||||
|
||||
console none
|
||||
|
||||
pre-start script
|
||||
test -x ${komari_agent_path} || { stop; exit 0; }
|
||||
end script
|
||||
|
||||
# Start
|
||||
script
|
||||
exec ${komari_agent_path} ${komari_args}
|
||||
end script
|
||||
EOF
|
||||
# enable Upstart unit
|
||||
initctl reload-configuration
|
||||
initctl start ${service_name}
|
||||
log_success "Upstart service configured and started"
|
||||
else
|
||||
log_error "Unsupported or unknown init system detected: $init_system"
|
||||
log_error "Supported init systems: systemd, openrc, procd, launchd"
|
||||
|
||||
@@ -14,6 +14,7 @@ type DiskInfo struct {
|
||||
|
||||
func Disk() DiskInfo {
|
||||
diskinfo := DiskInfo{}
|
||||
// 获取所有分区,使用 true 避免物理磁盘被 gopsutil 错误排除
|
||||
usage, err := disk.Partitions(true)
|
||||
if err != nil {
|
||||
diskinfo.Total = 0
|
||||
@@ -36,17 +37,39 @@ func Disk() DiskInfo {
|
||||
}
|
||||
} else {
|
||||
// 使用默认逻辑,排除临时文件系统和网络驱动器
|
||||
deviceMap := make(map[string]*disk.UsageStat)
|
||||
|
||||
for _, part := range usage {
|
||||
if isPhysicalDisk(part) {
|
||||
u, err := disk.Usage(part.Mountpoint)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
deviceID := part.Device
|
||||
// ZFS去重: 基于 pool 名称 (例如 pool/dataset -> pool)
|
||||
if strings.ToLower(part.Fstype) == "zfs" {
|
||||
if idx := strings.Index(deviceID, "/"); idx != -1 {
|
||||
deviceID = deviceID[:idx]
|
||||
}
|
||||
}
|
||||
|
||||
// 如果该设备已存在,且当前挂载点的 Total 更大,则替换(处理 quota 等情况)
|
||||
// 否则保留现有的(通常我们希望统计物理 pool 的总量)
|
||||
if existing, ok := deviceMap[deviceID]; ok {
|
||||
if u.Total > existing.Total {
|
||||
deviceMap[deviceID] = u
|
||||
}
|
||||
} else {
|
||||
diskinfo.Total += u.Total
|
||||
diskinfo.Used += u.Used
|
||||
deviceMap[deviceID] = u
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, u := range deviceMap {
|
||||
diskinfo.Total += u.Total
|
||||
diskinfo.Used += u.Used
|
||||
}
|
||||
}
|
||||
}
|
||||
return diskinfo
|
||||
@@ -77,6 +100,7 @@ func isPhysicalDisk(part disk.PartitionStat) bool {
|
||||
"/etc/resolv.conf",
|
||||
"/etc/host", // /etc/hosts,/etc/hostname
|
||||
"/dev/hugepages",
|
||||
"/nix/store",
|
||||
}
|
||||
for _, mp := range mountpointsToExclude {
|
||||
if mountpoint == mp || strings.HasPrefix(mountpoint, mp) {
|
||||
@@ -85,6 +109,17 @@ func isPhysicalDisk(part disk.PartitionStat) bool {
|
||||
}
|
||||
|
||||
fstype := strings.ToLower(part.Fstype)
|
||||
|
||||
// 针对 Linux autofs:排除自动挂载的 trigger,真实文件系统会作为单独分区出现不会被排除。
|
||||
// 将 autofs 视为“非物理磁盘”可以避免重复统计容量。
|
||||
if fstype == "autofs" && !strings.HasPrefix(part.Device, "/dev/") {
|
||||
return false
|
||||
}
|
||||
|
||||
// 针对 Linux 下通过 ntfs-3g 挂载的 NTFS 分区 (fuseblk),这是实际物理磁盘,不应排除
|
||||
if fstype == "fuseblk" {
|
||||
return true
|
||||
}
|
||||
var fstypeToExclude = []string{
|
||||
"tmpfs",
|
||||
"devtmpfs",
|
||||
|
||||
@@ -4,52 +4,251 @@
|
||||
package monitoring
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func GpuName() string {
|
||||
// 调整优先级:专用显卡厂商优先,避免只识别集成显卡
|
||||
accept := []string{"nvidia", "amd", "radeon", "vga", "3d"}
|
||||
if name := getFromLspci(); name != "None" {
|
||||
return name
|
||||
}
|
||||
|
||||
if name := getFromSysfsDRM(); name != "None" {
|
||||
return name
|
||||
}
|
||||
return "None"
|
||||
}
|
||||
|
||||
func getFromLspci() string {
|
||||
out, err := exec.Command("lspci").Output()
|
||||
if err == nil {
|
||||
lines := strings.Split(string(out), "\n")
|
||||
|
||||
// 首先尝试找专用显卡
|
||||
for _, line := range lines {
|
||||
lower := strings.ToLower(line)
|
||||
|
||||
// 跳过集成显卡和管理控制器
|
||||
if strings.Contains(lower, "aspeed") ||
|
||||
strings.Contains(lower, "matrox") ||
|
||||
strings.Contains(lower, "management") {
|
||||
continue
|
||||
}
|
||||
|
||||
// 优先匹配专用显卡厂商
|
||||
for _, a := range accept {
|
||||
if strings.Contains(lower, a) {
|
||||
parts := strings.SplitN(line, ":", 4)
|
||||
if len(parts) >= 4 {
|
||||
return strings.TrimSpace(parts[3])
|
||||
} else if len(parts) == 3 {
|
||||
return strings.TrimSpace(parts[2])
|
||||
} else if len(parts) == 2 {
|
||||
return strings.TrimSpace(parts[1])
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return "None"
|
||||
}
|
||||
excludePatterns := []string{
|
||||
"^1111", // 1111 (rev 02)
|
||||
`(?i)^cirrus logic (cl[-\s]?)?gd 5`, // CL-GD 系列 1990 年代中期的产物, 现常用于虚拟机
|
||||
"(?i)virtio",
|
||||
"(?i)vmware",
|
||||
`(?i)qxl`, // SPICE 虚拟显卡
|
||||
`(?i)hyper-v`,
|
||||
}
|
||||
|
||||
lines := strings.Split(string(out), "\n")
|
||||
|
||||
priorityVendors := []string{"nvidia", "amd", "radeon", "intel", "arc", "snap", "qualcomm", "snapdragon"}
|
||||
|
||||
isExcluded := func(name string) bool {
|
||||
for _, pattern := range excludePatterns {
|
||||
if matched, _ := regexp.MatchString(pattern, name); matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有找到专用显卡,返回第一个VGA设备作为兜底
|
||||
for _, line := range lines {
|
||||
if strings.Contains(strings.ToLower(line), "vga") {
|
||||
parts := strings.SplitN(line, ":", 4)
|
||||
if len(parts) >= 3 {
|
||||
return strings.TrimSpace(parts[2])
|
||||
return false
|
||||
}
|
||||
|
||||
extractName := func(line string) string {
|
||||
// 取最后一个冒号之后的内容
|
||||
idx := strings.LastIndex(line, ":")
|
||||
if idx == -1 || idx == len(line)-1 {
|
||||
return ""
|
||||
}
|
||||
name := strings.TrimSpace(line[idx+1:])
|
||||
|
||||
// 去除末尾的 (rev xx)
|
||||
if parenIdx := strings.LastIndex(name, "("); parenIdx != -1 {
|
||||
name = strings.TrimSpace(name[:parenIdx])
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// 寻找 priorityVendors
|
||||
for _, line := range lines {
|
||||
lower := strings.ToLower(line)
|
||||
|
||||
// 必须确认是显示设备,防止匹配到 Intel 网卡或 Qualcomm 蓝牙
|
||||
if !strings.Contains(lower, "vga") && !strings.Contains(lower, "3d") && !strings.Contains(lower, "display") {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, vendor := range priorityVendors {
|
||||
if strings.Contains(lower, vendor) {
|
||||
name := extractName(line)
|
||||
if name != "" && !isExcluded(name) {
|
||||
// 找到独显立刻返回
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 任意非黑名单的 VGA 设备
|
||||
for _, line := range lines {
|
||||
lower := strings.ToLower(line)
|
||||
if strings.Contains(lower, "vga") || strings.Contains(lower, "3d") || strings.Contains(lower, "display") {
|
||||
name := extractName(line)
|
||||
if name != "" && !isExcluded(name) {
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "None"
|
||||
|
||||
}
|
||||
|
||||
func getFromSysfsDRM() string {
|
||||
matches, _ := filepath.Glob("/sys/class/drm/card*")
|
||||
|
||||
excludedDrivers := map[string]bool{
|
||||
"virtio-pci": true,
|
||||
"virtio_gpu": true,
|
||||
"bochs-drm": true,
|
||||
"qxl": true,
|
||||
"vmwgfx": true,
|
||||
"cirrus": true,
|
||||
"vboxvideo": true,
|
||||
"hyperv_fb": true,
|
||||
"simpledrm": true,
|
||||
"simplefb": true,
|
||||
"cirrus-qemu": true,
|
||||
}
|
||||
|
||||
for _, path := range matches {
|
||||
// 驱动名称
|
||||
driverLink, err := os.Readlink(filepath.Join(path, "device", "driver"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
driverName := filepath.Base(driverLink)
|
||||
|
||||
if excludedDrivers[driverName] {
|
||||
continue
|
||||
}
|
||||
|
||||
// 设备树 compatible 提取具体型号
|
||||
// /sys/class/drm/card0/device/of_node/compatible
|
||||
// "qcom,adreno-750.1\0qcom,adreno"
|
||||
exactModel := ""
|
||||
compatibleBytes, err := os.ReadFile(filepath.Join(path, "device", "of_node", "compatible"))
|
||||
if err == nil {
|
||||
exactModel = parseSocModel(driverName, compatibleBytes)
|
||||
}
|
||||
|
||||
// 有具体型号则直接返回
|
||||
if exactModel != "" {
|
||||
return exactModel
|
||||
}
|
||||
|
||||
// 通用的驱动名称映射
|
||||
switch driverName {
|
||||
case "vc4", "vc4-drm":
|
||||
return "Broadcom VideoCore IV/VI (Raspberry Pi)"
|
||||
case "v3d", "v3d-drm":
|
||||
return "Broadcom V3D (Raspberry Pi 4/5)"
|
||||
case "msm", "msm_drm":
|
||||
return "Qualcomm Adreno (Unknown Model)"
|
||||
case "panfrost":
|
||||
return "ARM Mali (Panfrost)"
|
||||
case "lima":
|
||||
return "ARM Mali (Lima)"
|
||||
case "sun4i-drm", "sunxi-drm":
|
||||
return "Allwinner Display Engine"
|
||||
case "tegra":
|
||||
return "NVIDIA Tegra"
|
||||
case "ast": // LXC 容器映射物理显卡
|
||||
return "ASPEED Technology, Inc. ASPEED Graphics Family"
|
||||
case "i915", "i915-drm":
|
||||
return "Intel Integrated Graphics"
|
||||
case "mgag200":
|
||||
return "Matrox G200 Series"
|
||||
}
|
||||
|
||||
if driverName != "" {
|
||||
return "Direct Render Manager " + driverName
|
||||
}
|
||||
}
|
||||
|
||||
// 开发板 Model
|
||||
modelData, err := os.ReadFile("/sys/firmware/devicetree/base/model")
|
||||
if err == nil {
|
||||
model := string(modelData)
|
||||
if strings.Contains(model, "Raspberry Pi") {
|
||||
return "Broadcom VideoCore (Integrated)"
|
||||
}
|
||||
}
|
||||
|
||||
return "None"
|
||||
}
|
||||
|
||||
// parseSocModel 解析设备树 compatible 字符串,提取人性化名称
|
||||
func parseSocModel(driver string, rawBytes []byte) string {
|
||||
// compatible 文件包含多个以 \0 分隔的字符串
|
||||
content := string(bytes.ReplaceAll(rawBytes, []byte{0}, []byte(" ")))
|
||||
lower := strings.ToLower(content)
|
||||
|
||||
// 高通 Adreno (Qualcomm)
|
||||
if driver == "msm" || strings.Contains(lower, "adreno") {
|
||||
// "adreno-750", "adreno-660"
|
||||
re := regexp.MustCompile(`adreno[-_](\d+)`)
|
||||
matches := re.FindStringSubmatch(lower)
|
||||
if len(matches) > 1 {
|
||||
return "Qualcomm Adreno " + matches[1]
|
||||
}
|
||||
return "Qualcomm Adreno"
|
||||
}
|
||||
|
||||
// ARM Mali (Rockchip/MediaTek/AmLogic)
|
||||
if driver == "panfrost" || driver == "lima" || strings.Contains(lower, "mali") {
|
||||
// "mali-g610", "mali-t860"
|
||||
re := regexp.MustCompile(`mali[-_]([a-z]\d+)`)
|
||||
matches := re.FindStringSubmatch(lower)
|
||||
if len(matches) > 1 {
|
||||
return "ARM Mali " + strings.ToUpper(matches[1]) // Mali G610
|
||||
}
|
||||
return "ARM Mali" // 泛指
|
||||
}
|
||||
|
||||
// 树莓派 VideoCore
|
||||
if driver == "vc4" || driver == "vc4-drm" || driver == "v3d" {
|
||||
if strings.Contains(lower, "bcm2712") {
|
||||
return "Broadcom VideoCore VII (Pi 5)"
|
||||
}
|
||||
if strings.Contains(lower, "bcm2711") {
|
||||
return "Broadcom VideoCore VI (Pi 4)"
|
||||
}
|
||||
if strings.Contains(lower, "bcm2837") || strings.Contains(lower, "bcm2835") {
|
||||
return "Broadcom VideoCore IV"
|
||||
}
|
||||
}
|
||||
|
||||
// Allwinner (全志)
|
||||
// "allwinner,sun50i-h6-display-engine"
|
||||
if strings.Contains(lower, "allwinner") || strings.Contains(lower, "sun50i") || strings.Contains(lower, "sun8i") {
|
||||
re := regexp.MustCompile(`sun\d+i-([a-z0-9]+)`)
|
||||
matches := re.FindStringSubmatch(lower)
|
||||
if len(matches) > 1 {
|
||||
model := strings.ToUpper(matches[1])
|
||||
return "Allwinner " + model
|
||||
}
|
||||
return "Allwinner Display Engine"
|
||||
}
|
||||
|
||||
// NVIDIA Tegra
|
||||
if driver == "tegra" {
|
||||
if strings.Contains(lower, "tegra194") {
|
||||
return "NVIDIA Tegra Xavier"
|
||||
}
|
||||
if strings.Contains(lower, "tegra234") {
|
||||
return "NVIDIA Orin"
|
||||
}
|
||||
if strings.Contains(lower, "tegra210") {
|
||||
return "NVIDIA Tegra X1"
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -1,47 +1,239 @@
|
||||
package monitoring
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/shirou/gopsutil/v4/mem"
|
||||
)
|
||||
|
||||
type RamInfo struct {
|
||||
Total uint64 `json:"total"`
|
||||
Used uint64 `json:"used"`
|
||||
Mode string
|
||||
}
|
||||
|
||||
func Ram() RamInfo {
|
||||
raminfo := RamInfo{}
|
||||
v, err := mem.VirtualMemory()
|
||||
type ProcMemInfo struct {
|
||||
MemTotal uint64
|
||||
MemFree uint64
|
||||
MemAvailable uint64
|
||||
Buffers uint64
|
||||
Cached uint64
|
||||
SwapTotal uint64
|
||||
SwapFree uint64
|
||||
SwapCached uint64
|
||||
Shmem uint64
|
||||
SReclaimable uint64
|
||||
Zswap uint64
|
||||
Zswapped uint64
|
||||
}
|
||||
|
||||
// readProcMeminfo reads /proc/meminfo and returns a filled ProcMemInfo struct
|
||||
func ReadProcMeminfo() (*ProcMemInfo, error) {
|
||||
file, err := os.Open("/proc/meminfo")
|
||||
if err != nil {
|
||||
raminfo.Total = 0
|
||||
raminfo.Used = 0
|
||||
return raminfo
|
||||
return nil, err
|
||||
}
|
||||
if flags.MemoryIncludeCache {
|
||||
defer file.Close()
|
||||
|
||||
info := &ProcMemInfo{}
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) < 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
key := strings.TrimSuffix(parts[0], ":")
|
||||
valStr := parts[1]
|
||||
val, err := strconv.ParseUint(valStr, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
val *= 1024 // Convert kB to bytes
|
||||
|
||||
switch key {
|
||||
case "MemTotal":
|
||||
info.MemTotal = val
|
||||
case "MemFree":
|
||||
info.MemFree = val
|
||||
case "MemAvailable":
|
||||
info.MemAvailable = val
|
||||
case "Buffers":
|
||||
info.Buffers = val
|
||||
case "Cached":
|
||||
info.Cached = val
|
||||
case "SwapTotal":
|
||||
info.SwapTotal = val
|
||||
case "SwapFree":
|
||||
info.SwapFree = val
|
||||
case "SwapCached":
|
||||
info.SwapCached = val
|
||||
case "Shmem":
|
||||
info.Shmem = val
|
||||
case "SReclaimable":
|
||||
info.SReclaimable = val
|
||||
case "Zswap":
|
||||
info.Zswap = val
|
||||
case "Zswapped":
|
||||
info.Zswapped = val
|
||||
}
|
||||
}
|
||||
return info, scanner.Err()
|
||||
}
|
||||
|
||||
func GetMemHtopLike() RamInfo {
|
||||
raminfo := RamInfo{Mode: "htoplike"}
|
||||
if runtime.GOOS == "linux" {
|
||||
info, err := ReadProcMeminfo()
|
||||
if err == nil && info.MemTotal > 0 {
|
||||
raminfo.Total = info.MemTotal
|
||||
// htop logic:
|
||||
// usedDiff = free + cached + sreclaimable + buffers
|
||||
usedDiff := info.MemFree + info.Cached + info.SReclaimable + info.Buffers
|
||||
|
||||
if info.MemTotal >= usedDiff {
|
||||
raminfo.Used = info.MemTotal - usedDiff
|
||||
} else {
|
||||
raminfo.Used = info.MemTotal - info.MemFree
|
||||
}
|
||||
|
||||
// Adjust for Zswap
|
||||
if info.Zswap > 0 || info.Zswapped > 0 {
|
||||
if raminfo.Used > info.Zswap {
|
||||
raminfo.Used -= info.Zswap
|
||||
} else {
|
||||
raminfo.Used = 0
|
||||
}
|
||||
}
|
||||
return raminfo
|
||||
}
|
||||
}
|
||||
return raminfo
|
||||
}
|
||||
|
||||
func GetMemGopsutil() RamInfo {
|
||||
raminfo := RamInfo{Mode: "gopsutil"}
|
||||
v, err := mem.VirtualMemory()
|
||||
if err == nil {
|
||||
raminfo.Total = v.Total
|
||||
raminfo.Used = v.Total - v.Free
|
||||
raminfo.Used = v.Total - v.Available
|
||||
}
|
||||
return raminfo
|
||||
}
|
||||
|
||||
// 这我还能干嘛,大伙天天说和free显示不一样,我也没办法
|
||||
func CallFree() RamInfo {
|
||||
raminfo := RamInfo{Mode: "callFree"}
|
||||
|
||||
// Only works on Linux/Unix systems
|
||||
if runtime.GOOS != "linux" && runtime.GOOS != "freebsd" {
|
||||
return raminfo
|
||||
}
|
||||
raminfo.Total = v.Total
|
||||
if runtime.GOOS == "windows" {
|
||||
raminfo.Used = v.Total - v.Available
|
||||
} else {
|
||||
raminfo.Used = v.Total - v.Free - v.Buffers - v.Cached
|
||||
|
||||
// Execute 'free -b' command to get memory in bytes
|
||||
cmd := exec.Command("free", "-b")
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
return raminfo
|
||||
}
|
||||
|
||||
// Parse the output
|
||||
scanner := bufio.NewScanner(&out)
|
||||
lineNum := 0
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
lineNum++
|
||||
|
||||
// Skip the header line
|
||||
if lineNum == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Parse the "Mem:" line
|
||||
if strings.HasPrefix(line, "Mem:") {
|
||||
fields := strings.Fields(line)
|
||||
// Format: Mem: total used free shared buff/cache available
|
||||
if len(fields) >= 3 {
|
||||
total, err := strconv.ParseUint(fields[1], 10, 64)
|
||||
if err == nil {
|
||||
raminfo.Total = total
|
||||
}
|
||||
|
||||
used, err := strconv.ParseUint(fields[2], 10, 64)
|
||||
if err == nil {
|
||||
raminfo.Used = used
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return raminfo
|
||||
}
|
||||
|
||||
func Ram() RamInfo {
|
||||
// Use global config
|
||||
if pkg_flags.GlobalConfig.MemoryIncludeCache {
|
||||
v, err := mem.VirtualMemory()
|
||||
if err != nil {
|
||||
return RamInfo{}
|
||||
}
|
||||
return RamInfo{
|
||||
Total: v.Total,
|
||||
Used: v.Total - v.Free,
|
||||
Mode: "includeCache",
|
||||
}
|
||||
}
|
||||
|
||||
if pkg_flags.GlobalConfig.MemoryReportRawUsed {
|
||||
return GetMemHtopLike()
|
||||
}
|
||||
|
||||
if runtime.GOOS == "linux" {
|
||||
h := GetMemHtopLike()
|
||||
if h.Total > 0 {
|
||||
return h
|
||||
}
|
||||
}
|
||||
|
||||
// Default fallback
|
||||
return GetMemGopsutil()
|
||||
}
|
||||
|
||||
func Swap() RamInfo {
|
||||
swapinfo := RamInfo{}
|
||||
|
||||
if runtime.GOOS == "linux" {
|
||||
info, err := ReadProcMeminfo()
|
||||
if err == nil {
|
||||
swapinfo.Total = info.SwapTotal
|
||||
// used = total - free - cached
|
||||
// Check for underflow
|
||||
usedDeductions := info.SwapFree + info.SwapCached
|
||||
if info.SwapTotal >= usedDeductions {
|
||||
swapinfo.Used = info.SwapTotal - usedDeductions
|
||||
} else {
|
||||
swapinfo.Used = info.SwapTotal - info.SwapFree
|
||||
}
|
||||
return swapinfo
|
||||
}
|
||||
}
|
||||
|
||||
s, err := mem.SwapMemory()
|
||||
if err != nil {
|
||||
swapinfo.Total = 0
|
||||
swapinfo.Used = 0
|
||||
} else {
|
||||
swapinfo.Total = s.Total
|
||||
swapinfo.Used = s.Used
|
||||
return swapinfo
|
||||
}
|
||||
swapinfo.Total = s.Total
|
||||
swapinfo.Used = s.Used
|
||||
return swapinfo
|
||||
}
|
||||
|
||||
163
monitoring/unit/mem_note.md
Normal file
163
monitoring/unit/mem_note.md
Normal file
@@ -0,0 +1,163 @@
|
||||
## Htop
|
||||
|
||||
被 Zswap/Zram 占用的物理内存,不应该算作应用程序的内存消耗
|
||||
SReclaimable 归为 Cached
|
||||
|
||||
```c
|
||||
static void LinuxMachine_scanMemoryInfo(LinuxMachine* this) {
|
||||
Machine* host = &this->super;
|
||||
memory_t availableMem = 0;
|
||||
memory_t freeMem = 0;
|
||||
memory_t totalMem = 0;
|
||||
memory_t buffersMem = 0;
|
||||
memory_t cachedMem = 0;
|
||||
memory_t sharedMem = 0;
|
||||
memory_t swapTotalMem = 0;
|
||||
memory_t swapCacheMem = 0;
|
||||
memory_t swapFreeMem = 0;
|
||||
memory_t sreclaimableMem = 0;
|
||||
memory_t zswapCompMem = 0;
|
||||
memory_t zswapOrigMem = 0;
|
||||
|
||||
FILE* file = fopen(PROCMEMINFOFILE, "r");
|
||||
if (!file)
|
||||
CRT_fatalError("Cannot open " PROCMEMINFOFILE);
|
||||
|
||||
char buffer[128];
|
||||
while (fgets(buffer, sizeof(buffer), file)) {
|
||||
|
||||
#define tryRead(label, variable) \
|
||||
if (String_startsWith(buffer, label)) { \
|
||||
memory_t parsed_; \
|
||||
if (sscanf(buffer + strlen(label), "%llu kB", &parsed_) == 1) { \
|
||||
(variable) = parsed_; \
|
||||
} \
|
||||
break; \
|
||||
} else (void) 0 /* Require a ";" after the macro use. */
|
||||
|
||||
switch (buffer[0]) {
|
||||
case 'M':
|
||||
tryRead("MemAvailable:", availableMem);
|
||||
tryRead("MemFree:", freeMem);
|
||||
tryRead("MemTotal:", totalMem);
|
||||
break;
|
||||
case 'B':
|
||||
tryRead("Buffers:", buffersMem);
|
||||
break;
|
||||
case 'C':
|
||||
tryRead("Cached:", cachedMem);
|
||||
break;
|
||||
case 'S':
|
||||
switch (buffer[1]) {
|
||||
case 'h':
|
||||
tryRead("Shmem:", sharedMem);
|
||||
break;
|
||||
case 'w':
|
||||
tryRead("SwapTotal:", swapTotalMem);
|
||||
tryRead("SwapCached:", swapCacheMem);
|
||||
tryRead("SwapFree:", swapFreeMem);
|
||||
break;
|
||||
case 'R':
|
||||
tryRead("SReclaimable:", sreclaimableMem);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 'Z':
|
||||
tryRead("Zswap:", zswapCompMem);
|
||||
tryRead("Zswapped:", zswapOrigMem);
|
||||
break;
|
||||
}
|
||||
|
||||
#undef tryRead
|
||||
}
|
||||
|
||||
fclose(file);
|
||||
|
||||
/*
|
||||
* Compute memory partition like procps(free)
|
||||
* https://gitlab.com/procps-ng/procps/-/blob/master/proc/sysinfo.c
|
||||
*
|
||||
* Adjustments:
|
||||
* - Shmem in part of Cached (see https://lore.kernel.org/patchwork/patch/648763/),
|
||||
* do not show twice by subtracting from Cached and do not subtract twice from used.
|
||||
*/
|
||||
host->totalMem = totalMem;
|
||||
host->cachedMem = cachedMem + sreclaimableMem - sharedMem;
|
||||
host->sharedMem = sharedMem;
|
||||
const memory_t usedDiff = freeMem + cachedMem + sreclaimableMem + buffersMem;
|
||||
host->usedMem = (totalMem >= usedDiff) ? totalMem - usedDiff : totalMem - freeMem;
|
||||
host->buffersMem = buffersMem;
|
||||
host->availableMem = availableMem != 0 ? MINIMUM(availableMem, totalMem) : freeMem;
|
||||
host->totalSwap = swapTotalMem;
|
||||
host->usedSwap = swapTotalMem - swapFreeMem - swapCacheMem;
|
||||
host->cachedSwap = swapCacheMem;
|
||||
this->zswap.usedZswapComp = zswapCompMem;
|
||||
this->zswap.usedZswapOrig = zswapOrigMem;
|
||||
}
|
||||
|
||||
|
||||
|
||||
static void MemoryMeter_updateValues(Meter* this) {
|
||||
char* buffer = this->txtBuffer;
|
||||
size_t size = sizeof(this->txtBuffer);
|
||||
int written;
|
||||
|
||||
Settings *settings = this->host->settings;
|
||||
|
||||
/* shared, compressed and available memory are not supported on all platforms */
|
||||
this->values[MEMORY_METER_SHARED] = NAN;
|
||||
this->values[MEMORY_METER_COMPRESSED] = NAN;
|
||||
this->values[MEMORY_METER_AVAILABLE] = NAN;
|
||||
Platform_setMemoryValues(this);
|
||||
if ((this->mode == GRAPH_METERMODE || this->mode == BAR_METERMODE) && !settings->showCachedMemory) {
|
||||
this->values[MEMORY_METER_BUFFERS] = 0;
|
||||
this->values[MEMORY_METER_CACHE] = 0;
|
||||
}
|
||||
/* Do not print available memory in bar mode */
|
||||
static_assert(MEMORY_METER_AVAILABLE + 1 == MEMORY_METER_ITEMCOUNT,
|
||||
"MEMORY_METER_AVAILABLE is not the last item in MemoryMeterValues");
|
||||
this->curItems = MEMORY_METER_AVAILABLE;
|
||||
|
||||
/* we actually want to show "used + shared + compressed" */
|
||||
double used = this->values[MEMORY_METER_USED];
|
||||
if (isPositive(this->values[MEMORY_METER_SHARED]))
|
||||
used += this->values[MEMORY_METER_SHARED];
|
||||
if (isPositive(this->values[MEMORY_METER_COMPRESSED]))
|
||||
used += this->values[MEMORY_METER_COMPRESSED];
|
||||
|
||||
written = Meter_humanUnit(buffer, used, size);
|
||||
METER_BUFFER_CHECK(buffer, size, written);
|
||||
|
||||
METER_BUFFER_APPEND_CHR(buffer, size, '/');
|
||||
|
||||
Meter_humanUnit(buffer, this->total, size);
|
||||
}
|
||||
|
||||
void Platform_setMemoryValues(Meter* this) {
|
||||
const Machine* host = this->host;
|
||||
const LinuxMachine* lhost = (const LinuxMachine*) host;
|
||||
|
||||
this->total = host->totalMem;
|
||||
this->values[MEMORY_METER_USED] = host->usedMem;
|
||||
this->values[MEMORY_METER_SHARED] = host->sharedMem;
|
||||
this->values[MEMORY_METER_COMPRESSED] = 0; /* compressed */
|
||||
this->values[MEMORY_METER_BUFFERS] = host->buffersMem;
|
||||
this->values[MEMORY_METER_CACHE] = host->cachedMem;
|
||||
this->values[MEMORY_METER_AVAILABLE] = host->availableMem;
|
||||
|
||||
if (lhost->zfs.enabled != 0 && !Running_containerized) {
|
||||
// ZFS does not shrink below the value of zfs_arc_min.
|
||||
unsigned long long int shrinkableSize = 0;
|
||||
if (lhost->zfs.size > lhost->zfs.min)
|
||||
shrinkableSize = lhost->zfs.size - lhost->zfs.min;
|
||||
this->values[MEMORY_METER_USED] -= shrinkableSize;
|
||||
this->values[MEMORY_METER_CACHE] += shrinkableSize;
|
||||
this->values[MEMORY_METER_AVAILABLE] += shrinkableSize;
|
||||
}
|
||||
|
||||
if (lhost->zswap.usedZswapOrig > 0 || lhost->zswap.usedZswapComp > 0) {
|
||||
this->values[MEMORY_METER_USED] -= lhost->zswap.usedZswapComp;
|
||||
this->values[MEMORY_METER_COMPRESSED] += lhost->zswap.usedZswapComp;
|
||||
}
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user