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