Skip to content

Commit

Permalink
Use exceptions instead of negative return value
Browse files Browse the repository at this point in the history
  • Loading branch information
DasSkelett committed Mar 29, 2024
1 parent 3befef0 commit b536989
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
10 changes: 7 additions & 3 deletions wgkex/worker/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Any, Optional

import paho.mqtt.client as mqtt
import pyroute2.netlink.exceptions

from wgkex.common import logger
from wgkex.common.mqtt import (
Expand Down Expand Up @@ -231,9 +232,12 @@ def publish_metrics(client: mqtt.Client, topic: str, domain: str) -> None:
f"Could not get interface name for domain {domain}. Skipping metrics publication"
)
return
peer_count = get_connected_peers_count(iface)
if peer_count < 0:
# get_connected_peers_count() encountered some error, don't update metrics

try:
peer_count = get_connected_peers_count(iface)
except pyroute2.netlink.exceptions.NetlinkDumpInterrupted:
# Handle gracefully, don't update metrics
logger.info("Caught NetlinkDumpInterrupted exception while collecting metrics for domain {domain}")
return

# Publish metrics, retain it at MQTT broker so restarted wgkex broker has metrics right away
Expand Down
11 changes: 5 additions & 6 deletions wgkex/worker/netlink.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,9 @@ def get_connected_peers_count(wg_interface: str) -> int:
Returns:
The number of peers which have recently seen a handshake.
-1 if an internal error has been encountered.
Raises:
NetlinkDumpInterrupted if the interface data has changed while it was being returned by netlink
"""
three_mins_ago_in_secs = int((datetime.now() - timedelta(minutes=3)).timestamp())
logger.info("Counting connected wireguard peers for interface %s.", wg_interface)
Expand All @@ -227,12 +229,9 @@ def get_connected_peers_count(wg_interface: str) -> int:
msgs = wg.info(wg_interface)
except pyroute2.netlink.exceptions.NetlinkDumpInterrupted:
# Normal behaviour, data has changed while it was being returned by netlink.
# Retry once, otherwise return -1 and let the caller handle it.
# Retry once, don't catch the exception this time, and let the caller handle it.
# See https://github.com/svinota/pyroute2/issues/874
try:
msgs = wg.info(wg_interface)
except pyroute2.netlink.exceptions.NetlinkDumpInterrupted:
return -1
msgs = wg.info(wg_interface)

logger.debug("Got infos for connected peers: %s.", msgs)
count = 0
Expand Down

0 comments on commit b536989

Please sign in to comment.