netmgrd.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package netmgrd
  2. import "C"
  3. import (
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "hnyfkj.com.cn/rtu/linux/baseapp"
  8. modem1 "hnyfkj.com.cn/rtu/linux/air720u" // 合宙4G调制解调器
  9. modem2 "hnyfkj.com.cn/rtu/linux/ec200u" // 移远4G调制解调器
  10. )
  11. const MODULE_NAME = "NetworkManager"
  12. var (
  13. eth0LinkDegraded atomic.Bool // 当eth0网卡无法上网时标记降级
  14. isOnline atomic.Bool // 标记是否联网: true 或 false
  15. offlineStartTime time.Time // 离线开始时间, 不依赖系统时钟
  16. enableTimeSync atomic.Bool // 是否启用时间同步(默认: 启用)
  17. isSyncNTPTimeOK atomic.Bool // 标记系统的时间是否已同步成功
  18. lastSyncNTPTime time.Time // 记录同步时间, 为下次同步准备
  19. curNetType atomic.Int32 // 当前联网类型: "有线"、"蜂窝"
  20. mu1 sync.Mutex
  21. isRunning1 bool
  22. exitCh1 chan struct{}
  23. wg1 sync.WaitGroup
  24. )
  25. type NetType int32
  26. const (
  27. NetNone NetType = iota
  28. NetEth // 有线网络, 注册网卡名为"eth0"
  29. NetLTE // 蜂窝网络
  30. )
  31. func (n NetType) String() string {
  32. switch n {
  33. case NetEth:
  34. return "有线"
  35. case NetLTE:
  36. return "蜂窝"
  37. default:
  38. return "未知"
  39. }
  40. }
  41. func setNetType(n NetType) {
  42. curNetType.Store(int32(n))
  43. }
  44. func getNetType() NetType {
  45. return NetType(curNetType.Load())
  46. }
  47. func init() {
  48. enableTimeSync.Store(true) // 默认开启时间同步
  49. }
  50. func SetTimeSyncEnabled(enable bool) {
  51. enableTimeSync.Store(enable)
  52. }
  53. const (
  54. interval1 = time.Duration(1) * time.Second
  55. interval2 = time.Duration(3) * time.Second
  56. eth0ManagementAddr = "192.168.80.1/24"
  57. )
  58. func ModuleInit() {
  59. offlineStartTime = time.Now()
  60. go serviceRun()
  61. }
  62. // 联网保持服务
  63. func serviceRun() {
  64. // 1, 首次打开网络
  65. openNetwork()
  66. // 2, 监控联网状态
  67. t := time.NewTimer(interval1)
  68. defer t.Stop()
  69. for {
  70. select {
  71. case <-t.C:
  72. // 3.1 切换网络-看情况
  73. eth0CableOK, _ := isEth0CableConnected()
  74. if !eth0CableOK { // 检测到eth0的网线拔出后, 清除降级标记
  75. eth0LinkDegraded.CompareAndSwap(true, false)
  76. }
  77. if eth0CableOK && getNetType() != NetEth && !eth0LinkDegraded.Load() { /////////// 有线插入 && 当前不是有线 && 有线还未降级
  78. baseapp.Logger.Warnf("[%s] 检测到有线插入,正在尝试切换到有线网络...", MODULE_NAME)
  79. openNetwork()
  80. } else if (!eth0CableOK || eth0LinkDegraded.Load()) && getNetType() == NetEth { // (有线拔出 || 有线已降级) && 当前还是有线
  81. baseapp.Logger.Warnf("[%s] 检测到有线断网,正在尝试切换到蜂窝网络...", MODULE_NAME)
  82. openNetwork()
  83. }
  84. // 3.2, 联网检测-看结果
  85. dnsOK, pingOK, tcpOK, httpOK, httpTime := CheckNetwork()
  86. baseapp.Logger.Infof("[%s] 联网类型: %s; 检测结果: DNS OK=%v, PING OK=%v, TCP OK=%v, HTTP OK=%v", MODULE_NAME, getNetType().String(), dnsOK, pingOK, tcpOK, httpOK)
  87. // 3.3, 联网成功-在线时
  88. netOK := tcpOK || httpOK
  89. if netOK {
  90. isOnline.Store(true)
  91. if !enableTimeSync.Load() { // 时间同步功能被禁用, 下面不再同步
  92. isSyncNTPTimeOK.Store(false)
  93. t.Reset(interval2)
  94. continue
  95. }
  96. if isSyncNTPTimeOK.Load() && time.Since(lastSyncNTPTime) < (time.Duration(60)*time.Minute) {
  97. t.Reset(interval2)
  98. continue
  99. }
  100. var err error
  101. if !httpTime.IsZero() { // 优先使用HTTP时间, 实测速度快且精度高
  102. err = SetSystemTime(httpTime)
  103. }
  104. if httpTime.IsZero() || err != nil {
  105. err = SyncNTPTime() //// 同步HTTP时间失败, 则尝试同步标准时间
  106. }
  107. if err == nil {
  108. isSyncNTPTimeOK.Store(true)
  109. baseapp.Logger.Infof("[%s] ✅ 系统时间已同步: %s", MODULE_NAME, time.Now().Format("2006-01-02 15:04:05"))
  110. lastSyncNTPTime = time.Now()
  111. t.Reset(interval2)
  112. continue
  113. } else {
  114. isSyncNTPTimeOK.Store(false)
  115. baseapp.Logger.Errorf("[%s] 同步系统时间时有错误发生: %v!!", MODULE_NAME, err)
  116. t.Reset(interval1)
  117. continue
  118. }
  119. }
  120. // 3.4, 联网失败-离线时
  121. if isOnline.Load() { // 状态由"1"变为"0"
  122. offlineStartTime = time.Now() // 记录离线开始时间
  123. isOnline.Store(false)
  124. }
  125. if time.Since(offlineStartTime) >= (time.Duration(20)*time.Second) &&
  126. getNetType() == NetEth && !eth0LinkDegraded.Load() { // eth0无法联网
  127. offlineDur := time.Since(offlineStartTime).Round(time.Second)
  128. baseapp.Logger.Warnf(
  129. "[%s] eth0链路正常但持续无法访问外网(%v), 标记eth0为Degraded, 后续联网优先级将切换至蜂窝!",
  130. MODULE_NAME,
  131. offlineDur,
  132. )
  133. eth0LinkDegraded.Store(true) // 开始设置eth0网卡降级使用
  134. if err := SetupEth0ForManagement(eth0ManagementAddr); err != nil {
  135. baseapp.Logger.Errorf("[%s] 设置eth0管理地址失败: %v", MODULE_NAME, err)
  136. } else {
  137. baseapp.Logger.Infof("[%s] eth0已切换为管理口模式(%s)", MODULE_NAME, eth0ManagementAddr)
  138. }
  139. }
  140. if time.Since(offlineStartTime) >= (time.Duration(60) * time.Second) {
  141. baseapp.Logger.Warnf("[%s] 网络长时间的断开, 尝试重新激活...", MODULE_NAME)
  142. switch curModemType {
  143. case Air720U: //重启合宙4G调制解调器
  144. modem1.ModuleExit()
  145. modem1.ModuleInit(true)
  146. case EC200U: // 重启移远4G调制解调器
  147. modem2.ModuleExit()
  148. modem2.ModuleInit(true)
  149. }
  150. openNetwork()
  151. offlineStartTime = time.Now() // 重置离线开始时间
  152. }
  153. t.Reset(interval1)
  154. case <-baseapp.IsExit2():
  155. return
  156. } // select end
  157. } // for end
  158. }
  159. // 返回联网状态
  160. func IsInetAvailable() bool {
  161. return isOnline.Load()
  162. }
  163. // 时间是否同步
  164. func IsSyncedNtpTime() bool {
  165. return isSyncNTPTimeOK.Load()
  166. }
  167. // 等待所有成功
  168. func WaitAllOK(timeout time.Duration) bool {
  169. deadline := time.Now().Add(timeout)
  170. tick := 50 * time.Millisecond
  171. for {
  172. if IsInetAvailable() {
  173. if !enableTimeSync.Load() || IsSyncedNtpTime() {
  174. return true
  175. }
  176. }
  177. remaining := time.Until(deadline)
  178. if remaining <= 0 {
  179. return false
  180. }
  181. sleep := min(tick, remaining)
  182. time.Sleep(sleep)
  183. }
  184. }
  185. // 打开有线网络
  186. func openEth0Net() bool {
  187. mu1.Lock()
  188. defer mu1.Unlock()
  189. if isRunning1 {
  190. return true
  191. }
  192. killAllUdhcpc()
  193. err := disable4GInterfaces()
  194. if err != nil {
  195. baseapp.Logger.Errorf("[%s] 错误: %v!!", MODULE_NAME, err)
  196. return false
  197. }
  198. bExists, _ := udhcpcEth0Exists()
  199. if bExists {
  200. killEth0Udhcpc()
  201. }
  202. err = dialupEth0()
  203. if err != nil {
  204. baseapp.Logger.Errorf("[%s] 拨号连接\"eth0\"时发生错误: %v!!", MODULE_NAME, err)
  205. return false
  206. }
  207. ipv4, mask, err := getEth0Addr()
  208. if err != nil {
  209. baseapp.Logger.Errorf("[%s] 读取\"eth0\"地址时发生错误: %v!!", MODULE_NAME, err)
  210. return false
  211. }
  212. baseapp.Logger.Infof("[%s] \"eth0\"分配的地址: %s/%s", MODULE_NAME, ipv4, mask)
  213. exitCh1 = make(chan struct{})
  214. wg1.Add(1)
  215. go func() { // 启动携程守护"eth0"网卡上的 "udhcpc"后台服务进程
  216. defer wg1.Done()
  217. monitorEth0Udhcpc(exitCh1)
  218. }()
  219. isRunning1 = true
  220. return isRunning1
  221. }
  222. // 断开有线网络
  223. func closeEth0Net() {
  224. mu1.Lock()
  225. defer mu1.Unlock()
  226. if !isRunning1 {
  227. return
  228. }
  229. close(exitCh1)
  230. wg1.Wait() // 等待守护"eth0"网卡上的 "udhcpc"后台服务进程的携程退出
  231. bExists, _ := udhcpcEth0Exists()
  232. if bExists {
  233. killEth0Udhcpc()
  234. }
  235. isRunning1 = false
  236. }
  237. // 打开连接网络
  238. func openNetwork() {
  239. closeEth0Net()
  240. switch curModemType {
  241. case Air720U: //合宙4G调制解调器
  242. modem1.Stop4GNetwork()
  243. case EC200U: // 移远4G调制解调器
  244. modem2.Stop4GNetwork()
  245. }
  246. eth0CableOK, _ := isEth0CableConnected()
  247. if eth0CableOK && !eth0LinkDegraded.Load() { // 有线插入 && 有线未降级
  248. _ = openEth0Net()
  249. setNetType(NetEth)
  250. baseapp.Logger.Infof("[%s] ✅ 有线网络已激活", MODULE_NAME)
  251. return
  252. }
  253. start4GNetwork := func() bool {
  254. startOK := false
  255. switch curModemType {
  256. case Air720U: //合宙4G调制解调器
  257. if eth2CableOK, _ := modem1.Is4GCableConnected(); eth2CableOK {
  258. startOK = modem1.Start4GNetwork()
  259. time.Sleep(time.Duration(500) * time.Millisecond)
  260. enableEth0() // 恢复有线网口
  261. }
  262. case EC200U: // 移远4G调制解调器
  263. if usb0CableOK, _ := modem2.Is4GCableConnected(); usb0CableOK {
  264. startOK = modem2.Start4GNetwork()
  265. time.Sleep(time.Duration(500) * time.Millisecond)
  266. enableEth0() // 恢复有线网口
  267. }
  268. }
  269. return startOK
  270. }
  271. if start4GNetwork() {
  272. setNetType(NetLTE)
  273. baseapp.Logger.Infof("[%s] ✅ 蜂窝网络已激活(%s)", MODULE_NAME, curModemType.String())
  274. return
  275. }
  276. setNetType(NetNone)
  277. baseapp.Logger.Warnf("[%s] 当前无可用网络接口(有线/蜂窝均不可用)!", MODULE_NAME)
  278. }
  279. // 得到当前联网类型: 有线、蜂窝
  280. func GetCurrentNetType() NetType {
  281. return getNetType()
  282. }
  283. //export RTU_IsInetAvailable
  284. func RTU_IsInetAvailable() C.int {
  285. if IsInetAvailable() {
  286. return 1
  287. }
  288. return 0
  289. }
  290. //export RTU_IsSyncedNtpTime
  291. func RTU_IsSyncedNtpTime() C.int {
  292. if IsSyncedNtpTime() {
  293. return 1
  294. }
  295. return 0
  296. }