Skip to content

Instantly share code, notes, and snippets.

@nyx-rattapoom
Last active March 21, 2021 13:44
Show Gist options
  • Save nyx-rattapoom/f4228b201c0a6343e62805ed237cfa9a to your computer and use it in GitHub Desktop.
Save nyx-rattapoom/f4228b201c0a6343e62805ed237cfa9a to your computer and use it in GitHub Desktop.
Wireguard reconnection For NetworkManager When connection go wrong
package main
import (
"bytes"
"flag"
"net/http"
"os/exec"
"strings"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const MAX_FAILED = 5
const DELAY_DEV_CHECK_TIME = 3
const DELAY_TIME = 2
const DEV_NETWORK = "tun1"
func checkOnline(httpClient *http.Client, channel chan bool) {
response, err := httpClient.Get("http://clients3.google.com/generate_204")
log.Debug().Msg("Network requested")
if err != nil {
log.Error().Msg("Network error")
channel <- false
return
}
if response.StatusCode == 204 {
log.Debug().Msg("Network online")
channel <- true
} else {
log.Error().Msg("Not return 204 something went wrong !!!")
channel <- false
}
}
func isVirtualNetworkActive() bool {
_, output := executeCommand("nmcli", "connection", "show", "--active")
return strings.Contains(output, DEV_NETWORK)
}
func executeCommand(executable string, args ...string) (success bool, output string) {
var stdOut, stdErr bytes.Buffer
cmd := exec.Command(executable, args...)
cmd.Stdout = &stdOut
cmd.Stderr = &stdErr
err := cmd.Run()
if err != nil {
return false, stdErr.String()
}
return true, stdOut.String()
}
func resetNetwork() {
_, deactiveOutput := executeCommand("nmcli", "connection", "down", DEV_NETWORK)
log.Debug().Msg(deactiveOutput)
_, activateOutput := executeCommand("nmcli", "connection", "up", DEV_NETWORK)
log.Debug().Msg(activateOutput)
}
func main() {
debug := flag.Bool("debug", false, "sets log level to debug")
flag.Parse()
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
connectFailedCount := 0
checkConnectionChannel := make(chan bool)
var httpClient = &http.Client{
Timeout: time.Second * 1,
}
for {
if !isVirtualNetworkActive() {
log.Debug().Msgf("Taget network: %s not actived", DEV_NETWORK)
time.Sleep(time.Second * DELAY_DEV_CHECK_TIME)
continue
}
go checkOnline(httpClient, checkConnectionChannel)
isCheckOnlineResult := <-checkConnectionChannel
if isCheckOnlineResult {
connectFailedCount = 0
} else {
connectFailedCount += 1
}
if connectFailedCount >= MAX_FAILED {
log.Error().Msg("Connection down count reached reset network !")
resetNetwork()
connectFailedCount = 0
}
time.Sleep(time.Second * DELAY_TIME)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment