arcbox-daemon 0.10.2

ArcBox daemon process
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
//! Service startup: DNS, Docker API, gRPC servers.
//!
//! gRPC is started once with all services. Machine/Sandbox/Snapshot services
//! use `SharedRuntime` (backed by `OnceLock`) and return `UNAVAILABLE` until
//! `init_runtime()` fills it. This avoids restarting the gRPC server mid-boot.

use std::net::{IpAddr, Ipv4Addr};
use std::sync::Arc;

use anyhow::{Context, Result};
use arcbox_api::SystemServiceImpl;
#[cfg(target_os = "macos")]
use arcbox_constants::container_network::ContainerNetwork;
use arcbox_constants::ports::KUBERNETES_API_HOST_PORT;
use arcbox_core::{Runtime, VmLifecycleState};
use arcbox_docker::{DockerApiServer, DockerContextManager, ServerConfig};
use tokio::sync::watch;
use tracing::{info, warn};

use crate::context::{ControlPlane, DaemonContext, ServiceHandles};
use crate::dns_service::DnsService;

#[cfg(target_os = "macos")]
const ROUTE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
#[cfg(target_os = "macos")]
const ROUTE_EVENT_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(250);

/// Starts the control plane and binds the DNS socket.
///
/// Called before `init_runtime()`. gRPC comes first so a client watching
/// the setup stream sees a DNS bind failure as `FAILED` with its cause;
/// the DNS socket is bound here, before the VM boots, so an explicitly
/// requested port that is taken costs no boot, and the previous daemon
/// has already released its socket because the lease is held.
pub async fn start_control_plane(ctx: &DaemonContext) -> Result<ControlPlane> {
    let grpc = start_grpc(ctx).await?;
    let dns = DnsService::bind_requested(ctx.dns_port, ctx.profile.dns_host_port())
        .await
        .context("Failed to start DNS service")?;
    Ok(ControlPlane { grpc, dns })
}

/// Starts the gRPC server with all services.
///
/// Machine/Sandbox/Snapshot services return `UNAVAILABLE` until
/// `init_runtime()` sets the runtime. SystemService works immediately so
/// clients can observe setup progress.
async fn start_grpc(ctx: &DaemonContext) -> Result<tokio::task::JoinHandle<()>> {
    let socket_path = &ctx.layout.grpc_socket;
    let listener = crate::control_plane::bind(socket_path)?;

    info!(socket = %socket_path.display(), "control plane listening (Connect + gRPC + gRPC-Web)");

    let system_service = SystemServiceImpl::new(
        Arc::clone(&ctx.setup_state),
        Arc::clone(&ctx.shared_runtime),
        Arc::clone(&ctx.early_runtime),
    );
    // Every service is served over Connect (CORE-53, CORE-68). The sandbox
    // control/data-plane split (CORE-57) is preserved inside it, so a cloud
    // deployment can still host those halves in different processes.
    // Reflection rides along and answers over all three wire formats.
    let app = crate::control_plane::into_app(crate::control_plane::connect_router(
        Arc::clone(&ctx.shared_runtime),
        system_service,
    )?);

    let shutdown = ctx.shutdown.clone();
    let handle = tokio::spawn(crate::control_plane::serve(listener, app, shutdown));

    Ok(handle)
}

/// Starts DNS, Docker API, and Kubernetes services.
///
/// Called after `init_runtime()` — the runtime must be available.
pub async fn start_services(
    ctx: &DaemonContext,
    runtime: &Arc<Runtime>,
    control_plane: ControlPlane,
) -> Result<ServiceHandles> {
    let ControlPlane {
        grpc,
        dns: dns_service,
    } = control_plane;
    let linux_vm = runtime.config().vm.autostart;

    // A custom instance pool must be routable before any API reports ready.
    // Production keeps its existing best-effort recovery semantics.
    #[cfg(target_os = "macos")]
    if linux_vm && !runtime.machine_manager().storage_is_held()? {
        ensure_isolated_container_route(
            runtime,
            &ctx.setup_state,
            &ctx.container_network_lease_slot,
        )
        .await?;
    }

    let dns_port = dns_service.host_port()?;

    // VM-host-only mode: the Docker API, Docker CLI integration, and the
    // Kubernetes proxy all depend on the Linux VM, so they are skipped when it
    // is not booted.
    // Bind every promised endpoint before publishing the Runtime or spawning a
    // server task. A failure then leaves no partially-ready control plane, and
    // an ephemeral port can be recorded from the socket that actually owns it.
    let docker_service = if linux_vm {
        let docker_server = DockerApiServer::new(
            ServerConfig {
                socket_path: ctx.layout.docker_socket.clone(),
            },
            Arc::clone(runtime),
        );
        let listener = docker_server.bind().with_context(|| {
            format!(
                "Failed to bind the Docker API socket: {}",
                ctx.layout.docker_socket.display()
            )
        })?;
        Some((docker_server, listener))
    } else {
        None
    };

    let kubernetes_proxy = if linux_vm {
        let port = ctx.kubernetes_port.unwrap_or(KUBERNETES_API_HOST_PORT);
        match crate::kubernetes_proxy::KubernetesProxy::bind(port).await {
            Ok(proxy) => {
                runtime.set_kubernetes_host_endpoint(
                    proxy.host_port(),
                    ctx.kubernetes_context.clone(),
                )?;
                Some(proxy)
            }
            Err(error) if ctx.kubernetes_port.is_some() => {
                return Err(error).context("Failed to start Kubernetes API proxy");
            }
            Err(error) => {
                tracing::warn!(%error, "Kubernetes API proxy unavailable");
                None
            }
        }
    } else {
        None
    };

    // Machines are VMs of their own, so SSH does not depend on the Linux VM.
    let ssh = crate::ssh_service::SshService::bind_requested(
        ctx.ssh_port,
        &ctx.layout,
        ctx.profile.ssh_host(),
        Arc::clone(runtime),
    )
    .await?;

    // Normal RPCs become available only after their advertised listeners are
    // bound. Kubernetes RPCs remain unavailable when its best-effort default
    // listener could not bind; an explicit listener is required to succeed.
    ctx.shared_runtime
        .set(Arc::clone(runtime))
        .map_err(|_| anyhow::anyhow!("start_services called twice"))?;

    register_host_dns(runtime).await;

    let dns_shutdown = ctx.shutdown.clone();
    let network_manager = Arc::clone(runtime.network_manager());
    let dns = tokio::spawn(async move {
        if let Err(e) = dns_service.run(network_manager, dns_shutdown).await {
            tracing::error!("DNS service error: {}", e);
        }
    });

    let docker = docker_service.map(|(docker_server, listener)| {
        let docker_shutdown = ctx.shutdown.clone();
        tokio::spawn(async move {
            if let Err(e) = docker_server.serve(listener, docker_shutdown).await {
                tracing::error!("Docker API server error: {}", e);
            }
        })
    });

    let kubernetes_proxy = kubernetes_proxy.map(|proxy| proxy.start(Arc::clone(runtime)));
    let ssh = ssh.map(|service| service.start(ctx.shutdown.clone()));

    // Mirror route-install events into SetupStatus. VM (re)starts install
    // the container route from vm_lifecycle, outside the cold-start
    // recovery path that sets the flag directly — without this bridge,
    // route_installed would stay stale until the next daemon restart.
    let route_events = runtime.event_bus().subscribe();
    let route_state = Arc::clone(&ctx.setup_state);
    let route_shutdown = ctx.shutdown.clone();
    drop(tokio::spawn(async move {
        route_status_loop(route_events, route_state, route_shutdown).await;
    }));

    #[cfg(target_os = "macos")]
    let route_guard = linux_vm.then(|| {
        let runtime = Arc::clone(runtime);
        let setup_state = Arc::clone(&ctx.setup_state);
        let shutdown = ctx.shutdown.clone();
        let container_network_lease = Arc::clone(&ctx.container_network_lease_slot);
        tokio::spawn(async move {
            container_route_guard(runtime, setup_state, shutdown, container_network_lease).await;
        })
    });
    #[cfg(not(target_os = "macos"))]
    let route_guard = None;

    Ok(ServiceHandles {
        dns,
        dns_port,
        docker,
        grpc,
        kubernetes_proxy,
        ssh,
        route_guard,
    })
}

/// Enables the production Docker context after critical recovery succeeds.
pub fn enable_docker_integration(ctx: &DaemonContext) {
    if ctx.docker_integration {
        match DockerContextManager::new_with_context_name(
            ctx.layout.docker_socket.clone(),
            ctx.profile.docker_context_name(),
        ) {
            Ok(ctx_manager) => {
                if let Err(e) = ctx_manager.enable() {
                    warn!("Failed to enable Docker integration: {}", e);
                } else {
                    info!("Docker CLI integration enabled");
                }
            }
            Err(e) => {
                warn!("Failed to create Docker context manager: {}", e);
            }
        }
    }
}

// =============================================================================
// Helpers
// =============================================================================

/// Starts the `vm_running` mirror for the System VM.
///
/// Spawned from `init_runtime`, not from [`start_services`]: the VM reaches
/// `VmLifecycleState::Running` partway through `Runtime::init` — that is what
/// publishes `VM_READY` — and `init` then waits for the guest container
/// runtime. A mirror started once `boot_runtime` has returned would report
/// `vm_running = false` across that whole window while the agent is already
/// answering, which is exactly what the field promises it is not.
pub fn spawn_vm_running_mirror(ctx: &DaemonContext, runtime: &Arc<Runtime>) {
    let state = runtime.subscribe_system_vm_state();
    let setup_state = Arc::clone(&ctx.setup_state);
    let shutdown = ctx.shutdown.clone();
    drop(tokio::spawn(async move {
        vm_running_loop(state, setup_state, shutdown).await;
    }));
}

/// Replays durable recovery state and every live update into the control plane.
pub fn spawn_storage_recovery_mirror(ctx: &DaemonContext, runtime: &Arc<Runtime>) {
    let (initial, mut updates) = runtime.subscribe_storage_recovery();
    if let Some(initial) = initial {
        ctx.setup_state.set_storage_recovery(initial);
    }
    let runtime = Arc::clone(runtime);
    let setup = Arc::clone(&ctx.setup_state);
    let shutdown = ctx.shutdown.clone();
    tokio::spawn(async move {
        loop {
            tokio::select! {
                () = shutdown.cancelled() => break,
                update = updates.recv() => match update {
                    Ok(progress) => setup.set_storage_recovery(progress),
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                        let (latest, receiver) = runtime.subscribe_storage_recovery();
                        updates = receiver;
                        if let Some(latest) = latest { setup.set_storage_recovery(latest); }
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                }
            }
        }
    });
}

/// Mirrors the System VM's lifecycle state into `SetupState.vm_running`.
///
/// The flag reports readiness level 2 — `VmLifecycleState::is_ready`, the
/// agent has answered a ping — which is the level that matches what a client
/// reads the field to mean. Level 1 (`MachineState::Running`) counts a VM
/// whose agent is not up, so RPCs against it fail; level 3 (guest dockerd)
/// is narrower than "the VM is running" and already has its own signal.
///
/// Driven from the lifecycle watch rather than set once on a successful guest
/// query, so it tracks both edges: idle stop, backend switch, and crash
/// recovery all move it without anything else having to remember to.
async fn vm_running_loop(
    mut state: watch::Receiver<VmLifecycleState>,
    setup_state: Arc<arcbox_api::SetupState>,
    shutdown: tokio_util::sync::CancellationToken,
) {
    loop {
        setup_state.set_vm_running(state.borrow_and_update().is_ready());
        tokio::select! {
            () = shutdown.cancelled() => break,
            // The sender lives as long as the runtime; an error means it is
            // gone, so there is nothing left to mirror.
            changed = state.changed() => if changed.is_err() { break },
        }
    }
}

/// Mirrors VM lifecycle events into `SetupState.route_installed`.
///
/// `ContainerRouteInstalled` sets the flag; `MachineStopped` clears it.
async fn route_status_loop(
    mut events: tokio::sync::broadcast::Receiver<arcbox_core::event::Event>,
    setup_state: Arc<arcbox_api::SetupState>,
    shutdown: tokio_util::sync::CancellationToken,
) {
    use arcbox_core::event::Event;
    use tokio::sync::broadcast::error::RecvError;

    loop {
        tokio::select! {
            () = shutdown.cancelled() => break,
            event = events.recv() => match event {
                Ok(Event::ContainerRouteInstalled { .. }) => {
                    setup_state.set_route_installed(true);
                }
                Ok(Event::MachineStopped { .. }) => {
                    setup_state.set_route_installed(false);
                }
                Ok(_) => {}
                // Missed events under load; state converges on the next
                // route-install or stop event.
                Err(RecvError::Lagged(_)) => {}
                Err(RecvError::Closed) => break,
            },
        }
    }
}

#[cfg(target_os = "macos")]
async fn container_route_guard(
    runtime: Arc<Runtime>,
    setup_state: Arc<arcbox_api::SetupState>,
    shutdown: tokio_util::sync::CancellationToken,
    container_network_lease: crate::context::SharedContainerNetworkLease,
) {
    use arcbox_core::route_reconciler::RouteMode;

    let container_network = runtime.config().container.cidr;
    let mut ticker = tokio::time::interval(ROUTE_POLL_INTERVAL);
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    let mut watcher = open_route_watcher();
    // Custom routes stay daemon-owned for lease cleanup, so VM arrival edges
    // trigger the same retrying route setup instead of a detached core hook.
    let mut vm_state = runtime.subscribe_system_vm_state();
    let mut active: Option<(String, RouteMode)> = None;
    let mut consecutive_failures = 0u32;

    loop {
        let (route_event, vm_became_ready) = tokio::select! {
            () = shutdown.cancelled() => break,
            _ = ticker.tick() => (false, false),
            changed = vm_state.changed() => {
                if changed.is_err() {
                    break;
                }
                (false, vm_state.borrow().is_ready())
            }
            event = next_managed_route_event(watcher.as_ref(), container_network) => {
                match event {
                    Ok(()) => (true, false),
                    Err(error) if error.raw_os_error() == Some(libc::ENOBUFS) => {
                        tracing::debug!(
                            "route event queue overflowed; reconciling current state"
                        );
                        (true, false)
                    }
                    Err(error) => {
                        tracing::warn!(%error, "route event watcher failed; polling remains active");
                        watcher = None;
                        (false, false)
                    }
                }
            }
        };

        if route_event {
            tokio::select! {
                () = shutdown.cancelled() => break,
                () = tokio::time::sleep(ROUTE_EVENT_DEBOUNCE) => {}
            }
            if let Some(watcher) = watcher.as_ref() {
                drain_route_events(watcher);
            }
        } else if watcher.is_none() {
            watcher = open_route_watcher();
        }

        if vm_became_ready
            && let Err(error) =
                ensure_isolated_container_route(&runtime, &setup_state, &container_network_lease)
                    .await
        {
            tracing::debug!(%error, "container route was not ready on the VM arrival edge");
        }

        let runtime_for_bridge = Arc::clone(&runtime);
        let resolution = match tokio::task::spawn_blocking(move || {
            resolve_container_bridge(&runtime_for_bridge)
        })
        .await
        {
            Ok(resolution) => resolution,
            Err(error) => {
                tracing::warn!(%error, "container bridge resolution task failed");
                BridgeResolution::Inconclusive
            }
        };
        let bridge = match route_action(
            resolution,
            active.as_ref().map(|(bridge, _)| bridge.as_str()),
        ) {
            RouteAction::Reconcile(bridge) => bridge,
            RouteAction::TearDown => {
                if active.take().is_some()
                    && let Some(lease) = container_network_lease.get()
                    && let Err(error) = lease.cleanup_route().await
                {
                    tracing::warn!(%error, "failed to remove stopped VM container route");
                }
                setup_state.set_route_installed(false);
                consecutive_failures = 0;
                continue;
            }
            RouteAction::Wait => {
                tracing::debug!("container bridge discovery inconclusive; keeping route state");
                continue;
            }
        };

        let current_mode = active
            .as_ref()
            .filter(|(active_bridge, _)| active_bridge == &bridge)
            .map(|(_, mode)| *mode);
        let result = match current_mode {
            Some(mode) => {
                arcbox_core::route_reconciler::reconcile_route_for_bridge_with_network(
                    &bridge,
                    container_network,
                    mode,
                )
                .await
            }
            None => {
                arcbox_core::route_reconciler::initialize_route_for_bridge_with_network(
                    &bridge,
                    container_network,
                )
                .await
            }
        };

        match result {
            Ok(mode) => {
                if let Some(lease) = container_network_lease.get()
                    && let Err(error) = lease.record_route(bridge.clone())
                {
                    setup_state.set_failed(&format!("failed to record container route: {error}"));
                    shutdown.cancel();
                    break;
                }
                let was_installed = setup_state.current().route_installed;
                active = Some((bridge, mode));
                setup_state.set_route_installed(true);
                consecutive_failures = 0;
                if !was_installed {
                    runtime.event_bus().publish(
                        arcbox_core::event::Event::ContainerRouteInstalled {
                            name: arcbox_core::DEFAULT_MACHINE_NAME.to_string(),
                        },
                    );
                }
            }
            Err(error) if is_route_ownership_conflict(&error, container_network) => {
                if let Some(lease) = container_network_lease.get()
                    && let Err(cleanup_error) = lease.cleanup_route().await
                {
                    tracing::warn!(%cleanup_error, "failed to remove conflicting container route");
                }
                setup_state.set_failed(&format!(
                    "container network {container_network} now conflicts with a host route: {error}"
                ));
                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                shutdown.cancel();
                break;
            }
            Err(error) => {
                setup_state.set_route_installed(false);
                consecutive_failures = consecutive_failures.saturating_add(1);
                if should_log_route_failure(consecutive_failures) {
                    tracing::warn!(
                        %error,
                        %bridge,
                        consecutive_failures,
                        "container route reconciliation failed"
                    );
                }
            }
        }
    }
}

#[cfg(target_os = "macos")]
fn is_route_ownership_conflict(
    error: &arcbox_core::route_reconciler::RouteError,
    network: ContainerNetwork,
) -> bool {
    network != ContainerNetwork::default()
        && matches!(
            error,
            arcbox_core::route_reconciler::RouteError::RouteConflict { .. }
                | arcbox_core::route_reconciler::RouteError::RouteOverlap { .. }
        )
}

#[cfg(target_os = "macos")]
fn open_route_watcher() -> Option<tokio::io::unix::AsyncFd<arcbox_route::RouteWatcher>> {
    match arcbox_route::RouteWatcher::open().and_then(tokio::io::unix::AsyncFd::new) {
        Ok(watcher) => Some(watcher),
        Err(error) => {
            tracing::warn!(%error, "route event watcher unavailable; using polling");
            None
        }
    }
}

#[cfg(target_os = "macos")]
async fn next_managed_route_event(
    watcher: Option<&tokio::io::unix::AsyncFd<arcbox_route::RouteWatcher>>,
    container_network: ContainerNetwork,
) -> std::io::Result<()> {
    let Some(watcher) = watcher else {
        return std::future::pending().await;
    };

    loop {
        let mut ready = watcher.readable().await?;
        match ready.try_io(|inner| inner.get_ref().read_event()) {
            Ok(Ok(Some(event)))
                if event
                    .network
                    .is_some_and(|network| is_relevant_route(network, container_network)) =>
            {
                return Ok(());
            }
            Ok(Ok(_)) => {}
            Ok(Err(error)) if error.kind() == std::io::ErrorKind::InvalidData => {
                tracing::debug!(%error, "ignored malformed route event");
            }
            Ok(Err(error)) => return Err(error),
            Err(_would_block) => {}
        }
    }
}

#[cfg(target_os = "macos")]
fn drain_route_events(watcher: &tokio::io::unix::AsyncFd<arcbox_route::RouteWatcher>) {
    for _ in 0..256 {
        match watcher.get_ref().read_event() {
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
            Err(_) => break,
        }
    }
}

#[cfg(target_os = "macos")]
fn is_relevant_route(route: arcbox_route::Ipv4Net, container_network: ContainerNetwork) -> bool {
    let preferred =
        arcbox_route::Ipv4Net::new(container_network.addr(), container_network.prefix())
            .expect("ContainerNetwork is always a valid Ipv4Net");
    if container_network == ContainerNetwork::default() {
        return route == preferred
            || route.prefix() == preferred.prefix() + 1 && route.overlaps(preferred);
    }

    route.prefix() != 0 && route.overlaps(preferred)
}

#[cfg(target_os = "macos")]
async fn ensure_isolated_container_route(
    runtime: &Arc<Runtime>,
    setup_state: &Arc<arcbox_api::SetupState>,
    container_network_lease: &crate::context::SharedContainerNetworkLease,
) -> Result<()> {
    let container_network = runtime.config().container.cidr;
    if container_network == ContainerNetwork::default() {
        return Ok(());
    }

    let machine_manager = runtime.machine_manager();
    let machine_is_running = machine_manager
        .get(arcbox_core::DEFAULT_MACHINE_NAME)
        .is_some_and(|machine| {
            matches!(
                machine.state,
                arcbox_core::machine::MachineState::Starting
                    | arcbox_core::machine::MachineState::Running
            )
        });
    anyhow::ensure!(
        machine_is_running,
        "container bridge is not ready for {container_network}"
    );

    #[cfg(feature = "vmnet")]
    if let Some(bridge) = {
        use arcbox_core::bridge_discovery::MachineBridgeExt as _;
        machine_manager.vmnet_bridge_name(arcbox_core::DEFAULT_MACHINE_NAME)
    } {
        arcbox_core::route_reconciler::ensure_route_for_bridge_with_network(
            &bridge,
            container_network,
        )
        .await
        .with_context(|| {
            format!("failed to install isolated container route {container_network}")
        })?;
        container_network_lease
            .get()
            .context("isolated container network lease is missing")?
            .record_route(bridge)?;
        setup_state.set_route_installed(true);
        return Ok(());
    }

    let bridge_mac = machine_manager
        .bridge_mac(arcbox_core::DEFAULT_MACHINE_NAME)
        .with_context(|| format!("container bridge MAC is not ready for {container_network}"))?;
    arcbox_core::route_reconciler::ensure_route_with_retry_for_network(
        &bridge_mac,
        container_network,
    )
    .await
    .with_context(|| format!("failed to install isolated container route {container_network}"))?;
    let BridgeResolution::Found(bridge) = resolve_container_bridge(runtime) else {
        anyhow::bail!("container bridge is not ready for {container_network}");
    };
    container_network_lease
        .get()
        .context("isolated container network lease is missing")?
        .record_route(bridge)?;
    setup_state.set_route_installed(true);
    Ok(())
}

/// What one bridge-resolution attempt established.
///
/// The distinction the route guard turns on: only the machine record can say
/// authoritatively that no container route should exist. Discovery itself
/// cannot, because it finds the bridge by looking the guest MAC up in each
/// bridge's forwarding table (`ifbridge::find_bridge_by_mac` → `list_fdb`),
/// and FDB entries age out when the guest goes quiet (20 min by default on
/// macOS). Reading that silence as "the bridge is gone" tears down a healthy
/// route on an idle VM.
#[cfg(target_os = "macos")]
#[derive(Debug, PartialEq, Eq)]
enum BridgeResolution {
    /// The bridge the container route must target.
    Found(String),
    /// No System VM is running, so no container route should exist.
    Absent,
    /// Discovery could not answer. Keep whatever route state is in place.
    Inconclusive,
}

/// What the route guard does with one resolution attempt.
#[cfg(target_os = "macos")]
#[derive(Debug, PartialEq, Eq)]
enum RouteAction {
    /// Reconcile the container route against this bridge.
    Reconcile(String),
    /// Remove the route and report it uninstalled.
    TearDown,
    /// Leave the route and its reported state alone until the next attempt.
    Wait,
}

/// Decides the guard's move from a resolution and the bridge it last acted on.
///
/// An inconclusive lookup falls back to the remembered bridge rather than
/// skipping the tick: this loop is woken by managed-route events, so the case
/// where discovery is stale is *also* the case where a route may have just been
/// deleted. Skipping there would leave the route unrepaired while
/// `route_installed` still reported `true`. With no bridge ever resolved there
/// is nothing to reconcile against, and waiting is all that is left.
#[cfg(target_os = "macos")]
fn route_action(resolution: BridgeResolution, active: Option<&str>) -> RouteAction {
    match resolution {
        BridgeResolution::Found(bridge) => RouteAction::Reconcile(bridge),
        BridgeResolution::Absent => RouteAction::TearDown,
        BridgeResolution::Inconclusive => active.map_or(RouteAction::Wait, |bridge| {
            RouteAction::Reconcile(bridge.to_string())
        }),
    }
}

/// Classifies a bridge lookup against the machine's own state.
///
/// `discover` is lazy so a stopped VM costs no forwarding-table walk.
#[cfg(target_os = "macos")]
fn classify_bridge(
    machine_state: Option<arcbox_core::machine::MachineState>,
    discover: impl FnOnce() -> Option<String>,
) -> BridgeResolution {
    let running = matches!(
        machine_state,
        Some(
            arcbox_core::machine::MachineState::Starting
                | arcbox_core::machine::MachineState::Running
        )
    );
    if !running {
        return BridgeResolution::Absent;
    }
    discover().map_or(BridgeResolution::Inconclusive, BridgeResolution::Found)
}

#[cfg(target_os = "macos")]
fn system_vm_state(runtime: &Runtime) -> Option<arcbox_core::machine::MachineState> {
    runtime
        .machine_manager()
        .get(arcbox_core::DEFAULT_MACHINE_NAME)
        .map(|machine| machine.state)
}

#[cfg(all(target_os = "macos", feature = "vmnet"))]
fn resolve_container_bridge(runtime: &Runtime) -> BridgeResolution {
    classify_bridge(system_vm_state(runtime), || {
        use arcbox_core::bridge_discovery::MachineBridgeExt as _;
        runtime
            .machine_manager()
            .vmnet_bridge_name(arcbox_core::DEFAULT_MACHINE_NAME)
            .or_else(|| {
                // The binary may include vmnet support while this signed daemon
                // is using VZ NAT (notably development builds without
                // com.apple.vm.networking).
                let mac = runtime
                    .machine_manager()
                    .bridge_mac(arcbox_core::DEFAULT_MACHINE_NAME)?;
                arcbox_core::bridge_discovery::resolve_bridge_by_mac(&mac).map(|bridge| bridge.name)
            })
    })
}

#[cfg(all(target_os = "macos", not(feature = "vmnet")))]
fn resolve_container_bridge(runtime: &Runtime) -> BridgeResolution {
    classify_bridge(system_vm_state(runtime), || {
        let mac = runtime
            .machine_manager()
            .bridge_mac(arcbox_core::DEFAULT_MACHINE_NAME)?;
        arcbox_core::bridge_discovery::resolve_bridge_by_mac(&mac).map(|bridge| bridge.name)
    })
}

#[cfg(target_os = "macos")]
fn should_log_route_failure(consecutive_failures: u32) -> bool {
    consecutive_failures == 1 || consecutive_failures.is_multiple_of(30)
}

async fn register_host_dns(runtime: &Arc<Runtime>) {
    let network_cfg = &runtime.config().network;
    let gateway_ip = network_cfg
        .gateway
        .as_ref()
        .and_then(|s| s.parse::<Ipv4Addr>().ok())
        .or_else(|| first_address_in_subnet(&network_cfg.subnet))
        .unwrap_or(Ipv4Addr::new(10, 0, 2, 1));
    let ip = IpAddr::V4(gateway_ip);
    runtime
        .register_host_dns(
            &[
                "host".into(),
                "host.docker.internal".into(),
                "gateway.docker.internal".into(),
            ],
            ip,
        )
        .await;
}

fn first_address_in_subnet(subnet: &str) -> Option<Ipv4Addr> {
    let (ip_str, prefix_str) = subnet.split_once('/')?;
    let base: Ipv4Addr = ip_str.parse().ok()?;
    let prefix: u8 = prefix_str.parse().ok()?;
    if prefix == 0 || prefix >= 32 {
        return None;
    }
    let mask: u32 = (!0u32) << (32 - prefix);
    let network = u32::from(base) & mask;
    let first = network.checked_add(1)?;
    let broadcast = network | !mask;
    if first > broadcast {
        None
    } else {
        Some(Ipv4Addr::from(first))
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use arcbox_api::SetupState;
    use arcbox_core::event::{Event, EventBus};

    use super::*;

    /// The regression this enum exists for: the bridge is found by looking the
    /// guest MAC up in bridge forwarding tables, which forget an idle guest
    /// after ~20 minutes. A running VM plus a silent FDB must not read as
    /// "no route should exist" — that tears down a healthy route and drops
    /// `route_installed`, sending the desktop back to localhost.
    #[cfg(target_os = "macos")]
    #[test]
    fn a_running_vm_with_no_fdb_entry_is_inconclusive_not_absent() {
        use arcbox_core::machine::MachineState;

        for state in [MachineState::Starting, MachineState::Running] {
            assert_eq!(
                classify_bridge(Some(state), || None),
                BridgeResolution::Inconclusive,
                "{state:?} with a silent FDB"
            );
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn only_the_machine_record_can_say_no_bridge_should_exist() {
        use arcbox_core::machine::MachineState;

        // No machine record, and a stopped one, are both authoritative — even
        // if a stale FDB entry still names a bridge.
        assert_eq!(
            classify_bridge(None, || Some("bridge100".to_string())),
            BridgeResolution::Absent
        );
        assert_eq!(
            classify_bridge(Some(MachineState::Stopped), || Some(
                "bridge100".to_string()
            )),
            BridgeResolution::Absent
        );
    }

    /// The loop is woken by managed-route events, so "discovery is stale" and
    /// "a route was just deleted" are the same tick. Falling back to the
    /// remembered bridge is what repairs it; skipping would leave the route
    /// gone while `route_installed` still said true.
    #[cfg(target_os = "macos")]
    #[test]
    fn an_inconclusive_lookup_still_reconciles_the_remembered_bridge() {
        assert_eq!(
            route_action(BridgeResolution::Inconclusive, Some("bridge100")),
            RouteAction::Reconcile("bridge100".to_string())
        );
        // Nothing resolved yet: there is no bridge to reconcile against.
        assert_eq!(
            route_action(BridgeResolution::Inconclusive, None),
            RouteAction::Wait
        );
    }

    /// A stopped VM tears the route down even if the guard still remembers the
    /// bridge it last used — that memory must not outlive the machine.
    #[cfg(target_os = "macos")]
    #[test]
    fn an_absent_machine_tears_down_despite_a_remembered_bridge() {
        assert_eq!(
            route_action(BridgeResolution::Absent, Some("bridge100")),
            RouteAction::TearDown
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn a_stopped_vm_costs_no_forwarding_table_walk() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        use arcbox_core::machine::MachineState;

        let walks = AtomicUsize::new(0);
        let _ = classify_bridge(Some(MachineState::Stopped), || {
            walks.fetch_add(1, Ordering::Relaxed);
            None
        });
        assert_eq!(walks.load(Ordering::Relaxed), 0);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn route_event_filter_tracks_all_instance_network_overlaps() {
        let network: ContainerNetwork = "10.64.32.0/20".parse().unwrap();
        let preferred = arcbox_route::Ipv4Net::new(network.addr(), network.prefix()).unwrap();
        let covering: arcbox_route::Ipv4Net = "10.64.0.0/16".parse().unwrap();
        let contained: arcbox_route::Ipv4Net = "10.64.35.0/24".parse().unwrap();
        let default: arcbox_route::Ipv4Net = "0.0.0.0/0".parse().unwrap();
        let other: arcbox_route::Ipv4Net = "10.64.64.0/20".parse().unwrap();

        assert!(is_relevant_route(preferred, network));
        assert!(is_relevant_route(covering, network));
        assert!(is_relevant_route(contained, network));
        assert!(!is_relevant_route(default, network));
        assert!(!is_relevant_route(other, network));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn only_isolated_route_ownership_conflicts_are_fatal() {
        use arcbox_core::route_reconciler::RouteError;

        let isolated: ContainerNetwork = "10.64.32.0/20".parse().unwrap();
        let conflict = RouteError::RouteConflict {
            subnet: isolated.to_string(),
        };
        let overlap = RouteError::RouteOverlap {
            network: isolated,
            route: "10.64.0.0/16".parse().unwrap(),
        };

        assert!(is_route_ownership_conflict(&conflict, isolated));
        assert!(is_route_ownership_conflict(&overlap, isolated));
        assert!(!is_route_ownership_conflict(
            &conflict,
            ContainerNetwork::default()
        ));
        assert!(!is_route_ownership_conflict(
            &RouteError::BridgeNotReady,
            isolated
        ));
    }

    /// Polls until `route_installed` matches `want` or times out.
    async fn wait_for_route_installed(state: &SetupState, want: bool) -> bool {
        for _ in 0..200 {
            if state.current().route_installed == want {
                return true;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        false
    }

    /// Polls until `vm_running` matches `want` or times out.
    async fn wait_for_vm_running(state: &SetupState, want: bool) -> bool {
        for _ in 0..200 {
            if state.current().vm_running == want {
                return true;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        false
    }

    /// The flag has to fall as well as rise. Its predecessor was set once by
    /// cold-start recovery and never cleared, so a client saw `vm_running`
    /// stay true for the rest of the daemon's life after any VM stop.
    #[tokio::test]
    async fn vm_running_loop_follows_the_lifecycle_both_ways() {
        let (lifecycle, rx) = watch::channel(VmLifecycleState::Stopped);
        let setup_state = Arc::new(SetupState::new());
        let shutdown = tokio_util::sync::CancellationToken::new();

        let task = tokio::spawn(vm_running_loop(
            rx,
            Arc::clone(&setup_state),
            shutdown.clone(),
        ));

        assert!(wait_for_vm_running(&setup_state, false).await);

        lifecycle.send(VmLifecycleState::Running).expect("receiver");
        assert!(wait_for_vm_running(&setup_state, true).await);

        // Idle still counts as running: the VM is up, just quiet.
        lifecycle.send(VmLifecycleState::Idle).expect("receiver");
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert!(setup_state.current().vm_running);

        // The regression this test exists for.
        lifecycle.send(VmLifecycleState::Stopped).expect("receiver");
        assert!(wait_for_vm_running(&setup_state, false).await);

        shutdown.cancel();
        tokio::time::timeout(Duration::from_secs(1), task)
            .await
            .expect("loop exits on shutdown")
            .expect("loop task panicked");
    }

    #[tokio::test]
    async fn route_status_loop_mirrors_events_into_setup_state() {
        let bus = EventBus::new();
        let setup_state = Arc::new(SetupState::new());
        let shutdown = tokio_util::sync::CancellationToken::new();

        let task = tokio::spawn(route_status_loop(
            bus.subscribe(),
            Arc::clone(&setup_state),
            shutdown.clone(),
        ));

        assert!(!setup_state.current().route_installed);

        bus.publish(Event::ContainerRouteInstalled {
            name: "default".into(),
        });
        assert!(wait_for_route_installed(&setup_state, true).await);

        // Unrelated events leave the flag untouched.
        bus.publish(Event::MachineIdle {
            name: "default".into(),
        });
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert!(setup_state.current().route_installed);

        // A stopped VM cannot own a usable container route.
        bus.publish(Event::MachineStopped {
            name: "default".into(),
        });
        assert!(wait_for_route_installed(&setup_state, false).await);

        shutdown.cancel();
        tokio::time::timeout(Duration::from_secs(1), task)
            .await
            .expect("loop exits on shutdown")
            .expect("loop task panicked");
    }
}