utils.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package tool
  2. import (
  3. "math"
  4. "strconv"
  5. "time"
  6. "ehang.io/nps/lib/common"
  7. "github.com/astaxie/beego"
  8. "github.com/shirou/gopsutil/v3/cpu"
  9. "github.com/shirou/gopsutil/v3/load"
  10. "github.com/shirou/gopsutil/v3/mem"
  11. "github.com/shirou/gopsutil/v3/net"
  12. )
  13. var (
  14. ports []int
  15. ServerStatus []map[string]interface{}
  16. )
  17. func StartSystemInfo() {
  18. if b, err := beego.AppConfig.Bool("system_info_display"); err == nil && b {
  19. ServerStatus = make([]map[string]interface{}, 0, 1500)
  20. go getSeverStatus()
  21. }
  22. }
  23. func InitAllowPort() {
  24. p := beego.AppConfig.String("allow_ports")
  25. ports = common.GetPorts(p)
  26. }
  27. func TestServerPort(p int, m string) (b bool) {
  28. if m == "p2p" || m == "secret" {
  29. return true
  30. }
  31. if p > 65535 || p < 0 {
  32. return false
  33. }
  34. if len(ports) != 0 {
  35. if !common.InIntArr(ports, p) {
  36. return false
  37. }
  38. }
  39. if m == "udp" {
  40. b = common.TestUdpPort(p)
  41. } else {
  42. b = common.TestTcpPort(p)
  43. }
  44. return
  45. }
  46. func getSeverStatus() {
  47. for {
  48. if len(ServerStatus) < 10 {
  49. time.Sleep(time.Second)
  50. } else {
  51. time.Sleep(time.Minute)
  52. }
  53. cpuPercet, _ := cpu.Percent(0, true)
  54. var cpuAll float64
  55. for _, v := range cpuPercet {
  56. cpuAll += v
  57. }
  58. m := make(map[string]interface{})
  59. loads, _ := load.Avg()
  60. m["load1"] = loads.Load1
  61. m["load5"] = loads.Load5
  62. m["load15"] = loads.Load15
  63. m["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
  64. swap, _ := mem.SwapMemory()
  65. m["swap_mem"] = math.Round(swap.UsedPercent)
  66. vir, _ := mem.VirtualMemory()
  67. m["virtual_mem"] = math.Round(vir.UsedPercent)
  68. conn, _ := net.ProtoCounters(nil)
  69. io1, _ := net.IOCounters(false)
  70. time.Sleep(time.Millisecond * 500)
  71. io2, _ := net.IOCounters(false)
  72. if len(io2) > 0 && len(io1) > 0 {
  73. m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
  74. m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
  75. }
  76. t := time.Now()
  77. m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
  78. for _, v := range conn {
  79. m[v.Protocol] = v.Stats["CurrEstab"]
  80. }
  81. if len(ServerStatus) >= 1440 {
  82. ServerStatus = ServerStatus[1:]
  83. }
  84. ServerStatus = append(ServerStatus, m)
  85. }
  86. }