Skip to content

Commit

Permalink
Fix stats sending loop (#148)
Browse files Browse the repository at this point in the history
* Update gateway.rs

* don't hold lock in match

* Update gateway.rs

* bump version
  • Loading branch information
t-aleksander authored Jan 24, 2025
1 parent e6fcab7 commit 2ba8294
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 31 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "defguard-gateway"
version = "1.2.0"
version = "1.2.1"
edition = "2021"

[dependencies]
Expand Down
53 changes: 24 additions & 29 deletions src/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,11 @@ impl Gateway {
}

// check if all IPs are the same
!new_peers
.iter()
.all(|peer| match self.peers.get(&peer.pubkey) {
Some(p) => peer.allowed_ips == p.allowed_ips,
None => false,
})
!new_peers.iter().all(|peer| {
self.peers
.get(&peer.pubkey)
.map_or(false, |p| peer.allowed_ips == p.allowed_ips)
})
}

/// Starts tokio thread collecting stats and sending them to backend service via gRPC.
Expand All @@ -188,13 +187,12 @@ impl Gateway {
let mut peer_map = HashMap::new();
let mut interval = interval(period);
let mut id = 1;
loop {
'outer: loop {
// wait until next iteration
interval.tick().await;
let mut payload = Payload::Empty(());

debug!("Sending active peer stats update.");
match wgapi.lock().unwrap().read_interface_data() {
debug!("Sending active peer stats updates.");
let interface_data = wgapi.lock().unwrap().read_interface_data();
match interface_data {
Ok(host) => {
let peers = host.peers;
debug!(
Expand All @@ -205,13 +203,22 @@ impl Gateway {
p.last_handshake
.map_or(false, |lhs| lhs != SystemTime::UNIX_EPOCH)
}) {
let has_changed = match peer_map.get(&peer.public_key) {
Some(last_peer) => *last_peer != peer,
None => true,
};
let has_changed = peer_map
.get(&peer.public_key)
.map_or(true, |last_peer| *last_peer != peer);
if has_changed {
peer_map.insert(peer.public_key.clone(), peer.clone());
payload = Payload::PeerStats((&peer).into());
id += 1;
if tx
.send(StatsUpdate {
id,
payload: Some(Payload::PeerStats((&peer).into())),
})
.is_err()
{
debug!("Stats stream disappeared");
break 'outer;
}
} else {
debug!(
"Stats for peer {} have not changed. Skipping.",
Expand All @@ -222,19 +229,7 @@ impl Gateway {
}
Err(err) => error!("Failed to retrieve WireGuard interface stats: {err}"),
}

id += 1;
if tx
.send(StatsUpdate {
id,
payload: Some(payload),
})
.is_err()
{
debug!("Stats stream disappeared");
break;
}
debug!("Active peer stats update sent.");
debug!("Sent peer stats updates for all peers.");
}
});
self.stats_thread = Some(handle);
Expand Down

0 comments on commit 2ba8294

Please sign in to comment.