Skip to main content

dora_coordinator/
events.rs

1use crate::control::ControlEvent;
2use crate::state::DaemonConnection;
3use dora_core::config::NodeId;
4use dora_message::{
5    BuildId, DataflowId,
6    common::DaemonId,
7    coordinator_to_cli::LogMessage,
8    daemon_to_coordinator::{
9        DataflowDaemonResult, FaultToleranceSnapshot, NetworkMetrics, NodeMetrics,
10    },
11};
12use eyre::WrapErr;
13use futures::Stream;
14use std::collections::BTreeMap;
15use tokio::sync::{mpsc, oneshot};
16use tokio_stream::wrappers::ReceiverStream;
17use uuid::Uuid;
18
19#[derive(Debug)]
20pub enum Event {
21    DaemonHeartbeat {
22        daemon_id: DaemonId,
23        ft_stats: Option<FaultToleranceSnapshot>,
24    },
25    Dataflow {
26        uuid: Uuid,
27        event: DataflowEvent,
28    },
29    Control(ControlEvent),
30    Daemon(DaemonRequest),
31    DaemonHeartbeatInterval,
32    /// A daemon reported the zenoh endpoint it bound, for the coordinator to
33    /// hand to daemons registering later.
34    DaemonZenohEndpoint {
35        daemon_id: DaemonId,
36        /// Connection-instance ID stamped at registration, checked the same way
37        /// `DaemonExit` checks it (#2392): a report from a superseded
38        /// connection must not overwrite the endpoint of the connection that
39        /// replaced it, which for a restarted daemon is a different port.
40        connection_id: Uuid,
41        /// `Some` confirms the advertised endpoint, `None` withdraws it.
42        endpoint: Option<String>,
43    },
44    CtrlC,
45    Log(LogMessage),
46    DaemonExit {
47        daemon_id: DaemonId,
48        /// Connection-instance ID stamped at registration time. Used to guard
49        /// against a stale connection's exit evicting a freshly re-registered
50        /// connection that reused the same `DaemonId` (#2392).
51        connection_id: Uuid,
52    },
53    DataflowBuildResult {
54        build_id: BuildId,
55        daemon_id: DaemonId,
56        result: eyre::Result<()>,
57    },
58    DataflowSpawnResult {
59        dataflow_id: Uuid,
60        daemon_id: DaemonId,
61        result: eyre::Result<()>,
62    },
63    NodeMetrics {
64        dataflow_id: Uuid,
65        metrics: BTreeMap<NodeId, NodeMetrics>,
66        network: Option<NetworkMetrics>,
67    },
68    TopicDebugData {
69        dataflow_id: Uuid,
70        subscription_ids: Vec<Uuid>,
71        payload: Vec<u8>,
72    },
73    DaemonStatusReport {
74        daemon_id: DaemonId,
75        running_dataflows: Vec<dora_message::daemon_to_coordinator::DataflowStatusEntry>,
76    },
77    DaemonStateCatchUpAck {
78        daemon_id: DaemonId,
79        dataflow_id: DataflowId,
80        ack_sequence: u64,
81    },
82    /// Daemon reports that a node has stopped and will not be restarted.
83    /// Triggers an immediate update of cached `node_metrics` so
84    /// `dora node list` shows status `Stopped` (or `Failed` for a
85    /// non-clean exit) instead of the stale "Running" snapshot from
86    /// before the exit. `daemon_id` is verified against
87    /// `running_dataflows[df].node_to_daemon[node_id]` so a stale or
88    /// foreign daemon cannot poison another daemon's node state.
89    DaemonNodeStopped {
90        daemon_id: DaemonId,
91        dataflow_id: Uuid,
92        node_id: NodeId,
93        clean_stop: bool,
94    },
95}
96
97impl Event {
98    /// Whether this event should be logged.
99    #[allow(clippy::match_like_matches_macro)]
100    pub fn log(&self) -> bool {
101        match self {
102            Event::DaemonHeartbeatInterval => false,
103            _ => true,
104        }
105    }
106
107    pub(crate) fn kind(&self) -> &'static str {
108        match self {
109            Event::DaemonHeartbeat { .. } => "DaemonHeartbeat",
110            Event::Dataflow { .. } => "Dataflow",
111            Event::Control(_) => "Control",
112            Event::Daemon(_) => "Daemon",
113            Event::DaemonHeartbeatInterval => "DaemonHeartbeatInterval",
114            Event::DaemonZenohEndpoint { .. } => "DaemonZenohEndpoint",
115            Event::CtrlC => "CtrlC",
116            Event::Log(_) => "Log",
117            Event::DaemonExit { .. } => "DaemonExit",
118            Event::DataflowBuildResult { .. } => "DataflowBuildResult",
119            Event::DataflowSpawnResult { .. } => "DataflowSpawnResult",
120            Event::NodeMetrics { .. } => "NodeMetrics",
121            Event::TopicDebugData { .. } => "TopicDebugData",
122            Event::DaemonStatusReport { .. } => "DaemonStatusReport",
123            Event::DaemonStateCatchUpAck { .. } => "DaemonStateCatchUpAck",
124            Event::DaemonNodeStopped { .. } => "DaemonNodeStopped",
125        }
126    }
127}
128
129#[derive(Debug)]
130pub enum DataflowEvent {
131    DataflowFinishedOnDaemon {
132        daemon_id: DaemonId,
133        result: DataflowDaemonResult,
134    },
135    ReadyOnDaemon {
136        daemon_id: DaemonId,
137        exited_before_subscribe: Vec<NodeId>,
138    },
139}
140
141#[allow(private_interfaces)]
142pub enum DaemonRequest {
143    Register {
144        version_check_result: Result<(), String>,
145        machine_id: Option<String>,
146        labels: BTreeMap<String, String>,
147        connection: DaemonConnection,
148        /// Sends back the assigned DaemonId on successful registration.
149        daemon_id_tx: oneshot::Sender<DaemonId>,
150    },
151}
152
153// Manual Debug since DaemonConnection doesn't derive Debug
154impl std::fmt::Debug for DaemonRequest {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        match self {
157            DaemonRequest::Register {
158                version_check_result,
159                machine_id,
160                labels,
161                ..
162            } => f
163                .debug_struct("Register")
164                .field("version_check_result", version_check_result)
165                .field("machine_id", machine_id)
166                .field("labels", labels)
167                .finish_non_exhaustive(),
168        }
169    }
170}
171
172pub(crate) fn set_up_ctrlc_handler() -> Result<impl Stream<Item = Event>, eyre::ErrReport> {
173    let (ctrlc_tx, ctrlc_rx) = mpsc::channel(1);
174
175    let mut ctrlc_sent = false;
176    ctrlc::set_handler(move || {
177        if ctrlc_sent {
178            tracing::warn!("received second ctrlc signal -> aborting immediately");
179            std::process::abort();
180        } else {
181            tracing::info!("received ctrlc signal");
182            if ctrlc_tx.blocking_send(Event::CtrlC).is_err() {
183                tracing::error!("failed to report ctrl-c event to dora-coordinator");
184            }
185
186            ctrlc_sent = true;
187        }
188    })
189    .wrap_err("failed to set ctrl-c handler")?;
190
191    Ok(ReceiverStream::new(ctrlc_rx))
192}