The code explains itself and you can define the number of retries. Also the waiting times time between retries and bot give the total retry time.
On completion, it will state the result and also states if there was domain resolving available. Without the last resolving does not work. You will also get that result if the entered domain is invalid.
It will only check and restart, if needed, active WireGuard connections and if the the profile in peers is active or not is not being checked. I replaced also /interface/ by /in/ to have a shorter line in the code.
I reused and altered a bit of code published here by Anav to fit this code.
I have not tested a outcomes of the script and if run into problems then let me know in this thread. Also for suggestions.
Code: Select all
{; # BeginOfScript
# scripted by msatter
# function: bring up stalled WireGuard interfaces after restart of the router
:local timesRetried 15; # how many times WireGuard is tried to be restarted
:local loopDelay "10s"; # (loopDelay * timesRetried ) = total timeout
:local restarted true; # set default to true
:local domainResolved false # also checking if the endpoint domain-names could be resolved
:local retried 0; # set to starting value
while ( $restarted && ( $retried < $timesRetried ) ) do={ # loop till all Wireguard interfaces are working or there the maximum retries is reached
:set $restarted false
:foreach wg in=[/interface/wireguard/find disabled=no] do={
:local peer [/interface/wireguard/get $wg name]
# scripted by Anav looking for domain names. Adapted by msatter. ( /in/ = /interface/ )
:foreach i in=[/in/wireguard/peers/find interface=$peer endpoint-address~"[a-z]\$"] do={
:if ([:resolve [/interface/wireguard/peers/get $i value-name=endpoint-address]]) do={ :set $domainResolved true
:set $lastHandshake [/in/wireguard/peers/get $i last-handshake]
:if (([:tostr $lastHandshake] = "") || ( $lastHandshake > [:totime [/in/wireguard/peers/get $i persistent-keepalive]])) do={
/in/wireguard/ disable $peer; :delay 1s; /in/wireguard/ enable $peer; # restarting the WireGuard connection
:set $restarted true
}; # EndIf
}; # EndIf
}; # EndForeach
}; # EndForeach
:if (restarted) do={
:put "Check loop: $retried"
:set $retried ($retried + 1)
:put "Checking loop: $retried"
:delay $loopDelay; # waiting time till following check
}; #EndIf
}; # EndWhile
:if ( !$domainResolved ) do={:put "One or more domains could not be resolved, all/some domain based endpoints could not be brought up in the set time of ($timesRetried * $loopDelay)"} else={
:if ( $restarted && ( $retried > $timesRestied ) ) do={:put "Not all WireGuard interfaces could be brought up in the set time of ($timesRetried * $loopDelay)"}
:if ( !$restarted && ( $retried > 0 ) ) do={:put "No WireGuard interfaces are down, after $retried retries"}
:if ( $retried = 0 ) do={:put "No WireGuard interfaces had to be restared"}
}; # EndElse
}; #EndOfScript