sys_server_monitor.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package apis
  2. import (
  3. "fmt"
  4. "github.com/shirou/gopsutil/v3/net"
  5. "regexp"
  6. "runtime"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/go-admin-team/go-admin-core/sdk/api"
  12. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  13. _ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
  14. "github.com/shirou/gopsutil/v3/cpu"
  15. "github.com/shirou/gopsutil/v3/disk"
  16. "github.com/shirou/gopsutil/v3/host"
  17. "github.com/shirou/gopsutil/v3/mem"
  18. )
  19. const (
  20. B = 1
  21. KB = 1024 * B
  22. MB = 1024 * KB
  23. GB = 1024 * MB
  24. )
  25. var (
  26. Version string
  27. expectDiskFsTypes = []string{
  28. "apfs", "ext4", "ext3", "ext2", "f2fs", "reiserfs", "jfs", "btrfs",
  29. "fuseblk", "zfs", "simfs", "ntfs", "fat32", "exfat", "xfs", "fuse.rclone",
  30. }
  31. excludeNetInterfaces = []string{
  32. "lo", "tun", "docker", "veth", "br-", "vmbr", "vnet", "kube",
  33. }
  34. getMacDiskNo = regexp.MustCompile(`\/dev\/disk(\d)s.*`)
  35. )
  36. var (
  37. netInSpeed, netOutSpeed, netInTransfer, netOutTransfer, lastUpdateNetStats uint64
  38. cachedBootTime time.Time
  39. )
  40. type ServerMonitor struct {
  41. api.Api
  42. }
  43. // GetHourDiffer 获取相差时间
  44. func GetHourDiffer(startTime, endTime string) int64 {
  45. var hour int64
  46. t1, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
  47. t2, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
  48. if err == nil && t1.Before(t2) {
  49. diff := t2.Unix() - t1.Unix() //
  50. hour = diff / 3600
  51. return hour
  52. } else {
  53. return hour
  54. }
  55. }
  56. // ServerInfo 获取系统信息
  57. // @Summary 系统信息
  58. // @Description 获取JSON
  59. // @Tags 系统信息
  60. // @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
  61. // @Router /api/v1/server-monitor [get]
  62. // @Security Bearer
  63. func (e ServerMonitor) ServerInfo(c *gin.Context) {
  64. e.Context = c
  65. sysInfo, err := host.Info()
  66. osDic := make(map[string]interface{}, 0)
  67. osDic["goOs"] = runtime.GOOS
  68. osDic["arch"] = runtime.GOARCH
  69. osDic["mem"] = runtime.MemProfileRate
  70. osDic["compiler"] = runtime.Compiler
  71. osDic["version"] = runtime.Version()
  72. osDic["numGoroutine"] = runtime.NumGoroutine()
  73. osDic["ip"] = pkg.GetLocaHonst()
  74. osDic["projectDir"] = pkg.GetCurrentPath()
  75. osDic["hostName"] = sysInfo.Hostname
  76. osDic["time"] = time.Now().Format("2006-01-02 15:04:05")
  77. mem, _ := mem.VirtualMemory()
  78. memDic := make(map[string]interface{}, 0)
  79. memDic["used"] = mem.Used / MB
  80. memDic["total"] = mem.Total / MB
  81. fmt.Println("mem", int(mem.Total/mem.Used*100))
  82. memDic["percent"] = pkg.Round(mem.UsedPercent, 2)
  83. swapDic := make(map[string]interface{}, 0)
  84. swapDic["used"] = mem.SwapTotal - mem.SwapFree
  85. swapDic["total"] = mem.SwapTotal
  86. cpuDic := make(map[string]interface{}, 0)
  87. cpuDic["cpuInfo"], _ = cpu.Info()
  88. percent, _ := cpu.Percent(0, false)
  89. cpuDic["percent"] = pkg.Round(percent[0], 2)
  90. cpuDic["cpuNum"], _ = cpu.Counts(false)
  91. //服务器磁盘信息
  92. disklist := make([]disk.UsageStat, 0)
  93. //所有分区
  94. var diskTotal, diskUsed, diskUsedPercent float64
  95. diskInfo, err := disk.Partitions(true)
  96. if err == nil {
  97. for _, p := range diskInfo {
  98. diskDetail, err := disk.Usage(p.Mountpoint)
  99. if err == nil {
  100. diskDetail.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", diskDetail.UsedPercent), 64)
  101. diskDetail.Total = diskDetail.Total / 1024 / 1024
  102. diskDetail.Used = diskDetail.Used / 1024 / 1024
  103. diskDetail.Free = diskDetail.Free / 1024 / 1024
  104. disklist = append(disklist, *diskDetail)
  105. }
  106. }
  107. }
  108. d, _ := disk.Usage("/")
  109. diskTotal = float64(d.Total / GB)
  110. diskUsed = float64(d.Used / GB)
  111. diskUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", d.UsedPercent), 64)
  112. diskDic := make(map[string]interface{}, 0)
  113. diskDic["total"] = diskTotal
  114. diskDic["used"] = diskUsed
  115. diskDic["percent"] = diskUsedPercent
  116. bootTime, _ := host.BootTime()
  117. cachedBootTime = time.Unix(int64(bootTime), 0)
  118. TrackNetworkSpeed()
  119. netDic := make(map[string]interface{}, 0)
  120. netDic["in"] = pkg.Round(float64(netInSpeed/KB), 2)
  121. netDic["out"] = pkg.Round(float64(netOutSpeed/KB), 2)
  122. e.Custom(gin.H{
  123. "code": 200,
  124. "os": osDic,
  125. "mem": memDic,
  126. "cpu": cpuDic,
  127. "disk": diskDic,
  128. "net": netDic,
  129. "swap": swapDic,
  130. "location": "Aliyun",
  131. "bootTime": GetHourDiffer(cachedBootTime.Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05")),
  132. })
  133. }
  134. func TrackNetworkSpeed() {
  135. var innerNetInTransfer, innerNetOutTransfer uint64
  136. nc, err := net.IOCounters(true)
  137. if err == nil {
  138. for _, v := range nc {
  139. if isListContainsStr(excludeNetInterfaces, v.Name) {
  140. continue
  141. }
  142. innerNetInTransfer += v.BytesRecv
  143. innerNetOutTransfer += v.BytesSent
  144. }
  145. now := uint64(time.Now().Unix())
  146. diff := now - lastUpdateNetStats
  147. if diff > 0 {
  148. netInSpeed = (innerNetInTransfer - netInTransfer) / diff
  149. fmt.Println("netInSpeed", netInSpeed)
  150. netOutSpeed = (innerNetOutTransfer - netOutTransfer) / diff
  151. fmt.Println("netOutSpeed", netOutSpeed)
  152. }
  153. netInTransfer = innerNetInTransfer
  154. netOutTransfer = innerNetOutTransfer
  155. lastUpdateNetStats = now
  156. }
  157. }
  158. func isListContainsStr(list []string, str string) bool {
  159. for i := 0; i < len(list); i++ {
  160. if strings.Contains(str, list[i]) {
  161. return true
  162. }
  163. }
  164. return false
  165. }