1use std::{
2 collections::{BTreeMap, BTreeSet},
3 fs::{self, File},
4 io::{self, Read},
5 net::TcpListener,
6 os::{
7 fd::{AsFd, RawFd},
8 unix::fs::MetadataExt,
9 },
10 time::{Duration, Instant, SystemTime},
11};
12
13use rustix::{
14 fs::{self as rfs, FileType, Mode, OFlags},
15 io::{fcntl_setfd, FdFlags},
16};
17use sha2::{Digest, Sha256};
18use subc_os::child_spawn::{monotonic_ns, InheritedDescriptors};
19
20use crate::{
21 config_store::{StoreRoot, StoreWriterLock},
22 live_children::{self, AdoptedPids},
23 run_dir_lock::{RunDirLock, RUN_DIR_LOCK_FILE_NAME},
24 supervise::{
25 handover::{
26 self, Cohort, Handover, HexBytes, LockPaths, LockRole, StreamWitness, VerifiedImage,
27 },
28 live_upgrade::{
29 reconcile_child_with_container, reconcile_child_with_unrecorded_fence,
30 InheritedStreams, ReconciledChild,
31 },
32 resume_hello::Preparation,
33 RegisteredConfiguredModule,
34 },
35};
36
37#[cfg(any(target_os = "linux", feature = "test-support"))]
38use std::path::PathBuf;
39
40use super::{
41 start_lock_path, BootstrapConfig, BootstrapError, Path, StartLock, Supervisor, SupervisorHandle,
42};
43
44pub const HANDOVER_VERSIONS: &[u32] = handover::HANDOVER_VERSIONS;
46
47pub struct ResumeBootstrap {
49 config: BootstrapConfig,
50 inherited: Result<Inherited, io::Error>,
51}
52
53impl ResumeBootstrap {
54 pub fn validate(
58 config: BootstrapConfig,
59 path: &Path,
60 key_fd: RawFd,
61 inherited: InheritedDescriptors,
62 ) -> Result<Self, BootstrapError> {
63 let inherited = validate(&config, path, key_fd, inherited)?;
64 Ok(Self { config, inherited })
65 }
66
67 pub async fn run(self) -> Result<(), BootstrapError> {
68 let inherited = match self.inherited {
69 Ok(inherited) => Some(inherited),
70 Err(error) => {
71 tracing::warn!(%error, "running image did not match the upgrade target; starting cold");
72 eprintln!("ck-subc: running image did not match the upgrade target; starting cold: {error}");
73 None
74 }
75 };
76 super::run_with_config_inner(self.config, inherited).await
77 }
78}
79
80pub(super) struct Inherited {
81 pub(super) start: StartLock,
82 pub(super) run: RunDirLock,
83 pub(super) store: Option<(StoreRoot, StoreWriterLock)>,
84 pub(super) tcp_listeners: Option<Vec<TcpListener>>,
85 pub(super) resume: Resume,
86}
87
88pub(super) struct Resume {
89 handover: Handover,
90 streams: BTreeMap<RawFd, std::os::fd::OwnedFd>,
91 deadline: Instant,
92 #[cfg(feature = "test-support")]
93 pause_install: Option<(String, PathBuf)>,
94}
95
96fn refused(error: impl std::fmt::Display) -> BootstrapError {
97 BootstrapError::Resume(io::Error::other(error.to_string()))
98}
99
100fn validate(
101 config: &BootstrapConfig,
102 path: &Path,
103 key_fd: RawFd,
104 mut inherited: InheritedDescriptors,
105) -> Result<Result<Inherited, io::Error>, BootstrapError> {
106 let record = config
107 .live_children_path
108 .as_ref()
109 .ok_or_else(|| refused("no live-children record configured"))?;
110 let expected = record.with_file_name(handover::HANDOVER_FILE_NAME);
111 if path.as_os_str() != expected.as_os_str() {
112 return Err(refused(
113 "handover path does not match the configured run directory",
114 ));
115 }
116 let file = File::from(
117 rfs::open(
118 path,
119 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
120 Mode::empty(),
121 )
122 .map_err(refused)?,
123 );
124 let stat = file.metadata().map_err(refused)?;
125 if !stat.is_file() || stat.uid() != subc_os::effective_uid() || stat.mode() & 0o7777 != 0o600 {
126 return Err(refused(
127 "handover must be a regular file owned by this user with mode 0600",
128 ));
129 }
130 let key =
131 read_key(File::from(inherited.take_key(key_fd).map_err(refused)?)).map_err(refused)?;
132 let mut bytes = Vec::new();
133 (&file).read_to_end(&mut bytes).map_err(refused)?;
134 let mut handover = handover::decode(&bytes, &key).map_err(refused)?;
135 validate_cohort(&handover)?;
136 let now_ms = crate::stderr_tail::unix_ms(SystemTime::now());
137 let deadline = Instant::now()
138 .checked_add(Duration::from_millis(
139 handover.reconnect_by_ms.saturating_sub(now_ms),
140 ))
141 .ok_or_else(|| refused("handover reconnect deadline is out of range"))?;
142
143 let run = record.with_file_name(RUN_DIR_LOCK_FILE_NAME);
144 let publication = start_lock_path(&config.connection_file_path);
145 let store = config
146 .config_store_root()
147 .map(StoreWriterLock::inherited_layout)
148 .transpose()
149 .map_err(refused)?;
150 let paths = LockPaths {
151 run_dir: &run,
152 publication: &publication,
153 store_writer: store.as_ref().map(|(_, lock)| lock.as_path()),
154 };
155 let expected_fds = handover.descriptor_numbers().collect();
156 let mut descriptors = inherited.into_named(&expected_fds).map_err(refused)?;
157 handover::validate_inherited_fds(&handover, config, &paths, |fd| {
158 descriptors.get(&fd).map(AsFd::as_fd)
159 })
160 .map_err(refused)?;
161
162 if let Err(error) = verify_running_image(config, &handover.verified_image) {
163 return Ok(Err(error));
166 }
167
168 let current = fs::symlink_metadata(path).map_err(refused)?;
169 if current.dev() != stat.dev() || current.ino() != stat.ino() {
170 return Err(refused("handover file changed during validation"));
171 }
172 fs::remove_file(path).map_err(refused)?;
173 for fd in descriptors.values() {
174 fcntl_setfd(fd, FdFlags::CLOEXEC).map_err(refused)?;
175 }
176
177 let mut locks: BTreeMap<_, _> = handover
178 .locks
179 .drain(..)
180 .map(|lock| {
181 (
182 lock.role,
183 File::from(
184 descriptors
185 .remove(&lock.fd)
186 .expect("validated lock descriptor"),
187 ),
188 )
189 })
190 .collect();
191 let start = StartLock {
192 _file: locks
193 .remove(&LockRole::Publication)
194 .expect("validated publication lock"),
195 };
196 let run = RunDirLock::from_inherited(
197 record.clone(),
198 locks.remove(&LockRole::RunDir).expect("validated run lock"),
199 );
200 let store = store.map(|(root, _)| {
201 (
202 root,
203 StoreWriterLock::from_inherited(
204 locks
205 .remove(&LockRole::StoreWriter)
206 .expect("validated store lock"),
207 ),
208 )
209 });
210 let tcp_listeners = handover.listeners.take().map(|listeners| {
211 listeners
212 .iter()
213 .map(|listener| {
214 TcpListener::from(
215 descriptors
216 .remove(&listener.fd)
217 .expect("validated listener descriptor"),
218 )
219 })
220 .collect()
221 });
222 Ok(Ok(Inherited {
223 start,
224 run,
225 store,
226 tcp_listeners,
227 resume: Resume {
228 handover,
229 streams: descriptors,
230 deadline,
231 #[cfg(feature = "test-support")]
232 pause_install: config
233 .upgrade_binary
234 .as_ref()
235 .filter(|binary| binary.test_hooks)
236 .and_then(|_| std::env::var("SUBC_TEST_RESUME_PAUSE_MODULE").ok())
237 .map(|module| (module, record.with_file_name("rp.sock"))),
240 },
241 }))
242}
243
244fn read_key(mut pipe: File) -> io::Result<[u8; 32]> {
245 let flags = rfs::fcntl_getfl(&pipe)?;
246 if FileType::from_raw_mode(rfs::fstat(&pipe)?.st_mode) != FileType::Fifo
247 || flags.intersects(OFlags::WRONLY | OFlags::RDWR)
248 {
249 return Err(io::Error::other(
250 "handover key descriptor must be a pipe read end",
251 ));
252 }
253 rfs::fcntl_setfl(&pipe, flags | OFlags::NONBLOCK)?;
256 let mut key = [0; 32];
257 pipe.read_exact(&mut key)?;
258 if pipe.read(&mut [0])? != 0 {
259 return Err(io::Error::other("handover key must be exactly 32 bytes"));
260 }
261 Ok(key)
262}
263
264fn validate_cohort(handover: &Handover) -> Result<(), BootstrapError> {
265 let cohort = &handover.cohort;
266 let mut modules = BTreeSet::new();
267 let carried: BTreeSet<_> = cohort.carried.iter().collect();
268 let mut children = BTreeSet::new();
269 let mut pids = BTreeSet::new();
270 if !cohort
271 .carried
272 .iter()
273 .chain(&cohort.restarting)
274 .chain(&cohort.stopped)
275 .all(|id| modules.insert(id))
276 || !handover
277 .children
278 .iter()
279 .all(|child| children.insert(&child.module_id) && pids.insert(child.pid))
280 || carried != children
281 {
282 return Err(refused("handover children and cohort disagree"));
283 }
284 let mut streams = BTreeSet::new();
285 for stream in handover
286 .children
287 .iter()
288 .flat_map(|child| [&child.stdout, &child.stderr])
289 {
290 if let StreamWitness::Open { fd, .. } = stream {
291 if !streams.insert(*fd) {
292 return Err(refused(format!(
293 "duplicate handover stream descriptor {fd}"
294 )));
295 }
296 }
297 }
298 Ok(())
299}
300
301fn verify_running_image(_config: &BootstrapConfig, expected: &VerifiedImage) -> io::Result<()> {
302 #[cfg(target_os = "linux")]
303 let (path, cdhash_matches) = (PathBuf::from("/proc/self/exe"), expected.cdhash.is_none());
304 #[cfg(target_os = "macos")]
305 let (path, cdhash_matches) = {
306 use subc_os::code_signature::{self, SignatureError};
307 let cdhash_matches = match (expected.cdhash, code_signature::self_cdhash()) {
308 (Some(expected), Ok(actual)) => expected.0 == actual.0,
309 #[cfg(feature = "test-support")]
310 (None, Err(SignatureError::NotSigned)) => _config
311 .upgrade_binary
312 .as_ref()
313 .is_some_and(|binary| binary.test_hooks),
314 (_, Err(SignatureError::NotSigned)) | (None, Ok(_)) => false,
315 (_, Err(error)) => return Err(io::Error::other(error)),
316 };
317 (std::env::current_exe()?, cdhash_matches)
318 };
319 let mut digest = Sha256::new();
320 io::copy(&mut File::open(path)?, &mut digest)?;
321 if !cdhash_matches || HexBytes(digest.finalize().into()) != expected.sha256 {
322 return Err(io::Error::other(
323 "running executable digest or code signature differs from the verified target",
324 ));
325 }
326 Ok(())
327}
328
329pub(super) fn discard_leftover(owner: &RunDirLock) {
331 let path = owner
332 .live_children_record()
333 .with_file_name(handover::HANDOVER_FILE_NAME);
334 if let Err(error) = fs::remove_file(&path) {
335 if error.kind() != io::ErrorKind::NotFound {
336 tracing::warn!(path = %path.display(), %error, "could not remove a leftover daemon handover");
337 }
338 }
339}
340
341pub(super) struct AdoptionPlan {
342 pub(super) protected: AdoptedPids,
343 pub(super) monotonic_ns: u64,
344 cohort: Cohort,
345 children: BTreeMap<String, (ReconciledChild, InheritedStreams)>,
346 unrecorded_fences: BTreeMap<String, live_children::RecordedChild>,
347 attempt: HexBytes<16>,
348 started_at_ms: u64,
349 deadline: Instant,
350 #[cfg(feature = "test-support")]
351 pause_install: Option<(String, PathBuf)>,
352}
353
354impl Resume {
355 pub(super) fn verified_digest(&self) -> HexBytes<32> {
356 self.handover.verified_image.sha256
357 }
358
359 pub(super) fn reconcile(mut self, owner: &RunDirLock) -> Result<AdoptionPlan, BootstrapError> {
360 let path = owner.live_children_record();
361 let (records, reasons) = match live_children::read_record_entries(path) {
362 Ok(record) => (record.0, Some(record.1)),
363 Err(error) => {
364 tracing::warn!(%error, "could not read the carried children's durable identities");
367 (Vec::new(), None)
368 }
369 };
370 let (containers, processes): (Vec<_>, Vec<_>) = records
374 .iter()
375 .partition(|record| record.child.is_group_container());
376 let by_pid: BTreeMap<_, _> = processes
377 .into_iter()
378 .map(|record| (record.child.pid, record))
379 .collect();
380 let containers: BTreeMap<_, _> = containers
381 .into_iter()
382 .map(|record| (record.child.pid, record))
383 .collect();
384 let unrecorded_fences =
385 fence_unrecorded_containers(path, &records, reasons, &self.handover.children);
386 let mut adopted = Vec::new();
387 let mut held = Vec::new();
388 let mut children = BTreeMap::new();
389 for mut child in self.handover.children {
390 let streams = [&mut child.stdout, &mut child.stderr].map(|stream| {
391 match std::mem::replace(stream, StreamWitness::Ended {}) {
392 StreamWitness::Open { fd, tail } => Some((
393 self.streams
394 .remove(&fd)
395 .expect("validated stream descriptor"),
396 tail,
397 )),
398 StreamWitness::Ended {} => None,
399 }
400 });
401 let pid = child.pid;
402 let module = child.module_id.clone();
403 let carried_pgid = child.carried_container.as_ref().map(|carried| carried.pgid);
404 let container = carried_pgid.and_then(|pgid| containers.get(&pgid).copied());
405 let process = by_pid.get(&pid).copied();
406 let reconciled = if unrecorded_fences.contains_key(&module) {
407 reconcile_child_with_unrecorded_fence(child, process)
408 } else {
409 reconcile_child_with_container(child, process, container)
410 }
411 .map_err(refused)?;
412 match &reconciled {
413 ReconciledChild::Adopt(child) => {
414 adopted.push(pid);
415 adopted.extend(child.carried_pgid());
416 }
417 ReconciledChild::Held(_) => held.push(pid),
418 ReconciledChild::Exited => {}
419 }
420 if let Some(pgid) = carried_pgid {
424 if !matches!(&reconciled, ReconciledChild::Adopt(child) if child.carried_pgid().is_some())
425 {
426 held.push(pgid);
427 }
428 }
429 children.insert(module, (reconciled, streams));
430 }
431 Ok(AdoptionPlan {
432 protected: AdoptedPids::from_classes(adopted, held),
433 monotonic_ns: self.handover.monotonic_ns,
434 cohort: self.handover.cohort,
435 children,
436 unrecorded_fences,
437 attempt: self.handover.attempt_id,
438 started_at_ms: self.handover.started_at_ms,
439 deadline: self.deadline,
440 #[cfg(feature = "test-support")]
441 pause_install: self.pause_install,
442 })
443 }
444}
445
446pub(super) fn fence_unrecorded_containers(
453 path: &Path,
454 records: &[live_children::RecordedChild],
455 reasons: Option<BTreeMap<u32, live_children::RetainedReason>>,
456 children: &[handover::ChildWitness],
457) -> BTreeMap<String, live_children::RecordedChild> {
458 let recorded = |pgid: u32| {
459 records
460 .iter()
461 .any(|record| record.child.is_group_container() && record.child.pid == pgid)
462 };
463 let missing: Vec<_> = children
464 .iter()
465 .filter_map(|child| {
466 let carried = child.carried_container.as_ref()?;
467 (!recorded(carried.pgid)).then(|| live_children::RecordedChild {
468 child: live_children::LiveChild {
469 module_id: child.module_id.clone(),
470 pid: carried.pgid,
471 protocol: records
472 .iter()
473 .find(|record| record.child.module_id == child.module_id)
474 .map_or(subc_control::ModuleProtocol::Subc, |record| {
475 record.child.protocol
476 }),
477 start_time: Some(carried.created_start_time),
478 executable: None,
479 cgroup_name: None,
480 container: Some(live_children::ContainerIdentity {
481 pgid: Some(carried.pgid),
482 created_start_time: Some(carried.created_start_time),
483 boot_id: Some(carried.boot_id.clone()),
484 session_id: Some(carried.session_id),
485 cgroup_path: None,
486 }),
487 },
488 resume_token_sha256: None,
489 })
490 })
491 .collect();
492 if missing.is_empty() {
493 return BTreeMap::new();
494 }
495 for row in &missing {
496 tracing::warn!(module_id = %row.child.module_id, pgid = row.child.pid,
497 "the handover names a carried container the record lacks; recording it as a fence");
498 }
499 let result = reasons.map_or_else(
502 || {
503 Err(std::io::Error::other(
504 "the existing recovery record is unreadable",
505 ))
506 },
507 |reasons| {
508 let rows: Vec<_> = records.iter().chain(&missing).cloned().collect();
509 live_children::write_record_with_reasons(path, &rows, reasons)
510 },
511 );
512 match result {
513 Ok(()) => BTreeMap::new(),
514 Err(error) => {
515 for row in &missing {
516 tracing::error!(module_id = %row.child.module_id, pgid = row.child.pid, %error,
517 "could not record the carried container fence; holding the module and retrying");
518 }
519 missing
520 .into_iter()
521 .map(|row| (row.child.module_id.clone(), row))
522 .collect()
523 }
524 }
525}
526
527type RegisteredCohort = BTreeMap<String, (RegisteredConfiguredModule, bool)>;
528pub(super) type PlannedStarts = Vec<(String, Option<RegisteredConfiguredModule>, bool)>;
529type Preparations = BTreeMap<String, Preparation>;
530
531impl AdoptionPlan {
532 fn modules(&self) -> impl Iterator<Item = &String> {
533 self.cohort
534 .carried
535 .iter()
536 .chain(&self.cohort.restarting)
537 .chain(&self.cohort.stopped)
538 }
539
540 pub(super) fn begin_report(&self, supervisor: &SupervisorHandle) {
541 supervisor.begin_resume_report(
542 self.attempt.to_string(),
543 self.started_at_ms,
544 self.modules().cloned(),
545 );
546 }
547
548 pub(super) fn enabled(&self, module: &str, configured: bool) -> Option<bool> {
549 self.modules()
550 .any(|id| id == module)
551 .then(|| self.cohort.allow_start(module, Some(configured)))
552 }
553
554 pub(super) fn stage_preparations(
555 &self,
556 handle: &SupervisorHandle,
557 registered: &RegisteredCohort,
558 ) -> Result<Preparations, BootstrapError> {
559 self.children
560 .iter()
561 .filter_map(|(module, (child, _))| {
562 let ReconciledChild::Adopt(child) = child else {
563 return None;
564 };
565 registered.get(module).filter(|(_, enabled)| *enabled)?;
566 Some(
567 child
568 .begin_preparation(handle, self.deadline.into())
569 .map(|guard| (module.clone(), guard))
570 .map_err(refused),
571 )
572 })
573 .collect()
574 }
575
576 pub(super) async fn install(
577 mut self,
578 supervisor: &Supervisor,
579 mut registered: RegisteredCohort,
580 mut preparations: Preparations,
581 ) -> Result<PlannedStarts, BootstrapError> {
582 let mut planned = Vec::new();
583 let mut installing = tokio::task::JoinSet::new();
584 let attempt = self.attempt.0;
585 let deadline = self.deadline.into();
586 for module in self
587 .cohort
588 .carried
589 .into_iter()
590 .chain(self.cohort.restarting)
591 .chain(self.cohort.stopped)
592 {
593 let (registered, enabled) = match registered.remove(&module) {
594 Some((registered, enabled)) => (Some(registered), enabled),
595 None => (None, false),
596 };
597 match self.children.remove(&module) {
598 Some((ReconciledChild::Adopt(child), streams)) => {
599 if let Some(registered) = registered {
600 let supervisor = supervisor.clone();
601 let preparation = preparations.remove(&module);
602 #[cfg(feature = "test-support")]
603 let pause = self
604 .pause_install
605 .as_ref()
606 .filter(|(id, _)| *id == module)
607 .map(|(_, path)| path.clone());
608 installing.spawn(async move {
609 let _preparation = preparation;
610 #[cfg(feature = "test-support")]
611 if let Some(path) = pause {
612 let _ = tokio::time::timeout_at(
613 deadline,
614 crate::control::upgrade_in_place::wait_at_gate(&path, 1),
615 )
616 .await;
617 }
618 supervisor
619 .start_adopted_after_upgrade(
620 registered, *child, streams, attempt, deadline, enabled,
621 )
622 .await
623 });
624 } else {
625 supervisor.stop_unconfigured_after_upgrade(*child);
626 }
627 }
628 Some((ReconciledChild::Held(child), _)) => {
629 supervisor.watch_unresolved_with_fence(
630 *child,
631 registered,
632 enabled,
633 self.unrecorded_fences.remove(&module),
634 );
635 }
636 Some((ReconciledChild::Exited, _)) | None => {
637 planned.push((module, registered, enabled))
638 }
639 }
640 }
641 while let Some(result) = installing.join_next().await {
642 result.map_err(refused)?.map_err(refused)?;
643 }
644 Ok(planned)
645 }
646}
647
648pub(super) fn log_accept(sample: u64) {
649 match monotonic_ns() {
650 Ok(now) => tracing::info!(
651 resume_accept_ms = now.saturating_sub(sample) / 1_000_000,
652 "local listener accepting daemon upgrade reconnects"
653 ),
654 Err(error) => {
655 tracing::warn!(%error, "could not measure when the local listener started accepting")
656 }
657 }
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663 use std::io::Write;
664
665 #[test]
669 fn an_unrecorded_carried_container_stays_fenced_across_a_cold_start() {
670 use std::os::unix::process::CommandExt;
671 struct Owned(std::process::Child);
672 impl Drop for Owned {
673 fn drop(&mut self) {
674 let _ = self.0.kill();
675 let _ = self.0.wait();
676 }
677 }
678 let scratch = cortexkit_test_support::ScratchDir::new("resume-unrecorded-container");
679 let sleep = |group: i32| {
680 Owned(
681 std::process::Command::new("/bin/sleep")
682 .arg("60")
683 .process_group(group)
684 .spawn()
685 .unwrap(),
686 )
687 };
688 let pin = sleep(0);
689 let pgid = pin.0.id();
690 let _helper = sleep(i32::try_from(pgid).unwrap());
691 let created = subc_os::process_group::inspect(pgid)
692 .unwrap()
693 .unwrap()
694 .start_time;
695 let mut handover = handover::decode(
696 include_bytes!("../../tests/fixtures/handover-format-2.txt"),
697 b"0123456789abcdef0123456789abcdef",
698 )
699 .unwrap();
700 let child = &mut handover.children[0];
701 child.module_id = "carrier".into();
702 child.pid = pgid;
703 child.start_time = created;
704 child.carried_container = Some(handover::CarriedContainerWitness {
705 pgid,
706 pin_pid: pgid,
707 created_start_time: created,
708 boot_id: subc_os::boot_id::current().unwrap(),
709 session_id: subc_os::process_group::session_id(std::process::id())
710 .unwrap()
711 .unwrap(),
712 });
713 let module_row = live_children::RecordedChild {
714 child: live_children::LiveChild {
715 module_id: "carrier".into(),
716 pid: pgid,
717 protocol: subc_control::ModuleProtocol::Subc,
718 start_time: Some(created),
719 executable: None,
720 cgroup_name: None,
721 container: None,
722 },
723 resume_token_sha256: None,
724 };
725 let path = scratch.join("live-children.json");
726 let blocked_path = scratch.join("blocked-record");
727 std::fs::create_dir(&blocked_path).unwrap();
728 let pending = fence_unrecorded_containers(
729 &blocked_path,
730 std::slice::from_ref(&module_row),
731 Some(BTreeMap::new()),
732 &handover.children[..1],
733 );
734 assert!(pending["carrier"].child.is_group_container());
735 assert_eq!(pending["carrier"].child.pid, pgid);
736 live_children::write_record_with_reasons(
737 &path,
738 std::slice::from_ref(&module_row),
739 BTreeMap::new(),
740 )
741 .unwrap();
742
743 assert!(fence_unrecorded_containers(
744 &path,
745 std::slice::from_ref(&module_row),
746 Some(BTreeMap::new()),
747 &handover.children[..1],
748 )
749 .is_empty());
750 let resumed = crate::child_roster::ChildRoster::default();
752 resumed.record_to_with_adopted(path.clone(), &AdoptedPids::from_classes([], [pgid]));
753 assert!(resumed.previous_instance("carrier").is_some());
754 drop(resumed);
755 assert!(live_children::read_record_entries(&path)
756 .unwrap()
757 .0
758 .iter()
759 .any(|row| row.child.is_group_container() && row.child.pid == pgid));
760
761 let cold = crate::child_roster::ChildRoster::default();
764 cold.record_to_with_adopted(path.clone(), &AdoptedPids::none());
765 assert!(
766 cold.previous_instance("carrier").is_some(),
767 "a cold start must not start the module beside the container's helper"
768 );
769 }
770
771 #[test]
772 fn duplicate_stream_descriptor_is_refused_before_adoption() {
773 let mut handover = handover::decode(
774 include_bytes!("../../tests/fixtures/handover-format-2.txt"),
775 b"0123456789abcdef0123456789abcdef",
776 )
777 .unwrap();
778 validate_cohort(&handover).unwrap();
779 let StreamWitness::Open { fd, .. } = handover.children[0].stdout else {
780 panic!("golden handover must have an open stdout");
781 };
782 handover.children[1].stderr = StreamWitness::Open { fd, tail: vec![] };
783 assert!(validate_cohort(&handover)
784 .unwrap_err()
785 .to_string()
786 .contains("duplicate handover stream descriptor"));
787 }
788
789 #[test]
790 fn handover_key_requires_exactly_32_bytes_and_a_closed_writer() {
791 for key in [&[7; 31][..], &[7; 32], &[7; 33]] {
792 let (reader, mut writer) = io::pipe().unwrap();
793 writer.write_all(key).unwrap();
794 drop(writer);
795 let result = read_key(File::from(std::os::fd::OwnedFd::from(reader)));
796 if key.len() == 32 {
797 assert_eq!(result.unwrap(), [7; 32]);
798 } else {
799 assert!(result.is_err());
800 }
801 }
802 let (reader, mut writer) = io::pipe().unwrap();
803 writer.write_all(&[7; 32]).unwrap();
804 let error = read_key(File::from(std::os::fd::OwnedFd::from(reader))).unwrap_err();
805 assert_eq!(error.kind(), io::ErrorKind::WouldBlock);
806 drop(writer);
807 }
808}