service_mode_gui.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // ============================================================================
  2. //go:build !service
  3. // service_mode_gui.go — 服务模式的 GUI 侧控制
  4. //
  5. // 界面进程里的服务模式配套逻辑:探测服务端口、兜底启动电源 API、界面在线
  6. // 登记循环。这些依赖 GUI 的 apiLogRing / 界面 API 地址;独立服务模式
  7. // (-tags service)不编译本文件。
  8. // ============================================================================
  9. package main
  10. import (
  11. "bytes"
  12. "encoding/json"
  13. "fmt"
  14. "log"
  15. "net/http"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/gin-gonic/gin"
  20. )
  21. // ----------------------------------------------------------------------------
  22. // 界面版的兜底:启动时探测服务端口,若 Windows 服务未运行,就在界面进程内
  23. // 起一份同样的电源 API,保证无论是否安装服务,该端口都能用。
  24. // ----------------------------------------------------------------------------
  25. var (
  26. uiServiceMu sync.Mutex
  27. uiServiceServer *http.Server
  28. uiServiceAddr string
  29. )
  30. // probeServiceAPI 探测地址上的 HTTP 响应:
  31. // inUse=端口上已有服务在应答;isService=应答方是本程序的服务模式(/health 返回 service=true);
  32. // version=应答方上报的版本号(无则空)
  33. func probeServiceAPI(addr string) (inUse, isService bool, version string) {
  34. client := &http.Client{Timeout: 800 * time.Millisecond}
  35. resp, err := client.Get("http://" + addr + "/health")
  36. if err != nil {
  37. return false, false, ""
  38. }
  39. defer resp.Body.Close()
  40. if resp.StatusCode != http.StatusOK {
  41. return true, false, ""
  42. }
  43. var body struct {
  44. Service bool `json:"service"`
  45. Version string `json:"version"`
  46. }
  47. if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
  48. return true, false, ""
  49. }
  50. return true, body.Service, body.Version
  51. }
  52. // ensureUIServiceAPI 界面版启动/保存设置时调用:
  53. // 服务端口已被真正的 Windows 服务占用则跳过;被其他程序占用则记录日志;
  54. // 端口空闲时由界面进程兜底启动同样的电源 API。
  55. func ensureUIServiceAPI(addr string) {
  56. addr = strings.TrimSpace(addr)
  57. if addr == "" {
  58. addr = DefaultServiceAddr
  59. }
  60. inUse, isService, _ := probeServiceAPI(pingAddr(addr))
  61. if isService {
  62. return // Windows 服务(或上一份界面兜底)已在运行,避免抢端口
  63. }
  64. if inUse {
  65. // 端口被其他程序占用:无法兜底,记录到日志便于排查
  66. log.Printf("service api addr %s is occupied by another program, skip fallback", addr)
  67. fmt.Fprintf(apiLogRing, "[SYS] 服务电源接口 %s 已被其他程序占用,跳过兜底启动\n", addr)
  68. return
  69. }
  70. uiServiceMu.Lock()
  71. defer uiServiceMu.Unlock()
  72. if uiServiceServer != nil && uiServiceAddr == addr {
  73. return // 同一地址已由界面进程兜底启动
  74. }
  75. if uiServiceServer != nil {
  76. stopServicePowerAPI(uiServiceServer) // 地址变化时先停旧服务
  77. uiServiceServer = nil
  78. }
  79. // 兜底只监听本机回环:默认服务地址可能是 0.0.0.0,避免把电源接口暴露到局域网
  80. uiServiceServer = startServicePowerAPI(loopbackAddr(addr))
  81. uiServiceAddr = addr
  82. }
  83. // stopUIServiceFallback 停止界面进程兜底的电源 API(安装/启动真正的服务前释放端口)
  84. func stopUIServiceFallback() {
  85. uiServiceMu.Lock()
  86. defer uiServiceMu.Unlock()
  87. if uiServiceServer != nil {
  88. stopServicePowerAPI(uiServiceServer)
  89. uiServiceServer = nil
  90. uiServiceAddr = ""
  91. }
  92. }
  93. // ServiceModeStatus 服务模式运行状态(服务页展示)
  94. type ServiceModeStatus struct {
  95. Addr string `json:"addr"` // 服务模式监听地址
  96. Running bool `json:"running"` // 该地址上的电源 API 是否可用
  97. Managed bool `json:"managed"` // true=由真正的 Windows 服务提供;false=界面进程兜底
  98. Occupied bool `json:"occupied"` // 端口被其他程序占用(既非服务模式也非本程序)
  99. Version string `json:"version"` // 服务端版本(可用时)
  100. }
  101. // serviceProbeAddrs 可能正在运行服务模式的地址(界面配置 + 默认),已去重并转为本机可探测形式
  102. func serviceProbeAddrs() []string {
  103. addrs := []string{pingAddr(serviceListenAddr())}
  104. if d := pingAddr(DefaultServiceAddr); d != addrs[0] {
  105. addrs = append(addrs, d)
  106. }
  107. return addrs
  108. }
  109. // serviceModeStatus 汇总服务模式状态,供服务页显示
  110. //
  111. // Windows 服务以 LocalSystem 运行,读取的是 SYSTEM 账户的配置(实际监听默认
  112. // 0.0.0.0:9090);界面读取的是当前用户配置,两者可能不同。因此这里同时探测
  113. // 界面配置地址与默认地址,避免「服务在跑却显示未运行」。
  114. func serviceModeStatus() ServiceModeStatus {
  115. status := ServiceModeStatus{Addr: serviceListenAddr(), Managed: windowsServiceRunning()}
  116. for _, addr := range serviceProbeAddrs() {
  117. inUse, isService, version := probeServiceAPI(addr)
  118. if inUse && isService {
  119. status.Running = true
  120. status.Addr = addr
  121. status.Version = version
  122. return status
  123. }
  124. if inUse {
  125. status.Occupied = true
  126. status.Addr = addr
  127. }
  128. }
  129. return status
  130. }
  131. // ----------------------------------------------------------------------------
  132. // 界面登记循环:界面启动后把自己的 API 地址告知服务模式(每 30 秒心跳),
  133. // 服务模式收到自身未实现的请求时会转发到该地址。
  134. // ----------------------------------------------------------------------------
  135. // startUIRegistration 启动后台登记协程(进程内仅需调用一次)
  136. func startUIRegistration() {
  137. go func() {
  138. for {
  139. registerUIWithService()
  140. time.Sleep(30 * time.Second)
  141. }
  142. }()
  143. }
  144. // registerUIWithService 向可能存在的服务模式登记当前界面 API 地址;失败静默(服务未安装属正常)
  145. func registerUIWithService() {
  146. uiAddr := currentAPIAddr()
  147. if uiAddr == "" {
  148. return // 界面 API 未启动,无需登记
  149. }
  150. payload, err := json.Marshal(gin.H{"addr": pingAddr(uiAddr)})
  151. if err != nil {
  152. return
  153. }
  154. client := &http.Client{Timeout: 2 * time.Second}
  155. for _, addr := range serviceProbeAddrs() {
  156. req, err := http.NewRequest(http.MethodPost, "http://"+addr+"/api/ui/register", bytes.NewReader(payload))
  157. if err != nil {
  158. continue
  159. }
  160. req.Header.Set("Content-Type", "application/json")
  161. resp, err := client.Do(req)
  162. if err != nil {
  163. continue
  164. }
  165. resp.Body.Close()
  166. if resp.StatusCode == http.StatusOK {
  167. return
  168. }
  169. }
  170. }