page1_handler.go 16 KB

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