1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use std::{
collections::HashMap,
io,
sync::{Arc, atomic::AtomicUsize},
time::Duration,
};
use futures::StreamExt;
use kameo::{
Actor,
actor::ActorRef,
message::{Context, Message, StreamMessage},
};
use smol_str::ToSmolStr;
use ts_netmon::{Event, Family, InterfaceId, Netmon};
use crate::env::Env;
pub struct NetmonActor {
mon: Arc<dyn Netmon>,
state: State,
env: Env,
_id: Id,
}
/// Map from the unique part of a route to its metric.
pub type Routes = HashMap<ts_netmon::RouteUnique, usize>;
/// The unique id of a [`NetmonActor`] instance.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id {
pub ty: ts_netmon::MonType,
pub id: usize,
}
impl Id {
fn new(ty: ts_netmon::MonType) -> Self {
static ID: AtomicUsize = AtomicUsize::new(0);
Self {
ty,
id: ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
}
}
}
/// Netmon state at a point in time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct State {
/// The id of the [`NetmonActor`] that generated this [`State`].
pub id: Id,
/// Interfaces detected on a [`Netmon`].
pub interfaces: HashMap<InterfaceId, ts_netmon::Interface>,
/// Routes per interface.
pub routes: HashMap<InterfaceId, Routes>,
/// Addresses per interface.
///
/// To recover the full address with the prefix len, use key's `addr()` as the address
/// and the value as the prefix len.
///
/// The representation is split this way to support [`Netmon::interface_unique_addrs`].
pub addrs: HashMap<InterfaceId, HashMap<ipnet::IpNet, u8>>,
/// The interface that has the IPv4 default route, if any.
pub default_route_interface_v4: Option<InterfaceId>,
/// The interface that has the IPv6 default route, if any.
pub default_route_interface_v6: Option<InterfaceId>,
}
#[expect(dead_code)]
impl State {
/// Iterate the addresses on all interfaces in the `up` state.
pub fn up_addrs(&self) -> impl Iterator<Item = (InterfaceId, ipnet::IpNet)> {
self.addrs
.iter()
.filter_map(|(id, addrs)| {
let interface = self.interfaces.get(id)?;
if !interface.up {
return None;
}
Some(
addrs
.iter()
.map(|(ipn, &pfx)| (id.clone(), ipnet::IpNet::new_assert(ipn.addr(), pfx))),
)
})
.flatten()
}
/// Iterate the routes on all interfaces in the `up` state.
pub fn up_routes(&self) -> impl Iterator<Item = (InterfaceId, ts_netmon::Route)> {
self.routes
.iter()
.filter_map(|(id, routes)| {
let interface = self.interfaces.get(id)?;
if !interface.up {
return None;
}
Some(routes.iter().map(|((dst, gws), &metric)| {
(
id.clone(),
ts_netmon::Route {
gateway: gws.clone(),
metric,
dst: *dst,
},
)
}))
})
.flatten()
}
}
impl Actor for NetmonActor {
type Args = (Env, Arc<dyn Netmon>);
type Error = io::Error;
async fn on_start((env, mon): Self::Args, slf: ActorRef<Self>) -> Result<Self, Self::Error> {
let id = Id::new(mon.ty());
slf.attach_stream(
{
use tokio_stream::StreamExt;
mon.with_default_route_events()?
.chunks_timeout(256, Duration::from_millis(100))
.boxed()
},
(),
(),
);
env.register(Some(mon.ty().as_ref().to_smolstr()), &slf)
.await
.unwrap();
Ok(Self {
env,
mon,
state: State {
id: id.clone(),
addrs: Default::default(),
routes: Default::default(),
interfaces: Default::default(),
default_route_interface_v4: None,
default_route_interface_v6: None,
},
_id: id,
})
}
}
impl Message<StreamMessage<Vec<io::Result<Event>>, (), ()>> for NetmonActor {
type Reply = ();
async fn handle(
&mut self,
msg: StreamMessage<Vec<io::Result<Event>>, (), ()>,
_ctx: &mut Context<Self, Self::Reply>,
) {
let events = match msg {
StreamMessage::Started(_) | StreamMessage::Finished(_) => {
return;
}
StreamMessage::Next(val) => val,
};
if events.is_empty() {
tracing::warn!("empty netmon event");
return;
}
let mut modified = false;
for event in &events {
let event_modified = self.handle_event(event);
if event_modified {
tracing::trace!(mutating_netmon_event = ?event);
}
modified = modified || event_modified;
}
if !modified {
return;
}
tracing::debug!(n_coalesced_events = events.len(), "netmon mutation");
self.env
.publish(Arc::new(self.state.clone()))
.await
.unwrap();
}
}
impl NetmonActor {
fn handle_event(&mut self, event: &io::Result<Event>) -> bool {
let event = match event {
Ok(event) => event,
Err(e) => {
tracing::error!(error = %e, "netmon error");
return false;
}
};
let mut modified = false;
match &event {
Event::RouteUpsert(interface, route) => {
let old = self
.state
.routes
.entry(interface.clone())
.or_default()
.insert(route.unique(), route.metric);
modified = old.is_none_or(|old| old != route.metric);
}
Event::RouteRemoved(interface, route) => {
let mut empty = false;
self.state.routes.entry(interface.clone()).and_modify(|r| {
modified = r.remove(&route.unique()).is_some();
empty = r.is_empty();
});
if empty {
self.state.routes.remove(interface);
}
}
Event::AddrUpsert(interface, addr) => {
let (addr, pfx_len) = self.split_interface_addr(addr);
let old = self
.state
.addrs
.entry(interface.clone())
.or_default()
.insert(addr, pfx_len);
modified = old.is_none_or(|old| old != pfx_len);
}
Event::AddrRemoved(interface, addr) => {
let mut empty = false;
let (addr, _pfx_len) = self.split_interface_addr(addr);
self.state.addrs.entry(interface.clone()).and_modify(|e| {
modified = e.remove(&addr).is_some();
empty = e.is_empty();
});
if empty {
self.state.addrs.remove(interface);
}
}
Event::InterfaceUpsert(interface) => {
let old = self
.state
.interfaces
.insert(interface.id.clone(), interface.clone());
modified = old.is_none_or(|old| &old != interface);
}
Event::InterfaceRemoved(interface) => {
self.state.interfaces.retain(|x, _| {
let ret = x != interface;
if !ret {
modified = true;
}
ret
});
// NOTE(npry): the below modification of routes and addrs on link deletion is due to
// divergence in platform behavior:
//
// - rtnetlink has a strongly-consistent event ordering model (as it's a single
// reliable socket) that orders route and address deletion events before link
// deletions, but it doesn't seem to _guarantee_ individual deletions for all
// routes and addresses related to a link when it's deleted; the link deletion
// itself seems to be intended to clean those up.
// - Win32 notify APIs are, on the other hand, free to race between route, address,
// and link modifications, but are ordered within each logical resource stream and
// appear to exhaustively issue deletion events for all routes and addresses _at
// some point_ when a link is deleted. The link deletion event, however, may issue
// in an arbitrary order wrt. the other events. The implication of this is that we
// technically shouldn't proactively delete the other resources when the link is
// removed, since we could be deleting routes and addresses related to a future
// generation of the link in a race condition.
//
// This logic is meant to rectify that and make our state reflect what the platform
// has told us it should be regardless of the underlying consistency model.
if self.mon.strong_delete_consistency() {
modified = modified || self.state.routes.remove(interface).is_some();
modified = modified || self.state.addrs.remove(interface).is_some();
}
}
Event::DefaultRouteInterface(iface, family) => {
let pre_v4 = self.state.default_route_interface_v4.clone();
let pre_v6 = self.state.default_route_interface_v6.clone();
match family {
Family::Ipv4 => self.state.default_route_interface_v4 = iface.clone(),
Family::Ipv6 => self.state.default_route_interface_v6 = iface.clone(),
}
if pre_v4 != self.state.default_route_interface_v4
|| pre_v6 != self.state.default_route_interface_v6
{
modified = true;
}
}
}
if !modified {
tracing::trace!(?event, "netmon event with no delta");
}
modified
}
/// Split the interface addr according to [`Netmon::interface_unique_addrs`]:
///
/// - If interface addresses are unique, returns (addr/0, prefix_len)
/// - If interface addresses are not unique, returns (addr/prefix_len, prefix_len)
fn split_interface_addr(&self, addr: &ipnet::IpNet) -> (ipnet::IpNet, u8) {
if self.mon.interface_unique_addrs() {
(ipnet::IpNet::new_assert(addr.addr(), 0), addr.prefix_len())
} else {
(*addr, addr.prefix_len())
}
}
}