page1_handler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 cpuStat struct {
  16. sync.Mutex
  17. lastIdle uint64
  18. lastTotal uint64
  19. usage float64
  20. }
  21. var systemInfoCache struct {
  22. sync.RWMutex
  23. data map[string]any
  24. }
  25. func initCPUUsage() {
  26. updateCPUUsage()
  27. }
  28. func updateSystemInfoCache() {
  29. memPercent, memUsed, memTotal := getMemInfo()
  30. diskPercent, diskUsed, diskTotal := getDiskInfo()
  31. data := map[string]any{
  32. "cpu_usage": updateCPUUsage(),
  33. "cpu_cores": getCPUCore(),
  34. "cpu_freq": getCPUFreq(),
  35. "cpu_temp": getCPUTemperature(),
  36. "mem_percent": memPercent,
  37. "mem_used": memUsed,
  38. "mem_total": memTotal,
  39. "disk_percent": diskPercent,
  40. "disk_used": diskUsed,
  41. "disk_total": diskTotal,
  42. }
  43. systemInfoCache.Lock()
  44. systemInfoCache.data = data
  45. systemInfoCache.Unlock()
  46. }
  47. func startSystemInfoCache() {
  48. updateSystemInfoCache()
  49. go func() {
  50. ticker := time.NewTicker(5 * time.Second)
  51. defer ticker.Stop()
  52. for range ticker.C {
  53. updateSystemInfoCache()
  54. }
  55. }()
  56. }
  57. func systemInfoHandler(w http.ResponseWriter, r *http.Request) {
  58. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  59. systemInfoCache.RLock()
  60. data := systemInfoCache.data
  61. systemInfoCache.RUnlock()
  62. json.NewEncoder(w).Encode(data)
  63. }
  64. func updateCPUUsage() float64 {
  65. cpuStat.Lock()
  66. defer cpuStat.Unlock()
  67. data, err := os.ReadFile("/proc/stat")
  68. if err != nil {
  69. return cpuStat.usage
  70. }
  71. fields := strings.Fields(strings.SplitN(string(data), "\n", 2)[0])
  72. if len(fields) < 5 {
  73. return cpuStat.usage
  74. }
  75. var idle uint64
  76. var total uint64
  77. for i := 1; i < len(fields); i++ {
  78. v, err := strconv.ParseUint(fields[i], 10, 64)
  79. if err != nil {
  80. continue
  81. }
  82. total += v
  83. if i == 4 || i == 5 {
  84. idle += v
  85. }
  86. }
  87. if cpuStat.lastTotal == 0 {
  88. cpuStat.lastTotal = total
  89. cpuStat.lastIdle = idle
  90. return 0
  91. }
  92. deltaTotal := total - cpuStat.lastTotal
  93. deltaIdle := idle - cpuStat.lastIdle
  94. cpuStat.lastTotal = total
  95. cpuStat.lastIdle = idle
  96. if deltaTotal == 0 {
  97. return cpuStat.usage
  98. }
  99. cpuStat.usage = float64(deltaTotal-deltaIdle) * 100 / float64(deltaTotal)
  100. return cpuStat.usage
  101. }
  102. func getCPUCore() int {
  103. return runtime.NumCPU()
  104. }
  105. func getCPUFreq() string {
  106. var total, count int
  107. for i := 0; ; i++ {
  108. data, err := os.ReadFile(fmt.Sprintf("/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i))
  109. if err != nil {
  110. break
  111. }
  112. freq, err := strconv.Atoi(strings.TrimSpace(string(data)))
  113. if err != nil {
  114. continue
  115. }
  116. total += freq / 1000
  117. count++
  118. }
  119. if count > 0 {
  120. return strconv.Itoa(total / count)
  121. }
  122. data, err := os.ReadFile("/proc/cpuinfo")
  123. if err == nil {
  124. for _, line := range strings.Split(string(data), "\n") {
  125. if strings.HasPrefix(line, "cpu MHz") {
  126. f := strings.Split(line, ":")
  127. if len(f) == 2 {
  128. v, err := strconv.ParseFloat(strings.TrimSpace(f[1]), 64)
  129. if err == nil {
  130. return strconv.Itoa(int(v))
  131. }
  132. }
  133. }
  134. }
  135. }
  136. return noValue
  137. }
  138. func getCPUTemperature() string {
  139. files, _ := filepath.Glob("/sys/class/thermal/thermal_zone*/temp")
  140. max := 0
  141. for _, f := range files {
  142. data, err := os.ReadFile(f)
  143. if err != nil {
  144. continue
  145. }
  146. temp, err := strconv.Atoi(strings.TrimSpace(string(data)))
  147. if err == nil && temp > max {
  148. max = temp
  149. }
  150. }
  151. if max == 0 {
  152. return noValue
  153. }
  154. return fmt.Sprintf("%d℃", max/1000)
  155. }
  156. func getMemInfo() (int, string, string) {
  157. data, err := os.ReadFile("/proc/meminfo")
  158. if err != nil {
  159. return 0, noValue, noValue
  160. }
  161. var total, avail uint64
  162. for _, line := range strings.Split(string(data), "\n") {
  163. f := strings.Fields(line)
  164. if len(f) < 2 {
  165. continue
  166. }
  167. switch f[0] {
  168. case "MemTotal:":
  169. total, _ = strconv.ParseUint(f[1], 10, 64)
  170. case "MemAvailable:":
  171. avail, _ = strconv.ParseUint(f[1], 10, 64)
  172. }
  173. }
  174. if total == 0 {
  175. return 0, noValue, noValue
  176. }
  177. used := total - avail
  178. return int(used * 100 / total), formatSize(used * 1024), formatSize(total * 1024)
  179. }
  180. func getDiskInfo() (int, string, string) {
  181. out, err := exec.Command("df", "-hP", "/").Output()
  182. if err != nil {
  183. return 0, noValue, noValue
  184. }
  185. lines := strings.Split(string(out), "\n")
  186. if len(lines) < 2 {
  187. return 0, noValue, noValue
  188. }
  189. f := strings.Fields(lines[1])
  190. if len(f) < 5 {
  191. return 0, noValue, noValue
  192. }
  193. percent, err := strconv.Atoi(strings.TrimSuffix(f[4], "%"))
  194. if err != nil {
  195. percent = 0
  196. }
  197. return percent, f[2], f[1]
  198. }
  199. func formatSize(size uint64) string {
  200. const (
  201. KB = 1024
  202. MB = KB * 1024
  203. GB = MB * 1024
  204. )
  205. switch {
  206. case size >= GB:
  207. return fmt.Sprintf("%.1fGB", float64(size)/GB)
  208. case size >= MB:
  209. return fmt.Sprintf("%.0fMB", float64(size)/MB)
  210. case size >= KB:
  211. return fmt.Sprintf("%.0fKB", float64(size)/KB)
  212. default:
  213. return fmt.Sprintf("%dB", size)
  214. }
  215. }
  216. func systemLoadAverageHandler(w http.ResponseWriter, r *http.Request) {
  217. data, err := os.ReadFile("/proc/loadavg")
  218. if err != nil {
  219. http.Error(w, err.Error(), http.StatusInternalServerError)
  220. return
  221. }
  222. fields := strings.Fields(string(data))
  223. if len(fields) < 4 {
  224. http.Error(w, "invalid /proc/loadavg", http.StatusInternalServerError)
  225. return
  226. }
  227. boot, uptime := noValue, noValue
  228. if b, err := os.ReadFile("/proc/uptime"); err == nil {
  229. if fields := strings.Fields(string(b)); len(fields) > 0 {
  230. if sec, err := strconv.ParseFloat(fields[0], 64); err == nil {
  231. d := time.Duration(sec) * time.Second
  232. boot = time.Now().Add(-d).Format("2006-01-02 15:04:05")
  233. day := int(d.Hours() / 24)
  234. if day > 0 {
  235. uptime = fmt.Sprintf("%d天 %02d:%02d:%02d",
  236. int(d.Hours()/24), int(d.Hours())%24, int(d.Minutes())%60, int(d.Seconds())%60)
  237. } else {
  238. uptime = fmt.Sprintf("%02d:%02d:%02d",
  239. int(d.Hours())%24, int(d.Minutes())%60, int(d.Seconds())%60)
  240. }
  241. }
  242. }
  243. }
  244. resp := struct {
  245. Load1m string `json:"load1m"`
  246. Load5m string `json:"load5m"`
  247. Load15m string `json:"load15m"`
  248. RunQueue string `json:"runQueue"`
  249. BootTime string `json:"bootTime"`
  250. UpTime string `json:"uptime"`
  251. }{
  252. Load1m: formatLoad(fields[0]),
  253. Load5m: formatLoad(fields[1]),
  254. Load15m: formatLoad(fields[2]),
  255. RunQueue: fields[3],
  256. BootTime: boot,
  257. UpTime: uptime,
  258. }
  259. w.Header().Set("Content-Type", "application/json")
  260. json.NewEncoder(w).Encode(resp)
  261. }
  262. func formatLoad(v string) string {
  263. f, err := strconv.ParseFloat(v, 64)
  264. if err != nil {
  265. return noValue
  266. }
  267. return strconv.FormatFloat(f, 'f', 2, 64)
  268. }
  269. var services = []struct {
  270. name string
  271. dir string
  272. bin string
  273. }{
  274. {"yfkj-networkd.service", "/opt/yfkj/networkd.service", "networkd"},
  275. {"yfkj-timesyncd.service", "/opt/yfkj/timesyncd.service", "timesyncd"},
  276. {"yfkj-gnss.service", "/opt/yfkj/gnss.service", "gnss"},
  277. {"yfkj-sshd-mqtt-bridge.service", "/opt/yfkj/sshd-mqtt-bridge.service", "sshd-mqtt-bridge"},
  278. {"yfkj-camera-capture.service", "/opt/yfkj/camera-capture.service", "camera-capture"},
  279. {"yfkj-app-install.service", "/opt/yfkj/app-install.service", "app-install"},
  280. {"yfkj-web-ui.service", "/opt/yfkj/web-ui.service", "web-ui"},
  281. {"yfkj-frp-client.service", "/opt/yfkj/frp-client.service", "frpc"},
  282. {"yfkj-upgrade.service", "/opt/yfkj/upgrade.service", "upgrade"},
  283. {"yfkj-local-startup.service", "/opt/yfkj/local-startup.service", "startup.sh"},
  284. }
  285. var serviceStatusActive struct {
  286. sync.Mutex
  287. lastAccess time.Time
  288. }
  289. var serviceStatusCache struct {
  290. sync.RWMutex
  291. data map[string]string
  292. }
  293. func updateServiceStatus() {
  294. data := make(map[string]string, len(services)*2)
  295. args := []string{"show",
  296. "-p", "Id",
  297. "-p", "LoadState",
  298. "-p", "ActiveState",
  299. "-p", "SubState",
  300. "-p", "Result",
  301. }
  302. for _, s := range services {
  303. args = append(args, s.name)
  304. }
  305. statusMap := make(map[string]string, len(services))
  306. out, _ := exec.Command("systemctl", args...).CombinedOutput()
  307. var name, loadState, activeState, subState, result string
  308. save := func() {
  309. if name == "" {
  310. return
  311. }
  312. status := noValue
  313. switch {
  314. case activeState == "active" && subState == "running":
  315. status = "🟢运行中"
  316. case activeState == "active" && subState == "exited":
  317. status = "🔵已完成"
  318. case loadState == "loaded" && activeState == "inactive":
  319. status = "🟡已停止"
  320. case activeState == "failed" && result == "timeout":
  321. status = "🔴超时停"
  322. case activeState == "failed":
  323. status = "🔴异常停"
  324. }
  325. statusMap[name] = status
  326. }
  327. for line := range strings.SplitSeq(string(out), "\n") {
  328. if line == "" { // Empty line indicates the end of a service status block
  329. save() ///// Save the previous service status before starting a new one
  330. name = ""
  331. loadState = ""
  332. activeState = ""
  333. subState = ""
  334. result = ""
  335. continue
  336. }
  337. if v, ok := strings.CutPrefix(line, "Id="); ok {
  338. name = v
  339. } else if v, ok := strings.CutPrefix(line, "LoadState="); ok {
  340. loadState = v
  341. } else if v, ok := strings.CutPrefix(line, "ActiveState="); ok {
  342. activeState = v
  343. } else if v, ok := strings.CutPrefix(line, "SubState="); ok {
  344. subState = v
  345. } else if v, ok := strings.CutPrefix(line, "Result="); ok {
  346. result = v
  347. }
  348. }
  349. save() // Save the last service status
  350. for i, s := range services {
  351. n := i + 1
  352. if v, ok := statusMap[s.name]; ok {
  353. data[fmt.Sprintf("var%d", n)] = v
  354. } else {
  355. data[fmt.Sprintf("var%d", n)] = noValue
  356. }
  357. if v, err := os.ReadFile(filepath.Join(s.dir, "version.txt")); err == nil {
  358. data[fmt.Sprintf("var%d%d", n, n)] = "v" + strings.TrimSpace(string(v))
  359. } else {
  360. data[fmt.Sprintf("var%d%d", n, n)] = noValue
  361. }
  362. }
  363. serviceStatusCache.Lock()
  364. serviceStatusCache.data = data
  365. serviceStatusCache.Unlock()
  366. }
  367. func startServiceCache() {
  368. go func() {
  369. ticker := time.NewTicker(5 * time.Second)
  370. defer ticker.Stop()
  371. for range ticker.C {
  372. serviceStatusActive.Lock()
  373. if !serviceStatusActive.lastAccess.IsZero() && time.Since(serviceStatusActive.lastAccess) >= 10*time.Second {
  374. serviceStatusActive.lastAccess = time.Time{}
  375. }
  376. active := !serviceStatusActive.lastAccess.IsZero()
  377. serviceStatusActive.Unlock()
  378. if active {
  379. updateServiceStatus()
  380. }
  381. }
  382. }()
  383. }
  384. func serviceStatusHandler(w http.ResponseWriter, r *http.Request) {
  385. if r.Method != http.MethodGet {
  386. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  387. return
  388. }
  389. serviceStatusActive.Lock()
  390. first := serviceStatusActive.lastAccess.IsZero() || time.Since(serviceStatusActive.lastAccess) >= 10*time.Second
  391. serviceStatusActive.lastAccess = time.Now()
  392. serviceStatusActive.Unlock()
  393. if first {
  394. updateServiceStatus()
  395. }
  396. serviceStatusCache.RLock()
  397. data := serviceStatusCache.data
  398. serviceStatusCache.RUnlock()
  399. w.Header().Set("Content-Type", "application/json")
  400. json.NewEncoder(w).Encode(data)
  401. }
  402. type VersionSwitchReq struct {
  403. Service string `json:"service"`
  404. Action string `json:"action"`
  405. Password string `json:"password"`
  406. }
  407. type VersionResp struct {
  408. Status string `json:"status"`
  409. Message string `json:"message,omitempty"`
  410. }
  411. var versionSwitchLock sync.Mutex
  412. func serviceVersionSwitchHandler(w http.ResponseWriter, r *http.Request) {
  413. if r.Method != http.MethodPost {
  414. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  415. return
  416. }
  417. versionSwitchLock.Lock()
  418. defer versionSwitchLock.Unlock()
  419. var req VersionSwitchReq
  420. if json.NewDecoder(r.Body).Decode(&req) != nil {
  421. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid request"})
  422. return
  423. }
  424. if req.Password != "yfkj123456" {
  425. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "输入的密码不正确"})
  426. return
  427. }
  428. var cfg struct{ name, dir, bin string }
  429. for _, v := range services {
  430. if v.name == req.Service {
  431. cfg = v
  432. break
  433. }
  434. }
  435. if cfg.name == "" {
  436. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "unknown service"})
  437. return
  438. }
  439. link := filepath.Join(cfg.dir, cfg.bin)
  440. oldLink, err := os.Readlink(link)
  441. if err != nil {
  442. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "读取当前版本失败"})
  443. return
  444. }
  445. current := filepath.Base(filepath.Dir(oldLink))
  446. if current != "a" && current != "b" && current != "c" {
  447. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "当前版本状态异常"})
  448. return
  449. }
  450. target := ""
  451. switch req.Action {
  452. case "factory":
  453. if current == "a" {
  454. json.NewEncoder(w).Encode(VersionResp{Status: "ok", Message: "当前已是出厂版本"})
  455. return
  456. }
  457. target = "a"
  458. case "previous":
  459. switch current {
  460. case "b":
  461. if info, err := os.Stat(filepath.Join(cfg.dir, "c", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  462. target = "c"
  463. }
  464. case "c":
  465. if info, err := os.Stat(filepath.Join(cfg.dir, "b", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  466. target = "b"
  467. }
  468. }
  469. if target == "" {
  470. json.NewEncoder(w).Encode(VersionResp{
  471. Status: "error",
  472. Message: "当前没有可回退的上一版本",
  473. })
  474. return
  475. }
  476. default:
  477. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid action"})
  478. return
  479. }
  480. targetBin := filepath.Join(cfg.dir, target, cfg.bin)
  481. info, err := os.Stat(targetBin)
  482. if err != nil || info.IsDir() || info.Size() == 0 || info.Mode().Perm()&0111 == 0 {
  483. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("目标版本文件异常: %s", target)})
  484. return
  485. }
  486. if out, err := exec.Command("systemctl", "stop", req.Service).CombinedOutput(); err != nil {
  487. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("停止当前服务失败: %s", out)})
  488. return
  489. }
  490. tmp := filepath.Join(cfg.dir, cfg.bin+".tmp")
  491. os.Remove(tmp)
  492. if err := os.Symlink(filepath.Join(target, cfg.bin), tmp); err != nil {
  493. exec.Command("systemctl", "start", req.Service).Run()
  494. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  495. return
  496. }
  497. if err := os.Rename(tmp, link); err != nil {
  498. os.Remove(tmp)
  499. exec.Command("systemctl", "start", req.Service).Run()
  500. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  501. return
  502. }
  503. if out, err := exec.Command("systemctl", "start", req.Service).CombinedOutput(); err != nil {
  504. tmp := filepath.Join(cfg.dir, cfg.bin+".tmp")
  505. os.Remove(tmp)
  506. if e := os.Symlink(oldLink, tmp); e == nil {
  507. if e = os.Rename(tmp, link); e != nil {
  508. os.Remove(tmp)
  509. }
  510. }
  511. exec.Command("systemctl", "start", req.Service).Run()
  512. json.NewEncoder(w).Encode(VersionResp{
  513. Status: "error",
  514. Message: fmt.Sprintf("目标版本启动失败,已恢复旧版本: %s", out),
  515. })
  516. return
  517. }
  518. json.NewEncoder(w).Encode(VersionResp{Status: "ok"})
  519. }