netmgrd.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. eth0NetDegraded 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.90.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 || getNetType() == NetNone) && eth0NetDegraded.CompareAndSwap(true, false) {
  75. baseapp.Logger.Infof("[%s] eth0网线已拔出或当前无可用网络, 清除有线网络降级标志, 恢复正常联网尝试", MODULE_NAME)
  76. }
  77. if eth0CableOK && getNetType() != NetEth && !eth0NetDegraded.Load() { //////////// 有线插入 && 当前不是有线 && 有线还未降级
  78. baseapp.Logger.Warnf("[%s] 检测到有线插入,正在尝试切换到有线网络...", MODULE_NAME)
  79. openNetwork()
  80. } else if (!eth0CableOK || eth0NetDegraded.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",
  87. MODULE_NAME, getNetType().String(), dnsOK, pingOK, tcpOK, httpOK)
  88. // 3.3, 联网成功-在线时
  89. netOK := tcpOK || httpOK
  90. if netOK {
  91. isOnline.Store(true)
  92. if !enableTimeSync.Load() { // 时间同步功能被禁用, 下面不再同步
  93. isSyncNTPTimeOK.Store(false)
  94. t.Reset(interval2)
  95. continue
  96. }
  97. if isSyncNTPTimeOK.Load() && time.Since(lastSyncNTPTime) < (time.Duration(60)*time.Minute) {
  98. t.Reset(interval2)
  99. continue
  100. }
  101. var err error
  102. if !httpTime.IsZero() { // 优先使用HTTP时间, 实测速度快且精度高
  103. err = SetSystemTime(httpTime)
  104. }
  105. if httpTime.IsZero() || err != nil {
  106. err = SyncNTPTime() //// 同步HTTP时间失败, 则尝试同步标准时间
  107. }
  108. if err == nil {
  109. isSyncNTPTimeOK.Store(true)
  110. baseapp.Logger.Infof("[%s] ✅ 系统时间已同步: %s", MODULE_NAME, time.Now().Format("2006-01-02 15:04:05"))
  111. lastSyncNTPTime = time.Now()
  112. t.Reset(interval2)
  113. continue
  114. } else {
  115. isSyncNTPTimeOK.Store(false)
  116. baseapp.Logger.Errorf("[%s] 同步系统时间时有错误发生: %v!!", MODULE_NAME, err)
  117. t.Reset(interval1)
  118. continue
  119. }
  120. }
  121. // 3.4, 联网失败-离线时
  122. if isOnline.Load() { // 状态由"1"变为"0"
  123. offlineStartTime = time.Now() // 记录离线开始时间
  124. isOnline.Store(false)
  125. }
  126. if time.Since(offlineStartTime) >= (time.Duration(20)*time.Second) &&
  127. getNetType() == NetEth && !eth0NetDegraded.Load() { // eth0无法联网/
  128. eth0NetDegraded.Store(true) /////////////// 开始设置eth0网卡降级使用/
  129. offlineDur := time.Since(offlineStartTime).Round(time.Second)
  130. baseapp.Logger.Warnf(
  131. "[%s] eth0持续无法访问公网(%v), 已降级有线网络, 将尝试连接蜂窝网络!",
  132. MODULE_NAME,
  133. offlineDur,
  134. )
  135. if err := SetupEth0ForManagement(eth0ManagementAddr); err != nil {
  136. baseapp.Logger.Errorf("[%s] 设置eth0管理地址失败: %v", MODULE_NAME, err)
  137. } else {
  138. baseapp.Logger.Infof("[%s] eth0已切换为管理口模式(%s)", MODULE_NAME, eth0ManagementAddr)
  139. }
  140. }
  141. if time.Since(offlineStartTime) >= (time.Duration(60) * time.Second) {
  142. baseapp.Logger.Warnf("[%s] 网络长时间的断开, 尝试重新激活...", MODULE_NAME)
  143. switch curModemType {
  144. case Air720U: //重启合宙4G调制解调器
  145. modem1.ModuleExit()
  146. modem1.ModuleInit(true)
  147. case EC200U: // 重启移远4G调制解调器
  148. modem2.ModuleExit()
  149. modem2.ModuleInit(true)
  150. }
  151. openNetwork()
  152. offlineStartTime = time.Now() // 重置离线开始时间
  153. }
  154. t.Reset(interval1)
  155. case <-baseapp.IsExit2():
  156. return
  157. } // select end
  158. } // for end
  159. }
  160. // 返回联网状态
  161. func IsInetAvailable() bool {
  162. return isOnline.Load()
  163. }
  164. // 时间是否同步
  165. func IsSyncedNtpTime() bool {
  166. return isSyncNTPTimeOK.Load()
  167. }
  168. // 等待所有成功
  169. func WaitAllOK(timeout time.Duration) bool {
  170. deadline := time.Now().Add(timeout)
  171. tick := 50 * time.Millisecond
  172. for {
  173. if IsInetAvailable() {
  174. if !enableTimeSync.Load() || IsSyncedNtpTime() {
  175. return true
  176. }
  177. }
  178. remaining := time.Until(deadline)
  179. if remaining <= 0 {
  180. return false
  181. }
  182. sleep := min(tick, remaining)
  183. time.Sleep(sleep)
  184. }
  185. }
  186. // 打开有线网络
  187. func openEth0Net() bool {
  188. mu1.Lock()
  189. defer mu1.Unlock()
  190. if isRunning1 {
  191. return true
  192. }
  193. killAllUdhcpc()
  194. err := disable4GInterfaces()
  195. if err != nil {
  196. baseapp.Logger.Errorf("[%s] 错误: %v!!", MODULE_NAME, err)
  197. return false
  198. }
  199. bExists, _ := udhcpcEth0Exists()
  200. if bExists {
  201. killEth0Udhcpc()
  202. }
  203. err = dialupEth0()
  204. if err != nil {
  205. baseapp.Logger.Errorf("[%s] 拨号连接\"eth0\"时发生错误: %v!!", MODULE_NAME, err)
  206. return false
  207. }
  208. ipv4, mask, err := getEth0Addr()
  209. if err != nil {
  210. baseapp.Logger.Errorf("[%s] 读取\"eth0\"地址时发生错误: %v!!", MODULE_NAME, err)
  211. return false
  212. }
  213. baseapp.Logger.Infof("[%s] \"eth0\"分配的地址: %s/%s", MODULE_NAME, ipv4, mask)
  214. exitCh1 = make(chan struct{})
  215. wg1.Add(1)
  216. go func() { // 启动携程守护"eth0"网卡上的 "udhcpc"后台服务进程
  217. defer wg1.Done()
  218. monitorEth0Udhcpc(exitCh1)
  219. }()
  220. isRunning1 = true
  221. return isRunning1
  222. }
  223. // 断开有线网络
  224. func closeEth0Net() {
  225. mu1.Lock()
  226. defer mu1.Unlock()
  227. if !isRunning1 {
  228. return
  229. }
  230. close(exitCh1)
  231. wg1.Wait() // 等待守护"eth0"上的 "udhcpc"后台服务进程的携程退出
  232. bExists, _ := udhcpcEth0Exists()
  233. if bExists {
  234. killEth0Udhcpc()
  235. }
  236. isRunning1 = false
  237. }
  238. // 打开连接网络
  239. func openNetwork() {
  240. closeEth0Net()
  241. switch curModemType {
  242. case Air720U: //合宙4G调制解调器
  243. modem1.Stop4GNetwork()
  244. case EC200U: // 移远4G调制解调器
  245. modem2.Stop4GNetwork()
  246. }
  247. eth0CableOK, _ := isEth0CableConnected()
  248. if eth0CableOK && !eth0NetDegraded.Load() { // 有线插入 && 有线未降级
  249. _ = openEth0Net()
  250. setNetType(NetEth)
  251. baseapp.Logger.Infof("[%s] ✅ 有线网络已激活", MODULE_NAME)
  252. return
  253. }
  254. start4GNetwork := func() bool {
  255. startOK := false
  256. switch curModemType {
  257. case Air720U: //合宙4G调制解调器
  258. if eth2CableOK, _ := modem1.Is4GCableConnected(); eth2CableOK {
  259. startOK = modem1.Start4GNetwork()
  260. time.Sleep(time.Duration(500) * time.Millisecond)
  261. enableEth0() // 恢复有线网口
  262. }
  263. case EC200U: // 移远4G调制解调器
  264. if usb0CableOK, _ := modem2.Is4GCableConnected(); usb0CableOK {
  265. startOK = modem2.Start4GNetwork()
  266. time.Sleep(time.Duration(500) * time.Millisecond)
  267. enableEth0() // 恢复有线网口
  268. }
  269. }
  270. return startOK
  271. }
  272. if start4GNetwork() {
  273. setNetType(NetLTE)
  274. baseapp.Logger.Infof("[%s] ✅ 蜂窝网络已激活(%s)", MODULE_NAME, curModemType.String())
  275. return
  276. }
  277. setNetType(NetNone)
  278. baseapp.Logger.Warnf("[%s] 当前无可用网络接口(有线/蜂窝均不可用)!", MODULE_NAME)
  279. }
  280. // 得到当前联网类型: 有线、蜂窝
  281. func GetCurrentNetType() NetType {
  282. return getNetType()
  283. }
  284. //export RTU_IsInetAvailable
  285. func RTU_IsInetAvailable() C.int {
  286. if IsInetAvailable() {
  287. return 1
  288. }
  289. return 0
  290. }
  291. //export RTU_IsSyncedNtpTime
  292. func RTU_IsSyncedNtpTime() C.int {
  293. if IsSyncedNtpTime() {
  294. return 1
  295. }
  296. return 0
  297. }