Skip to main content

robonix_executor/
lifecycle.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2//! Shared Driver lifecycle for the Executor service.
3
4use crate::active_plans::PlanRuntime;
5use crate::pb::contracts::robonix_lifecycle_driver_client::RobonixLifecycleDriverClient;
6use crate::pb::contracts::robonix_lifecycle_driver_server::RobonixLifecycleDriver;
7use crate::pb::lifecycle::{DriverRequest, DriverResponse};
8use anyhow::{Context, Result};
9use robonix_atlas::client::AtlasClient;
10use robonix_atlas::pb::LifecycleState;
11use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
12use std::sync::Arc;
13use std::time::Duration;
14use tokio::sync::{Mutex, watch};
15use tonic::{Request, Response, Status};
16
17pub const SHARED_DRIVER_CONTRACT: &str = "robonix/lifecycle/driver";
18const CMD_INIT: u32 = 0;
19const CMD_ACTIVATE: u32 = 1;
20const CMD_DEACTIVATE: u32 = 2;
21const CMD_SHUTDOWN: u32 = 3;
22
23/// Publish lifecycle transitions and request graceful gRPC shutdown.
24#[derive(Clone)]
25pub struct ExecutorLifecycleDriver {
26    /// Registry connection for authoritative provider state.
27    atlas: AtlasClient,
28    /// Registered Executor provider identity.
29    provider_id: String,
30    /// Execution admission and active work shared with both Execute RPCs.
31    runtime: PlanRuntime,
32    /// Serialize lifecycle commands through their Atlas acknowledgement.
33    transition_lock: Arc<Mutex<()>>,
34    /// Retain shutdown requests until the server and heartbeat observe them.
35    shutdown_tx: watch::Sender<bool>,
36}
37
38impl ExecutorLifecycleDriver {
39    pub fn new(atlas: AtlasClient, provider_id: String, runtime: PlanRuntime) -> Self {
40        let (shutdown_tx, _) = watch::channel(false);
41        Self {
42            atlas,
43            provider_id,
44            runtime,
45            transition_lock: Arc::new(Mutex::new(())),
46            shutdown_tx,
47        }
48    }
49
50    pub fn subscribe_shutdown(&self) -> watch::Receiver<bool> {
51        self.shutdown_tx.subscribe()
52    }
53
54    async fn transition(&self, command: u32) -> Result<&'static str> {
55        let _transition = self.transition_lock.lock().await;
56        let (state, label) = match command {
57            CMD_INIT | CMD_DEACTIVATE => (LifecycleState::StateInactive, "inactive"),
58            CMD_ACTIVATE => (LifecycleState::StateActive, "active"),
59            CMD_SHUTDOWN => (LifecycleState::StateTerminated, "terminated"),
60            _ => anyhow::bail!("unknown lifecycle command code {command}"),
61        };
62        if command != CMD_ACTIVATE {
63            self.runtime
64                .close_admission()
65                .await
66                .map_err(anyhow::Error::msg)?;
67        }
68        // Do not reopen admission if publishing a non-active state fails.
69        self.atlas
70            .clone()
71            .set_lifecycle_state(&self.provider_id, state, "")
72            .await
73            .with_context(|| format!("publish lifecycle state for '{}'", self.provider_id))?;
74        if command == CMD_ACTIVATE {
75            self.runtime.open_admission().await;
76        }
77        if command == CMD_SHUTDOWN {
78            self.shutdown_tx.send_replace(true);
79        }
80        Ok(label)
81    }
82}
83
84#[tonic::async_trait]
85impl RobonixLifecycleDriver for ExecutorLifecycleDriver {
86    async fn driver(
87        &self,
88        request: Request<DriverRequest>,
89    ) -> Result<Response<DriverResponse>, Status> {
90        let response = match self.transition(request.into_inner().command).await {
91            Ok(state) => DriverResponse {
92                ok: true,
93                state: state.into(),
94                error: String::new(),
95            },
96            Err(error) => DriverResponse {
97                ok: false,
98                state: "error".into(),
99                error: format!("{error:#}"),
100            },
101        };
102        Ok(Response::new(response))
103    }
104}
105
106/// Preserve a shutdown sent before a waiter starts polling.
107pub async fn wait_for_shutdown(mut shutdown: watch::Receiver<bool>) {
108    while !*shutdown.borrow_and_update() {
109        if shutdown.changed().await.is_err() {
110            break;
111        }
112    }
113}
114
115/// Use a dialable address of the same family when binding all interfaces.
116pub fn advertised_endpoint(listen_addr: SocketAddr) -> String {
117    let ip = match listen_addr.ip() {
118        IpAddr::V4(ip) if ip.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
119        IpAddr::V6(ip) if ip.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
120        ip => ip,
121    };
122    SocketAddr::new(ip, listen_addr.port()).to_string()
123}
124
125/// The listener is already bound; self-dial proves the shared Driver is serving
126/// before publishing the legal REGISTERED → INACTIVE → ACTIVE transitions.
127pub async fn initialize_and_activate(endpoint: &str) -> Result<()> {
128    tokio::time::timeout(Duration::from_secs(5), async {
129        let mut client = RobonixLifecycleDriverClient::connect(format!("http://{endpoint}"))
130            .await
131            .context("connect startup lifecycle Driver")?;
132        for command in [CMD_INIT, CMD_ACTIVATE] {
133            let response = client
134                .driver(DriverRequest {
135                    command,
136                    config_json: "{}".into(),
137                })
138                .await
139                .context("call startup lifecycle Driver")?
140                .into_inner();
141            if !response.ok {
142                anyhow::bail!("startup lifecycle Driver failed: {}", response.error);
143            }
144        }
145        Ok(())
146    })
147    .await
148    .context("startup lifecycle Driver timed out")?
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::grpc_server::ExecutorServiceImpl;
155    use crate::pb::contracts::robonix_lifecycle_driver_server::RobonixLifecycleDriverServer;
156    use crate::pb::contracts::robonix_system_executor_execute_client::RobonixSystemExecutorExecuteClient;
157    use crate::pb::contracts::robonix_system_executor_execute_server::RobonixSystemExecutorExecuteServer;
158    use crate::pb::contracts::robonix_system_executor_execute_stream_client::RobonixSystemExecutorExecuteStreamClient;
159    use crate::pb::contracts::robonix_system_executor_execute_stream_server::RobonixSystemExecutorExecuteStreamServer;
160    use crate::pb::contracts::robonix_system_executor_get_health_client::RobonixSystemExecutorGetHealthClient;
161    use crate::pb::contracts::robonix_system_executor_get_health_server::RobonixSystemExecutorGetHealthServer;
162    use crate::pb::module_health::GetModuleHealthRequest;
163    use crate::pb::pilot::{Plan, RtdlNode};
164    use crate::verification::VerificationPolicy;
165    use robonix_atlas::client::grpc_params;
166    use robonix_atlas::pb::{Kind, Transport};
167    use robonix_atlas::service::{AtlasRegistry, serve_atlas};
168
169    #[test]
170    fn wildcard_endpoints_keep_the_address_family() {
171        for (listen, expected) in [
172            ("0.0.0.0:51001", "127.0.0.1:51001"),
173            ("[::]:51001", "[::1]:51001"),
174            ("127.0.0.2:51001", "127.0.0.2:51001"),
175        ] {
176            assert_eq!(advertised_endpoint(listen.parse().unwrap()), expected);
177        }
178    }
179
180    async fn assert_plan_admission(
181        execute: &mut RobonixSystemExecutorExecuteClient<tonic::transport::Channel>,
182        active: bool,
183    ) {
184        let result = execute
185            .execute(Plan {
186                plan_id: "admission-check".into(),
187                nodes: vec![RtdlNode {
188                    op_id: "root".into(),
189                    description: "check lifecycle admission".into(),
190                    ..Default::default()
191                }],
192                ..Default::default()
193            })
194            .await;
195        if !active {
196            assert!(
197                result
198                    .unwrap_err()
199                    .message()
200                    .contains("not accepting plans")
201            );
202            return;
203        }
204        let mut stream = result.unwrap().into_inner();
205        let mut completed = false;
206        while let Some(event) = stream.message().await.unwrap() {
207            if let Some(complete) = event.plan_complete {
208                assert!(!complete.any_failed);
209                completed = true;
210            }
211        }
212        assert!(completed, "admitted plan must report completion");
213    }
214
215    /// Exercise the generated Driver RPC against Atlas, including rejected
216    /// transitions and shutdown acknowledgement before server exit.
217    #[tokio::test]
218    async fn driver_publishes_only_legal_transitions() {
219        let atlas_port = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
220        let atlas_addr = atlas_port.local_addr().unwrap();
221        drop(atlas_port);
222        let atlas_server =
223            tokio::spawn(serve_atlas(Arc::new(AtlasRegistry::default()), atlas_addr));
224        let mut atlas =
225            AtlasClient::connect_with_retry(atlas_addr.to_string(), 50, Duration::from_millis(10))
226                .await
227                .unwrap();
228        let provider_id = "executor-driver-test";
229        atlas
230            .register_service(provider_id, crate::config::EXECUTOR_NAMESPACE, "")
231            .await
232            .unwrap();
233        let incoming =
234            tonic::transport::server::TcpIncoming::bind("127.0.0.1:0".parse().unwrap()).unwrap();
235        let endpoint = incoming.local_addr().unwrap().to_string();
236        atlas
237            .declare_capability(
238                provider_id,
239                SHARED_DRIVER_CONTRACT,
240                Transport::Grpc,
241                &endpoint,
242                grpc_params(
243                    "capabilities/lifecycle/driver.v1.toml",
244                    "robonix.contracts.RobonixLifecycleDriver",
245                    "/robonix.contracts.RobonixLifecycleDriver/Driver",
246                ),
247            )
248            .await
249            .unwrap();
250        let svc = ExecutorServiceImpl::new(
251            atlas.clone(),
252            provider_id.into(),
253            Arc::new(VerificationPolicy::new(false, vec![])),
254        );
255        let runtime = svc.runtime.clone();
256        runtime.close_admission().await.unwrap();
257        let driver =
258            ExecutorLifecycleDriver::new(atlas.clone(), provider_id.into(), runtime.clone());
259        let shutdown = driver.subscribe_shutdown();
260        let server = tokio::spawn(
261            tonic::transport::Server::builder()
262                .add_service(RobonixLifecycleDriverServer::new(driver))
263                .add_service(RobonixSystemExecutorExecuteServer::new(svc.clone()))
264                .add_service(RobonixSystemExecutorExecuteStreamServer::new(svc.clone()))
265                .add_service(RobonixSystemExecutorGetHealthServer::new(svc))
266                .serve_with_incoming_shutdown(incoming, wait_for_shutdown(shutdown)),
267        );
268        let mut client = RobonixLifecycleDriverClient::connect(format!("http://{endpoint}"))
269            .await
270            .unwrap();
271        let mut execute = RobonixSystemExecutorExecuteClient::connect(format!("http://{endpoint}"))
272            .await
273            .unwrap();
274        let mut health =
275            RobonixSystemExecutorGetHealthClient::connect(format!("http://{endpoint}"))
276                .await
277                .unwrap();
278        for (command, expected_ok, expected_state, busy) in [
279            (CMD_ACTIVATE, false, LifecycleState::StateRegistered, false),
280            (CMD_INIT, true, LifecycleState::StateInactive, false),
281            (CMD_ACTIVATE, true, LifecycleState::StateActive, false),
282            (CMD_INIT, false, LifecycleState::StateActive, true),
283            (CMD_DEACTIVATE, false, LifecycleState::StateActive, true),
284            (CMD_SHUTDOWN, false, LifecycleState::StateActive, true),
285            (99, false, LifecycleState::StateActive, false),
286            (CMD_DEACTIVATE, true, LifecycleState::StateInactive, false),
287            (CMD_ACTIVATE, true, LifecycleState::StateActive, false),
288            (CMD_SHUTDOWN, true, LifecycleState::StateTerminated, false),
289        ] {
290            if busy {
291                runtime.register_plan("busy").await.unwrap();
292            }
293            let idle_input = if matches!(command, CMD_DEACTIVATE | CMD_SHUTDOWN) && !busy {
294                let mut stream_client =
295                    RobonixSystemExecutorExecuteStreamClient::connect(format!("http://{endpoint}"))
296                        .await
297                        .unwrap();
298                let (tx, rx) = tokio::sync::mpsc::channel(1);
299                let request = tokio::spawn(async move {
300                    stream_client
301                        .execute_stream(tokio_stream::wrappers::ReceiverStream::new(rx))
302                        .await
303                });
304                tokio::task::yield_now().await;
305                Some((tx, request))
306            } else {
307                None
308            };
309            let response = client
310                .driver(DriverRequest {
311                    command,
312                    config_json: "{}".into(),
313                })
314                .await
315                .unwrap()
316                .into_inner();
317            assert_eq!(response.ok, expected_ok, "command {command}: {response:?}");
318            assert_eq!(response.error.is_empty(), expected_ok);
319            if let Some((_tx, request)) = idle_input {
320                let error = tokio::time::timeout(Duration::from_secs(2), request)
321                    .await
322                    .unwrap()
323                    .unwrap()
324                    .unwrap_err();
325                assert!(
326                    error.message().contains("not accepting plans")
327                        || (command == CMD_SHUTDOWN && error.code() == tonic::Code::Unavailable)
328                );
329            }
330            if busy {
331                assert!(response.error.contains("active plans"));
332                runtime.complete_plan("busy").await;
333            }
334            let provider = atlas
335                .query(Kind::Service, provider_id, "", "", Transport::Unspecified)
336                .await
337                .unwrap()
338                .pop()
339                .unwrap();
340            assert_eq!(provider.state, expected_state as i32, "command {command}");
341            if expected_state != LifecycleState::StateTerminated {
342                let active = expected_state == LifecycleState::StateActive;
343                let module = health
344                    .get_module_health(GetModuleHealthRequest {})
345                    .await
346                    .unwrap()
347                    .into_inner()
348                    .report
349                    .unwrap()
350                    .module
351                    .unwrap();
352                assert_eq!(module.state, if active { "active" } else { "inactive" });
353                assert_plan_admission(&mut execute, active).await;
354            }
355        }
356        drop(client);
357        drop(execute);
358        drop(health);
359        tokio::time::timeout(Duration::from_secs(2), server)
360            .await
361            .expect("Driver shutdown must stop the server")
362            .unwrap()
363            .unwrap();
364        atlas_server.abort();
365    }
366}
浙ICP备2023005800号-2 浙公网安备33010902005384号