netmgrd.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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网卡降级使用
  128. if _, _, err := getEth0Addr(); err != nil { // 当eth0未分配到有效地址时
  129. SetupEth0ForManagement("192.168.80.1/24") // 给eth0设置一个静态的地址
  130. }
  131. }
  132. if time.Since(offlineStartTime) >= (time.Duration(60) * time.Second) {
  133. baseapp.Logger.Warnf("[%s] 网络长时间的断开, 尝试重新激活...", MODULE_NAME)
  134. switch curModemType {
  135. case Air720U: //重启合宙4G调制解调器
  136. modem1.ModuleExit()
  137. modem1.ModuleInit(true)
  138. case EC200U: // 重启移远4G调制解调器
  139. modem2.ModuleExit()
  140. modem2.ModuleInit(true)
  141. }
  142. openNetwork()
  143. offlineStartTime = time.Now() // 重置离线开始时间
  144. }
  145. t.Reset(interval1)
  146. case <-baseapp.IsExit2():
  147. return
  148. } // select end
  149. } // for end
  150. }
  151. // 返回联网状态
  152. func IsInetAvailable() bool {
  153. return isOnline.Load()
  154. }
  155. // 时间是否同步
  156. func IsSyncedNtpTime() bool {
  157. return isSyncNTPTimeOK.Load()
  158. }
  159. // 等待所有成功
  160. func WaitAllOK(timeout time.Duration) bool {
  161. deadline := time.Now().Add(timeout)
  162. tick := 50 * time.Millisecond
  163. for {
  164. if IsInetAvailable() {
  165. if !enableTimeSync.Load() || IsSyncedNtpTime() {
  166. return true
  167. }
  168. }
  169. remaining := time.Until(deadline)
  170. if remaining <= 0 {
  171. return false
  172. }
  173. sleep := min(tick, remaining)
  174. time.Sleep(sleep)
  175. }
  176. }
  177. // 打开有线网络
  178. func openEth0Net() bool {
  179. mu1.Lock()
  180. defer mu1.Unlock()
  181. if isRunning1 {
  182. return true
  183. }
  184. killAllUdhcpc()
  185. err := disable4GInterfaces()
  186. if err != nil {
  187. baseapp.Logger.Errorf("[%s] 错误: %v!!", MODULE_NAME, err)
  188. return false
  189. }
  190. bExists, _ := udhcpcEth0Exists()
  191. if bExists {
  192. killEth0Udhcpc()
  193. }
  194. err = dialupEth0()
  195. if err != nil {
  196. baseapp.Logger.Errorf("[%s] 拨号连接\"eth0\"时发生错误: %v!!", MODULE_NAME, err)
  197. return false
  198. }
  199. ipv4, mask, err := getEth0Addr()
  200. if err != nil {
  201. baseapp.Logger.Errorf("[%s] 读取\"eth0\"地址时发生错误: %v!!", MODULE_NAME, err)
  202. return false
  203. }
  204. baseapp.Logger.Infof("[%s] \"eth0\"分配的地址: %s/%s", MODULE_NAME, ipv4, mask)
  205. exitCh1 = make(chan struct{})
  206. wg1.Add(1)
  207. go func() { // 启动携程守护"eth0"网卡上的 "udhcpc"后台服务进程
  208. defer wg1.Done()
  209. monitorEth0Udhcpc(exitCh1)
  210. }()
  211. isRunning1 = true
  212. return isRunning1
  213. }
  214. // 断开有线网络
  215. func closeEth0Net() {
  216. mu1.Lock()
  217. defer mu1.Unlock()
  218. if !isRunning1 {
  219. return
  220. }
  221. close(exitCh1)
  222. wg1.Wait() // 等待守护"eth0"网卡上的 "udhcpc"后台服务进程的携程退出
  223. bExists, _ := udhcpcEth0Exists()
  224. if bExists {
  225. killEth0Udhcpc()
  226. }
  227. isRunning1 = false
  228. }
  229. // 打开连接网络
  230. func openNetwork() {
  231. closeEth0Net()
  232. switch curModemType {
  233. case Air720U: //合宙4G调制解调器
  234. modem1.Stop4GNetwork()
  235. case EC200U: // 移远4G调制解调器
  236. modem2.Stop4GNetwork()
  237. }
  238. eth0CableOK, _ := isEth0CableConnected()
  239. if eth0CableOK && !eth0LinkDegraded.Load() { // 有线插入 && 有线未降级
  240. _ = openEth0Net()
  241. setNetType(NetEth)
  242. baseapp.Logger.Infof("[%s] ✅ 有线网络已激活", MODULE_NAME)
  243. return
  244. }
  245. start4GNetwork := func() bool {
  246. startOK := false
  247. switch curModemType {
  248. case Air720U: //合宙4G调制解调器
  249. if eth2CableOK, _ := modem1.Is4GCableConnected(); eth2CableOK {
  250. startOK = modem1.Start4GNetwork()
  251. time.Sleep(time.Duration(500) * time.Millisecond)
  252. enableEth0() // 恢复有线网口
  253. }
  254. case EC200U: // 移远4G调制解调器
  255. if usb0CableOK, _ := modem2.Is4GCableConnected(); usb0CableOK {
  256. startOK = modem2.Start4GNetwork()
  257. time.Sleep(time.Duration(500) * time.Millisecond)
  258. enableEth0() // 恢复有线网口
  259. }
  260. }
  261. return startOK
  262. }
  263. if start4GNetwork() {
  264. setNetType(NetLTE)
  265. baseapp.Logger.Infof("[%s] ✅ 蜂窝网络已激活(%s)", MODULE_NAME, curModemType.String())
  266. return
  267. }
  268. setNetType(NetNone)
  269. baseapp.Logger.Warnf("[%s] 当前无可用网络接口(有线/蜂窝均不可用)!", MODULE_NAME)
  270. }
  271. // 得到当前联网类型: 有线、蜂窝
  272. func GetCurrentNetType() NetType {
  273. return getNetType()
  274. }
  275. //export RTU_IsInetAvailable
  276. func RTU_IsInetAvailable() C.int {
  277. if IsInetAvailable() {
  278. return 1
  279. }
  280. return 0
  281. }
  282. //export RTU_IsSyncedNtpTime
  283. func RTU_IsSyncedNtpTime() C.int {
  284. if IsSyncedNtpTime() {
  285. return 1
  286. }
  287. return 0
  288. }