netmgrd.go 8.4 KB

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