fix(easytier-ohrs): support concurrent multi-instance shared mobile TUN and ownership attribution

- Remove single-instance refusal guards in run_network_instance_from_json and run_config_server_instance while still rejecting duplicate starts of the same config/instance ID.
- Synchronize all running TUN-enabled instances over a shared TUN fd via upstream attach_mobile_tun_fd on OHOS instead of clobbering earlier members with replace_tun_fd=true.
- Register the merged authoritative packet-plane DNS resolver across all running instances and attribute console-pushed instances with configServerId in collectRuntimeStateJson.
- Add concurrent local + config-server integration test verifying earlier instances retain state and selective single-instance teardown.
This commit is contained in:
FrankHan052176
2026-11-27 04:00:44 +08:00
parent 1e523d61ea
commit a096b6b01d
5 changed files with 432 additions and 85 deletions
@@ -21,6 +21,7 @@ pub(crate) fn stop_kernel(
clear_tun_attached(&config_id);
if stop_web_client(&config_id) {
clear_runtime_config_snapshot(&config_id);
let _ = tun_watcher::sync_shared_tun_fd_sync();
let _ = local_dns::refresh_all_sync();
tun_watcher::bump_policy_revision();
return true;
@@ -39,7 +40,9 @@ pub(crate) fn stop_kernel(
});
if ret {
clear_runtime_config_snapshot(&config_id);
ASYNC_RUNTIME.block_on(local_dns::unregister_instance_packet_dns(instance_id));
}
let _ = tun_watcher::sync_shared_tun_fd_sync();
let _ = local_dns::refresh_all_sync();
tun_watcher::bump_policy_revision();
ret
@@ -88,22 +91,32 @@ pub(crate) fn set_tun_fd(
return false;
};
INSTANCE_MANAGER
.attach_tun_fd(instance_id, fd)
.map(|_| {
mark_tun_attached(&config_id);
tun_watcher::bump_policy_revision();
ohrs_log_info!(
"[Rust] set_tun_fd success instance={} fd={} marked_attached=true",
config_id,
fd
);
true
})
.unwrap_or_else(|err| {
ohrs_log_error!("[Rust] set_tun_fd failed {}: {}", config_id, err);
false
})
#[cfg(target_env = "ohos")]
{
let _ = (instance_id, mark_tun_attached);
tun_watcher::set_virtual_tun_fd(fd);
is_tun_attached(&config_id) || fd <= 0
}
#[cfg(not(target_env = "ohos"))]
{
INSTANCE_MANAGER
.attach_tun_fd(instance_id, fd)
.map(|_| {
mark_tun_attached(&config_id);
tun_watcher::bump_policy_revision();
ohrs_log_info!(
"[Rust] set_tun_fd success instance={} fd={} marked_attached=true",
config_id,
fd
);
true
})
.unwrap_or_else(|err| {
ohrs_log_error!("[Rust] set_tun_fd failed {}: {}", config_id, err);
false
})
}
}
pub(crate) fn collect_runtime_state() -> RuntimeAggregateState {
@@ -130,9 +143,15 @@ pub(crate) fn collect_runtime_state() -> RuntimeAggregateState {
.collect::<std::collections::HashMap<_, _>>();
let mut active_config_ids = live_infos.keys().cloned().collect::<Vec<_>>();
let mut web_client_status = std::collections::HashMap::<String, bool>::new();
let mut remote_owner_by_instance_id = std::collections::HashMap::<String, String>::new();
if let Ok(guard) = WEB_CLIENTS.lock() {
for (config_id, managed) in guard.iter() {
web_client_status.insert(config_id.clone(), managed._client.is_connected());
if let Ok(tracked) = managed.hooks.instance_ids.lock() {
for id in tracked.iter() {
remote_owner_by_instance_id.insert(id.to_string(), config_id.clone());
}
}
if !active_config_ids.iter().any(|value| value == config_id) {
active_config_ids.push(config_id.clone());
}
@@ -141,6 +160,7 @@ pub(crate) fn collect_runtime_state() -> RuntimeAggregateState {
let mut instances = Vec::with_capacity(active_config_ids.len());
for config_id in active_config_ids {
let remote_owner = remote_owner_by_instance_id.get(&config_id).cloned();
if let Some(info) = live_infos.remove(&config_id) {
let snapshot = get_runtime_config_snapshot(&config_id);
let live_loader = snapshot.is_none().then(|| {
@@ -159,17 +179,13 @@ pub(crate) fn collect_runtime_state() -> RuntimeAggregateState {
.filter(|name| !name.trim().is_empty())
})
.unwrap_or_else(|| config_id.clone());
let effective_config = snapshot
.map(|snapshot| snapshot.config)
.or_else(|| {
live_loader.and_then(|loader| NetworkConfig::new_from_config(loader).ok())
});
instances.push(runtime_instance_from_running_info(
config_id,
display_name,
effective_config,
info,
));
let effective_config = snapshot.map(|snapshot| snapshot.config).or_else(|| {
live_loader.and_then(|loader| NetworkConfig::new_from_config(loader).ok())
});
let mut state =
runtime_instance_from_running_info(config_id, display_name, effective_config, info);
state.config_server_id = remote_owner;
instances.push(state);
} else if let Some(&connected) = web_client_status.get(&config_id) {
// Config-server control plane shell: never fabricate a default virtual IP,
// peer or route from the local config draft, otherwise it shadows real
@@ -188,6 +204,7 @@ pub(crate) fn collect_runtime_state() -> RuntimeAggregateState {
need_exit_node: false,
error_message: None,
config_server_connected: Some(connected),
config_server_id: None,
my_node_info: None,
events: Vec::new(),
routes: Vec::new(),
@@ -202,6 +219,7 @@ pub(crate) fn collect_runtime_state() -> RuntimeAggregateState {
true,
);
inst.tun_required = false;
inst.config_server_id = remote_owner;
instances.push(inst);
} else {
let tun_attached = is_tun_attached(&config_id);
@@ -216,6 +234,7 @@ pub(crate) fn collect_runtime_state() -> RuntimeAggregateState {
need_exit_node: false,
error_message: None,
config_server_connected: None,
config_server_id: remote_owner,
my_node_info: None,
events: Vec::new(),
routes: Vec::new(),
+255 -26
View File
@@ -153,21 +153,11 @@ impl WebClientHooks for TrackedWebClientHooks {
}
let _ = local_dns::refresh_all_async().await;
tun_watcher::bump_policy_revision();
ohrs_log_info!(
"[Rust] web_client removed {} remote instance(s)",
ids.len()
);
ohrs_log_info!("[Rust] web_client removed {} remote instance(s)", ids.len());
Ok(())
}
}
fn has_active_web_clients() -> bool {
WEB_CLIENTS
.lock()
.map(|guard| !guard.is_empty())
.unwrap_or(false)
}
fn is_config_server_config(config: &NetworkConfig) -> bool {
matches!(
NetworkingMethod::try_from(config.networking_method.unwrap_or_default())
@@ -238,8 +228,12 @@ fn web_client_machine_id_options(explicit_machine_id: Option<String>) -> Machine
}
fn run_config_server_instance(config_id: &str, config: &NetworkConfig) -> bool {
if !INSTANCE_MANAGER.instance_ids().is_empty() || has_active_web_clients() {
ohrs_log_error!("[Rust] there is a running instance!");
if WEB_CLIENTS
.lock()
.ok()
.is_some_and(|guard| guard.contains_key(config_id))
{
ohrs_log_error!("[Rust] config server instance {} already exists", config_id);
return false;
}
@@ -414,6 +408,7 @@ fn stop_runtime_inner() -> bool {
&& ok;
}
clear_all_runtime_config_snapshots();
runtime::state::clear_all_tun_attached();
local_dns::stop_all_sync();
tun_watcher::clear_virtual_tun_fd();
tun_watcher::bump_policy_revision();
@@ -460,11 +455,6 @@ pub(crate) fn run_network_instance_from_json(cfg_json: &str, display_name: Optio
}
};
if !INSTANCE_MANAGER.instance_ids().is_empty() || has_active_web_clients() {
ohrs_log_error!("[Rust] there is a running instance!");
return false;
}
let inst_id = cfg.get_id();
let tun_enabled = !cfg.get_flags().no_tun;
if INSTANCE_MANAGER.instance_ids().contains(&inst_id) {
@@ -796,10 +786,8 @@ mod tests {
#[test]
fn web_client_resolves_and_persists_machine_id_in_state_dir() {
let _ = stop_runtime_inner();
let temp_root = std::env::temp_dir().join(format!(
"easytier-ohrs-machine-id-test-{}",
Uuid::new_v4()
));
let temp_root =
std::env::temp_dir().join(format!("easytier-ohrs-machine-id-test-{}", Uuid::new_v4()));
let state_dir = temp_root.join("easytier-state");
assert!(set_state_dir(state_dir.to_string_lossy().into_owned()));
@@ -825,10 +813,8 @@ mod tests {
#[test]
fn web_client_receives_console_pushed_config_without_shell_pollution() {
let _ = stop_runtime_inner();
let temp_root = std::env::temp_dir().join(format!(
"easytier-ohrs-webclient-e2e-{}",
Uuid::new_v4()
));
let temp_root =
std::env::temp_dir().join(format!("easytier-ohrs-webclient-e2e-{}", Uuid::new_v4()));
let state_dir = temp_root.join("easytier-state");
assert!(set_state_dir(state_dir.to_string_lossy().into_owned()));
@@ -1057,4 +1043,247 @@ mod tests {
let _ = std::fs::remove_dir_all(&temp_root);
}
#[test]
fn concurrent_local_instances_and_config_server_preserve_earlier_state() {
let _ = stop_runtime_inner();
let temp_root =
std::env::temp_dir().join(format!("easytier-ohrs-multi-inst-test-{}", Uuid::new_v4()));
let state_dir = temp_root.join("easytier-state");
assert!(set_state_dir(state_dir.to_string_lossy().into_owned()));
let id_a = Uuid::new_v4().to_string();
let id_b = Uuid::new_v4().to_string();
let cfg_a = serde_json::json!({
"instance_id": id_a,
"networking_method": "Manual",
"dhcp": false,
"virtual_ipv4": "10.66.1.2",
"network_length": 24,
"hostname": "node-a",
"network_name": "mesh-a",
"network_secret": "sec-a",
"no_tun": true,
"listener_urls": []
})
.to_string();
let cfg_b = serde_json::json!({
"instance_id": id_b,
"networking_method": "Manual",
"dhcp": false,
"virtual_ipv4": "10.66.2.2",
"network_length": 24,
"hostname": "node-b",
"network_name": "mesh-b",
"network_secret": "sec-b",
"no_tun": true,
"listener_urls": []
})
.to_string();
assert!(run_network_instance_from_json(
&cfg_a,
Some("First".to_string())
));
assert!(run_network_instance_from_json(
&cfg_b,
Some("Second".to_string())
));
// Duplicate start of an already-running id must fail without disturbing running instances.
assert!(!run_network_instance_from_json(
&cfg_a,
Some("First".to_string())
));
let wait_for_ips = |expected: &[(&str, &str)]| {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
let state = collect_runtime_state_inner();
let all_ready = expected.iter().all(|(id, ip)| {
state.instances.iter().any(|inst| {
inst.instance_id == *id
&& inst.running
&& inst
.my_node_info
.as_ref()
.and_then(|n| n.virtual_ipv4.as_deref())
== Some(*ip)
})
});
if all_ready {
return state;
}
assert!(
std::time::Instant::now() < deadline,
"timed out waiting for concurrent instances: {:?}",
expected
);
std::thread::sleep(Duration::from_millis(25));
}
};
let both = wait_for_ips(&[(&id_a, "10.66.1.2"), (&id_b, "10.66.2.2")]);
assert_eq!(both.running_instance_count, 2);
let inst_a = both
.instances
.iter()
.find(|i| i.instance_id == id_a)
.expect("earlier instance A must remain present");
assert_eq!(inst_a.display_name, "First");
assert!(inst_a.config_server_id.is_none());
// Start a config server alongside the two local instances and push a remote instance.
let mock_server = MockWebServer::default();
let (addr, server_rpc_slot) = ASYNC_RUNTIME.block_on(async {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind mock config server");
let addr = listener.local_addr().expect("local addr");
let server_rpc_slot: Arc<tokio::sync::Mutex<Option<Arc<BidirectRpcManager>>>> =
Arc::new(tokio::sync::Mutex::new(None));
let slot_clone = server_rpc_slot.clone();
let svc = mock_server.clone();
tokio::spawn(async move {
if let Ok((stream, _peer)) = listener.accept().await {
let tunnel = TcpTunnelUpgrader::new(TunnelInfo::default())
.upgrade(TestTcpSocket(stream))
.expect("upgrade tcp tunnel");
let rpc = Arc::new(BidirectRpcManager::new());
rpc.rpc_server()
.registry()
.register(WebServerServiceServer::new(svc), "");
rpc.run_with_tunnel(tunnel);
*slot_clone.lock().await = Some(rpc);
}
});
(addr, server_rpc_slot)
});
let shell_id = Uuid::new_v4().to_string();
let shell_json = serde_json::json!({
"instance_id": shell_id,
"networking_method": "PublicServer",
"public_server_url": format!("tcp://{addr}/multi-token"),
"no_tun": true
})
.to_string();
assert!(run_network_instance_from_json(
&shell_json,
Some("Console".to_string())
));
ASYNC_RUNTIME.block_on(async {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while mock_server
.last_heartbeat
.lock()
.ok()
.and_then(|g| g.clone())
.is_none()
{
assert!(tokio::time::Instant::now() < deadline);
let _ = tokio::time::timeout(
Duration::from_millis(200),
mock_server.heartbeat_notify.notified(),
)
.await;
}
});
let pushed_id = Uuid::new_v4();
let rpc = ASYNC_RUNTIME
.block_on(async { server_rpc_slot.lock().await.clone() })
.expect("server rpc handle");
let client = rpc
.rpc_client()
.scoped_client::<WebClientServiceClientFactory<BaseController>>(1, 1, String::new());
let pushed_cfg = NetworkConfig {
instance_id: Some(pushed_id.to_string()),
networking_method: Some(NetworkingMethod::Standalone as i32),
dhcp: Some(false),
virtual_ipv4: Some("10.66.3.2".to_string()),
network_length: Some(24),
hostname: Some("remote-c".to_string()),
network_name: Some("mesh-c".to_string()),
network_secret: Some("sec-c".to_string()),
no_tun: Some(true),
listener_urls: vec![],
..Default::default()
};
ASYNC_RUNTIME
.block_on(client.run_network_instance(
BaseController::default(),
RunNetworkInstanceRequest {
inst_id: Some(pushed_id.into()),
config: Some(pushed_cfg),
overwrite: true,
source: easytier::proto::api::manage::ConfigSource::Web as i32,
},
))
.expect("push remote instance");
let pushed_id_str = pushed_id.to_string();
let all_three = wait_for_ips(&[
(&id_a, "10.66.1.2"),
(&id_b, "10.66.2.2"),
(&pushed_id_str, "10.66.3.2"),
]);
let pushed_state = all_three
.instances
.iter()
.find(|i| i.instance_id == pushed_id_str)
.expect("pushed instance present");
assert_eq!(
pushed_state.config_server_id.as_deref(),
Some(shell_id.as_str())
);
let local_a_state = all_three
.instances
.iter()
.find(|i| i.instance_id == id_a)
.expect("local instance A present");
assert!(local_a_state.config_server_id.is_none());
// Stopping only the config server removes only the shell + its pushed instance,
// leaving earlier local instances A and B completely intact.
assert!(exports::runtime_api::stop_kernel(
shell_id,
stop_web_client,
parse_instance_uuid,
));
let after_shell_stop = collect_runtime_state_inner();
assert_eq!(after_shell_stop.running_instance_count, 2);
assert!(
after_shell_stop
.instances
.iter()
.any(|i| i.instance_id == id_a)
);
assert!(
after_shell_stop
.instances
.iter()
.any(|i| i.instance_id == id_b)
);
// Stopping B leaves A intact.
assert!(exports::runtime_api::stop_kernel(
id_b,
stop_web_client,
parse_instance_uuid,
));
let after_b_stop = collect_runtime_state_inner();
assert_eq!(after_b_stop.running_instance_count, 1);
assert_eq!(after_b_stop.instances[0].instance_id, id_a);
assert_eq!(
after_b_stop.instances[0]
.my_node_info
.as_ref()
.and_then(|n| n.virtual_ipv4.as_deref()),
Some("10.66.1.2")
);
assert!(stop_runtime_inner());
let _ = std::fs::remove_dir_all(&temp_root);
}
}
@@ -660,11 +660,11 @@ pub async fn clear_all_packet_dns() {
pub async fn refresh_all_async() -> bool {
let _guard = REFRESH_LOCK.lock().await;
let instance_ids = INSTANCE_MANAGER.instance_ids();
let all_running_ids: HashSet<Uuid> = instance_ids.iter().copied().collect();
let mut contributions = Vec::new();
let mut active_dns_instances: Vec<Uuid> = Vec::new();
for id in instance_ids {
for &id in &instance_ids {
let Some(cfg) = INSTANCE_MANAGER.config(id) else {
continue;
};
@@ -679,7 +679,6 @@ pub async fn refresh_all_async() -> bool {
if !magic_dns_on && !has_custom_zones {
continue;
}
active_dns_instances.push(id);
let mut contrib = ZoneContribution {
auto_domain: None,
@@ -708,14 +707,13 @@ pub async fn refresh_all_async() -> bool {
contributions.push(contrib);
}
let active_dns_id_set: HashSet<Uuid> = active_dns_instances.iter().copied().collect();
let stale_ids: Vec<Uuid> = PACKET_REGISTRATIONS
.lock()
.ok()
.map(|guard| {
guard
.keys()
.filter(|id| !active_dns_id_set.contains(id))
.filter(|id| !all_running_ids.contains(id))
.copied()
.collect()
})
@@ -737,9 +735,10 @@ pub async fn refresh_all_async() -> bool {
if new_catalog.zones.is_empty() {
clear_all_packet_dns().await;
} else {
// Register the packet-plane resolver (100.100.100.101) for each DNS-active instance
// (shared by both ProxyHub L3 TUN and standalone :vpn modes).
for id in active_dns_instances {
// Register the shared packet-plane resolver (100.100.100.101) on every running
// instance whenever any zone is active, so SharedVirtualNic can deliver DNS queries
// arriving with any member's source IP regardless of which instance enabled MagicDNS.
for id in instance_ids {
let already = PACKET_REGISTRATIONS
.lock()
.ok()
@@ -19,6 +19,20 @@ pub fn clear_tun_attached(instance_id: &str) {
}
}
#[cfg(target_env = "ohos")]
pub fn replace_tun_attached(instance_ids: impl IntoIterator<Item = String>) {
if let Ok(mut guard) = ATTACHED_TUN_INSTANCE_IDS.lock() {
guard.clear();
guard.extend(instance_ids);
}
}
pub fn clear_all_tun_attached() {
if let Ok(mut guard) = ATTACHED_TUN_INSTANCE_IDS.lock() {
guard.clear();
}
}
pub fn is_tun_attached(instance_id: &str) -> bool {
ATTACHED_TUN_INSTANCE_IDS
.lock()
@@ -112,6 +126,8 @@ pub struct RuntimeInstanceState {
pub error_message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub config_server_connected: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub config_server_id: Option<String>,
pub my_node_info: Option<MyNodeInfo>,
pub events: Vec<String>,
pub routes: Vec<RouteView>,
@@ -432,6 +448,7 @@ pub fn runtime_instance_from_running_info(
need_exit_node,
error_message: info.error_msg,
config_server_connected: None,
config_server_id: None,
my_node_info: info.my_node_info.map(my_node_info_to_view),
events: info.events,
routes: info.routes.into_iter().map(route_to_view).collect(),
@@ -487,6 +504,7 @@ pub fn runtime_instance_from_config_snapshot(
need_exit_node: !config.exit_nodes.is_empty(),
error_message: None,
config_server_connected: None,
config_server_id: None,
my_node_info: Some(my_node_info),
events: Vec::new(),
routes: configured_route_views(&endpoint_urls, public_server_url.as_deref()),
@@ -1,8 +1,15 @@
use super::local_dns;
use super::state::clear_all_tun_attached;
#[cfg(not(target_env = "ohos"))]
use super::state::mark_tun_attached;
#[cfg(target_env = "ohos")]
use super::state::replace_tun_attached;
use super::{ASYNC_RUNTIME, INSTANCE_MANAGER};
#[cfg(not(target_env = "ohos"))]
use easytier::common::config::ConfigLoader;
use easytier::common::global_ctx::GlobalCtxEvent;
use easytier::instance::factory::subscribe_native_instance_event;
use once_cell::sync::Lazy;
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
use tokio::sync::broadcast::error::RecvError;
use uuid::Uuid;
@@ -10,9 +17,11 @@ use uuid::Uuid;
static ACTIVE_VIRTUAL_TUN_FD: AtomicI32 = AtomicI32::new(-1);
static POLICY_REVISION: AtomicU64 = AtomicU64::new(1);
static TOPOLOGY_REVISION: AtomicU64 = AtomicU64::new(1);
static TUN_SYNC_LOCK: Lazy<tokio::sync::Mutex<()>> = Lazy::new(|| tokio::sync::Mutex::new(()));
pub fn set_virtual_tun_fd(fd: i32) {
ACTIVE_VIRTUAL_TUN_FD.store(fd, Ordering::Release);
sync_shared_tun_fd_sync();
bump_policy_revision();
}
@@ -22,6 +31,7 @@ pub fn get_virtual_tun_fd() -> i32 {
pub fn clear_virtual_tun_fd() {
ACTIVE_VIRTUAL_TUN_FD.store(-1, Ordering::Release);
sync_shared_tun_fd_sync();
}
pub fn bump_policy_revision() {
@@ -41,25 +51,94 @@ pub fn topology_revision() -> i64 {
TOPOLOGY_REVISION.load(Ordering::Acquire) as i64
}
fn attach_active_tun_fd(instance_id: Uuid) -> bool {
/// Synchronizes all currently running TUN-enabled instances against the active
/// shared mobile TUN file descriptor using upstream `attach_mobile_tun_fd` on OHOS
/// (opening the shared fd once and multiplexing all disjoint instances cleanly).
pub async fn sync_shared_tun_fd_async() -> bool {
let _guard = TUN_SYNC_LOCK.lock().await;
let fd = get_virtual_tun_fd();
if fd <= 0 {
return false;
let instance_ids = INSTANCE_MANAGER.instance_ids();
if instance_ids.is_empty() {
clear_all_tun_attached();
return fd <= 0;
}
match INSTANCE_MANAGER.attach_tun_fd(instance_id, fd) {
Ok(_) => {
mark_tun_attached(&instance_id.to_string());
true
#[cfg(target_env = "ohos")]
{
match easytier::instance::factory::attach_mobile_tun_fd(
INSTANCE_MANAGER.as_ref(),
fd.max(0),
None,
)
.await
{
Ok(config) => {
if fd <= 0 {
clear_all_tun_attached();
} else {
replace_tun_attached(config.instance_ids.iter().map(Uuid::to_string));
}
for rejected in &config.rejected {
ohrs_log_error!(
"[Rust] shared mobile TUN rejected instance={} err={}",
rejected.instance_id,
rejected.error
);
}
ohrs_log_info!(
"[Rust] shared mobile TUN synced fd={} attached={} rejected={}",
fd,
config.instance_ids.len(),
config.rejected.len()
);
true
}
Err(err) => {
ohrs_log_error!("[Rust] shared mobile TUN sync failed fd={}: {:#}", fd, err);
false
}
}
Err(_) => false,
}
#[cfg(not(target_env = "ohos"))]
{
if fd <= 0 {
clear_all_tun_attached();
return true;
}
let mut ok = true;
for id in instance_ids {
let tun_enabled = INSTANCE_MANAGER
.config(id)
.map(|cfg| !cfg.get_flags().no_tun)
.unwrap_or(false);
if !tun_enabled {
continue;
}
match INSTANCE_MANAGER.attach_tun_fd(id, fd) {
Ok(_) => mark_tun_attached(&id.to_string()),
Err(_) => ok = false,
}
}
ok
}
}
pub fn sync_shared_tun_fd_sync() -> bool {
if tokio::runtime::Handle::try_current().is_ok() {
ASYNC_RUNTIME.spawn(async {
let _ = sync_shared_tun_fd_async().await;
});
return true;
}
ASYNC_RUNTIME.block_on(sync_shared_tun_fd_async())
}
/// Event-driven watcher that replaces the legacy 250ms Unix-socket polling thread.
/// Automatically attaches (and re-attaches after DHCP IP assignment) the active
/// ProxyHub virtual TUN fd, refreshes the local authoritative MagicDNS/custom-DNS
/// catalog in-memory, and bumps atomic policy/topology revisions only when real
/// network events fire (0 background wakeups when idle).
/// Automatically attaches (and re-attaches after DHCP IP / route changes) all running
/// instances to the active shared TUN fd, refreshes the local authoritative
/// MagicDNS/custom-DNS catalog in-memory, and bumps atomic policy/topology revisions
/// only when real network events fire (0 background wakeups when idle).
pub fn spawn_instance_watcher(instance_id: Uuid, tun_enabled: bool) {
let Some(instance) = INSTANCE_MANAGER.instance(instance_id) else {
return;
@@ -67,9 +146,6 @@ pub fn spawn_instance_watcher(instance_id: Uuid, tun_enabled: bool) {
let Some(mut receiver) = subscribe_native_instance_event(&instance) else {
return;
};
if tun_enabled {
let _ = attach_active_tun_fd(instance_id);
}
bump_policy_revision();
ASYNC_RUNTIME.spawn(async move {
@@ -81,14 +157,20 @@ pub fn spawn_instance_watcher(instance_id: Uuid, tun_enabled: bool) {
}
}
}
if tun_enabled && get_virtual_tun_fd() > 0 {
let _ = sync_shared_tun_fd_async().await;
}
let _ = local_dns::refresh_all_async().await;
bump_policy_revision();
loop {
match receiver.recv().await {
Ok(event) => match event {
GlobalCtxEvent::DhcpIpv4Changed(_, Some(_)) => {
if tun_enabled {
let _ = attach_active_tun_fd(instance_id);
GlobalCtxEvent::DhcpIpv4Changed(_, Some(_))
| GlobalCtxEvent::ProxyCidrsUpdated(_, _)
| GlobalCtxEvent::PublicIpv6RoutesUpdated(_, _)
| GlobalCtxEvent::ConfigPatched(_) => {
if tun_enabled && get_virtual_tun_fd() > 0 {
let _ = sync_shared_tun_fd_async().await;
}
let _ = local_dns::refresh_all_async().await;
bump_policy_revision();
@@ -96,11 +178,8 @@ pub fn spawn_instance_watcher(instance_id: Uuid, tun_enabled: bool) {
GlobalCtxEvent::TunDeviceReady(_)
| GlobalCtxEvent::DhcpIpv4Changed(_, None)
| GlobalCtxEvent::DhcpIpv4Conflicted(_)
| GlobalCtxEvent::ProxyCidrsUpdated(_, _)
| GlobalCtxEvent::PublicIpv6RoutesUpdated(_, _)
| GlobalCtxEvent::PeerAdded(_)
| GlobalCtxEvent::PeerRemoved(_)
| GlobalCtxEvent::ConfigPatched(_) => {
| GlobalCtxEvent::PeerRemoved(_) => {
let _ = local_dns::refresh_all_async().await;
bump_policy_revision();
}
@@ -110,13 +189,16 @@ pub fn spawn_instance_watcher(instance_id: Uuid, tun_enabled: bool) {
_ => {}
},
Err(RecvError::Lagged(_)) => {
if tun_enabled {
let _ = attach_active_tun_fd(instance_id);
if tun_enabled && get_virtual_tun_fd() > 0 {
let _ = sync_shared_tun_fd_async().await;
}
let _ = local_dns::refresh_all_async().await;
bump_policy_revision();
}
Err(RecvError::Closed) => {
if tun_enabled && get_virtual_tun_fd() > 0 {
let _ = sync_shared_tun_fd_async().await;
}
let _ = local_dns::refresh_all_async().await;
bump_policy_revision();
break;