page1_handler.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. data, err := os.ReadFile("/sys/class/thermal/thermal_zone0/temp")
  140. if err != nil {
  141. return noValue
  142. }
  143. temp, err := strconv.Atoi(strings.TrimSpace(string(data)))
  144. if err != nil {
  145. return noValue
  146. }
  147. return fmt.Sprintf("%d℃", temp/1000)
  148. }
  149. func getMemInfo() (int, string, string) {
  150. data, err := os.ReadFile("/proc/meminfo")
  151. if err != nil {
  152. return 0, noValue, noValue
  153. }
  154. var total, avail uint64
  155. for _, line := range strings.Split(string(data), "\n") {
  156. f := strings.Fields(line)
  157. if len(f) < 2 {
  158. continue
  159. }
  160. switch f[0] {
  161. case "MemTotal:":
  162. total, _ = strconv.ParseUint(f[1], 10, 64)
  163. case "MemAvailable:":
  164. avail, _ = strconv.ParseUint(f[1], 10, 64)
  165. }
  166. }
  167. if total == 0 {
  168. return 0, noValue, noValue
  169. }
  170. used := total - avail
  171. return int(used * 100 / total), formatSize(used * 1024), formatSize(total * 1024)
  172. }
  173. func getDiskInfo() (int, string, string) {
  174. out, err := exec.Command("df", "-hP", "/").Output()
  175. if err != nil {
  176. return 0, noValue, noValue
  177. }
  178. lines := strings.Split(string(out), "\n")
  179. if len(lines) < 2 {
  180. return 0, noValue, noValue
  181. }
  182. f := strings.Fields(lines[1])
  183. if len(f) < 5 {
  184. return 0, noValue, noValue
  185. }
  186. percent, err := strconv.Atoi(strings.TrimSuffix(f[4], "%"))
  187. if err != nil {
  188. percent = 0
  189. }
  190. return percent, f[2], f[1]
  191. }
  192. func formatSize(size uint64) string {
  193. const (
  194. KB = 1024
  195. MB = KB * 1024
  196. GB = MB * 1024
  197. )
  198. switch {
  199. case size >= GB:
  200. return fmt.Sprintf("%.1fGB", float64(size)/GB)
  201. case size >= MB:
  202. return fmt.Sprintf("%.0fMB", float64(size)/MB)
  203. case size >= KB:
  204. return fmt.Sprintf("%.0fKB", float64(size)/KB)
  205. default:
  206. return fmt.Sprintf("%dB", size)
  207. }
  208. }
  209. func systemLoadAverageHandler(w http.ResponseWriter, r *http.Request) {
  210. data, err := os.ReadFile("/proc/loadavg")
  211. if err != nil {
  212. http.Error(w, err.Error(), http.StatusInternalServerError)
  213. return
  214. }
  215. fields := strings.Fields(string(data))
  216. if len(fields) < 4 {
  217. http.Error(w, "invalid /proc/loadavg", http.StatusInternalServerError)
  218. return
  219. }
  220. boot, uptime := noValue, noValue
  221. if b, err := os.ReadFile("/proc/uptime"); err == nil {
  222. if fields := strings.Fields(string(b)); len(fields) > 0 {
  223. if sec, err := strconv.ParseFloat(fields[0], 64); err == nil {
  224. d := time.Duration(sec) * time.Second
  225. boot = time.Now().Add(-d).Format("2006-01-02 15:04:05")
  226. day := int(d.Hours() / 24)
  227. if day > 0 {
  228. uptime = fmt.Sprintf("%d天 %02d:%02d:%02d",
  229. int(d.Hours()/24), int(d.Hours())%24, int(d.Minutes())%60, int(d.Seconds())%60)
  230. } else {
  231. uptime = fmt.Sprintf("%02d:%02d:%02d",
  232. int(d.Hours())%24, int(d.Minutes())%60, int(d.Seconds())%60)
  233. }
  234. }
  235. }
  236. }
  237. resp := struct {
  238. Load1m string `json:"load1m"`
  239. Load5m string `json:"load5m"`
  240. Load15m string `json:"load15m"`
  241. RunQueue string `json:"runQueue"`
  242. BootTime string `json:"bootTime"`
  243. UpTime string `json:"uptime"`
  244. }{
  245. Load1m: formatLoad(fields[0]),
  246. Load5m: formatLoad(fields[1]),
  247. Load15m: formatLoad(fields[2]),
  248. RunQueue: fields[3],
  249. BootTime: boot,
  250. UpTime: uptime,
  251. }
  252. w.Header().Set("Content-Type", "application/json")
  253. json.NewEncoder(w).Encode(resp)
  254. }
  255. func formatLoad(v string) string {
  256. f, err := strconv.ParseFloat(v, 64)
  257. if err != nil {
  258. return noValue
  259. }
  260. return strconv.FormatFloat(f, 'f', 2, 64)
  261. }
  262. var services = []struct {
  263. name string
  264. dir string
  265. bin string
  266. }{
  267. {"yfkj-networkd.service", "/opt/yfkj/networkd.service", "networkd"},
  268. {"yfkj-timesyncd.service", "/opt/yfkj/timesyncd.service", "timesyncd"},
  269. {"yfkj-gnss.service", "/opt/yfkj/gnss.service", "gnss"},
  270. {"yfkj-sshd-mqtt-bridge.service", "/opt/yfkj/sshd-mqtt-bridge.service", "sshd-mqtt-bridge"},
  271. {"yfkj-camera-capture.service", "/opt/yfkj/camera-capture.service", "camera-capture"},
  272. {"yfkj-app-install.service", "/opt/yfkj/app-install.service", "app-install"},
  273. {"yfkj-web-ui.service", "/opt/yfkj/web-ui.service", "web-ui"},
  274. {"yfkj-frp-client.service", "/opt/yfkj/frp-client.service", "frpc"},
  275. {"yfkj-upgrade.service", "/opt/yfkj/upgrade.service", "upgrade"},
  276. {"yfkj-local-startup.service", "/opt/yfkj/local-startup.service", "startup.sh"},
  277. }
  278. var serviceStatusActive struct {
  279. sync.Mutex
  280. lastAccess time.Time
  281. }
  282. var serviceStatusCache struct {
  283. sync.RWMutex
  284. data map[string]string
  285. }
  286. func updateServiceStatus() {
  287. data := make(map[string]string, len(services)*2)
  288. args := []string{"show",
  289. "-p", "Id",
  290. "-p", "LoadState",
  291. "-p", "ActiveState",
  292. "-p", "SubState",
  293. "-p", "Result",
  294. }
  295. for _, s := range services {
  296. args = append(args, s.name)
  297. }
  298. statusMap := make(map[string]string, len(services))
  299. out, _ := exec.Command("systemctl", args...).CombinedOutput()
  300. var name, loadState, activeState, subState, result string
  301. save := func() {
  302. if name == "" {
  303. return
  304. }
  305. status := noValue
  306. switch {
  307. case activeState == "active" && subState == "running":
  308. status = "🟢运行中"
  309. case activeState == "active" && subState == "exited":
  310. status = "🔵已完成"
  311. case loadState == "loaded" && activeState == "inactive":
  312. status = "🟡已停止"
  313. case activeState == "failed" && result == "timeout":
  314. status = "🔴超时停"
  315. case activeState == "failed":
  316. status = "🔴异常停"
  317. }
  318. statusMap[name] = status
  319. }
  320. for line := range strings.SplitSeq(string(out), "\n") {
  321. if line == "" { // Empty line indicates the end of a service status block
  322. save() ///// Save the previous service status before starting a new one
  323. name = ""
  324. loadState = ""
  325. activeState = ""
  326. subState = ""
  327. result = ""
  328. continue
  329. }
  330. if v, ok := strings.CutPrefix(line, "Id="); ok {
  331. name = v
  332. } else if v, ok := strings.CutPrefix(line, "LoadState="); ok {
  333. loadState = v
  334. } else if v, ok := strings.CutPrefix(line, "ActiveState="); ok {
  335. activeState = v
  336. } else if v, ok := strings.CutPrefix(line, "SubState="); ok {
  337. subState = v
  338. } else if v, ok := strings.CutPrefix(line, "Result="); ok {
  339. result = v
  340. }
  341. }
  342. save() // Save the last service status
  343. for i, s := range services {
  344. n := i + 1
  345. if v, ok := statusMap[s.name]; ok {
  346. data[fmt.Sprintf("var%d", n)] = v
  347. } else {
  348. data[fmt.Sprintf("var%d", n)] = noValue
  349. }
  350. if v, err := os.ReadFile(filepath.Join(s.dir, "version.txt")); err == nil {
  351. data[fmt.Sprintf("var%d%d", n, n)] = "v" + strings.TrimSpace(string(v))
  352. } else {
  353. data[fmt.Sprintf("var%d%d", n, n)] = noValue
  354. }
  355. }
  356. serviceStatusCache.Lock()
  357. serviceStatusCache.data = data
  358. serviceStatusCache.Unlock()
  359. }
  360. func startServiceCache() {
  361. go func() {
  362. ticker := time.NewTicker(5 * time.Second)
  363. defer ticker.Stop()
  364. for range ticker.C {
  365. serviceStatusActive.Lock()
  366. if !serviceStatusActive.lastAccess.IsZero() && time.Since(serviceStatusActive.lastAccess) >= 10*time.Second {
  367. serviceStatusActive.lastAccess = time.Time{}
  368. }
  369. active := !serviceStatusActive.lastAccess.IsZero()
  370. serviceStatusActive.Unlock()
  371. if active {
  372. updateServiceStatus()
  373. }
  374. }
  375. }()
  376. }
  377. func serviceStatusHandler(w http.ResponseWriter, r *http.Request) {
  378. if r.Method != http.MethodGet {
  379. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  380. return
  381. }
  382. serviceStatusActive.Lock()
  383. first := serviceStatusActive.lastAccess.IsZero() || time.Since(serviceStatusActive.lastAccess) >= 10*time.Second
  384. serviceStatusActive.lastAccess = time.Now()
  385. serviceStatusActive.Unlock()
  386. if first {
  387. updateServiceStatus()
  388. }
  389. serviceStatusCache.RLock()
  390. data := serviceStatusCache.data
  391. serviceStatusCache.RUnlock()
  392. w.Header().Set("Content-Type", "application/json")
  393. json.NewEncoder(w).Encode(data)
  394. }
  395. type VersionSwitchReq struct {
  396. Service string `json:"service"`
  397. Action string `json:"action"`
  398. Password string `json:"password"`
  399. }
  400. type VersionResp struct {
  401. Status string `json:"status"`
  402. Message string `json:"message,omitempty"`
  403. }
  404. var versionSwitchLock sync.Mutex
  405. func serviceVersionSwitchHandler(w http.ResponseWriter, r *http.Request) {
  406. if r.Method != http.MethodPost {
  407. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  408. return
  409. }
  410. versionSwitchLock.Lock()
  411. defer versionSwitchLock.Unlock()
  412. var req VersionSwitchReq
  413. if json.NewDecoder(r.Body).Decode(&req) != nil {
  414. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid request"})
  415. return
  416. }
  417. if req.Password != "yfkj123456" {
  418. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "输入的密码不正确"})
  419. return
  420. }
  421. var cfg struct{ name, dir, bin string }
  422. for _, v := range services {
  423. if v.name == req.Service {
  424. cfg = v
  425. break
  426. }
  427. }
  428. if cfg.name == "" {
  429. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "unknown service"})
  430. return
  431. }
  432. link := filepath.Join(cfg.dir, cfg.bin)
  433. oldLink, err := os.Readlink(link)
  434. if err != nil {
  435. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "读取当前版本失败"})
  436. return
  437. }
  438. current := filepath.Base(filepath.Dir(oldLink))
  439. if current != "a" && current != "b" && current != "c" {
  440. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "当前版本状态异常"})
  441. return
  442. }
  443. target := ""
  444. switch req.Action {
  445. case "factory":
  446. if current == "a" {
  447. json.NewEncoder(w).Encode(VersionResp{Status: "ok", Message: "当前已是出厂版本"})
  448. return
  449. }
  450. target = "a"
  451. case "previous":
  452. switch current {
  453. case "b":
  454. if info, err := os.Stat(filepath.Join(cfg.dir, "c", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  455. target = "c"
  456. }
  457. case "c":
  458. if info, err := os.Stat(filepath.Join(cfg.dir, "b", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  459. target = "b"
  460. }
  461. }
  462. if target == "" {
  463. json.NewEncoder(w).Encode(VersionResp{Status: "error",
  464. Message: "当前没有可回退的上一版本"})
  465. return
  466. }
  467. default:
  468. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid action"})
  469. return
  470. }
  471. targetBin := filepath.Join(cfg.dir, target, cfg.bin)
  472. info, err := os.Stat(targetBin)
  473. if err != nil || info.IsDir() || info.Size() == 0 || info.Mode().Perm()&0111 == 0 {
  474. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("目标版本文件异常: %s", target)})
  475. return
  476. }
  477. if out, err := exec.Command("systemctl", "stop", req.Service).CombinedOutput(); err != nil {
  478. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("停止当前服务失败: %s", out)})
  479. return
  480. }
  481. tmp := filepath.Join(cfg.dir, cfg.bin+".tmp")
  482. os.Remove(tmp)
  483. if err := os.Symlink(filepath.Join(target, cfg.bin), tmp); err != nil {
  484. exec.Command("systemctl", "start", req.Service).Run()
  485. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  486. return
  487. }
  488. if err := os.Rename(tmp, link); err != nil {
  489. os.Remove(tmp)
  490. exec.Command("systemctl", "start", req.Service).Run()
  491. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  492. return
  493. }
  494. if out, err := exec.Command("systemctl", "start", req.Service).CombinedOutput(); err != nil {
  495. startErr := fmt.Errorf("目标版本启动失败: %s", out)
  496. os.Remove(tmp)
  497. if e := os.Symlink(oldLink, tmp); e != nil {
  498. json.NewEncoder(w).Encode(VersionResp{Status: "error",
  499. Message: fmt.Sprintf("%v: 创建回滚链接失败: %v", startErr, e)})
  500. return
  501. }
  502. if e := os.Rename(tmp, link); e != nil {
  503. os.Remove(tmp)
  504. json.NewEncoder(w).Encode(VersionResp{Status: "error",
  505. Message: fmt.Sprintf("%v: 切换回滚链接失败: %v", startErr, e)})
  506. return
  507. }
  508. if e := exec.Command("systemctl", "start", req.Service).Run(); e != nil {
  509. json.NewEncoder(w).Encode(VersionResp{Status: "error",
  510. Message: fmt.Sprintf("%v: 启动回滚版本失败: %v", startErr, e)})
  511. return
  512. }
  513. json.NewEncoder(w).Encode(VersionResp{Status: "error",
  514. Message: "目标版本启动失败,已恢复到旧有版本"})
  515. return
  516. }
  517. json.NewEncoder(w).Encode(VersionResp{Status: "ok"})
  518. }
  519. func downloadUpgradeLog(w http.ResponseWriter, r *http.Request) {
  520. if r.Method != http.MethodGet {
  521. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  522. return
  523. }
  524. filename := fmt.Sprintf("upgrade.log.%s.tar.gz", time.Now().Format("20060102150405"))
  525. tmpFile := fmt.Sprintf("/tmp/%d.tar.gz", time.Now().UnixNano())
  526. defer os.Remove(tmpFile)
  527. cmd := exec.Command(
  528. "tar",
  529. "--warning=no-file-changed",
  530. "-czf",
  531. tmpFile,
  532. "-C",
  533. "/opt/yfkj/upgrade.service/log",
  534. ".",
  535. )
  536. out, err := cmd.CombinedOutput()
  537. if err != nil {
  538. if exitErr, ok := err.(*exec.ExitError); !ok || exitErr.ExitCode() != 1 {
  539. http.Error(w, string(out), http.StatusInternalServerError)
  540. return
  541. }
  542. }
  543. w.Header().Set("Content-Type", "application/gzip")
  544. w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
  545. http.ServeFile(w, r, tmpFile)
  546. }