page1_handler.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. var lastCPU struct {
  16. idle, total uint64
  17. mu sync.Mutex
  18. }
  19. func initCPUUsage() {
  20. getCPUUsage()
  21. }
  22. func systemInfoHandler(w http.ResponseWriter, r *http.Request) {
  23. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  24. memPercent, memUsed, memTotal := getMemInfo()
  25. diskPercent, diskUsed, diskTotal := getDiskInfo()
  26. json.NewEncoder(w).Encode(map[string]any{
  27. "cpu_usage": getCPUUsage(),
  28. "cpu_cores": getCPUCore(),
  29. "cpu_freq": getCPUFreq(),
  30. "cpu_temp": getCPUTemperature(),
  31. "mem_percent": memPercent,
  32. "mem_used": memUsed,
  33. "mem_total": memTotal,
  34. "disk_percent": diskPercent,
  35. "disk_used": diskUsed,
  36. "disk_total": diskTotal,
  37. })
  38. }
  39. func getCPUUsage() int {
  40. lastCPU.mu.Lock()
  41. defer lastCPU.mu.Unlock()
  42. data, err := os.ReadFile("/proc/stat")
  43. if err != nil {
  44. return 0
  45. }
  46. f := strings.Fields(strings.Split(string(data), "\n")[0])
  47. if len(f) < 5 {
  48. return 0
  49. }
  50. var idle, total uint64
  51. for i := 1; i < len(f); i++ {
  52. v, err := strconv.ParseUint(f[i], 10, 64)
  53. if err != nil {
  54. continue
  55. }
  56. total += v
  57. // idle + iowait
  58. if i == 4 || i == 5 {
  59. idle += v
  60. }
  61. }
  62. if lastCPU.total == 0 {
  63. lastCPU.idle = idle
  64. lastCPU.total = total
  65. return 0
  66. }
  67. dt := total - lastCPU.total
  68. di := idle - lastCPU.idle
  69. lastCPU.idle = idle
  70. lastCPU.total = total
  71. if dt == 0 {
  72. return 0
  73. }
  74. return int((dt - di) * 100 / dt)
  75. }
  76. func getCPUCore() int {
  77. return runtime.NumCPU()
  78. }
  79. func getCPUFreq() string {
  80. var total, count int
  81. for i := 0; ; i++ {
  82. data, err := os.ReadFile(fmt.Sprintf("/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i))
  83. if err != nil {
  84. break
  85. }
  86. freq, err := strconv.Atoi(strings.TrimSpace(string(data)))
  87. if err != nil {
  88. continue
  89. }
  90. total += freq / 1000
  91. count++
  92. }
  93. if count > 0 {
  94. return strconv.Itoa(total / count)
  95. }
  96. data, err := os.ReadFile("/proc/cpuinfo")
  97. if err == nil {
  98. for _, line := range strings.Split(string(data), "\n") {
  99. if strings.HasPrefix(line, "cpu MHz") {
  100. f := strings.Split(line, ":")
  101. if len(f) == 2 {
  102. v, err := strconv.ParseFloat(strings.TrimSpace(f[1]), 64)
  103. if err == nil {
  104. return strconv.Itoa(int(v))
  105. }
  106. }
  107. }
  108. }
  109. }
  110. return noValue
  111. }
  112. func getCPUTemperature() string {
  113. files, _ := filepath.Glob("/sys/class/thermal/thermal_zone*/temp")
  114. max := 0
  115. for _, f := range files {
  116. data, err := os.ReadFile(f)
  117. if err != nil {
  118. continue
  119. }
  120. temp, err := strconv.Atoi(strings.TrimSpace(string(data)))
  121. if err == nil && temp > max {
  122. max = temp
  123. }
  124. }
  125. if max == 0 {
  126. return noValue
  127. }
  128. return fmt.Sprintf("%d℃", max/1000)
  129. }
  130. func getMemInfo() (int, string, string) {
  131. data, err := os.ReadFile("/proc/meminfo")
  132. if err != nil {
  133. return 0, noValue, noValue
  134. }
  135. var total, avail uint64
  136. for _, line := range strings.Split(string(data), "\n") {
  137. f := strings.Fields(line)
  138. if len(f) < 2 {
  139. continue
  140. }
  141. switch f[0] {
  142. case "MemTotal:":
  143. total, _ = strconv.ParseUint(f[1], 10, 64)
  144. case "MemAvailable:":
  145. avail, _ = strconv.ParseUint(f[1], 10, 64)
  146. }
  147. }
  148. if total == 0 {
  149. return 0, noValue, noValue
  150. }
  151. used := total - avail
  152. return int(used * 100 / total),
  153. formatSize(used * 1024),
  154. formatSize(total * 1024)
  155. }
  156. func getDiskInfo() (int, string, string) {
  157. out, err := exec.Command("df", "-h", "/").Output()
  158. if err != nil {
  159. return 0, noValue, noValue
  160. }
  161. lines := strings.Split(string(out), "\n")
  162. if len(lines) < 2 {
  163. return 0, noValue, noValue
  164. }
  165. f := strings.Fields(lines[1])
  166. if len(f) < 5 {
  167. return 0, noValue, noValue
  168. }
  169. percent, err := strconv.Atoi(strings.TrimSuffix(f[4], "%"))
  170. if err != nil {
  171. percent = 0
  172. }
  173. return percent, f[2], f[1]
  174. }
  175. func formatSize(size uint64) string {
  176. const (
  177. KB = 1024
  178. MB = KB * 1024
  179. GB = MB * 1024
  180. )
  181. switch {
  182. case size >= GB:
  183. return fmt.Sprintf("%.1fGB", float64(size)/GB)
  184. case size >= MB:
  185. return fmt.Sprintf("%.0fMB", float64(size)/MB)
  186. case size >= KB:
  187. return fmt.Sprintf("%.0fKB", float64(size)/KB)
  188. default:
  189. return fmt.Sprintf("%dB", size)
  190. }
  191. }
  192. func systemLoadAverageHandler(w http.ResponseWriter, r *http.Request) {
  193. data, err := os.ReadFile("/proc/loadavg")
  194. if err != nil {
  195. http.Error(w, err.Error(), http.StatusInternalServerError)
  196. return
  197. }
  198. fields := strings.Fields(string(data))
  199. if len(fields) < 4 {
  200. http.Error(w, "invalid /proc/loadavg", http.StatusInternalServerError)
  201. return
  202. }
  203. boot, uptime := noValue, noValue
  204. if b, err := os.ReadFile("/proc/uptime"); err == nil {
  205. if fields := strings.Fields(string(b)); len(fields) > 0 {
  206. if sec, err := strconv.ParseFloat(fields[0], 64); err == nil {
  207. d := time.Duration(sec) * time.Second
  208. boot = time.Now().Add(-d).Format("2006-01-02 15:04:05")
  209. day := int(d.Hours() / 24)
  210. if day > 0 {
  211. uptime = fmt.Sprintf("%d天 %02d:%02d:%02d",
  212. int(d.Hours()/24), int(d.Hours())%24, int(d.Minutes())%60, int(d.Seconds())%60)
  213. } else {
  214. uptime = fmt.Sprintf("%02d:%02d:%02d",
  215. int(d.Hours())%24, int(d.Minutes())%60, int(d.Seconds())%60)
  216. }
  217. }
  218. }
  219. }
  220. resp := struct {
  221. Load1m string `json:"load1m"`
  222. Load5m string `json:"load5m"`
  223. Load15m string `json:"load15m"`
  224. RunQueue string `json:"runQueue"`
  225. BootTime string `json:"bootTime"`
  226. UpTime string `json:"uptime"`
  227. }{
  228. Load1m: formatLoad(fields[0]),
  229. Load5m: formatLoad(fields[1]),
  230. Load15m: formatLoad(fields[2]),
  231. RunQueue: fields[3],
  232. BootTime: boot,
  233. UpTime: uptime,
  234. }
  235. w.Header().Set("Content-Type", "application/json")
  236. json.NewEncoder(w).Encode(resp)
  237. }
  238. func formatLoad(v string) string {
  239. f, err := strconv.ParseFloat(v, 64)
  240. if err != nil {
  241. return noValue
  242. }
  243. return strconv.FormatFloat(f, 'f', 2, 64)
  244. }
  245. func serviceStatusHandler(w http.ResponseWriter, r *http.Request) {
  246. if r.Method != http.MethodGet {
  247. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  248. return
  249. }
  250. services := []struct {
  251. name string
  252. dir string
  253. }{
  254. {"yfkj-networkd.service", "/opt/yfkj/networkd.service"},
  255. {"yfkj-timesyncd.service", "/opt/yfkj/timesyncd.service"},
  256. {"yfkj-gnss.service", "/opt/yfkj/gnss.service"},
  257. {"yfkj-sshd-mqtt-bridge.service", "/opt/yfkj/sshd-mqtt-bridge.service"},
  258. {"yfkj-camera-capture.service", "/opt/yfkj/camera-capture.service"},
  259. {"yfkj-app-install.service", "/opt/yfkj/app-install.service"},
  260. {"yfkj-web-ui.service", "/opt/yfkj/web-ui.service"},
  261. {"yfkj-upgrade.service", "/opt/yfkj/upgrade.service"},
  262. }
  263. data := make(map[string]string, len(services)*2)
  264. for i, s := range services {
  265. n := i + 1
  266. status := noValue
  267. if out, err := exec.Command("systemctl", "is-active", s.name).Output(); err == nil {
  268. if strings.TrimSpace(string(out)) == "active" {
  269. status = "🟢运行中..."
  270. }
  271. }
  272. data[fmt.Sprintf("var%d", n)] = status
  273. if v, err := os.ReadFile(filepath.Join(s.dir, "version.txt")); err == nil {
  274. data[fmt.Sprintf("var%d%d", n, n)] = "v" + strings.TrimSpace(string(v))
  275. } else {
  276. data[fmt.Sprintf("var%d%d", n, n)] = noValue
  277. }
  278. }
  279. w.Header().Set("Content-Type", "application/json")
  280. json.NewEncoder(w).Encode(data)
  281. }