Skip to main content

mj_controller/controller/
backend.rs

1//! Backend target, locator, and capacity conversion for provisioned sessions.
2
3use 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    /// Inspect the actual execution checkout in a background worker.
25    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                // A plain folder opened through `mj go` has no branch. Say so
65                // briefly rather than echoing multi-line git stderr, which wraps
66                // the banner.
67                "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    /// The session checkout's branch, distance from upstream, and changed
79    /// files, read with the target's own `git`. Builds on
80    /// [`Self::session_working_context`], so it works wherever that does: a
81    /// local checkout, a container, or an SSH host.
82    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        // No upstream is an ordinary state, so a failing count is `None`
113        // rather than an error.
114        let ahead_behind = run(
115            &["rev-list", "--left-right", "--count", "@{upstream}...HEAD"],
116            "count commits against upstream",
117        )?;
118        // A repository with no commit yet has no HEAD to diff against.
119        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 resource_probe(&self, session_id: &str) -> Result<targets::SessionResourceProbe> {
274        let session = self
275            .state
276            .sessions
277            .get(session_id)
278            .with_context(|| format!("unknown session {session_id}"))?;
279        let locator = session.target.as_ref().context("session has no target")?;
280        let backend = backend_locator(locator, session, &self.config)?;
281        targets::resource_probe(&backend, session_id)
282    }
283
284    pub fn deployment_capacity_targets(&self) -> Vec<targets::DeploymentCapacityTarget> {
285        use targets::{DeploymentCapacityKind, DeploymentCapacityTarget};
286
287        let mut local_ids = Vec::new();
288        let mut ssh_hosts: BTreeMap<String, (Vec<String>, Vec<CommandSpec>)> = BTreeMap::new();
289        let mut targets = Vec::new();
290        for (target_id, template) in &self.config.targets {
291            match template {
292                TargetTemplate::LocalBare
293                | TargetTemplate::LocalPodman { .. }
294                | TargetTemplate::LocalDocker { .. }
295                | TargetTemplate::AppleContainer { .. } => {
296                    local_ids.push(target_id.clone());
297                }
298                TargetTemplate::SshBare { ssh, .. }
299                | TargetTemplate::SshPodman { ssh, .. }
300                | TargetTemplate::SshDocker { ssh, .. } => {
301                    let entry = ssh_hosts.entry(ssh.host.clone()).or_default();
302                    entry.0.push(target_id.clone());
303                    let command = targets::ssh_host_capacity_command(&SshTarget::from(ssh));
304                    if !entry.1.contains(&command) {
305                        entry.1.push(command);
306                    }
307                }
308                TargetTemplate::AwsEc2 { .. } => {
309                    let mut probes = Vec::new();
310                    let mut probe_error = None;
311                    for session in self.state.sessions.values().filter(|session| {
312                        session.target_template_id == *target_id
313                            && session.state.is_active()
314                            && session.target.is_some()
315                    }) {
316                        let result = backend_locator(
317                            session.target.as_ref().expect("filtered target"),
318                            session,
319                            &self.config,
320                        )
321                        .and_then(|locator| {
322                            targets::aws_allocated_capacity_command(&locator, &session.id)
323                        });
324                        match result {
325                            Ok(command) => probes.push(command),
326                            Err(error) => probe_error = Some(format!("{error:#}")),
327                        }
328                    }
329                    targets.push(DeploymentCapacityTarget {
330                        id: format!("aws:{target_id}"),
331                        host: target_id.clone(),
332                        target_ids: vec![target_id.clone()],
333                        kind: DeploymentCapacityKind::AwsFleet,
334                        local: false,
335                        probes,
336                        probe_error,
337                    });
338                }
339            }
340        }
341        if !local_ids.is_empty() {
342            targets.push(DeploymentCapacityTarget {
343                id: "local".into(),
344                host: "local".into(),
345                target_ids: local_ids,
346                kind: DeploymentCapacityKind::Host,
347                local: true,
348                probes: Vec::new(),
349                probe_error: None,
350            });
351        }
352        targets.extend(ssh_hosts.into_iter().map(|(host, (target_ids, probes))| {
353            DeploymentCapacityTarget {
354                id: format!("ssh:{host}"),
355                host,
356                target_ids,
357                kind: DeploymentCapacityKind::Host,
358                local: false,
359                probes,
360                probe_error: None,
361            }
362        }));
363        targets.sort_by(|left, right| left.id.cmp(&right.id));
364        targets
365    }
366
367    /// The full check behind the Targets pane's Test action.
368    pub fn test_target(&self, target_id: &str, executor: &impl CommandExecutor) -> Result<()> {
369        verify_target(
370            self.configured_target(target_id)?,
371            executor,
372            TargetCheck::BeforeLaunch,
373        )
374    }
375
376    /// The check a session wizard runs before it offers a target: the same
377    /// one a launch runs, worded for a launch that has not happened yet.
378    pub fn check_target_readiness(
379        &self,
380        target_id: &str,
381        executor: &impl CommandExecutor,
382    ) -> Result<()> {
383        preflight_target(
384            self.configured_target(target_id)?,
385            executor,
386            TargetCheck::BeforeLaunch,
387        )
388    }
389
390    fn configured_target(&self, target_id: &str) -> Result<&TargetTemplate> {
391        self.config
392            .targets
393            .get(target_id)
394            .with_context(|| format!("unknown target template {target_id:?}"))
395    }
396}
397
398/// When a target is checked, which decides how its refusal ends.
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400pub(super) enum TargetCheck {
401    /// Before anything is launched: the session wizard's target row, the
402    /// Targets pane.
403    BeforeLaunch,
404    /// Inside a launch, resume, or move, whose failure the launch-failure
405    /// dialog reports with its Retry launch button.
406    Launch,
407}
408
409impl TargetCheck {
410    /// The clause that points at the failure dialog's Retry launch. Before a
411    /// launch there is no such dialog to point at (launch finding R6-3).
412    const fn then_retry(self) -> &'static str {
413        match self {
414            Self::BeforeLaunch => "",
415            Self::Launch => ", then Retry launch",
416        }
417    }
418}
419
420/// Check a target before a launch, resume, or move uses it.
421///
422/// An SSH host's container runtime is verified by `mj setup`, `mj doctor`,
423/// and the Targets pane's Test action; here it is assumed to still be as
424/// they left it, and only the host's reachability is checked. That probe
425/// joins an open shared connection, so it usually costs one SSH channel.
426pub(super) fn preflight_target(
427    template: &TargetTemplate,
428    executor: &impl CommandExecutor,
429    check: TargetCheck,
430) -> Result<()> {
431    match template {
432        TargetTemplate::SshBare { ssh, .. }
433        | TargetTemplate::SshPodman { ssh, .. }
434        | TargetTemplate::SshDocker { ssh, .. } => {
435            verify_ssh_connectivity(&SshTarget::from(ssh), executor)
436        }
437        _ => verify_target(template, executor, check),
438    }
439}
440
441/// Whether a local container engine can run sessions, as the launch
442/// preflight and the dashboard's Targets pane judge it.
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444pub(crate) enum LocalEngineReadiness {
445    Ready,
446    /// The engine's command is not on this host.
447    NotInstalled,
448    /// The command is there, but the engine did not answer its check.
449    NotReady,
450}
451
452/// Run the launch preflight's engine check for a local container target
453/// kind (`local-podman`, `local-docker`, or `apple-container`).
454///
455/// Answers `None` for any other kind: their readiness is not a local engine's.
456pub(crate) fn local_engine_readiness(
457    kind: &str,
458    executor: &impl CommandExecutor,
459) -> Option<LocalEngineReadiness> {
460    let result = match kind {
461        "local-podman" => targets::verify_local_podman(executor).map(|_| ()),
462        "local-docker" => targets::verify_local_docker(executor).map(|_| ()),
463        // The same command `verify_target` runs, without its sentence, which
464        // flattens the cause this needs to tell a missing command apart.
465        "apple-container" => executor
466            .execute(
467                &CommandSpec::new("container", ["system", "status"])
468                    .purpose("preflight Apple container runtime")
469                    .stage(ProvisionStage::Provisioning),
470            )
471            .and_then(|output| {
472                ensure!(output.status == 0, "container system status failed");
473                Ok(())
474            }),
475        _ => return None,
476    };
477    Some(match result {
478        Ok(()) => LocalEngineReadiness::Ready,
479        Err(error) if is_missing_command(&error) => LocalEngineReadiness::NotInstalled,
480        Err(_) => LocalEngineReadiness::NotReady,
481    })
482}
483
484/// Whether a command failed because its program is not installed.
485fn is_missing_command(error: &anyhow::Error) -> bool {
486    error.chain().any(|cause| {
487        cause
488            .downcast_ref::<std::io::Error>()
489            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
490    })
491}
492
493/// Check that a target's host and runtime can run sessions.
494pub(super) fn verify_target(
495    template: &TargetTemplate,
496    executor: &impl CommandExecutor,
497    check: TargetCheck,
498) -> Result<()> {
499    let then_retry = check.then_retry();
500    match template {
501        TargetTemplate::LocalPodman { .. } => targets::verify_local_podman(executor)
502            .map(|_| ())
503            .map_err(|error| {
504                anyhow::anyhow!(
505                    "local Podman is not ready. Fix the problem below{then_retry}: {error:#}"
506                )
507            }),
508        TargetTemplate::LocalDocker { .. } => targets::verify_local_docker(executor)
509            .map(|_| ())
510            .map_err(
511                |error| match error.downcast_ref::<targets::DockerUnavailable>() {
512                    // Leads with the sentence the launch options use, so a
513                    // missing Docker reads "not installed" in the wizard's
514                    // row too (launch finding R5-3).
515                    Some(problem) => anyhow::anyhow!(
516                        "{problem} {}",
517                        match check {
518                            TargetCheck::BeforeLaunch => problem.remedy(),
519                            TargetCheck::Launch => problem.launch_remedy(),
520                        }
521                    ),
522                    None => anyhow::anyhow!(
523                        "local Docker is not ready. Start Docker or fix the problem below{then_retry}: {error:#}"
524                    ),
525                },
526            ),
527        TargetTemplate::SshPodman { ssh, .. } => {
528            let ssh = SshTarget::from(ssh);
529            targets::verify_ssh_podman(&ssh, executor)
530                .map(|preflight| {
531                    for warning in preflight.warnings {
532                        executor.notify_notice(&warning.notice());
533                    }
534                })
535                .map_err(|error| {
536                    anyhow::anyhow!(
537                        "remote Podman is not ready on {}. Fix the problem below{then_retry}: {error:#}",
538                        ssh.destination
539                    )
540                })
541        }
542        TargetTemplate::SshDocker { ssh, .. } => {
543            let ssh = SshTarget::from(ssh);
544            targets::verify_ssh_docker(&ssh, executor)
545                .map(|_| ())
546                .map_err(|error| {
547                    anyhow::anyhow!(
548                        "remote Docker preflight failed for {}. Fix the problem below{then_retry}: {error:#}",
549                        ssh.destination
550                    )
551                })
552        }
553        TargetTemplate::AppleContainer { .. } => {
554            let command = CommandSpec::new("container", ["system", "status"])
555                .purpose("preflight Apple container runtime")
556                .stage(ProvisionStage::Provisioning);
557            let output = executor.execute(&command).map_err(|error| {
558                anyhow::anyhow!(
559                    "Apple container is not ready. Fix the problem below{then_retry}: {error}"
560                )
561            })?;
562            if output.status != 0 {
563                bail!(
564                    "Apple container is not ready. Start the runtime with `container system start`{then_retry}: container system status exited {}: {}",
565                    output.status,
566                    [
567                        String::from_utf8_lossy(&output.stdout).trim(),
568                        String::from_utf8_lossy(&output.stderr).trim(),
569                    ]
570                    .into_iter()
571                    .filter(|message| !message.is_empty())
572                    .collect::<Vec<_>>()
573                    .join("\n")
574                );
575            }
576            Ok(())
577        }
578        TargetTemplate::SshBare { ssh, .. } => {
579            verify_ssh_connectivity(&SshTarget::from(ssh), executor)
580        }
581        TargetTemplate::AwsEc2 {
582            aws_profile,
583            region,
584            launch_template,
585            launch_template_version,
586            ..
587        } => {
588            let mut identity_args = vec!["sts".into(), "get-caller-identity".into()];
589            if let Some(profile) = aws_profile {
590                identity_args.extend(["--profile".into(), profile.clone()]);
591            }
592            let identity = CommandSpec::new("aws", identity_args)
593                .purpose("verify AWS credentials")
594                .stage(ProvisionStage::Provisioning);
595            let output = executor.execute(&identity)?;
596            ensure!(
597                output.status == 0,
598                "AWS credential test failed with status {}: {}",
599                output.status,
600                String::from_utf8_lossy(&output.stderr).trim()
601            );
602
603            let mut launch_args = vec![
604                "ec2".into(),
605                "describe-launch-template-versions".into(),
606                "--region".into(),
607                region.clone(),
608                "--launch-template-name".into(),
609                launch_template.clone(),
610                "--versions".into(),
611                launch_template_version
612                    .clone()
613                    .unwrap_or_else(|| "$Default".into()),
614            ];
615            if let Some(profile) = aws_profile {
616                launch_args.extend(["--profile".into(), profile.clone()]);
617            }
618            let launch = CommandSpec::new("aws", launch_args)
619                .purpose("verify AWS launch template")
620                .stage(ProvisionStage::Provisioning);
621            let output = executor.execute(&launch)?;
622            ensure!(
623                output.status == 0,
624                "AWS launch-template test failed with status {}: {}",
625                output.status,
626                String::from_utf8_lossy(&output.stderr).trim()
627            );
628            Ok(())
629        }
630        TargetTemplate::LocalBare => Ok(()),
631    }
632}
633
634fn verify_ssh_connectivity(ssh: &SshTarget, executor: &impl CommandExecutor) -> Result<()> {
635    let output = executor.execute(&targets::ssh_connectivity_probe(ssh))?;
636    ensure!(
637        output.status == 0,
638        "SSH connectivity test failed for {} with status {}: {}",
639        ssh.destination,
640        output.status,
641        String::from_utf8_lossy(&output.stderr).trim()
642    );
643    Ok(())
644}
645
646pub(super) fn backend_bundle(
647    bundle: &ProjectBundle,
648    executor: &impl CommandExecutor,
649) -> Result<ProjectBundleSpec> {
650    let primary = bundle.primary().context("bundle primary is missing")?;
651    Ok(ProjectBundleSpec {
652        primary: primary.destination.to_string_lossy().into_owned(),
653        repositories: bundle
654            .repositories
655            .iter()
656            .map(|repository| {
657                let source = mj_core::remote_git::resolve_repository(repository, executor)
658                    .with_context(|| format!("repository {:?}", repository.id))?;
659                Ok(RepositorySpec {
660                    url: Some(source.fetch_url),
661                    push_urls: source.push_urls,
662                    destination: repository.destination.to_string_lossy().into_owned(),
663                    git_ref: None,
664                    reference: None,
665                })
666            })
667            .collect::<Result<Vec<_>>>()?,
668    })
669}
670
671/// Per-session container size overrides. They win over both the target
672/// template's values and any recorded resource allocation, and they are read
673/// only while a container is being created.
674#[derive(Debug, Clone, Copy, Default)]
675pub(super) struct ContainerOverrides<'a> {
676    pub cpus: Option<&'a str>,
677    pub memory: Option<&'a str>,
678}
679
680impl<'a> ContainerOverrides<'a> {
681    pub(super) fn for_session(session: &'a SessionRecord) -> Self {
682        Self {
683            cpus: session.container_cpus.as_deref(),
684            memory: session.container_memory.as_deref(),
685        }
686    }
687}
688
689pub(super) fn backend_target(
690    template: &TargetTemplate,
691    allocation: Option<&SessionResourceAllocation>,
692    overrides: ContainerOverrides<'_>,
693) -> Result<targets::TargetTemplate> {
694    Ok(match template {
695        TargetTemplate::LocalBare => targets::TargetTemplate::LocalBare,
696        TargetTemplate::LocalPodman { container } => {
697            let mut backend = backend_container(container, allocation, overrides);
698            backend.workspace_storage = (&container.workspace_storage).into();
699            targets::TargetTemplate::LocalPodman(backend)
700        }
701        TargetTemplate::LocalDocker { container } => targets::TargetTemplate::LocalDocker(
702            backend_container(container, allocation, overrides),
703        ),
704        TargetTemplate::AppleContainer { container } => targets::TargetTemplate::AppleContainer(
705            backend_container(container, allocation, overrides),
706        ),
707        TargetTemplate::AwsEc2 {
708            aws_profile,
709            region,
710            launch_template,
711            launch_template_version,
712            ssh_user,
713            identity_file,
714            ssh_args,
715            ..
716        } => targets::TargetTemplate::AwsEc2(AwsTemplate {
717            profile: aws_profile.clone().unwrap_or_else(|| "default".into()),
718            region: region.clone(),
719            launch_template: launch_template.clone(),
720            launch_template_version: launch_template_version.clone(),
721            instance_type: match allocation {
722                Some(SessionResourceAllocation::AwsEc2 { instance_type, .. }) => {
723                    Some(instance_type.clone())
724                }
725                _ => None,
726            },
727            // The address is filled after describe-instances.
728            ssh: SshTarget {
729                destination: format!("{ssh_user}@pending.invalid"),
730                ssh_args: targets::ssh_args_with_identity(ssh_args, identity_file.as_deref()),
731            },
732        }),
733        TargetTemplate::SshBare {
734            ssh,
735            workspace_prefix,
736            ..
737        } => targets::TargetTemplate::SshBare {
738            ssh: SshTarget::from(ssh),
739            workspace_prefix: workspace_prefix.to_string_lossy().into_owned(),
740        },
741        TargetTemplate::SshPodman { ssh, container, .. } => {
742            let mut backend = backend_container(container, allocation, overrides);
743            backend.workspace_storage = (&container.workspace_storage).into();
744            targets::TargetTemplate::SshPodman {
745                ssh: SshTarget::from(ssh),
746                container: backend,
747            }
748        }
749        TargetTemplate::SshDocker { ssh, container, .. } => targets::TargetTemplate::SshDocker {
750            ssh: SshTarget::from(ssh),
751            container: backend_container(container, allocation, overrides),
752        },
753    })
754}
755
756/// Every container image the daemon downloads in the background, once per
757/// (host, image, platform).
758///
759/// Every container target is covered, including Apple's `container` engine.
760/// A `never` policy is the one opt-out. The rest differ only in when they
761/// download: `always` and `newer` pull on every refresh, while the others
762/// pull only when the host has no copy of the image.
763///
764/// Several targets often share one image on one host, and that needs one
765/// download. When two such targets disagree about when to pull, the merged
766/// entry takes the more eager of the two.
767pub fn image_refresh_plan(config: &Config) -> Vec<ImageRefresh> {
768    let mut plan: Vec<ImageRefresh> = Vec::new();
769    for target in config.targets.values() {
770        let Some((host, container)) = target.image_host() else {
771            continue;
772        };
773        let Some(refresh) = targets::image_refresh(
774            host,
775            &container.image,
776            container.platform.as_deref(),
777            container.pull_policy,
778        ) else {
779            continue;
780        };
781        // Commands are decided by the host, the image, and the platform alone,
782        // so those three identify the duplicates worth collapsing.
783        if let Some(existing) = plan.iter_mut().find(|entry| {
784            entry.host == refresh.host
785                && entry.image == refresh.image
786                && entry.platform == refresh.platform
787        }) {
788            existing.when = existing.when.max(refresh.when);
789            continue;
790        }
791        plan.push(refresh);
792    }
793    plan
794}
795
796pub(crate) fn controller_github_token() -> Option<String> {
797    for name in ["GH_TOKEN", "GITHUB_TOKEN"] {
798        if let Ok(token) = std::env::var(name)
799            && let Some(token) = usable_github_token(&token)
800        {
801            return Some(token.to_owned());
802        }
803    }
804    let output = match Command::new("gh")
805        .args(["auth", "token", "--hostname", "github.com"])
806        .stdin(Stdio::null())
807        .stderr(Stdio::null())
808        .output()
809    {
810        Ok(output) => output,
811        Err(error) => {
812            tracing::debug!(%error, "could not query the GitHub CLI for a token");
813            return None;
814        }
815    };
816    if !output.status.success() {
817        tracing::debug!(status = ?output.status, "GitHub CLI did not return an authenticated token");
818        return None;
819    }
820    let token = match std::str::from_utf8(&output.stdout) {
821        Ok(token) => token,
822        Err(error) => {
823            tracing::debug!(%error, "GitHub CLI returned a non-UTF-8 token");
824            return None;
825        }
826    };
827    let Some(token) = usable_github_token(token) else {
828        tracing::debug!("GitHub CLI returned an empty or invalid token");
829        return None;
830    };
831    Some(token.to_owned())
832}
833
834fn usable_github_token(token: &str) -> Option<&str> {
835    let token = token.trim();
836    (!token.is_empty() && !token.chars().any(char::is_whitespace)).then_some(token)
837}
838
839pub(super) fn configure_github_token_environment(target: &mut targets::TargetTemplate) -> bool {
840    let container = match target {
841        targets::TargetTemplate::LocalPodman(container)
842        | targets::TargetTemplate::LocalDocker(container)
843        | targets::TargetTemplate::AppleContainer(container)
844        | targets::TargetTemplate::SshPodman { container, .. }
845        | targets::TargetTemplate::SshDocker { container, .. } => container,
846        targets::TargetTemplate::LocalBare
847        | targets::TargetTemplate::AwsEc2(_)
848        | targets::TargetTemplate::SshBare { .. } => return false,
849    };
850    container
851        .extra_run_args
852        .extend(["--env".to_owned(), "GH_TOKEN".to_owned()]);
853    true
854}
855
856pub(super) fn use_github_https_urls(bundle: &mut targets::ProjectBundleSpec) {
857    for repository in &mut bundle.repositories {
858        for source in repository
859            .url
860            .iter_mut()
861            .chain(repository.push_urls.iter_mut())
862        {
863            if let Some(github) = crate::setup::github_repository_from_origin(source) {
864                *source = format!(
865                    "https://github.com/{}/{}.git",
866                    github.owner, github.repository
867                );
868            }
869        }
870    }
871}
872
873fn backend_container(
874    container: &mj_core::config::ContainerTemplate,
875    allocation: Option<&SessionResourceAllocation>,
876    overrides: ContainerOverrides<'_>,
877) -> ContainerTemplate {
878    let mut extra_run_args = Vec::new();
879    if let Some(platform) = &container.platform {
880        extra_run_args.push(format!("--platform={platform}"));
881    }
882    let (cpus, memory) = match allocation {
883        Some(SessionResourceAllocation::Container { cpus, memory_bytes }) => {
884            (Some(cpus.to_string()), Some(memory_bytes.to_string()))
885        }
886        _ => (container.cpus.clone(), container.memory.clone()),
887    };
888    // The session's own overrides are the last word on size.
889    let cpus = overrides.cpus.map(str::to_owned).or(cpus);
890    let memory = overrides.memory.map(str::to_owned).or(memory);
891    if let Some(cpus) = cpus {
892        extra_run_args.push(format!("--cpus={cpus}"));
893    }
894    if let Some(memory) = memory {
895        extra_run_args.push(format!("--memory={memory}"));
896    }
897    for (key, value) in &container.environment {
898        extra_run_args.extend(["--env".to_string(), format!("{key}={value}")]);
899    }
900    ContainerTemplate {
901        image: container.image.clone(),
902        pull_policy: container.pull_policy,
903        extra_run_args,
904        workspace_storage: targets::PodmanWorkspaceStorage::ContainerLayer,
905        build_cache: container.build_cache.clone(),
906    }
907}
908
909pub(super) fn validate_resource_allocation(
910    template: &TargetTemplate,
911    allocation: Option<&SessionResourceAllocation>,
912) -> Result<()> {
913    if let Some(allocation) = allocation {
914        allocation.validate()?;
915    }
916    match (template, allocation) {
917        (_, None)
918        | (
919            TargetTemplate::LocalPodman { .. }
920            | TargetTemplate::LocalDocker { .. }
921            | TargetTemplate::AppleContainer { .. }
922            | TargetTemplate::SshPodman { .. }
923            | TargetTemplate::SshDocker { .. },
924            Some(SessionResourceAllocation::Container { .. }),
925        )
926        | (TargetTemplate::AwsEc2 { .. }, Some(SessionResourceAllocation::AwsEc2 { .. })) => Ok(()),
927        (TargetTemplate::LocalBare | TargetTemplate::SshBare { .. }, Some(_)) => {
928            bail!("bare targets have fixed host resources")
929        }
930        _ => bail!("resource allocation does not match the selected target kind"),
931    }
932}
933
934/// How long a freshly launched EC2 instance may take to accept SSH.
935const AWS_SSH_READY_TIMEOUT: Duration = Duration::from_secs(300);
936
937const AWS_SSH_READY_RETRY_DELAY: Duration = Duration::from_secs(3);
938
939/// Poll a remote host until it accepts SSH, or until the deadline passes.
940///
941/// `now` and `sleep` are injected so tests can drive the deadline without
942/// waiting in real time.
943fn wait_for_ssh_ready(
944    executor: &impl CommandExecutor,
945    probe: &CommandSpec,
946    timeout: Duration,
947    mut now: impl FnMut() -> Instant,
948    mut sleep: impl FnMut(Duration),
949) -> Result<()> {
950    let started = now();
951    loop {
952        if executor.cancellation_requested() {
953            bail!("cancelled while waiting for SSH on the new instance");
954        }
955        let failure = match executor.execute(probe) {
956            Ok(output) if output.status == 0 => return Ok(()),
957            Ok(output) => String::from_utf8_lossy(&output.stderr).trim().to_string(),
958            Err(error) => error.to_string(),
959        };
960        if now().duration_since(started) >= timeout {
961            bail!(
962                "{} timed out after {}s: {}",
963                probe.purpose,
964                timeout.as_secs(),
965                if failure.is_empty() {
966                    "the SSH probe reported no error output"
967                } else {
968                    failure.as_str()
969                }
970            );
971        }
972        sleep(AWS_SSH_READY_RETRY_DELAY);
973    }
974}
975
976pub(super) fn locator_after_provision(
977    canonical: &TargetTemplate,
978    backend: &targets::TargetTemplate,
979    session_id: &str,
980    first_output: Option<&CommandOutput>,
981    executor: &(impl CommandExecutor + Sync),
982) -> Result<TargetLocator> {
983    let generated = targets::resource_name(session_id)?;
984    Ok(match canonical {
985        TargetTemplate::LocalBare => TargetLocator::LocalBare {
986            worker_root: data_dir().join("workers").join(session_id),
987        },
988        TargetTemplate::LocalPodman { .. } => {
989            let targets::TargetTemplate::LocalPodman(container) = backend else {
990                bail!("session locator/template mismatch")
991            };
992            TargetLocator::LocalPodman {
993                borrowed_from: None,
994                container_id: generated,
995                workspace_storage: PodmanWorkspaceLocator::from(targets::podman_workspace_locator(
996                    container, session_id,
997                )?),
998            }
999        }
1000        TargetTemplate::LocalDocker { .. } => TargetLocator::LocalDocker {
1001            borrowed_from: None,
1002            container_id: generated,
1003        },
1004        TargetTemplate::AppleContainer { .. } => TargetLocator::AppleContainer {
1005            borrowed_from: None,
1006            container_id: generated,
1007        },
1008        TargetTemplate::SshBare { ssh, .. } => TargetLocator::SshBare {
1009            host: ssh.host.clone(),
1010            workspace: PathBuf::from(targets::workspace_for(backend, session_id)?),
1011            worker_id: None,
1012        },
1013        TargetTemplate::SshPodman { ssh, .. } => {
1014            let targets::TargetTemplate::SshPodman { container, .. } = backend else {
1015                bail!("session locator/template mismatch")
1016            };
1017            TargetLocator::SshPodman {
1018                borrowed_from: None,
1019                host: ssh.host.clone(),
1020                container_id: generated,
1021                workspace_storage: PodmanWorkspaceLocator::from(targets::podman_workspace_locator(
1022                    container, session_id,
1023                )?),
1024            }
1025        }
1026        TargetTemplate::SshDocker { ssh, .. } => TargetLocator::SshDocker {
1027            borrowed_from: None,
1028            host: ssh.host.clone(),
1029            container_id: generated,
1030        },
1031        TargetTemplate::AwsEc2 {
1032            aws_profile,
1033            region,
1034            ssh_user,
1035            address_source,
1036            identity_file,
1037            ssh_args,
1038            ..
1039        } => {
1040            let output = first_output.context("AWS launch produced no output")?;
1041            let json: serde_json::Value = serde_json::from_slice(&output.stdout)
1042                .context("parse aws ec2 run-instances response")?;
1043            let instance_id = json
1044                .pointer("/Instances/0/InstanceId")
1045                .and_then(serde_json::Value::as_str)
1046                .context("AWS response omitted instance ID")?
1047                .to_string();
1048            let profile = aws_profile.clone().unwrap_or_else(|| "default".into());
1049            execute_checked(
1050                executor,
1051                CommandSpec::new(
1052                    "aws",
1053                    [
1054                        "--profile".into(),
1055                        profile.clone(),
1056                        "--region".into(),
1057                        region.clone(),
1058                        "ec2".into(),
1059                        "wait".into(),
1060                        "instance-running".into(),
1061                        "--instance-ids".into(),
1062                        instance_id.clone(),
1063                    ],
1064                )
1065                .purpose("wait for EC2 session instance to run")
1066                .stage(ProvisionStage::Booting),
1067            )?;
1068            let field = match address_source {
1069                AwsAddressSource::PublicDns => "PublicDnsName",
1070                AwsAddressSource::PublicIp => "PublicIpAddress",
1071                AwsAddressSource::PrivateDns => "PrivateDnsName",
1072                AwsAddressSource::PrivateIp => "PrivateIpAddress",
1073            };
1074            let address = execute_checked(
1075                executor,
1076                CommandSpec::new(
1077                    "aws",
1078                    [
1079                        "--profile".into(),
1080                        profile.clone(),
1081                        "--region".into(),
1082                        region.clone(),
1083                        "ec2".into(),
1084                        "describe-instances".into(),
1085                        "--instance-ids".into(),
1086                        instance_id.clone(),
1087                        "--query".into(),
1088                        format!("Reservations[0].Instances[0].{field}"),
1089                        "--output".into(),
1090                        "text".into(),
1091                    ],
1092                )
1093                .purpose("resolve EC2 session address")
1094                .stage(ProvisionStage::Booting),
1095            )?;
1096            let address = String::from_utf8(address.stdout)
1097                .context("AWS address was not UTF-8")?
1098                .trim()
1099                .to_string();
1100            if address.is_empty() || address == "None" {
1101                bail!("AWS instance {instance_id} has no configured address");
1102            }
1103            let ssh = SshTarget {
1104                destination: format!("{ssh_user}@{address}"),
1105                ssh_args: targets::ssh_args_with_identity(ssh_args, identity_file.as_deref()),
1106            };
1107            wait_for_ssh_ready(
1108                executor,
1109                &crate::targets::ssh_command(&ssh, ["true"])
1110                    .purpose("wait for EC2 SSH availability")
1111                    .stage(ProvisionStage::Booting),
1112                AWS_SSH_READY_TIMEOUT,
1113                Instant::now,
1114                std::thread::sleep,
1115            )?;
1116            TargetLocator::AwsEc2 {
1117                instance_id,
1118                address: Some(address),
1119            }
1120        }
1121    })
1122}
1123
1124/// The execution-plan locator for a session's stored target.
1125///
1126/// The mapping itself lives in `mj_core::targets`; this only pairs the stored
1127/// locator with the target template the session was created against.
1128pub(super) fn backend_locator(
1129    locator: &TargetLocator,
1130    session: &SessionRecord,
1131    config: &Config,
1132) -> Result<targets::TargetLocator> {
1133    let runtime = if session.target_runtime.is_some() || targets::locator_needs_connection(locator)
1134    {
1135        Some(session.target_runtime_settings(config)?)
1136    } else {
1137        None
1138    };
1139    Ok(targets::TargetLocator::try_from(targets::RecordedTarget {
1140        locator,
1141        runtime: runtime.as_deref(),
1142        session_id: &session.id,
1143    })?)
1144}
1145
1146#[cfg(test)]
1147mod tests;