page1_handler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. }
  301. for _, s := range services {
  302. args = append(args, s.name)
  303. }
  304. statusMap := make(map[string]string, len(services))
  305. out, _ := exec.Command("systemctl", args...).CombinedOutput()
  306. var name, loadState, activeState, subState string
  307. save := func() {
  308. if name == "" {
  309. return
  310. }
  311. status := noValue
  312. switch {
  313. case activeState == "active" && subState == "running":
  314. status = "🟢运行中"
  315. case activeState == "active" && subState == "exited":
  316. status = "🔵已完成"
  317. case loadState == "loaded" && activeState == "inactive":
  318. status = "🟡已停止"
  319. }
  320. statusMap[name] = status
  321. }
  322. for line := range strings.SplitSeq(string(out), "\n") {
  323. if strings.HasPrefix(line, "Id=") {
  324. save() // Save the previous service status before starting a new one
  325. name = strings.TrimPrefix(line, "Id=")
  326. loadState = ""
  327. activeState = ""
  328. subState = ""
  329. } else if v, ok := strings.CutPrefix(line, "LoadState="); ok {
  330. loadState = v
  331. } else if v, ok := strings.CutPrefix(line, "ActiveState="); ok {
  332. activeState = v
  333. } else if v, ok := strings.CutPrefix(line, "SubState="); ok {
  334. subState = v
  335. }
  336. }
  337. save() // Save the last service status
  338. for i, s := range services {
  339. n := i + 1
  340. if v, ok := statusMap[s.name]; ok {
  341. data[fmt.Sprintf("var%d", n)] = v
  342. } else {
  343. data[fmt.Sprintf("var%d", n)] = noValue
  344. }
  345. if v, err := os.ReadFile(filepath.Join(s.dir, "version.txt")); err == nil {
  346. data[fmt.Sprintf("var%d%d", n, n)] = "v" + strings.TrimSpace(string(v))
  347. } else {
  348. data[fmt.Sprintf("var%d%d", n, n)] = noValue
  349. }
  350. }
  351. serviceStatusCache.Lock()
  352. serviceStatusCache.data = data
  353. serviceStatusCache.Unlock()
  354. }
  355. func startServiceCache() {
  356. go func() {
  357. ticker := time.NewTicker(5 * time.Second)
  358. defer ticker.Stop()
  359. for range ticker.C {
  360. serviceStatusActive.Lock()
  361. if !serviceStatusActive.lastAccess.IsZero() && time.Since(serviceStatusActive.lastAccess) >= 10*time.Second {
  362. serviceStatusActive.lastAccess = time.Time{}
  363. }
  364. active := !serviceStatusActive.lastAccess.IsZero()
  365. serviceStatusActive.Unlock()
  366. if active {
  367. updateServiceStatus()
  368. }
  369. }
  370. }()
  371. }
  372. func serviceStatusHandler(w http.ResponseWriter, r *http.Request) {
  373. if r.Method != http.MethodGet {
  374. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  375. return
  376. }
  377. serviceStatusActive.Lock()
  378. first := serviceStatusActive.lastAccess.IsZero() || time.Since(serviceStatusActive.lastAccess) >= 10*time.Second
  379. serviceStatusActive.lastAccess = time.Now()
  380. serviceStatusActive.Unlock()
  381. if first {
  382. updateServiceStatus()
  383. }
  384. serviceStatusCache.RLock()
  385. data := serviceStatusCache.data
  386. serviceStatusCache.RUnlock()
  387. w.Header().Set("Content-Type", "application/json")
  388. json.NewEncoder(w).Encode(data)
  389. }
  390. type VersionSwitchReq struct {
  391. Service string `json:"service"`
  392. Action string `json:"action"`
  393. Password string `json:"password"`
  394. }
  395. type VersionResp struct {
  396. Status string `json:"status"`
  397. Message string `json:"message,omitempty"`
  398. }
  399. var versionSwitchLock sync.Mutex
  400. func serviceVersionSwitchHandler(w http.ResponseWriter, r *http.Request) {
  401. if r.Method != http.MethodPost {
  402. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  403. return
  404. }
  405. versionSwitchLock.Lock()
  406. defer versionSwitchLock.Unlock()
  407. var req VersionSwitchReq
  408. if json.NewDecoder(r.Body).Decode(&req) != nil {
  409. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid request"})
  410. return
  411. }
  412. if req.Password != "yfkj123456" {
  413. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "输入的密码不正确"})
  414. return
  415. }
  416. var cfg struct{ name, dir, bin string }
  417. for _, v := range services {
  418. if v.name == req.Service {
  419. cfg = v
  420. break
  421. }
  422. }
  423. if cfg.name == "" {
  424. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "unknown service"})
  425. return
  426. }
  427. link := filepath.Join(cfg.dir, cfg.bin)
  428. oldLink, err := os.Readlink(link)
  429. if err != nil {
  430. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "读取当前版本失败"})
  431. return
  432. }
  433. current := filepath.Base(filepath.Dir(oldLink))
  434. if current != "a" && current != "b" && current != "c" {
  435. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "当前版本状态异常"})
  436. return
  437. }
  438. target := ""
  439. switch req.Action {
  440. case "factory":
  441. if current == "a" {
  442. json.NewEncoder(w).Encode(VersionResp{Status: "ok", Message: "当前已是出厂版本"})
  443. return
  444. }
  445. target = "a"
  446. case "previous":
  447. switch current {
  448. case "b":
  449. if info, err := os.Stat(filepath.Join(cfg.dir, "c", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  450. target = "c"
  451. }
  452. case "c":
  453. if info, err := os.Stat(filepath.Join(cfg.dir, "b", cfg.bin)); err == nil && !info.IsDir() && info.Size() > 0 && info.Mode().Perm()&0111 != 0 {
  454. target = "b"
  455. }
  456. }
  457. if target == "" {
  458. json.NewEncoder(w).Encode(VersionResp{
  459. Status: "error",
  460. Message: "当前没有可回退的上一版本",
  461. })
  462. return
  463. }
  464. default:
  465. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: "invalid action"})
  466. return
  467. }
  468. targetBin := filepath.Join(cfg.dir, target, cfg.bin)
  469. info, err := os.Stat(targetBin)
  470. if err != nil || info.IsDir() || info.Size() == 0 || info.Mode().Perm()&0111 == 0 {
  471. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("目标版本文件异常: %s", target)})
  472. return
  473. }
  474. if out, err := exec.Command("systemctl", "stop", req.Service).CombinedOutput(); err != nil {
  475. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: fmt.Sprintf("停止当前服务失败: %s", out)})
  476. return
  477. }
  478. tmp := filepath.Join(cfg.dir, cfg.bin+".tmp")
  479. os.Remove(tmp)
  480. if err := os.Symlink(filepath.Join(target, cfg.bin), tmp); err != nil {
  481. exec.Command("systemctl", "start", req.Service).Run()
  482. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  483. return
  484. }
  485. if err := os.Rename(tmp, link); err != nil {
  486. os.Remove(tmp)
  487. exec.Command("systemctl", "start", req.Service).Run()
  488. json.NewEncoder(w).Encode(VersionResp{Status: "error", Message: err.Error()})
  489. return
  490. }
  491. if out, err := exec.Command("systemctl", "start", req.Service).CombinedOutput(); err != nil {
  492. tmp := filepath.Join(cfg.dir, cfg.bin+".tmp")
  493. os.Remove(tmp)
  494. if e := os.Symlink(oldLink, tmp); e == nil {
  495. if e = os.Rename(tmp, link); e != nil {
  496. os.Remove(tmp)
  497. }
  498. }
  499. exec.Command("systemctl", "start", req.Service).Run()
  500. json.NewEncoder(w).Encode(VersionResp{
  501. Status: "error",
  502. Message: fmt.Sprintf("目标版本启动失败,已恢复旧版本: %s", out),
  503. })
  504. return
  505. }
  506. json.NewEncoder(w).Encode(VersionResp{Status: "ok"})
  507. }