package main import ( "os/exec" "sync/atomic" "time" ) // DutiesVPN VPN相关的责任 type DutiesVPN struct { PW *PingWorker VPNProtectTime int64 // 保护时间 MaxProtectTime int64 // 保护时间的最大值 } // Default 设置默认值 func (duties *DutiesVPN) Default(pw *PingWorker) { duties.PW = pw atomic.StoreInt64(&duties.MaxProtectTime, 40) //保护时间初始化为40秒 go duties.Duties() } //Reset 重置 func (duties *DutiesVPN) Reset() { atomic.StoreInt64(&duties.VPNProtectTime, time.Now().Unix()) } // RestartConnect 重置Openvpn连接 func (duties *DutiesVPN) RestartConnect() { _, err := exec.Command("pkill", "openvpn").CombinedOutput() ErrorLog(err) atomic.StoreInt64(&duties.VPNProtectTime, time.Now().Unix()+duties.MaxProtectTime) //重启后给予40秒openvpn的重试时间 } // Duties 保证openvpn的可行 func (duties *DutiesVPN) Duties() { duties.Reset() for { time.Sleep(time.Second * 2) if duties.PW.PingNet() { if !duties.PW.PingVPN() { now := time.Now().Unix() // openvpn需要一段时间connect 才能知道是否连接成功. 所以所有一段保护时间确保这段时间内是进行connect. if now >= atomic.LoadInt64(&duties.VPNProtectTime) { duties.RestartConnect() continue } } } } }