github.com/TeaOSLab/EdgeNode@v1.3.8/internal/nodes/node_status_executor_unix.go (about)

     1  //go:build !windows
     2  
     3  package nodes
     4  
     5  import (
     6  	"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
     7  	"github.com/TeaOSLab/EdgeNode/internal/monitor"
     8  	"github.com/iwind/TeaGo/maps"
     9  	"github.com/shirou/gopsutil/v3/load"
    10  	"github.com/shirou/gopsutil/v3/mem"
    11  	"runtime"
    12  	"runtime/debug"
    13  )
    14  
    15  // 更新内存
    16  func (this *NodeStatusExecutor) updateMem(status *nodeconfigs.NodeStatus) {
    17  	stat, err := mem.VirtualMemory()
    18  	if err != nil {
    19  		return
    20  	}
    21  
    22  	// 重新计算内存
    23  	if stat.Total > 0 {
    24  		stat.Used = stat.Total - stat.Free - stat.Buffers - stat.Cached
    25  		status.MemoryUsage = float64(stat.Used) / float64(stat.Total)
    26  	}
    27  
    28  	status.MemoryTotal = stat.Total
    29  
    30  	// 记录监控数据
    31  	monitor.SharedValueQueue.Add(nodeconfigs.NodeValueItemMemory, maps.Map{
    32  		"usage": status.MemoryUsage,
    33  		"total": status.MemoryTotal,
    34  		"used":  stat.Used,
    35  	})
    36  
    37  	// 内存严重不足时自动释放内存
    38  	if stat.Total > 0 {
    39  		var minFreeMemory = stat.Total / 8
    40  		if minFreeMemory > 1<<30 {
    41  			minFreeMemory = 1 << 30
    42  		}
    43  		if stat.Available > 0 && stat.Available < minFreeMemory {
    44  			runtime.GC()
    45  			debug.FreeOSMemory()
    46  		}
    47  	}
    48  }
    49  
    50  // 更新负载
    51  func (this *NodeStatusExecutor) updateLoad(status *nodeconfigs.NodeStatus) {
    52  	stat, err := load.Avg()
    53  	if err != nil {
    54  		status.Error = err.Error()
    55  		return
    56  	}
    57  	if stat == nil {
    58  		status.Error = "load is nil"
    59  		return
    60  	}
    61  	status.Load1m = stat.Load1
    62  	status.Load5m = stat.Load5
    63  	status.Load15m = stat.Load15
    64  
    65  	// 记录监控数据
    66  	monitor.SharedValueQueue.Add(nodeconfigs.NodeValueItemLoad, maps.Map{
    67  		"load1m":  status.Load1m,
    68  		"load5m":  status.Load5m,
    69  		"load15m": status.Load15m,
    70  	})
    71  }