Files

174 lines
4.1 KiB
Go
Raw Permalink Normal View History

2019-02-13 03:54:00 +08:00
package tool
import (
2019-08-10 11:15:25 +08:00
"math"
"math/rand"
2019-08-10 11:15:25 +08:00
"strconv"
2026-06-05 15:56:38 -06:00
"sync"
"sync/atomic"
2019-08-10 11:15:25 +08:00
"time"
2020-01-08 21:57:14 +08:00
"ehang.io/nps/lib/common"
2019-08-10 11:10:01 +08:00
"github.com/astaxie/beego"
2021-04-07 20:02:47 +08:00
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/load"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/net"
2019-02-13 03:54:00 +08:00
)
2019-03-29 15:21:30 +08:00
var (
2026-06-05 15:56:38 -06:00
ports []int
ServerStatus []map[string]interface{}
ServerStatusMu sync.RWMutex
IORateCache atomic.Value
2019-03-29 15:21:30 +08:00
)
2019-04-08 17:01:08 +08:00
func StartSystemInfo() {
if b, err := beego.AppConfig.Bool("system_info_display"); err == nil && b {
ServerStatus = make([]map[string]interface{}, 0, 1500)
go getSeverStatus()
}
2019-03-29 15:21:30 +08:00
}
2019-02-13 03:54:00 +08:00
2019-03-23 22:19:59 +08:00
func InitAllowPort() {
2019-03-05 09:23:18 +08:00
p := beego.AppConfig.String("allow_ports")
2019-02-15 22:59:28 +08:00
ports = common.GetPorts(p)
2019-02-13 03:54:00 +08:00
}
2019-02-15 22:59:28 +08:00
2019-02-13 03:54:00 +08:00
func TestServerPort(p int, m string) (b bool) {
2019-12-06 16:20:00 +08:00
if m == "p2p" || m == "secret" {
return true
}
if p > 65535 || p < 0 {
2019-02-23 23:29:48 +08:00
return false
}
2019-02-13 03:54:00 +08:00
if len(ports) != 0 {
if !common.InIntArr(ports, p) {
return false
}
}
if m == "udp" {
2019-02-13 03:54:00 +08:00
b = common.TestUdpPort(p)
} else {
b = common.TestTcpPort(p)
}
return
}
2019-03-29 15:21:30 +08:00
func GenerateServerPort(m string) int {
// allow_ports 已配置:在允许范围内随机选取,打乱顺序后逐个尝试以避免重复命中已占用端口
if len(ports) != 0 {
shuffled := make([]int, len(ports))
copy(shuffled, ports)
rand.Shuffle(len(shuffled), func(i, j int) {
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
})
for _, p := range shuffled {
if TestServerPort(p, m) {
return p
}
}
return 0
}
2026-06-05 15:56:38 -06:00
for i := 0; i < 1000; i++ {
//生成随机数 1024 - 65535
serverPort := rand.Intn(65535)
if serverPort < 1024 {
serverPort = 1024
}
if TestServerPort(serverPort, m) {
return serverPort
}
}
2026-06-05 15:56:38 -06:00
return 0 // 超过最大重试次数,返回0表示无法分配端口
}
2019-03-29 15:21:30 +08:00
func getSeverStatus() {
for {
if len(ServerStatus) < 10 {
time.Sleep(time.Second)
} else {
time.Sleep(time.Minute)
}
cpuPercet, _ := cpu.Percent(0, true)
var cpuAll float64
for _, v := range cpuPercet {
cpuAll += v
}
m := make(map[string]interface{})
loads, _ := load.Avg()
m["load1"] = loads.Load1
m["load5"] = loads.Load5
m["load15"] = loads.Load15
m["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
swap, _ := mem.SwapMemory()
m["swap_mem"] = math.Round(swap.UsedPercent)
vir, _ := mem.VirtualMemory()
m["virtual_mem"] = math.Round(vir.UsedPercent)
conn, _ := net.ProtoCounters(nil)
2026-06-05 15:56:38 -06:00
if cached, ok := IORateCache.Load().(map[string]uint64); ok {
m["io_send"] = cached["io_send"]
m["io_recv"] = cached["io_recv"]
2019-03-29 15:21:30 +08:00
}
t := time.Now()
m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
for _, v := range conn {
m[v.Protocol] = v.Stats["CurrEstab"]
}
if len(ServerStatus) >= 1440 {
2026-06-05 15:56:38 -06:00
ServerStatusMu.Lock()
2019-03-29 15:21:30 +08:00
ServerStatus = ServerStatus[1:]
2026-06-05 15:56:38 -06:00
ServerStatusMu.Unlock()
2019-03-29 15:21:30 +08:00
}
2026-06-05 15:56:38 -06:00
ServerStatusMu.Lock()
2019-03-29 15:21:30 +08:00
ServerStatus = append(ServerStatus, m)
2026-06-05 15:56:38 -06:00
ServerStatusMu.Unlock()
}
}
// StartIORateCollector 启动后台 IO 速率采集,每 2s 刷新一次 IORateCache
func StartIORateCollector() {
go collectIORate()
}
func collectIORate() {
var lastSent, lastRecv uint64
// 修复:无论首次 IOCounters 是否成功,都把 lastTime 设为 now,
// 否则首次有效采样的 elapsed 会是几十年,导致 sendRate/recvRate 直接为 0
lastTime := time.Now()
if io, err := net.IOCounters(false); err == nil && len(io) > 0 {
lastSent = io[0].BytesSent
lastRecv = io[0].BytesRecv
}
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for range ticker.C {
now := time.Now()
io, err := net.IOCounters(false)
if err != nil || len(io) == 0 {
continue
}
elapsed := now.Sub(lastTime).Seconds()
if elapsed <= 0 {
continue
}
var sendRate, recvRate uint64
if io[0].BytesSent >= lastSent {
sendRate = uint64(float64(io[0].BytesSent-lastSent) / elapsed)
}
if io[0].BytesRecv >= lastRecv {
recvRate = uint64(float64(io[0].BytesRecv-lastRecv) / elapsed)
}
lastSent = io[0].BytesSent
lastRecv = io[0].BytesRecv
lastTime = now
IORateCache.Store(map[string]uint64{
"io_send": sendRate,
"io_recv": recvRate,
})
2019-03-29 15:21:30 +08:00
}
}