page1_handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. var services = []struct {
  246. name string
  247. dir string
  248. bin string
  249. }{
  250. {"yfkj-networkd.service", "/opt/yfkj/networkd.service", "networkd"},
  251. {"yfkj-timesyncd.service", "/opt/yfkj/timesyncd.service", "timesyncd"},
  252. {"yfkj-gnss.service", "/opt/yfkj/gnss.service", "gnss"},
  253. {"yfkj-sshd-mqtt-bridge.service", "/opt/yfkj/sshd-mqtt-bridge.service", "sshd-mqtt-bridge"},
  254. {"yfkj-camera-capture.service", "/opt/yfkj/camera-capture.service", "camera-capture"},
  255. {"yfkj-app-install.service", "/opt/yfkj/app-install.service", "app-install"},
  256. {"yfkj-web-ui.service", "/opt/yfkj/web-ui.service", "web-ui"},
  257. {"yfkj-upgrade.service", "/opt/yfkj/upgrade.service", "upgrade"},
  258. }
  259. func serviceStatusHandler(w http.ResponseWriter, r *http.Request) {
  260. if r.Method != http.MethodGet {
  261. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  262. return
  263. }
  264. data := make(map[string]string, len(services)*2)
  265. for i, s := range services {
  266. n := i + 1
  267. status := noValue
  268. if out, err := exec.Command("systemctl", "is-active", s.name).Output(); err == nil &&
  269. strings.TrimSpace(string(out)) == "active" {
  270. status = "🟢运行中..."
  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. }
  282. type VersionSwitchReq struct {
  283. Service string `json:"service"`
  284. Action string `json:"action"`
  285. Password string `json:"password"`
  286. }
  287. type VersionResp struct {
  288. Status string `json:"status"`
  289. Message string `json:"message,omitempty"`
  290. }
  291. var versionSwitchLock sync.Mutex
  292. func serviceVersionSwitchHandler(w http.ResponseWriter, r *http.Request) {
  293. if r.Method != http.MethodPost {
  294. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  295. return
  296. }
  297. versionSwitchLock.Lock()
  298. defer versionSwitchLock.Unlock()
  299. var req VersionSwitchReq
  300. if json.NewDecoder(r.Body).Decode(&req) != nil {
  301. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid request"})
  302. return
  303. }
  304. if req.Password != "yfkj123456" {
  305. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "输入的密码不正确"})
  306. return
  307. }
  308. var cfg struct{ name, dir, bin string }
  309. for _, v := range services {
  310. if v.name == req.Service {
  311. cfg = v
  312. break
  313. }
  314. }
  315. if cfg.name == "" {
  316. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "unknown service"})
  317. return
  318. }
  319. link := filepath.Join(cfg.dir, cfg.bin)
  320. oldLink, err := os.Readlink(link)
  321. if err != nil {
  322. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "读取当前版本失败"})
  323. return
  324. }
  325. current := filepath.Base(filepath.Dir(oldLink))
  326. if current != "a" && current != "b" && current != "c" {
  327. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "当前版本状态异常"})
  328. return
  329. }
  330. target := ""
  331. switch req.Action {
  332. case "factory":
  333. if current == "a" {
  334. json.NewEncoder(w).Encode(VersionResp{Status: "ok", Message: "当前已是出厂版本"})
  335. return
  336. }
  337. target = "a"
  338. case "previous":
  339. switch current {
  340. case "b":
  341. if info, err := os.Stat(filepath.Join(cfg.dir, "c", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  342. target = "c"
  343. }
  344. case "c":
  345. if info, err := os.Stat(filepath.Join(cfg.dir, "b", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  346. target = "b"
  347. }
  348. }
  349. if target == "" {
  350. json.NewEncoder(w).Encode(VersionResp{
  351. Status: "error",
  352. Message: "当前没有可回退的上一版本",
  353. })
  354. return
  355. }
  356. default:
  357. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid action"})
  358. return
  359. }
  360. targetBin := filepath.Join(cfg.dir, target, cfg.bin)
  361. info, err := os.Stat(targetBin)
  362. if err != nil || info.IsDir() || info.Size() == 0 || info.Mode().Perm()&0111 == 0 {
  363. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("目标版本文件异常: %s", target)})
  364. return
  365. }
  366. if out, err := exec.Command("systemctl", "stop", req.Service).CombinedOutput(); err != nil {
  367. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("停止当前服务失败: %s", out)})
  368. return
  369. }
  370. tmp := filepath.Join(cfg.dir, cfg.bin+".tmp")
  371. os.Remove(tmp)
  372. if err := os.Symlink(filepath.Join(target, cfg.bin), tmp); err != nil {
  373. exec.Command("systemctl", "start", req.Service).Run()
  374. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  375. return
  376. }
  377. if err := os.Rename(tmp, link); err != nil {
  378. os.Remove(tmp)
  379. exec.Command("systemctl", "start", req.Service).Run()
  380. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  381. return
  382. }
  383. if out, err := exec.Command("systemctl", "start", req.Service).CombinedOutput(); err != nil {
  384. tmp := filepath.Join(cfg.dir, cfg.bin+".tmp")
  385. os.Remove(tmp)
  386. if e := os.Symlink(oldLink, tmp); e == nil {
  387. if e = os.Rename(tmp, link); e != nil {
  388. os.Remove(tmp)
  389. }
  390. }
  391. exec.Command("systemctl", "start", req.Service).Run()
  392. json.NewEncoder(w).Encode(VersionResp{
  393. Status: "error",
  394. Message: fmt.Sprintf("目标版本启动失败,已恢复旧版本: %s", out),
  395. })
  396. return
  397. }
  398. json.NewEncoder(w).Encode(VersionResp{Status: "ok"})
  399. }