1use std::collections::BTreeMap;
4use std::path::PathBuf;
5use std::process::{Command, Stdio};
6use std::time::{Duration, Instant};
7
8use anyhow::{Context, Result, bail, ensure};
9
10use mj_core::config::{AwsAddressSource, Config, ProjectBundle, TargetTemplate, data_dir};
11use mj_core::state::{
12 PodmanWorkspaceLocator, SessionRecord, SessionResourceAllocation, TargetLocator,
13 allocation_cpus,
14};
15
16use crate::targets::{
17 self, AwsTemplate, CommandExecutor, CommandOutput, CommandSpec, ContainerTemplate,
18 ImageRefresh, ProjectBundleSpec, ProvisionStage, RepositorySpec, SshTarget,
19};
20
21use super::{Controller, execute_checked};
22
23impl Controller {
24 pub fn session_working_context(
26 &self,
27 session_id: &str,
28 executor: &impl CommandExecutor,
29 ) -> Result<(PathBuf, String)> {
30 let session = self
31 .state
32 .sessions
33 .get(session_id)
34 .context("session is missing")?;
35 let locator = session
36 .target
37 .as_ref()
38 .context("target is still starting")?;
39 let backend = backend_locator(locator, session, &self.config)?;
40 let launch = self.current_worker_launch_config(session_id, &backend)?;
41 let output = executor.execute(&targets::command_on_locator(
42 &backend,
43 session_id,
44 vec![
45 "git".into(),
46 "-C".into(),
47 launch.cwd.to_string_lossy().into_owned(),
48 "rev-parse".into(),
49 "--abbrev-ref".into(),
50 "HEAD".into(),
51 ],
52 "read current session branch",
53 )?)?;
54 let branch = if output.status == 0 {
55 let branch = String::from_utf8(output.stdout).context("decode session branch")?;
56 if branch.trim() == "HEAD" {
57 "detached HEAD".to_owned()
58 } else {
59 branch.trim().to_owned()
60 }
61 } else {
62 let stderr = String::from_utf8_lossy(&output.stderr);
63 if stderr.contains("not a git repository") {
64 "not a git checkout".to_owned()
68 } else {
69 format!(
70 "unavailable: {}",
71 stderr.lines().next().unwrap_or("").trim()
72 )
73 }
74 };
75 Ok((launch.cwd, branch))
76 }
77
78 pub fn session_git_status(
83 &self,
84 session_id: &str,
85 executor: &impl CommandExecutor,
86 ) -> Result<mj_core::local_git::SessionGitStatus> {
87 let (cwd, branch) = self.session_working_context(session_id, executor)?;
88 if branch.starts_with("not a git") || branch.starts_with("unavailable") {
89 return Ok(mj_core::local_git::parse_git_status(
90 cwd, &branch, None, "", "",
91 ));
92 }
93 let session = self
94 .state
95 .sessions
96 .get(session_id)
97 .context("session is missing")?;
98 let locator = session
99 .target
100 .as_ref()
101 .context("target is still starting")?;
102 let backend = backend_locator(locator, session, &self.config)?;
103 let cwd_text = cwd.to_string_lossy().into_owned();
104 let run = |args: &[&str], purpose: &str| -> Result<Option<String>> {
105 let mut command = vec!["git".to_owned(), "-C".to_owned(), cwd_text.clone()];
106 command.extend(args.iter().map(|arg| (*arg).to_owned()));
107 let output = executor.execute(&targets::command_on_locator(
108 &backend, session_id, command, purpose,
109 )?)?;
110 Ok((output.status == 0).then(|| String::from_utf8_lossy(&output.stdout).into_owned()))
111 };
112 let ahead_behind = run(
115 &["rev-list", "--left-right", "--count", "@{upstream}...HEAD"],
116 "count commits against upstream",
117 )?;
118 let numstat = run(
120 &["--no-optional-locks", "diff", "--numstat", "HEAD"],
121 "count changed lines",
122 )?
123 .unwrap_or_default();
124 let porcelain = run(
125 &[
126 "--no-optional-locks",
127 "status",
128 "--porcelain",
129 "--untracked-files=normal",
130 ],
131 "list changed files",
132 )?
133 .unwrap_or_default();
134 Ok(mj_core::local_git::parse_git_status(
135 cwd,
136 &branch,
137 ahead_behind.as_deref(),
138 &numstat,
139 &porcelain,
140 ))
141 }
142
143 pub fn resolve_aws_resource_options(
144 &self,
145 target_id: &str,
146 executor: &impl CommandExecutor,
147 ) -> Result<Vec<SessionResourceAllocation>> {
148 let TargetTemplate::AwsEc2 {
149 aws_profile,
150 region,
151 launch_template,
152 launch_template_version,
153 ..
154 } = self
155 .config
156 .targets
157 .get(target_id)
158 .with_context(|| format!("unknown target template {target_id:?}"))?
159 else {
160 bail!("target {target_id:?} is not an AWS EC2 target");
161 };
162 let profile = aws_profile.as_deref().unwrap_or("default");
163 let launch_key = if launch_template.starts_with("lt-") {
164 "--launch-template-id"
165 } else {
166 "--launch-template-name"
167 };
168 let version = launch_template_version.as_deref().unwrap_or("$Default");
169 let describe_template = CommandSpec::new(
170 "aws",
171 [
172 "--profile",
173 profile,
174 "--region",
175 region,
176 "ec2",
177 "describe-launch-template-versions",
178 launch_key,
179 launch_template,
180 "--versions",
181 version,
182 "--output",
183 "json",
184 ],
185 )
186 .purpose("resolve EC2 launch template instance family");
187 let output = executor.execute(&describe_template)?;
188 if output.status != 0 {
189 bail!(
190 "{} failed with status {}: {}",
191 describe_template.purpose,
192 output.status,
193 String::from_utf8_lossy(&output.stderr).trim()
194 );
195 }
196 let response: serde_json::Value =
197 serde_json::from_slice(&output.stdout).context("parse EC2 launch template response")?;
198 let instance_type = response
199 .pointer("/LaunchTemplateVersions/0/LaunchTemplateData/InstanceType")
200 .and_then(serde_json::Value::as_str)
201 .context("launch template does not specify a concrete instance type")?;
202 let family = instance_type
203 .rsplit_once('.')
204 .map(|(family, _)| family)
205 .context("launch template instance type has no size suffix")?;
206 let filter = format!("Name=instance-type,Values={family}.*");
207 let describe_types = CommandSpec::new(
208 "aws",
209 [
210 "--profile",
211 profile,
212 "--region",
213 region,
214 "ec2",
215 "describe-instance-types",
216 "--filters",
217 &filter,
218 "--output",
219 "json",
220 ],
221 )
222 .purpose("discover EC2 instance sizes");
223 let output = executor.execute(&describe_types)?;
224 if output.status != 0 {
225 bail!(
226 "{} failed with status {}: {}",
227 describe_types.purpose,
228 output.status,
229 String::from_utf8_lossy(&output.stderr).trim()
230 );
231 }
232 let response: serde_json::Value =
233 serde_json::from_slice(&output.stdout).context("parse EC2 instance type response")?;
234 let mut options = response
235 .get("InstanceTypes")
236 .and_then(serde_json::Value::as_array)
237 .context("EC2 instance type response omitted InstanceTypes")?
238 .iter()
239 .filter_map(|entry| {
240 Some(SessionResourceAllocation::AwsEc2 {
241 instance_type: entry.get("InstanceType")?.as_str()?.to_owned(),
242 vcpus: entry.pointer("/VCpuInfo/DefaultVCpus")?.as_u64()?,
243 memory_bytes: entry
244 .pointer("/MemoryInfo/SizeInMiB")?
245 .as_u64()?
246 .checked_mul(1024 * 1024)?,
247 })
248 })
249 .collect::<Vec<_>>();
250 options.sort_by_key(allocation_cpus);
251 if !options.iter().any(|option| allocation_cpus(option) == 8) {
252 bail!("EC2 family {family:?} has no exact 8-vCPU baseline size");
253 }
254 Ok(options)
255 }
256
257 pub fn reconnect_command(&self, session_id: &str) -> Result<CommandSpec> {
258 let session = self
259 .state
260 .sessions
261 .get(session_id)
262 .with_context(|| format!("unknown session {session_id}"))?;
263 session.validate_configuration(&self.config)?;
264 let locator = session.target.as_ref().context("session has no target")?;
265 let backend = backend_locator(locator, session, &self.config)?;
266 targets::reconnect_plan(&backend, session_id)?
267 .commands
268 .into_iter()
269 .next()
270 .context("reconnect plan is empty")
271 }
272
273 pub fn deployment_capacity_targets(&self) -> Vec<targets::DeploymentCapacityTarget> {
274 use targets::{DeploymentCapacityKind, DeploymentCapacityTarget};
275
276 let mut local_ids = Vec::new();
277 let mut ssh_hosts: BTreeMap<String, (Vec<String>, Vec<CommandSpec>)> = BTreeMap::new();
278 let mut targets = Vec::new();
279 for (target_id, template) in &self.config.targets {
280 match template {
281 TargetTemplate::LocalBare
282 | TargetTemplate::LocalPodman { .. }
283 | TargetTemplate::LocalDocker { .. }
284 | TargetTemplate::AppleContainer { .. } => {
285 local_ids.push(target_id.clone());
286 }
287 TargetTemplate::SshBare { ssh, .. }
288 | TargetTemplate::SshPodman { ssh, .. }
289 | TargetTemplate::SshDocker { ssh, .. } => {
290 let entry = ssh_hosts.entry(ssh.host.clone()).or_default();
291 entry.0.push(target_id.clone());
292 let command = targets::ssh_host_capacity_command(&SshTarget::from(ssh));
293 if !entry.1.contains(&command) {
294 entry.1.push(command);
295 }
296 }
297 TargetTemplate::AwsEc2 { .. } => {
298 let mut probes = Vec::new();
299 let mut probe_error = None;
300 for session in self.state.sessions.values().filter(|session| {
301 session.target_template_id == *target_id
302 && session.state.is_active()
303 && session.target.is_some()
304 }) {
305 let result = backend_locator(
306 session.target.as_ref().expect("filtered target"),
307 session,
308 &self.config,
309 )
310 .and_then(|locator| {
311 targets::aws_allocated_capacity_command(&locator, &session.id)
312 });
313 match result {
314 Ok(command) => probes.push(command),
315 Err(error) => probe_error = Some(format!("{error:#}")),
316 }
317 }
318 targets.push(DeploymentCapacityTarget {
319 id: format!("aws:{target_id}"),
320 host: target_id.clone(),
321 target_ids: vec![target_id.clone()],
322 kind: DeploymentCapacityKind::AwsFleet,
323 local: false,
324 probes,
325 probe_error,
326 });
327 }
328 }
329 }
330 if !local_ids.is_empty() {
331 targets.push(DeploymentCapacityTarget {
332 id: "local".into(),
333 host: "local".into(),
334 target_ids: local_ids,
335 kind: DeploymentCapacityKind::Host,
336 local: true,
337 probes: Vec::new(),
338 probe_error: None,
339 });
340 }
341 targets.extend(ssh_hosts.into_iter().map(|(host, (target_ids, probes))| {
342 DeploymentCapacityTarget {
343 id: format!("ssh:{host}"),
344 host,
345 target_ids,
346 kind: DeploymentCapacityKind::Host,
347 local: false,
348 probes,
349 probe_error: None,
350 }
351 }));
352 targets.sort_by(|left, right| left.id.cmp(&right.id));
353 targets
354 }
355
356 pub fn test_target(&self, target_id: &str, executor: &impl CommandExecutor) -> Result<()> {
358 verify_target(
359 self.configured_target(target_id)?,
360 executor,
361 TargetCheck::BeforeLaunch,
362 )
363 }
364
365 pub fn check_target_readiness(
368 &self,
369 target_id: &str,
370 executor: &impl CommandExecutor,
371 ) -> Result<()> {
372 preflight_target(
373 self.configured_target(target_id)?,
374 executor,
375 TargetCheck::BeforeLaunch,
376 )
377 }
378
379 fn configured_target(&self, target_id: &str) -> Result<&TargetTemplate> {
380 self.config
381 .targets
382 .get(target_id)
383 .with_context(|| format!("unknown target template {target_id:?}"))
384 }
385}
386
387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
389pub(super) enum TargetCheck {
390 BeforeLaunch,
393 Launch,
396}
397
398impl TargetCheck {
399 const fn then_retry(self) -> &'static str {
402 match self {
403 Self::BeforeLaunch => "",
404 Self::Launch => ", then Retry launch",
405 }
406 }
407}
408
409pub(super) fn preflight_target(
416 template: &TargetTemplate,
417 executor: &impl CommandExecutor,
418 check: TargetCheck,
419) -> Result<()> {
420 match template {
421 TargetTemplate::SshBare { ssh, .. }
422 | TargetTemplate::SshPodman { ssh, .. }
423 | TargetTemplate::SshDocker { ssh, .. } => {
424 verify_ssh_connectivity(&SshTarget::from(ssh), executor)
425 }
426 _ => verify_target(template, executor, check),
427 }
428}
429
430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
433pub(crate) enum LocalEngineReadiness {
434 Ready,
435 NotInstalled,
437 NotReady,
439}
440
441pub(crate) fn local_engine_readiness(
446 kind: &str,
447 executor: &impl CommandExecutor,
448) -> Option<LocalEngineReadiness> {
449 let result = match kind {
450 "local-podman" => targets::verify_local_podman(executor).map(|_| ()),
451 "local-docker" => targets::verify_local_docker(executor).map(|_| ()),
452 "apple-container" => executor
455 .execute(
456 &CommandSpec::new("container", ["system", "status"])
457 .purpose("preflight Apple container runtime")
458 .stage(ProvisionStage::Provisioning),
459 )
460 .and_then(|output| {
461 ensure!(output.status == 0, "container system status failed");
462 Ok(())
463 }),
464 _ => return None,
465 };
466 Some(match result {
467 Ok(()) => LocalEngineReadiness::Ready,
468 Err(error) if is_missing_command(&error) => LocalEngineReadiness::NotInstalled,
469 Err(_) => LocalEngineReadiness::NotReady,
470 })
471}
472
473fn is_missing_command(error: &anyhow::Error) -> bool {
475 error.chain().any(|cause| {
476 cause
477 .downcast_ref::<std::io::Error>()
478 .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
479 })
480}
481
482pub(super) fn verify_target(
484 template: &TargetTemplate,
485 executor: &impl CommandExecutor,
486 check: TargetCheck,
487) -> Result<()> {
488 let then_retry = check.then_retry();
489 match template {
490 TargetTemplate::LocalPodman { .. } => targets::verify_local_podman(executor)
491 .map(|_| ())
492 .map_err(|error| {
493 anyhow::anyhow!(
494 "local Podman is not ready. Fix the problem below{then_retry}: {error:#}"
495 )
496 }),
497 TargetTemplate::LocalDocker { .. } => targets::verify_local_docker(executor)
498 .map(|_| ())
499 .map_err(
500 |error| match error.downcast_ref::<targets::DockerUnavailable>() {
501 Some(problem) => anyhow::anyhow!(
505 "{problem} {}",
506 match check {
507 TargetCheck::BeforeLaunch => problem.remedy(),
508 TargetCheck::Launch => problem.launch_remedy(),
509 }
510 ),
511 None => anyhow::anyhow!(
512 "local Docker is not ready. Start Docker or fix the problem below{then_retry}: {error:#}"
513 ),
514 },
515 ),
516 TargetTemplate::SshPodman { ssh, .. } => {
517 let ssh = SshTarget::from(ssh);
518 targets::verify_ssh_podman(&ssh, executor)
519 .map(|preflight| {
520 for warning in preflight.warnings {
521 executor.notify_notice(&warning.notice());
522 }
523 })
524 .map_err(|error| {
525 anyhow::anyhow!(
526 "remote Podman is not ready on {}. Fix the problem below{then_retry}: {error:#}",
527 ssh.destination
528 )
529 })
530 }
531 TargetTemplate::SshDocker { ssh, .. } => {
532 let ssh = SshTarget::from(ssh);
533 targets::verify_ssh_docker(&ssh, executor)
534 .map(|_| ())
535 .map_err(|error| {
536 anyhow::anyhow!(
537 "remote Docker preflight failed for {}. Fix the problem below{then_retry}: {error:#}",
538 ssh.destination
539 )
540 })
541 }
542 TargetTemplate::AppleContainer { .. } => {
543 let command = CommandSpec::new("container", ["system", "status"])
544 .purpose("preflight Apple container runtime")
545 .stage(ProvisionStage::Provisioning);
546 let output = executor.execute(&command).map_err(|error| {
547 anyhow::anyhow!(
548 "Apple container is not ready. Fix the problem below{then_retry}: {error}"
549 )
550 })?;
551 if output.status != 0 {
552 bail!(
553 "Apple container is not ready. Start the runtime with `container system start`{then_retry}: container system status exited {}: {}",
554 output.status,
555 [
556 String::from_utf8_lossy(&output.stdout).trim(),
557 String::from_utf8_lossy(&output.stderr).trim(),
558 ]
559 .into_iter()
560 .filter(|message| !message.is_empty())
561 .collect::<Vec<_>>()
562 .join("\n")
563 );
564 }
565 Ok(())
566 }
567 TargetTemplate::SshBare { ssh, .. } => {
568 verify_ssh_connectivity(&SshTarget::from(ssh), executor)
569 }
570 TargetTemplate::AwsEc2 {
571 aws_profile,
572 region,
573 launch_template,
574 launch_template_version,
575 ..
576 } => {
577 let mut identity_args = vec!["sts".into(), "get-caller-identity".into()];
578 if let Some(profile) = aws_profile {
579 identity_args.extend(["--profile".into(), profile.clone()]);
580 }
581 let identity = CommandSpec::new("aws", identity_args)
582 .purpose("verify AWS credentials")
583 .stage(ProvisionStage::Provisioning);
584 let output = executor.execute(&identity)?;
585 ensure!(
586 output.status == 0,
587 "AWS credential test failed with status {}: {}",
588 output.status,
589 String::from_utf8_lossy(&output.stderr).trim()
590 );
591
592 let mut launch_args = vec![
593 "ec2".into(),
594 "describe-launch-template-versions".into(),
595 "--region".into(),
596 region.clone(),
597 "--launch-template-name".into(),
598 launch_template.clone(),
599 "--versions".into(),
600 launch_template_version
601 .clone()
602 .unwrap_or_else(|| "$Default".into()),
603 ];
604 if let Some(profile) = aws_profile {
605 launch_args.extend(["--profile".into(), profile.clone()]);
606 }
607 let launch = CommandSpec::new("aws", launch_args)
608 .purpose("verify AWS launch template")
609 .stage(ProvisionStage::Provisioning);
610 let output = executor.execute(&launch)?;
611 ensure!(
612 output.status == 0,
613 "AWS launch-template test failed with status {}: {}",
614 output.status,
615 String::from_utf8_lossy(&output.stderr).trim()
616 );
617 Ok(())
618 }
619 TargetTemplate::LocalBare => Ok(()),
620 }
621}
622
623fn verify_ssh_connectivity(ssh: &SshTarget, executor: &impl CommandExecutor) -> Result<()> {
624 let output = executor.execute(&targets::ssh_connectivity_probe(ssh))?;
625 ensure!(
626 output.status == 0,
627 "SSH connectivity test failed for {} with status {}: {}",
628 ssh.destination,
629 output.status,
630 String::from_utf8_lossy(&output.stderr).trim()
631 );
632 Ok(())
633}
634
635pub(super) fn backend_bundle(
636 bundle: &ProjectBundle,
637 executor: &impl CommandExecutor,
638) -> Result<ProjectBundleSpec> {
639 let primary = bundle.primary().context("bundle primary is missing")?;
640 Ok(ProjectBundleSpec {
641 primary: primary.destination.to_string_lossy().into_owned(),
642 repositories: bundle
643 .repositories
644 .iter()
645 .map(|repository| {
646 let source = mj_core::remote_git::resolve_repository(repository, executor)
647 .with_context(|| format!("repository {:?}", repository.id))?;
648 Ok(RepositorySpec {
649 url: Some(source.fetch_url),
650 push_urls: source.push_urls,
651 destination: repository.destination.to_string_lossy().into_owned(),
652 git_ref: None,
653 reference: None,
654 })
655 })
656 .collect::<Result<Vec<_>>>()?,
657 })
658}
659
660#[derive(Debug, Clone, Copy, Default)]
664pub(super) struct ContainerOverrides<'a> {
665 pub cpus: Option<&'a str>,
666 pub memory: Option<&'a str>,
667}
668
669impl<'a> ContainerOverrides<'a> {
670 pub(super) fn for_session(session: &'a SessionRecord) -> Self {
671 Self {
672 cpus: session.container_cpus.as_deref(),
673 memory: session.container_memory.as_deref(),
674 }
675 }
676}
677
678pub(super) fn backend_target(
679 template: &TargetTemplate,
680 allocation: Option<&SessionResourceAllocation>,
681 overrides: ContainerOverrides<'_>,
682) -> Result<targets::TargetTemplate> {
683 Ok(match template {
684 TargetTemplate::LocalBare => targets::TargetTemplate::LocalBare,
685 TargetTemplate::LocalPodman { container } => {
686 let mut backend = backend_container(container, allocation, overrides);
687 backend.workspace_storage = (&container.workspace_storage).into();
688 targets::TargetTemplate::LocalPodman(backend)
689 }
690 TargetTemplate::LocalDocker { container } => targets::TargetTemplate::LocalDocker(
691 backend_container(container, allocation, overrides),
692 ),
693 TargetTemplate::AppleContainer { container } => targets::TargetTemplate::AppleContainer(
694 backend_container(container, allocation, overrides),
695 ),
696 TargetTemplate::AwsEc2 {
697 aws_profile,
698 region,
699 launch_template,
700 launch_template_version,
701 ssh_user,
702 identity_file,
703 ssh_args,
704 ..
705 } => targets::TargetTemplate::AwsEc2(AwsTemplate {
706 profile: aws_profile.clone().unwrap_or_else(|| "default".into()),
707 region: region.clone(),
708 launch_template: launch_template.clone(),
709 launch_template_version: launch_template_version.clone(),
710 instance_type: match allocation {
711 Some(SessionResourceAllocation::AwsEc2 { instance_type, .. }) => {
712 Some(instance_type.clone())
713 }
714 _ => None,
715 },
716 ssh: SshTarget {
718 destination: format!("{ssh_user}@pending.invalid"),
719 ssh_args: targets::ssh_args_with_identity(ssh_args, identity_file.as_deref()),
720 },
721 }),
722 TargetTemplate::SshBare {
723 ssh,
724 workspace_prefix,
725 ..
726 } => targets::TargetTemplate::SshBare {
727 ssh: SshTarget::from(ssh),
728 workspace_prefix: workspace_prefix.to_string_lossy().into_owned(),
729 },
730 TargetTemplate::SshPodman { ssh, container, .. } => {
731 let mut backend = backend_container(container, allocation, overrides);
732 backend.workspace_storage = (&container.workspace_storage).into();
733 targets::TargetTemplate::SshPodman {
734 ssh: SshTarget::from(ssh),
735 container: backend,
736 }
737 }
738 TargetTemplate::SshDocker { ssh, container, .. } => targets::TargetTemplate::SshDocker {
739 ssh: SshTarget::from(ssh),
740 container: backend_container(container, allocation, overrides),
741 },
742 })
743}
744
745pub fn image_refresh_plan(config: &Config) -> Vec<ImageRefresh> {
757 let mut plan: Vec<ImageRefresh> = Vec::new();
758 for target in config.targets.values() {
759 let Some((host, container)) = target.image_host() else {
760 continue;
761 };
762 let Some(refresh) = targets::image_refresh(
763 host,
764 &container.image,
765 container.platform.as_deref(),
766 container.pull_policy,
767 ) else {
768 continue;
769 };
770 if let Some(existing) = plan.iter_mut().find(|entry| {
773 entry.host == refresh.host
774 && entry.image == refresh.image
775 && entry.platform == refresh.platform
776 }) {
777 existing.when = existing.when.max(refresh.when);
778 continue;
779 }
780 plan.push(refresh);
781 }
782 plan
783}
784
785pub(crate) fn controller_github_token() -> Option<String> {
786 for name in ["GH_TOKEN", "GITHUB_TOKEN"] {
787 if let Ok(token) = std::env::var(name)
788 && let Some(token) = usable_github_token(&token)
789 {
790 return Some(token.to_owned());
791 }
792 }
793 let output = match Command::new("gh")
794 .args(["auth", "token", "--hostname", "github.com"])
795 .stdin(Stdio::null())
796 .stderr(Stdio::null())
797 .output()
798 {
799 Ok(output) => output,
800 Err(error) => {
801 tracing::debug!(%error, "could not query the GitHub CLI for a token");
802 return None;
803 }
804 };
805 if !output.status.success() {
806 tracing::debug!(status = ?output.status, "GitHub CLI did not return an authenticated token");
807 return None;
808 }
809 let token = match std::str::from_utf8(&output.stdout) {
810 Ok(token) => token,
811 Err(error) => {
812 tracing::debug!(%error, "GitHub CLI returned a non-UTF-8 token");
813 return None;
814 }
815 };
816 let Some(token) = usable_github_token(token) else {
817 tracing::debug!("GitHub CLI returned an empty or invalid token");
818 return None;
819 };
820 Some(token.to_owned())
821}
822
823fn usable_github_token(token: &str) -> Option<&str> {
824 let token = token.trim();
825 (!token.is_empty() && !token.chars().any(char::is_whitespace)).then_some(token)
826}
827
828pub(super) fn configure_github_token_environment(target: &mut targets::TargetTemplate) -> bool {
829 let container = match target {
830 targets::TargetTemplate::LocalPodman(container)
831 | targets::TargetTemplate::LocalDocker(container)
832 | targets::TargetTemplate::AppleContainer(container)
833 | targets::TargetTemplate::SshPodman { container, .. }
834 | targets::TargetTemplate::SshDocker { container, .. } => container,
835 targets::TargetTemplate::LocalBare
836 | targets::TargetTemplate::AwsEc2(_)
837 | targets::TargetTemplate::SshBare { .. } => return false,
838 };
839 container
840 .extra_run_args
841 .extend(["--env".to_owned(), "GH_TOKEN".to_owned()]);
842 true
843}
844
845pub(super) fn use_github_https_urls(bundle: &mut targets::ProjectBundleSpec) {
846 for repository in &mut bundle.repositories {
847 for source in repository
848 .url
849 .iter_mut()
850 .chain(repository.push_urls.iter_mut())
851 {
852 if let Some(github) = crate::setup::github_repository_from_origin(source) {
853 *source = format!(
854 "https://github.com/{}/{}.git",
855 github.owner, github.repository
856 );
857 }
858 }
859 }
860}
861
862fn backend_container(
863 container: &mj_core::config::ContainerTemplate,
864 allocation: Option<&SessionResourceAllocation>,
865 overrides: ContainerOverrides<'_>,
866) -> ContainerTemplate {
867 let mut extra_run_args = Vec::new();
868 if let Some(platform) = &container.platform {
869 extra_run_args.push(format!("--platform={platform}"));
870 }
871 let (cpus, memory) = match allocation {
872 Some(SessionResourceAllocation::Container { cpus, memory_bytes }) => {
873 (Some(cpus.to_string()), Some(memory_bytes.to_string()))
874 }
875 _ => (container.cpus.clone(), container.memory.clone()),
876 };
877 let cpus = overrides.cpus.map(str::to_owned).or(cpus);
879 let memory = overrides.memory.map(str::to_owned).or(memory);
880 if let Some(cpus) = cpus {
881 extra_run_args.push(format!("--cpus={cpus}"));
882 }
883 if let Some(memory) = memory {
884 extra_run_args.push(format!("--memory={memory}"));
885 }
886 for (key, value) in &container.environment {
887 extra_run_args.extend(["--env".to_string(), format!("{key}={value}")]);
888 }
889 ContainerTemplate {
890 image: container.image.clone(),
891 pull_policy: container.pull_policy,
892 extra_run_args,
893 workspace_storage: targets::PodmanWorkspaceStorage::ContainerLayer,
894 build_cache: container.build_cache.clone(),
895 }
896}
897
898pub(super) fn validate_resource_allocation(
899 template: &TargetTemplate,
900 allocation: Option<&SessionResourceAllocation>,
901) -> Result<()> {
902 if let Some(allocation) = allocation {
903 allocation.validate()?;
904 }
905 match (template, allocation) {
906 (_, None)
907 | (
908 TargetTemplate::LocalPodman { .. }
909 | TargetTemplate::LocalDocker { .. }
910 | TargetTemplate::AppleContainer { .. }
911 | TargetTemplate::SshPodman { .. }
912 | TargetTemplate::SshDocker { .. },
913 Some(SessionResourceAllocation::Container { .. }),
914 )
915 | (TargetTemplate::AwsEc2 { .. }, Some(SessionResourceAllocation::AwsEc2 { .. })) => Ok(()),
916 (TargetTemplate::LocalBare | TargetTemplate::SshBare { .. }, Some(_)) => {
917 bail!("bare targets have fixed host resources")
918 }
919 _ => bail!("resource allocation does not match the selected target kind"),
920 }
921}
922
923const AWS_SSH_READY_TIMEOUT: Duration = Duration::from_secs(300);
925
926const AWS_SSH_READY_RETRY_DELAY: Duration = Duration::from_secs(3);
927
928fn wait_for_ssh_ready(
933 executor: &impl CommandExecutor,
934 probe: &CommandSpec,
935 timeout: Duration,
936 mut now: impl FnMut() -> Instant,
937 mut sleep: impl FnMut(Duration),
938) -> Result<()> {
939 let started = now();
940 loop {
941 if executor.cancellation_requested() {
942 bail!("cancelled while waiting for SSH on the new instance");
943 }
944 let failure = match executor.execute(probe) {
945 Ok(output) if output.status == 0 => return Ok(()),
946 Ok(output) => String::from_utf8_lossy(&output.stderr).trim().to_string(),
947 Err(error) => error.to_string(),
948 };
949 if now().duration_since(started) >= timeout {
950 bail!(
951 "{} timed out after {}s: {}",
952 probe.purpose,
953 timeout.as_secs(),
954 if failure.is_empty() {
955 "the SSH probe reported no error output"
956 } else {
957 failure.as_str()
958 }
959 );
960 }
961 sleep(AWS_SSH_READY_RETRY_DELAY);
962 }
963}
964
965pub(super) fn locator_after_provision_named(
966 canonical: &TargetTemplate,
967 backend: &targets::TargetTemplate,
968 session_id: &str,
969 first_output: Option<&CommandOutput>,
970 executor: &(impl CommandExecutor + Sync),
971 name: &str,
972) -> Result<TargetLocator> {
973 let generated = name.to_owned();
974
975 Ok(match canonical {
976 TargetTemplate::LocalBare => TargetLocator::LocalBare {
977 worker_root: data_dir().join("workers").join(session_id),
978 },
979 TargetTemplate::LocalPodman { .. } => {
980 let targets::TargetTemplate::LocalPodman(container) = backend else {
981 bail!("session locator/template mismatch")
982 };
983 TargetLocator::LocalPodman {
984 borrowed_from: None,
985 container_id: generated,
986 workspace_storage: PodmanWorkspaceLocator::from(
987 targets::podman_workspace_locator_named(container, name)?,
988 ),
989 }
990 }
991 TargetTemplate::LocalDocker { .. } => TargetLocator::LocalDocker {
992 borrowed_from: None,
993 container_id: generated,
994 },
995 TargetTemplate::AppleContainer { .. } => TargetLocator::AppleContainer {
996 borrowed_from: None,
997 container_id: generated,
998 },
999 TargetTemplate::SshBare { ssh, .. } => TargetLocator::SshBare {
1000 host: ssh.host.clone(),
1001 workspace: PathBuf::from(targets::workspace_for(backend, session_id)?),
1002 worker_id: None,
1003 },
1004 TargetTemplate::SshPodman { ssh, .. } => {
1005 let targets::TargetTemplate::SshPodman { container, .. } = backend else {
1006 bail!("session locator/template mismatch")
1007 };
1008 TargetLocator::SshPodman {
1009 borrowed_from: None,
1010 host: ssh.host.clone(),
1011 container_id: generated,
1012 workspace_storage: PodmanWorkspaceLocator::from(
1013 targets::podman_workspace_locator_named(container, name)?,
1014 ),
1015 }
1016 }
1017 TargetTemplate::SshDocker { ssh, .. } => TargetLocator::SshDocker {
1018 borrowed_from: None,
1019 host: ssh.host.clone(),
1020 container_id: generated,
1021 },
1022 TargetTemplate::AwsEc2 {
1023 aws_profile,
1024 region,
1025 ssh_user,
1026 address_source,
1027 identity_file,
1028 ssh_args,
1029 ..
1030 } => {
1031 let output = first_output.context("AWS launch produced no output")?;
1032 let json: serde_json::Value = serde_json::from_slice(&output.stdout)
1033 .context("parse aws ec2 run-instances response")?;
1034 let instance_id = json
1035 .pointer("/Instances/0/InstanceId")
1036 .and_then(serde_json::Value::as_str)
1037 .context("AWS response omitted instance ID")?
1038 .to_string();
1039 let profile = aws_profile.clone().unwrap_or_else(|| "default".into());
1040 execute_checked(
1041 executor,
1042 CommandSpec::new(
1043 "aws",
1044 [
1045 "--profile".into(),
1046 profile.clone(),
1047 "--region".into(),
1048 region.clone(),
1049 "ec2".into(),
1050 "wait".into(),
1051 "instance-running".into(),
1052 "--instance-ids".into(),
1053 instance_id.clone(),
1054 ],
1055 )
1056 .purpose("wait for EC2 session instance to run")
1057 .stage(ProvisionStage::Booting),
1058 )?;
1059 let field = match address_source {
1060 AwsAddressSource::PublicDns => "PublicDnsName",
1061 AwsAddressSource::PublicIp => "PublicIpAddress",
1062 AwsAddressSource::PrivateDns => "PrivateDnsName",
1063 AwsAddressSource::PrivateIp => "PrivateIpAddress",
1064 };
1065 let address = execute_checked(
1066 executor,
1067 CommandSpec::new(
1068 "aws",
1069 [
1070 "--profile".into(),
1071 profile.clone(),
1072 "--region".into(),
1073 region.clone(),
1074 "ec2".into(),
1075 "describe-instances".into(),
1076 "--instance-ids".into(),
1077 instance_id.clone(),
1078 "--query".into(),
1079 format!("Reservations[0].Instances[0].{field}"),
1080 "--output".into(),
1081 "text".into(),
1082 ],
1083 )
1084 .purpose("resolve EC2 session address")
1085 .stage(ProvisionStage::Booting),
1086 )?;
1087 let address = String::from_utf8(address.stdout)
1088 .context("AWS address was not UTF-8")?
1089 .trim()
1090 .to_string();
1091 if address.is_empty() || address == "None" {
1092 bail!("AWS instance {instance_id} has no configured address");
1093 }
1094 let ssh = SshTarget {
1095 destination: format!("{ssh_user}@{address}"),
1096 ssh_args: targets::ssh_args_with_identity(ssh_args, identity_file.as_deref()),
1097 };
1098 wait_for_ssh_ready(
1099 executor,
1100 &crate::targets::ssh_command(&ssh, ["true"])
1101 .purpose("wait for EC2 SSH availability")
1102 .stage(ProvisionStage::Booting),
1103 AWS_SSH_READY_TIMEOUT,
1104 Instant::now,
1105 std::thread::sleep,
1106 )?;
1107 TargetLocator::AwsEc2 {
1108 instance_id,
1109 address: Some(address),
1110 }
1111 }
1112 })
1113}
1114
1115pub(super) fn backend_locator(
1120 locator: &TargetLocator,
1121 session: &SessionRecord,
1122 config: &Config,
1123) -> Result<targets::TargetLocator> {
1124 let runtime = if session.target_runtime.is_some() || targets::locator_needs_connection(locator)
1125 {
1126 Some(session.target_runtime_settings(config)?)
1127 } else {
1128 None
1129 };
1130 Ok(targets::TargetLocator::try_from(targets::RecordedTarget {
1131 locator,
1132 runtime: runtime.as_deref(),
1133 session_id: &session.id,
1134 })?)
1135}
1136
1137#[cfg(test)]
1138mod tests;