utils.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package tool
  2. import (
  3. "math"
  4. "strconv"
  5. "time"
  6. "github.com/astaxie/beego"
  7. "github.com/cnlh/nps/lib/common"
  8. "github.com/shirou/gopsutil/cpu"
  9. "github.com/shirou/gopsutil/load"
  10. "github.com/shirou/gopsutil/mem"
  11. "github.com/shirou/gopsutil/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 p > 65535 || p < 0 {
  29. return false
  30. }
  31. if len(ports) != 0 {
  32. if !common.InIntArr(ports, p) {
  33. return false
  34. }
  35. }
  36. if m == "udp" {
  37. b = common.TestUdpPort(p)
  38. } else {
  39. b = common.TestTcpPort(p)
  40. }
  41. return
  42. }
  43. func getSeverStatus() {
  44. for {
  45. if len(ServerStatus) < 10 {
  46. time.Sleep(time.Second)
  47. } else {
  48. time.Sleep(time.Minute)
  49. }
  50. cpuPercet, _ := cpu.Percent(0, true)
  51. var cpuAll float64
  52. for _, v := range cpuPercet {
  53. cpuAll += v
  54. }
  55. m := make(map[string]interface{})
  56. loads, _ := load.Avg()
  57. m["load1"] = loads.Load1
  58. m["load5"] = loads.Load5
  59. m["load15"] = loads.Load15
  60. m["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
  61. swap, _ := mem.SwapMemory()
  62. m["swap_mem"] = math.Round(swap.UsedPercent)
  63. vir, _ := mem.VirtualMemory()
  64. m["virtual_mem"] = math.Round(vir.UsedPercent)
  65. conn, _ := net.ProtoCounters(nil)
  66. io1, _ := net.IOCounters(false)
  67. time.Sleep(time.Millisecond * 500)
  68. io2, _ := net.IOCounters(false)
  69. if len(io2) > 0 && len(io1) > 0 {
  70. m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
  71. m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
  72. }
  73. t := time.Now()
  74. m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
  75. for _, v := range conn {
  76. m[v.Protocol] = v.Stats["CurrEstab"]
  77. }
  78. if len(ServerStatus) >= 1440 {
  79. ServerStatus = ServerStatus[1:]
  80. }
  81. ServerStatus = append(ServerStatus, m)
  82. }
  83. }