|
4 | 4 | # |
5 | 5 | # SPDX-License-Identifier: Apache-2.0 |
6 | 6 |
|
7 | | -get_conf_endpoint() { |
8 | | - grep "Endpoint" /etc/wireguard/wg0.conf | awk "{print \$3}" |
| 7 | +HANDSHAKE_TIMEOUT=180 |
| 8 | +LAST_REFRESH=0 |
| 9 | +STALE_SINCE=0 |
| 10 | +DSTACK_WORK_DIR=${DSTACK_WORK_DIR:-/dstack} |
| 11 | +IFNAME=dstack-wg0 |
| 12 | + |
| 13 | +get_latest_handshake() { |
| 14 | + wg show $IFNAME latest-handshakes 2>/dev/null | awk 'BEGIN { max = 0 } NF >= 2 { if ($2 > max) max = $2 } END { print max }' |
9 | 15 | } |
10 | 16 |
|
11 | | -get_current_endpoint() { |
12 | | - wg show wg0 endpoints | awk "{print \$2}" |
| 17 | +maybe_refresh() { |
| 18 | + now=$1 |
| 19 | + |
| 20 | + if [ "$LAST_REFRESH" -ne 0 ] && [ $((now - LAST_REFRESH)) -lt $HANDSHAKE_TIMEOUT ]; then |
| 21 | + return |
| 22 | + fi |
| 23 | + |
| 24 | + if ! command -v dstack-util >/dev/null 2>&1; then |
| 25 | + printf 'dstack-util not found; cannot refresh gateway.\n' >&2 |
| 26 | + LAST_REFRESH=$now |
| 27 | + return |
| 28 | + fi |
| 29 | + |
| 30 | + printf 'WireGuard handshake stale; refreshing dstack gateway...\n' |
| 31 | + if dstack-util gateway-refresh --work-dir "$DSTACK_WORK_DIR"; then |
| 32 | + printf 'dstack gateway refresh succeeded.\n' |
| 33 | + else |
| 34 | + printf 'dstack gateway refresh failed.\n' >&2 |
| 35 | + fi |
| 36 | + |
| 37 | + LAST_REFRESH=$now |
| 38 | + STALE_SINCE=$now |
13 | 39 | } |
14 | 40 |
|
15 | | -check_endpoint() { |
16 | | - CONF_ENDPOINT=$(get_conf_endpoint) |
17 | | - CURRENT_ENDPOINT=$(get_current_endpoint) |
| 41 | +check_handshake() { |
| 42 | + if ! command -v wg >/dev/null 2>&1; then |
| 43 | + return |
| 44 | + fi |
| 45 | + |
| 46 | + now=$(date +%s) |
| 47 | + latest=$(get_latest_handshake) |
| 48 | + |
| 49 | + if [ -z "$latest" ]; then |
| 50 | + latest=0 |
| 51 | + fi |
18 | 52 |
|
19 | | - if [ "$CURRENT_ENDPOINT" != "$CONF_ENDPOINT" ]; then |
20 | | - echo "Wg endpoint changed from $CONF_ENDPOINT to $CURRENT_ENDPOINT." |
21 | | - wg syncconf wg0 <(wg-quick strip wg0) |
| 53 | + if [ "$latest" -gt 0 ]; then |
| 54 | + if [ $((now - latest)) -ge $HANDSHAKE_TIMEOUT ]; then |
| 55 | + maybe_refresh "$now" |
| 56 | + else |
| 57 | + STALE_SINCE=0 |
| 58 | + fi |
| 59 | + else |
| 60 | + if [ "$STALE_SINCE" -eq 0 ]; then |
| 61 | + STALE_SINCE=$now |
| 62 | + fi |
| 63 | + if [ $((now - STALE_SINCE)) -ge $HANDSHAKE_TIMEOUT ]; then |
| 64 | + maybe_refresh "$now" |
| 65 | + fi |
22 | 66 | fi |
23 | 67 | } |
24 | 68 |
|
25 | 69 | while true; do |
26 | | - if [ -f /etc/wireguard/wg0.conf ]; then |
27 | | - check_endpoint |
| 70 | + if [ -f /etc/wireguard/$IFNAME.conf ]; then |
| 71 | + check_handshake |
| 72 | + else |
| 73 | + STALE_SINCE=0 |
28 | 74 | fi |
29 | 75 | sleep 10 |
30 | 76 | done |
0 commit comments