utils.go 2.0 KB

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