nps/server/tool/utils.go

91 lines
2.1 KiB
Go
Raw Normal View History

2019-02-12 19:54:00 +00:00
package tool
import (
"github.com/cnlh/nps/lib/common"
2019-02-16 12:43:26 +00:00
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
2019-03-29 07:21:30 +00:00
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/net"
"math"
"strconv"
"time"
2019-02-12 19:54:00 +00:00
)
2019-03-29 07:21:30 +00:00
var (
ports []int
ServerStatus []map[string]interface{}
)
2019-04-08 09:01:08 +00: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 07:21:30 +00:00
}
2019-02-12 19:54:00 +00:00
2019-03-23 14:19:59 +00:00
func InitAllowPort() {
2019-03-05 01:23:18 +00:00
p := beego.AppConfig.String("allow_ports")
2019-02-15 14:59:28 +00:00
ports = common.GetPorts(p)
2019-02-12 19:54:00 +00:00
}
2019-02-15 14:59:28 +00:00
2019-02-12 19:54:00 +00:00
func TestServerPort(p int, m string) (b bool) {
if p > 65535 || p < 0 {
2019-02-23 15:29:48 +00:00
return false
}
2019-02-12 19:54:00 +00:00
if len(ports) != 0 {
if !common.InIntArr(ports, p) {
return false
}
}
if m == "udp" {
2019-02-12 19:54:00 +00:00
b = common.TestUdpPort(p)
} else {
b = common.TestTcpPort(p)
}
return
}
2019-03-29 07:21:30 +00: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)
io1, _ := net.IOCounters(false)
time.Sleep(time.Millisecond * 500)
io2, _ := net.IOCounters(false)
if len(io2) > 0 && len(io1) > 0 {
m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
}
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 {
ServerStatus = ServerStatus[1:]
}
ServerStatus = append(ServerStatus, m)
}
}