1use std::io::{BufRead, BufReader, Read, Write};
20use std::path::{Path, PathBuf};
21use std::process::{Child, ChildStdin, Command, Stdio};
22use std::sync::{Mutex, PoisonError, mpsc};
23use std::time::{Duration, Instant};
24
25use serde::{Deserialize, Serialize};
26
27use super::{InstallError, Result, RuntimeKind, VerifiedPackage, bootstrap, install};
28
29const ACTIVATION: &str = "activation.json";
32const EXECUTABLE: &str = if cfg!(windows) {
34 "leanctx-cockpit.exe"
35} else {
36 "leanctx-cockpit"
37};
38const HANDSHAKE: Duration = Duration::from_secs(10);
40const EXIT_GRACE: Duration = Duration::from_secs(2);
42const RESTART_BACKOFF: [Duration; 3] = [
45 Duration::from_secs(1),
46 Duration::from_secs(5),
47 Duration::from_secs(30),
48];
49const STABLE: Duration = Duration::from_mins(1);
50const MAX_PORT_LINE: u64 = 256;
52
53pub struct CockpitLaunch {
55 pub engine_port: u16,
57 pub engine_token: String,
59 pub project_root: PathBuf,
60}
61
62#[derive(Clone, PartialEq, Eq)]
65pub struct CockpitEndpoint {
66 pub port: u16,
67 pub cockpit_token: String,
69}
70
71impl std::fmt::Debug for CockpitEndpoint {
72 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 formatter
74 .debug_struct("CockpitEndpoint")
75 .field("port", &self.port)
76 .field("cockpit_token", &"<redacted>")
77 .finish()
78 }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum CockpitUnavailable {
84 NotInstalled,
86 VerificationFailed,
88 StartFailed,
91 Disabled,
93 SourceBuild,
96}
97
98impl CockpitUnavailable {
99 pub const fn as_str(self) -> &'static str {
100 match self {
101 Self::NotInstalled => "not_installed",
102 Self::VerificationFailed => "verification_failed",
103 Self::StartFailed => "start_failed",
104 Self::Disabled => "disabled",
105 Self::SourceBuild => "source_build",
106 }
107 }
108
109 pub const fn message(self) -> &'static str {
113 match self {
114 Self::NotInstalled => {
115 "The Cockpit is not installed. Install it with: lean-ctx cockpit install"
116 }
117 Self::VerificationFailed => {
118 "The installed Cockpit did not verify and was not started. Reinstall it with: lean-ctx cockpit install"
119 }
120 Self::StartFailed => {
121 "The Cockpit is installed but did not start. See why: lean-ctx cockpit --foreground (it logs the cause)"
122 }
123 Self::Disabled => {
124 "The Cockpit is deactivated. Activate it again with: lean-ctx cockpit install"
125 }
126 Self::SourceBuild => {
127 "Source build: the Cockpit ships with official installs (install.sh, Homebrew, npm, AUR)"
128 }
129 }
130 }
131}
132
133const BUNDLE_FILES: [(&str, usize); 5] = [
135 ("channel.json", 65_536),
136 ("channel.sig", 64),
137 ("manifest.json", 65_536),
138 ("manifest.sig", 64),
139 ("archive.tar.gz", super::manifest::MAX_ARCHIVE),
140];
141
142fn read_bundle(path: &Path) -> Result<super::catalog::Bundle> {
145 let mut files: [Option<Vec<u8>>; 5] = Default::default();
146 if std::fs::symlink_metadata(path)?.is_dir() {
147 for (slot, (name, limit)) in files.iter_mut().zip(BUNDLE_FILES) {
148 *slot = Some(super::read_regular(&path.join(name), limit)?);
149 }
150 } else {
151 let packed = super::read_regular(path, super::manifest::MAX_ARCHIVE + (1 << 20))?;
152 let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(packed.as_slice()));
153 for entry in archive.entries().map_err(|_| InstallError::Archive)? {
154 let entry = entry.map_err(|_| InstallError::Archive)?;
155 let kind = entry.header().entry_type();
156 if kind.is_dir() {
157 continue;
158 }
159 let entry_path = entry
160 .path()
161 .map_err(|_| InstallError::Archive)?
162 .into_owned();
163 let parts: Vec<_> = entry_path.components().collect();
164 if !kind.is_file()
165 || parts.len() > 2
166 || parts
167 .iter()
168 .any(|part| !matches!(part, std::path::Component::Normal(_)))
169 {
170 return Err(InstallError::Archive);
171 }
172 let name = entry_path.file_name().and_then(|name| name.to_str());
173 let Some(index) = BUNDLE_FILES
174 .iter()
175 .position(|(known, _)| Some(*known) == name)
176 else {
177 return Err(InstallError::Archive);
178 };
179 let limit = BUNDLE_FILES[index].1;
180 let mut bytes = Vec::new();
181 entry
182 .take(limit as u64 + 1)
183 .read_to_end(&mut bytes)
184 .map_err(|_| InstallError::Archive)?;
185 if bytes.len() > limit || files[index].replace(bytes).is_some() {
186 return Err(InstallError::Archive);
187 }
188 }
189 }
190 let [
191 Some(catalog),
192 Some(catalog_signature),
193 Some(manifest),
194 Some(signature),
195 Some(archive),
196 ] = files
197 else {
198 return Err(InstallError::Archive);
199 };
200 Ok(super::catalog::Bundle {
201 catalog,
202 catalog_signature,
203 archive,
204 manifest,
205 signature,
206 })
207}
208
209fn import(bundle: &super::catalog::Bundle, downgrade: bool) -> Result<serde_json::Value> {
213 let channel = bootstrap::cockpit_channel()?.ok_or(InstallError::Policy)?;
214 let root = bootstrap::cockpit_root()?;
215 install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
216 let _guard = install::configuration_guard(&root)?;
217 let expected = install::active_manifest(&root)?;
218 let installation = super::catalog::import_kind(
219 RuntimeKind::Cockpit,
220 bundle,
221 &channel.key,
222 &root,
223 &expected,
224 downgrade,
225 )?;
226 activate_installation(&root, &installation, "bundle")
227}
228
229pub(crate) fn install_from(path: &Path, downgrade: bool) -> Result<serde_json::Value> {
231 import(&read_bundle(path)?, downgrade)
232}
233
234pub fn install_from_cli(args: &[String]) -> bool {
238 if args.is_empty() {
239 return false;
240 }
241 let downgrade = args.iter().any(|arg| arg == "--allow-downgrade");
242 let rest: Vec<&str> = args
243 .iter()
244 .map(String::as_str)
245 .filter(|arg| *arg != "--allow-downgrade")
246 .collect();
247 let path = match rest.as_slice() {
248 ["--from", path] => *path,
249 [flag] if flag.starts_with("--from=") => &flag["--from=".len()..],
250 _ => {
251 eprintln!(
252 "Usage: lean-ctx cockpit install [--from <dir|file.tar.gz> [--allow-downgrade]]"
253 );
254 std::process::exit(2);
255 }
256 };
257 match install_from(Path::new(path), downgrade) {
258 Ok(result) => {
259 println!(
260 "{}",
261 serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string())
262 );
263 println!("Open it with: lean-ctx cockpit");
264 }
265 Err(InstallError::Downgrade) => {
266 eprintln!(
267 "lean-ctx cockpit install --from: this bundle is older than the active Cockpit; \
268 add --allow-downgrade to install it"
269 );
270 std::process::exit(1);
271 }
272 Err(error) => {
273 eprintln!("lean-ctx cockpit install --from: the bundle was not installed ({error:?})");
274 std::process::exit(1);
275 }
276 }
277 true
278}
279
280fn bundled_dir() -> Option<PathBuf> {
282 let exe = std::env::current_exe().ok()?.canonicalize().ok()?;
283 let prefix = exe.parent()?.parent()?;
284 ["share", "libexec"]
285 .iter()
286 .map(|place| prefix.join(place).join("lean-ctx").join("cockpit"))
287 .find(|dir| dir.join("manifest.json").is_file())
288}
289
290fn import_bundled() {
294 let Some(dir) = bundled_dir() else {
295 return;
296 };
297 let Ok(manifest) = super::read_regular(&dir.join("manifest.json"), 65_536) else {
298 return;
299 };
300 let shipped = super::sha256(&manifest);
301 let active = bootstrap::cockpit_root()
302 .ok()
303 .and_then(|root| read_activation(&root).ok().flatten());
304 if active
307 .as_ref()
308 .is_some_and(|active| !active.enabled || active.manifest_sha256 == shipped)
309 {
310 return;
311 }
312 match read_bundle(&dir).and_then(|bundle| import(&bundle, false)) {
313 Ok(_) => tracing::info!("imported the bundled cockpit"),
314 Err(InstallError::Downgrade) => {
315 tracing::info!("bundled cockpit is older than the active one; kept the active one");
316 }
317 Err(error) => tracing::debug!("bundled cockpit not imported: {error:?}"),
318 }
319}
320
321#[derive(Serialize, Deserialize)]
322#[serde(deny_unknown_fields)]
323struct Activation {
324 schema_version: u32,
325 enabled: bool,
326 manifest_sha256: String,
327 trust_key_hex: String,
328}
329
330fn read_activation(root: &Path) -> Result<Option<Activation>> {
331 let path = root.join(ACTIVATION);
332 if !path.try_exists()? {
333 return Ok(None);
334 }
335 let activation: Activation = serde_json::from_slice(&super::read_regular(&path, 4096)?)
336 .map_err(|_| InstallError::State)?;
337 if activation.schema_version != 1
338 || !super::is_digest(&activation.manifest_sha256, 64)
339 || !super::is_digest(&activation.trust_key_hex, 64)
340 {
341 return Err(InstallError::State);
342 }
343 Ok(Some(activation))
344}
345
346fn write_activation(root: &Path, activation: &Activation) -> Result<()> {
348 let bytes = serde_json::to_vec_pretty(activation).map_err(|_| InstallError::State)?;
349 crate::core::updater::atomic_write_bytes(&root.join(ACTIVATION), &bytes)
350 .map_err(|_| InstallError::Commit)
351}
352
353fn activate_locked(root: &Path, selected: &str, key_hex: &str) -> Result<serde_json::Value> {
356 let key = super::trust_key(key_hex)?;
357 let package = install::verified_active_kind(RuntimeKind::Cockpit, root, selected, &key)?;
358 write_activation(
359 root,
360 &Activation {
361 schema_version: 1,
362 enabled: true,
363 manifest_sha256: selected.to_owned(),
364 trust_key_hex: key_hex.to_owned(),
365 },
366 )?;
367 Ok(serde_json::json!({"status": "activated", "kind": "cockpit",
368 "receipt": package.receipt, "runtime_started": false, "release_approved": false}))
369}
370
371fn authenticated() -> std::result::Result<(PathBuf, VerifiedPackage), CockpitUnavailable> {
373 let root = bootstrap::cockpit_root().map_err(|_| CockpitUnavailable::NotInstalled)?;
374 let activation = match read_activation(&root) {
375 Ok(Some(activation)) => activation,
376 Ok(None) => return Err(CockpitUnavailable::NotInstalled),
377 Err(_) => return Err(CockpitUnavailable::VerificationFailed),
378 };
379 if !activation.enabled {
380 return Err(CockpitUnavailable::Disabled);
381 }
382 let package = super::trust_key(&activation.trust_key_hex)
383 .and_then(|key| {
384 install::verified_active_kind(
385 RuntimeKind::Cockpit,
386 &root,
387 &activation.manifest_sha256,
388 &key,
389 )
390 })
391 .map_err(|_| CockpitUnavailable::VerificationFailed)?;
392 Ok((root, package))
393}
394
395fn install_configured(staging: Option<bool>) -> Result<serde_json::Value> {
399 let channel = bootstrap::cockpit_channel()?.ok_or(InstallError::Policy)?;
400 if staging.is_some_and(|staging| staging != channel.staging) {
401 return Err(InstallError::Usage);
402 }
403 let root = bootstrap::cockpit_root()?;
404 install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
405 let _guard = install::configuration_guard(&root)?;
406 let expected = install::active_manifest(&root)?;
407 let installation = super::catalog::sync_kind(
408 RuntimeKind::Cockpit,
409 channel.urls,
410 &channel.key,
411 &root,
412 &expected,
413 )?;
414 activate_installation(&root, &installation, "channel")
415}
416
417fn activate_installation(
420 root: &Path,
421 installation: &serde_json::Value,
422 source: &str,
423) -> Result<serde_json::Value> {
424 let selected = installation["receipt"]["manifest_sha256"]
425 .as_str()
426 .ok_or(InstallError::State)?;
427 let key = installation["artifact_key_hex"]
428 .as_str()
429 .ok_or(InstallError::State)?;
430 let activation = activate_locked(root, selected, key)?;
431 retire();
432 Ok(
433 serde_json::json!({"status": "installed_and_activated", "kind": "cockpit", "source": source,
434 "installation": installation, "activation": activation, "release_approved": false}),
435 )
436}
437
438pub fn install_cockpit() -> std::result::Result<serde_json::Value, CockpitUnavailable> {
442 install_configured(None).map_err(|error| match error {
443 InstallError::Manifest
444 | InstallError::Signature
445 | InstallError::Archive
446 | InstallError::Size
447 | InstallError::State
448 | InstallError::Downgrade => CockpitUnavailable::VerificationFailed,
449 _ => CockpitUnavailable::NotInstalled,
450 })
451}
452
453pub fn availability() -> std::result::Result<(), CockpitUnavailable> {
458 import_bundled();
459 match authenticated() {
460 Ok(_) => Ok(()),
461 Err(CockpitUnavailable::NotInstalled)
462 if bootstrap::cockpit_channel().ok().flatten().is_none() =>
463 {
464 Err(CockpitUnavailable::SourceBuild)
465 }
466 Err(reason) => Err(reason),
467 }
468}
469
470fn installs_opted_out() -> bool {
472 std::env::var_os("LEAN_CTX_NO_COCKPIT").is_some_and(|value| !value.is_empty() && value != "0")
473}
474
475pub fn available_or_installed() -> std::result::Result<(), CockpitUnavailable> {
478 match availability() {
479 Err(CockpitUnavailable::NotInstalled) if !installs_opted_out() => {
480 eprintln!(
481 "Installing the LeanCTX Cockpit (signed, free) from the LeanCTX runtime channel…"
482 );
483 install_cockpit()?;
484 availability()
485 }
486 other => other,
487 }
488}
489
490const AUTO_RETRY: Duration = Duration::from_hours(24);
492
493fn auto_attempt_marker() -> Option<PathBuf> {
494 crate::core::data_dir::resolve_data_dir()
495 .ok()
496 .map(|dir| dir.join("cockpit-auto-install.failed"))
497}
498
499fn retry_blocked(failed_at: Option<std::time::SystemTime>, now: std::time::SystemTime) -> bool {
501 failed_at
502 .and_then(|failed_at| now.duration_since(failed_at).ok())
503 .is_some_and(|elapsed| elapsed < AUTO_RETRY)
504}
505
506pub(crate) fn install_if_missing(retry_now: bool) -> bool {
512 if installs_opted_out()
513 || crate::core::telemetry_consent::ci_detected(crate::core::host_env::var)
514 {
515 return false;
516 }
517 if !matches!(availability(), Err(CockpitUnavailable::NotInstalled)) {
518 return false;
519 }
520 let marker = auto_attempt_marker();
521 let failed_at = marker
522 .as_deref()
523 .and_then(|path| std::fs::metadata(path).ok())
524 .and_then(|metadata| metadata.modified().ok());
525 if !retry_now && retry_blocked(failed_at, std::time::SystemTime::now()) {
526 return false;
527 }
528 match install_cockpit() {
529 Ok(_) => {
530 if let Some(path) = &marker {
531 let _ = std::fs::remove_file(path);
532 }
533 tracing::info!("installed the cockpit automatically");
534 true
535 }
536 Err(reason) => {
537 if let Some(path) = &marker {
538 let _ = std::fs::write(path, reason.as_str());
539 }
540 tracing::debug!("automatic cockpit install failed: {}", reason.as_str());
541 false
542 }
543 }
544}
545
546pub fn install_if_missing_in_background() {
549 let _ = std::thread::Builder::new()
550 .name("cockpit-install".into())
551 .spawn(|| {
552 install_if_missing(false);
553 });
554}
555
556pub(crate) fn status() -> serde_json::Value {
559 let (status, version) = match authenticated() {
560 Ok((_, package)) => ("installed", Some(package.receipt.version)),
561 Err(reason) => (reason.as_str(), None),
562 };
563 let channel = bootstrap::cockpit_channel().ok().flatten();
564 serde_json::json!({"schema_version": 1, "kind": "cockpit", "status": status,
565 "version": version, "channel_available": channel.is_some(),
566 "staging": channel.map(|channel| channel.staging),
567 "runtime_started": false, "release_approved": false})
568}
569
570fn deactivate() -> Result<serde_json::Value> {
571 let root = bootstrap::cockpit_root()?;
572 if !root.try_exists()? {
573 return Ok(serde_json::json!({"status": "not_installed", "kind": "cockpit"}));
574 }
575 let _guard = install::configuration_guard(&root)?;
576 let Some(mut activation) = read_activation(&root)? else {
577 return Ok(serde_json::json!({"status": "not_installed", "kind": "cockpit"}));
578 };
579 activation.enabled = false;
580 write_activation(&root, &activation)?;
581 retire();
582 Ok(serde_json::json!({"status": "disabled", "kind": "cockpit", "release_approved": false}))
583}
584
585pub(super) fn run_cli(
589 operation: &str,
590 staging: bool,
591 accepted: bool,
592 flags: &std::collections::BTreeMap<&str, &str>,
593) -> Result<serde_json::Value> {
594 match operation {
595 "status" if flags.is_empty() => Ok(status()),
596 "deactivate" if flags.is_empty() => deactivate(),
597 "sync-configured" if flags.is_empty() && accepted => install_configured(Some(staging)),
598 "activate" if staging && accepted && flags.len() == 4 => {
601 let get = |name| flags.get(name).copied().ok_or(InstallError::Usage);
602 let root = Path::new(get("--root")?);
603 let selected = get("--manifest-sha256")?;
604 if get("--expected-active")? != selected
605 || root != bootstrap::cockpit_root()?
606 || bootstrap::production_key(root)?.is_some()
607 {
608 return Err(InstallError::Usage);
609 }
610 let _guard = install::configuration_guard(root)?;
611 let result = activate_locked(root, selected, get("--trust-key-hex")?)?;
612 retire();
613 Ok(result)
614 }
615 _ => Err(InstallError::Usage),
616 }
617}
618
619#[cfg(any(windows, test))]
622const MEMORY_BUDGET_DEFAULT_MIB: u64 = 4096;
623#[cfg(any(windows, test))]
625const MEMORY_BUDGET_MIN_MIB: u64 = 256;
626const STDERR_TAIL: usize = 4096;
628const STDERR_SETTLE: Duration = Duration::from_millis(500);
630
631#[cfg(any(windows, test))]
635fn memory_budget(setting: Option<&str>) -> Option<u64> {
636 let mib = match setting.map(str::trim) {
637 Some("0") => return None,
638 Some(value) => value
639 .parse::<u64>()
640 .map_or(MEMORY_BUDGET_DEFAULT_MIB, |mib| {
641 mib.max(MEMORY_BUDGET_MIN_MIB)
642 }),
643 None => MEMORY_BUDGET_DEFAULT_MIB,
644 };
645 Some(mib.saturating_mul(1024 * 1024))
646}
647
648#[derive(Default)]
650struct StderrTail {
651 bytes: Vec<u8>,
652 cut: bool,
654}
655
656fn keep_tail(tail: &mut StderrTail, chunk: &[u8], cap: usize) {
658 tail.bytes.extend_from_slice(chunk);
659 if tail.bytes.len() > cap {
660 tail.bytes.drain(..tail.bytes.len() - cap);
661 tail.cut = true;
662 }
663}
664
665const MIN_SECRET_FRAGMENT: usize = 4;
667
668fn stderr_report(tail: &[u8], cut: bool, open_end: bool, secrets: &[String]) -> String {
675 let mut text = String::from_utf8_lossy(tail).into_owned();
676 if cut {
677 text = text
678 .split_once('\n')
679 .map_or_else(String::new, |(_, rest)| rest.to_owned());
680 }
681 if open_end {
682 text.truncate(text.rfind('\n').map_or(0, |end| end + 1));
683 }
684 for secret in secrets.iter().filter(|secret| !secret.is_empty()) {
685 text = text.replace(secret.as_str(), "[REDACTED:token]");
686 for len in (MIN_SECRET_FRAGMENT..secret.len()).rev() {
687 let (Some(head), Some(rest)) = (secret.get(..len), secret.get(secret.len() - len..))
688 else {
689 continue;
690 };
691 if let Some(kept) = text.strip_prefix(rest) {
692 text = format!("[REDACTED:token]{kept}");
693 }
694 if let Some(kept) = text.strip_suffix(head) {
695 text = format!("{kept}[REDACTED:token]");
696 }
697 }
698 }
699 crate::core::redaction::redact_text(&text)
700 .chars()
701 .filter(|c| !c.is_control() || matches!(c, '\n' | '\t'))
702 .collect::<String>()
703 .trim()
704 .to_owned()
705}
706
707#[cfg(windows)]
710struct MemoryJob {
711 handle: windows_sys::Win32::Foundation::HANDLE,
712 limit: u64,
713}
714
715#[cfg(windows)]
716impl MemoryJob {
717 fn assign(child: &Child, limit: Option<u64>) -> std::io::Result<Self> {
718 use std::os::windows::io::AsRawHandle;
719 use windows_sys::Win32::System::JobObjects::{
720 AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
721 JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
722 JobObjectExtendedLimitInformation, SetInformationJobObject,
723 };
724 let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
726 if handle.is_null() {
727 return Err(std::io::Error::last_os_error());
728 }
729 let job = Self {
730 handle,
731 limit: limit.unwrap_or(0),
732 };
733 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
734 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
735 if let Some(limit) = limit {
736 limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY;
737 limits.ProcessMemoryLimit = usize::try_from(limit).unwrap_or(usize::MAX);
738 }
739 let configured = unsafe {
741 SetInformationJobObject(
742 job.handle,
743 JobObjectExtendedLimitInformation,
744 std::ptr::from_ref(&limits).cast(),
745 std::mem::size_of_val(&limits) as u32,
746 )
747 };
748 if configured == 0 {
749 return Err(std::io::Error::last_os_error());
750 }
751 let assigned =
753 unsafe { AssignProcessToJobObject(job.handle, child.as_raw_handle().cast()) };
754 if assigned == 0 {
755 return Err(std::io::Error::last_os_error());
756 }
757 Ok(job)
758 }
759
760 fn peak(&self) -> Option<u64> {
762 use windows_sys::Win32::System::JobObjects::{
763 JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
764 QueryInformationJobObject,
765 };
766 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
767 let queried = unsafe {
769 QueryInformationJobObject(
770 self.handle,
771 JobObjectExtendedLimitInformation,
772 std::ptr::from_mut(&mut limits).cast(),
773 std::mem::size_of_val(&limits) as u32,
774 std::ptr::null_mut(),
775 )
776 };
777 (queried != 0).then_some(limits.PeakProcessMemoryUsed as u64)
778 }
779}
780
781#[cfg(windows)]
784unsafe impl Send for MemoryJob {}
785
786#[cfg(windows)]
787impl Drop for MemoryJob {
788 fn drop(&mut self) {
789 unsafe {
791 windows_sys::Win32::Foundation::CloseHandle(self.handle);
792 }
793 }
794}
795
796pub(super) struct Process {
798 child: Child,
799 stdin: Option<ChildStdin>,
800 port: u16,
801 stderr: std::sync::Arc<Mutex<StderrTail>>,
804 stderr_reader: Option<std::thread::JoinHandle<()>>,
805 secrets: Vec<String>,
807 killed: bool,
810 #[cfg(windows)]
813 job: Option<MemoryJob>,
814}
815
816impl Process {
817 fn exit_report(&mut self) -> String {
821 let (status, failed) = match self.child.try_wait() {
822 Ok(Some(status)) => (status.to_string(), !status.success()),
823 _ => ("still running".to_owned(), false),
824 };
825 let mut report = format!("status {status}");
826 if self.killed {
827 report.push_str(" (stopped by the supervisor)");
828 }
829 #[cfg(windows)]
830 if let Some(job) = &self.job {
831 if let Some(peak) = job.peak() {
832 let mib = |bytes: u64| bytes / (1024 * 1024);
833 if job.limit > 0 {
834 report.push_str(&format!(
835 ", peak memory {} MiB of its {} MiB budget",
836 mib(peak),
837 mib(job.limit)
838 ));
839 if peak.saturating_add(16 * 1024 * 1024) >= job.limit {
840 report.push_str(
841 " (it reached the budget; raise it with LEAN_CTX_COCKPIT_MEMORY_MB)",
842 );
843 } else if failed && !self.killed {
844 report.push_str(
847 " (an allocation beyond the budget may have failed; raise it with LEAN_CTX_COCKPIT_MEMORY_MB)",
848 );
849 }
850 } else {
851 report.push_str(&format!(", peak memory {} MiB", mib(peak)));
852 }
853 }
854 }
855 #[cfg(not(windows))]
856 let _ = failed;
857 let mut open_end = false;
858 if let Some(reader) = self.stderr_reader.take() {
859 let settle = Instant::now() + STDERR_SETTLE;
860 while !reader.is_finished() && Instant::now() < settle {
861 std::thread::sleep(Duration::from_millis(10));
862 }
863 if reader.is_finished() {
864 let _ = reader.join();
865 } else {
866 open_end = true;
869 }
870 }
871 let tail = self.stderr.lock().unwrap_or_else(PoisonError::into_inner);
872 let stderr = stderr_report(&tail.bytes, tail.cut, open_end, &self.secrets);
873 if !stderr.is_empty() {
874 report.push_str(&format!(
875 "; last stderr (redacted, at most {STDERR_TAIL} bytes):\n{stderr}"
876 ));
877 }
878 report
879 }
880
881 pub(super) fn stop(&mut self, grace: Duration) -> bool {
884 drop(self.stdin.take());
885 let deadline = Instant::now() + grace;
886 loop {
887 match self.child.try_wait() {
888 Ok(Some(_)) => return true,
889 Ok(None) if Instant::now() < deadline => {
890 std::thread::sleep(Duration::from_millis(20));
891 }
892 _ => {
893 let _ = self.child.kill();
894 let _ = self.child.wait();
895 self.killed = true;
896 return false;
897 }
898 }
899 }
900 }
901
902 fn running(&mut self) -> bool {
903 matches!(self.child.try_wait(), Ok(None))
904 }
905}
906
907impl Drop for Process {
908 fn drop(&mut self) {
909 self.stop(EXIT_GRACE);
910 }
911}
912
913pub(super) fn handshake(
916 mut command: Command,
917 start: &[u8],
918 secrets: Vec<String>,
919 deadline: Duration,
920) -> std::result::Result<Process, CockpitUnavailable> {
921 command
922 .stdin(Stdio::piped())
923 .stdout(Stdio::piped())
924 .stderr(Stdio::piped());
927 let child = command.spawn().map_err(|error| {
928 tracing::warn!("cockpit not started: the process could not be spawned: {error}");
929 CockpitUnavailable::StartFailed
930 })?;
931 #[cfg(windows)]
932 let job = {
933 let budget = memory_budget(std::env::var("LEAN_CTX_COCKPIT_MEMORY_MB").ok().as_deref());
934 match MemoryJob::assign(&child, budget) {
935 Ok(job) => Some(job),
936 Err(error) => {
937 tracing::warn!(
938 "cockpit runs without its memory budget, the job could not be set up: {error}"
939 );
940 None
941 }
942 }
943 };
944 let mut process = Process {
945 child,
946 stdin: None,
947 port: 0,
948 stderr: std::sync::Arc::default(),
949 stderr_reader: None,
950 secrets,
951 killed: false,
952 #[cfg(windows)]
953 job,
954 };
955 if let Some(mut stderr) = process.child.stderr.take() {
956 let tail = std::sync::Arc::clone(&process.stderr);
957 process.stderr_reader = std::thread::Builder::new()
958 .name("cockpit-stderr".to_owned())
959 .spawn(move || {
960 let mut chunk = [0_u8; 1024];
961 while let Ok(read @ 1..) = stderr.read(&mut chunk) {
962 let mut tail = tail.lock().unwrap_or_else(PoisonError::into_inner);
963 keep_tail(&mut tail, &chunk[..read], STDERR_TAIL);
964 }
965 })
966 .ok();
967 }
968 let (Some(mut stdin), Some(stdout)) = (process.child.stdin.take(), process.child.stdout.take())
969 else {
970 process.stop(Duration::ZERO);
971 return Err(CockpitUnavailable::StartFailed);
972 };
973 if stdin.write_all(start).and_then(|()| stdin.flush()).is_err() {
974 process.stop(Duration::ZERO);
975 return Err(CockpitUnavailable::StartFailed);
976 }
977 process.stdin = Some(stdin);
978 let (sender, receiver) = mpsc::sync_channel(1);
979 let reader = std::thread::Builder::new()
980 .name("cockpit-output".to_owned())
981 .spawn(move || {
982 let mut output = BufReader::new(stdout);
983 let mut line = Vec::new();
984 let read = (&mut output)
985 .take(MAX_PORT_LINE)
986 .read_until(b'\n', &mut line);
987 let _ = sender.send(read.ok().map(|_| line));
988 let _ = std::io::copy(&mut output, &mut std::io::sink());
990 });
991 let port = reader
992 .ok()
993 .and_then(|_| receiver.recv_timeout(deadline).ok().flatten())
994 .and_then(|line| listening(&line));
995 if let Some(port) = port {
996 process.port = port;
997 Ok(process)
998 } else {
999 let exited = process.child.try_wait().ok().flatten().is_some();
1000 process.stop(Duration::ZERO);
1001 let report = process.exit_report();
1002 if exited {
1003 tracing::warn!(
1004 "cockpit not started: it exited before naming its loopback port: {report}"
1005 );
1006 } else {
1007 tracing::warn!(
1008 "cockpit not started: it did not name its loopback port within {} s: {report}",
1009 deadline.as_secs()
1010 );
1011 }
1012 Err(CockpitUnavailable::StartFailed)
1013 }
1014}
1015
1016fn listening(line: &[u8]) -> Option<u16> {
1018 #[derive(Deserialize)]
1019 #[serde(deny_unknown_fields)]
1020 struct Listening {
1021 listening: u16,
1022 }
1023 if line.last() != Some(&b'\n') {
1024 return None;
1025 }
1026 serde_json::from_slice::<Listening>(line)
1027 .ok()
1028 .map(|listening| listening.listening)
1029 .filter(|port| *port != 0)
1030}
1031
1032struct Running {
1033 process: Process,
1034 prepared: Option<super::health::Prepared>,
1036 cockpit_token: String,
1037 launch: [u8; 32],
1038 started: Instant,
1039}
1040
1041impl Drop for Running {
1042 fn drop(&mut self) {
1043 self.process.stop(EXIT_GRACE);
1044 if let Some(prepared) = self.prepared.take() {
1045 let _ = prepared.close();
1046 }
1047 }
1048}
1049
1050struct State {
1051 running: Option<Running>,
1052 failures: usize,
1054 retry_at: Option<Instant>,
1055 last_failure: CockpitUnavailable,
1056}
1057
1058static STATE: Mutex<State> = Mutex::new(State {
1059 running: None,
1060 failures: 0,
1061 retry_at: None,
1062 last_failure: CockpitUnavailable::StartFailed,
1063});
1064
1065fn launch_key(launch: &CockpitLaunch) -> [u8; 32] {
1066 let mut hasher = blake3::Hasher::new();
1067 hasher.update(&launch.engine_port.to_le_bytes());
1068 hasher.update(&(launch.engine_token.len() as u64).to_le_bytes());
1069 hasher.update(launch.engine_token.as_bytes());
1070 hasher.update(launch.project_root.as_os_str().as_encoded_bytes());
1071 *hasher.finalize().as_bytes()
1072}
1073
1074pub fn cockpit_endpoint(
1077 launch: &CockpitLaunch,
1078) -> std::result::Result<CockpitEndpoint, CockpitUnavailable> {
1079 let key = launch_key(launch);
1080 let mut state = STATE.lock().unwrap_or_else(PoisonError::into_inner);
1081 let now = Instant::now();
1082 if let Some(running) = state.running.as_mut() {
1083 if running.process.running() {
1084 if running.launch == key {
1085 return Ok(CockpitEndpoint {
1086 port: running.process.port,
1087 cockpit_token: running.cockpit_token.clone(),
1088 });
1089 }
1090 state.running = None;
1092 } else {
1093 let stable = running.started.elapsed() >= STABLE;
1094 let report = running.process.exit_report();
1095 state.running = None;
1096 if stable {
1097 state.failures = 0;
1098 }
1099 tracing::warn!("cockpit exited ({report}); restarting after backoff");
1100 fail(&mut state, CockpitUnavailable::StartFailed, now);
1101 }
1102 }
1103 if state.retry_at.is_some_and(|at| now < at) {
1104 return Err(state.last_failure);
1105 }
1106 match start(launch, key) {
1107 Ok(running) => {
1108 let endpoint = CockpitEndpoint {
1109 port: running.process.port,
1110 cockpit_token: running.cockpit_token.clone(),
1111 };
1112 state.retry_at = None;
1113 state.running = Some(running);
1114 Ok(endpoint)
1115 }
1116 Err(
1118 reason @ (CockpitUnavailable::NotInstalled
1119 | CockpitUnavailable::Disabled
1120 | CockpitUnavailable::SourceBuild),
1121 ) => Err(reason),
1122 Err(reason) => {
1123 tracing::warn!("cockpit not started: {}", reason.as_str());
1124 fail(&mut state, reason, now);
1125 Err(reason)
1126 }
1127 }
1128}
1129
1130fn fail(state: &mut State, reason: CockpitUnavailable, now: Instant) {
1131 let wait = RESTART_BACKOFF[state.failures.min(RESTART_BACKOFF.len() - 1)];
1132 state.failures = state.failures.saturating_add(1);
1133 state.retry_at = Some(now + wait);
1134 state.last_failure = reason;
1135}
1136
1137pub fn retire() {
1140 let mut state = STATE.lock().unwrap_or_else(PoisonError::into_inner);
1141 state.running = None;
1142 state.failures = 0;
1143 state.retry_at = None;
1144}
1145
1146fn start(
1147 launch: &CockpitLaunch,
1148 key: [u8; 32],
1149) -> std::result::Result<Running, CockpitUnavailable> {
1150 import_bundled();
1151 let (root, package) = match authenticated() {
1152 Err(CockpitUnavailable::NotInstalled)
1153 if bootstrap::cockpit_channel().ok().flatten().is_none() =>
1154 {
1155 return Err(CockpitUnavailable::SourceBuild);
1156 }
1157 other => other?,
1158 };
1159 let mut token = [0_u8; 32];
1160 getrandom::fill(&mut token).map_err(|_| CockpitUnavailable::StartFailed)?;
1161 let cockpit_token = hex::encode(token);
1162 let start_line = start_line(launch, &cockpit_token).ok_or(CockpitUnavailable::StartFailed)?;
1163 let (prepared, command) = super::health::prepare_binary(&package.binary, &root, EXECUTABLE)
1164 .map_err(|error| {
1165 tracing::warn!("cockpit not started: its private copy was not prepared ({error:?})");
1166 CockpitUnavailable::StartFailed
1167 })?;
1168 match handshake(
1169 command,
1170 &start_line,
1171 vec![cockpit_token.clone(), launch.engine_token.clone()],
1172 HANDSHAKE,
1173 ) {
1174 Ok(process) => Ok(Running {
1175 process,
1176 prepared: Some(prepared),
1177 cockpit_token,
1178 launch: key,
1179 started: Instant::now(),
1180 }),
1181 Err(reason) => {
1182 let _ = prepared.close();
1183 Err(reason)
1184 }
1185 }
1186}
1187
1188fn start_line(launch: &CockpitLaunch, cockpit_token: &str) -> Option<Vec<u8>> {
1190 let engine_exe = std::env::current_exe().ok()?;
1191 let data_dir = crate::core::data_dir::resolve_data_dir().ok()?;
1194 let state_dir = crate::core::paths::state_dir().ok()?;
1195 if !data_dir.is_absolute() || !state_dir.is_absolute() {
1196 return None;
1197 }
1198 let home_dir = dirs::home_dir()
1200 .filter(|home| home.is_absolute())
1201 .and_then(|home| home.to_str().map(str::to_owned));
1202 let cache_dir = crate::core::paths::cache_dir()
1204 .ok()
1205 .filter(|cache| cache.is_absolute())
1206 .and_then(|cache| cache.to_str().map(str::to_owned));
1207 let config_dir = crate::core::paths::config_dir_read_only()
1210 .ok()
1211 .filter(|config| config.is_absolute())
1212 .and_then(|config| config.to_str().map(str::to_owned));
1213 let search_path = std::env::var("PATH").ok();
1214 let mut line = serde_json::to_vec(&serde_json::json!({
1215 "home_dir": home_dir,
1216 "engine_cache_dir": cache_dir,
1217 "engine_config_dir": config_dir,
1218 "search_path": search_path,
1219 "cockpit_token": cockpit_token,
1220 "engine_url": format!("http://127.0.0.1:{}", launch.engine_port),
1221 "engine_token": launch.engine_token,
1222 "engine_exe": engine_exe.to_str()?,
1223 "project_root": launch.project_root.to_str()?,
1224 "data_dir": data_dir.to_str()?,
1225 "engine_state_dir": state_dir.to_str()?,
1226 "engine_version": env!("CARGO_PKG_VERSION"),
1227 }))
1228 .ok()?;
1229 line.push(b'\n');
1230 Some(line)
1231}
1232
1233#[cfg(all(test, unix))]
1234#[path = "cockpit_tests.rs"]
1235mod tests;
1236
1237#[cfg(all(test, windows))]
1238mod windows_tests {
1239 use super::*;
1240
1241 #[test]
1242 fn the_memory_job_reports_its_peak_and_ends_the_cockpit_when_closed() {
1243 let mut child = Command::new("cmd")
1244 .args(["/C", "ping -n 30 127.0.0.1 >NUL"])
1245 .stdout(Stdio::null())
1246 .spawn()
1247 .unwrap();
1248 let job = MemoryJob::assign(&child, memory_budget(Some("256"))).unwrap();
1249 assert_eq!(job.limit, 256 * 1024 * 1024);
1250 assert!(job.peak().is_some_and(|peak| peak > 0));
1251 assert!(child.try_wait().unwrap().is_none());
1252 drop(job);
1253 let deadline = Instant::now() + Duration::from_secs(10);
1254 while child.try_wait().unwrap().is_none() {
1255 assert!(Instant::now() < deadline, "closing the job ends the child");
1256 std::thread::sleep(Duration::from_millis(20));
1257 }
1258 }
1259}