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    pub fn test_target(&self, target_id: &str, executor: &impl CommandExecutor) -> Result<()> {
368        let template = self
369            .config
370            .targets
371            .get(target_id)
372            .with_context(|| format!("unknown target template {target_id:?}"))?;
373        preflight_target(template, executor)
374    }
375}
376
377pub(super) fn preflight_target(
378    template: &TargetTemplate,
379    executor: &impl CommandExecutor,
380) -> Result<()> {
381    match template {
382        TargetTemplate::LocalPodman { .. } => targets::verify_local_podman(executor)
383            .map(|_| ())
384            .map_err(|error| {
385                anyhow::anyhow!(
386                    "local Podman is not ready. Fix the problem below, then Retry launch: {error:#}"
387                )
388            }),
389        TargetTemplate::LocalDocker { .. } => targets::verify_local_docker(executor)
390            .map(|_| ())
391            .map_err(|error| {
392                anyhow::anyhow!(
393                    "local Docker is not ready. Start Docker or fix the problem below, then Retry launch: {error:#}"
394                )
395            }),
396        TargetTemplate::SshPodman { ssh, .. } => {
397            let ssh = SshTarget::from(ssh);
398            targets::verify_ssh_podman(&ssh, executor)
399                .map(|preflight| {
400                    for warning in preflight.warnings {
401                        executor.notify_notice(&warning.notice());
402                    }
403                })
404                .map_err(|error| {
405                    anyhow::anyhow!(
406                        "remote Podman is not ready on {}. Fix the problem below, then Retry launch: {error:#}",
407                        ssh.destination
408                    )
409                })
410        }
411        TargetTemplate::SshDocker { ssh, .. } => {
412            let ssh = SshTarget::from(ssh);
413            targets::verify_ssh_docker(&ssh, executor)
414                .map(|_| ())
415                .map_err(|error| {
416                    anyhow::anyhow!(
417                        "remote Docker preflight failed for {}. Fix the problem below, then Retry launch: {error:#}",
418                        ssh.destination
419                    )
420                })
421        }
422        TargetTemplate::AppleContainer { .. } => {
423            let command = CommandSpec::new("container", ["system", "status"])
424                .purpose("preflight Apple container runtime")
425                .stage(ProvisionStage::Provisioning);
426            let output = executor.execute(&command).map_err(|error| {
427                anyhow::anyhow!(
428                    "Apple container is not ready. Fix the problem below, then Retry launch: {error}"
429                )
430            })?;
431            if output.status != 0 {
432                bail!(
433                    "Apple container is not ready. Start the runtime with `container system start`, then Retry launch: container system status exited {}: {}",
434                    output.status,
435                    [
436                        String::from_utf8_lossy(&output.stdout).trim(),
437                        String::from_utf8_lossy(&output.stderr).trim(),
438                    ]
439                    .into_iter()
440                    .filter(|message| !message.is_empty())
441                    .collect::<Vec<_>>()
442                    .join("\n")
443                );
444            }
445            Ok(())
446        }
447        TargetTemplate::SshBare { ssh, .. } => {
448            let ssh = SshTarget::from(ssh);
449            let command = targets::ssh_connectivity_probe(&ssh);
450            let output = executor.execute(&command)?;
451            ensure!(
452                output.status == 0,
453                "SSH connectivity test failed for {} with status {}: {}",
454                ssh.destination,
455                output.status,
456                String::from_utf8_lossy(&output.stderr).trim()
457            );
458            Ok(())
459        }
460        TargetTemplate::AwsEc2 {
461            aws_profile,
462            region,
463            launch_template,
464            launch_template_version,
465            ..
466        } => {
467            let mut identity_args = vec!["sts".into(), "get-caller-identity".into()];
468            if let Some(profile) = aws_profile {
469                identity_args.extend(["--profile".into(), profile.clone()]);
470            }
471            let identity = CommandSpec::new("aws", identity_args)
472                .purpose("verify AWS credentials")
473                .stage(ProvisionStage::Provisioning);
474            let output = executor.execute(&identity)?;
475            ensure!(
476                output.status == 0,
477                "AWS credential test failed with status {}: {}",
478                output.status,
479                String::from_utf8_lossy(&output.stderr).trim()
480            );
481
482            let mut launch_args = vec![
483                "ec2".into(),
484                "describe-launch-template-versions".into(),
485                "--region".into(),
486                region.clone(),
487                "--launch-template-name".into(),
488                launch_template.clone(),
489                "--versions".into(),
490                launch_template_version
491                    .clone()
492                    .unwrap_or_else(|| "$Default".into()),
493            ];
494            if let Some(profile) = aws_profile {
495                launch_args.extend(["--profile".into(), profile.clone()]);
496            }
497            let launch = CommandSpec::new("aws", launch_args)
498                .purpose("verify AWS launch template")
499                .stage(ProvisionStage::Provisioning);
500            let output = executor.execute(&launch)?;
501            ensure!(
502                output.status == 0,
503                "AWS launch-template test failed with status {}: {}",
504                output.status,
505                String::from_utf8_lossy(&output.stderr).trim()
506            );
507            Ok(())
508        }
509        TargetTemplate::LocalBare => Ok(()),
510    }
511}
512
513pub(super) fn backend_bundle(
514    bundle: &ProjectBundle,
515    executor: &impl CommandExecutor,
516) -> Result<ProjectBundleSpec> {
517    let primary = bundle.primary().context("bundle primary is missing")?;
518    Ok(ProjectBundleSpec {
519        primary: primary.destination.to_string_lossy().into_owned(),
520        repositories: bundle
521            .repositories
522            .iter()
523            .map(|repository| {
524                let source = mj_core::remote_git::resolve_repository(repository, executor)
525                    .with_context(|| format!("repository {:?}", repository.id))?;
526                Ok(RepositorySpec {
527                    url: Some(source.fetch_url),
528                    push_urls: source.push_urls,
529                    destination: repository.destination.to_string_lossy().into_owned(),
530                    git_ref: None,
531                    reference: None,
532                })
533            })
534            .collect::<Result<Vec<_>>>()?,
535    })
536}
537
538/// Per-session container size overrides. They win over both the target
539/// template's values and any recorded resource allocation, and they are read
540/// only while a container is being created.
541#[derive(Debug, Clone, Copy, Default)]
542pub(super) struct ContainerOverrides<'a> {
543    pub cpus: Option<&'a str>,
544    pub memory: Option<&'a str>,
545}
546
547impl<'a> ContainerOverrides<'a> {
548    pub(super) fn for_session(session: &'a SessionRecord) -> Self {
549        Self {
550            cpus: session.container_cpus.as_deref(),
551            memory: session.container_memory.as_deref(),
552        }
553    }
554}
555
556pub(super) fn backend_target(
557    template: &TargetTemplate,
558    allocation: Option<&SessionResourceAllocation>,
559    overrides: ContainerOverrides<'_>,
560) -> Result<targets::TargetTemplate> {
561    Ok(match template {
562        TargetTemplate::LocalBare => targets::TargetTemplate::LocalBare,
563        TargetTemplate::LocalPodman { container } => {
564            let mut backend = backend_container(container, allocation, overrides);
565            backend.workspace_storage = (&container.workspace_storage).into();
566            targets::TargetTemplate::LocalPodman(backend)
567        }
568        TargetTemplate::LocalDocker { container } => targets::TargetTemplate::LocalDocker(
569            backend_container(container, allocation, overrides),
570        ),
571        TargetTemplate::AppleContainer { container } => targets::TargetTemplate::AppleContainer(
572            backend_container(container, allocation, overrides),
573        ),
574        TargetTemplate::AwsEc2 {
575            aws_profile,
576            region,
577            launch_template,
578            launch_template_version,
579            ssh_user,
580            identity_file,
581            ssh_args,
582            ..
583        } => targets::TargetTemplate::AwsEc2(AwsTemplate {
584            profile: aws_profile.clone().unwrap_or_else(|| "default".into()),
585            region: region.clone(),
586            launch_template: launch_template.clone(),
587            launch_template_version: launch_template_version.clone(),
588            instance_type: match allocation {
589                Some(SessionResourceAllocation::AwsEc2 { instance_type, .. }) => {
590                    Some(instance_type.clone())
591                }
592                _ => None,
593            },
594            // The address is filled after describe-instances.
595            ssh: SshTarget {
596                destination: format!("{ssh_user}@pending.invalid"),
597                ssh_args: targets::ssh_args_with_identity(ssh_args, identity_file.as_deref()),
598            },
599        }),
600        TargetTemplate::SshBare {
601            ssh,
602            workspace_prefix,
603            ..
604        } => targets::TargetTemplate::SshBare {
605            ssh: SshTarget::from(ssh),
606            workspace_prefix: workspace_prefix.to_string_lossy().into_owned(),
607        },
608        TargetTemplate::SshPodman { ssh, container, .. } => {
609            let mut backend = backend_container(container, allocation, overrides);
610            backend.workspace_storage = (&container.workspace_storage).into();
611            targets::TargetTemplate::SshPodman {
612                ssh: SshTarget::from(ssh),
613                container: backend,
614            }
615        }
616        TargetTemplate::SshDocker { ssh, container, .. } => targets::TargetTemplate::SshDocker {
617            ssh: SshTarget::from(ssh),
618            container: backend_container(container, allocation, overrides),
619        },
620    })
621}
622
623/// Every container image the daemon downloads in the background, once per
624/// (host, image, platform).
625///
626/// Every container target is covered, including Apple's `container` engine.
627/// A `never` policy is the one opt-out. The rest differ only in when they
628/// download: `always` and `newer` pull on every refresh, while the others
629/// pull only when the host has no copy of the image.
630///
631/// Several targets often share one image on one host, and that needs one
632/// download. When two such targets disagree about when to pull, the merged
633/// entry takes the more eager of the two.
634pub fn image_refresh_plan(config: &Config) -> Vec<ImageRefresh> {
635    let mut plan: Vec<ImageRefresh> = Vec::new();
636    for target in config.targets.values() {
637        let Some((host, container)) = target.image_host() else {
638            continue;
639        };
640        let Some(refresh) = targets::image_refresh(
641            host,
642            &container.image,
643            container.platform.as_deref(),
644            container.pull_policy,
645        ) else {
646            continue;
647        };
648        // Commands are decided by the host, the image, and the platform alone,
649        // so those three identify the duplicates worth collapsing.
650        if let Some(existing) = plan.iter_mut().find(|entry| {
651            entry.host == refresh.host
652                && entry.image == refresh.image
653                && entry.platform == refresh.platform
654        }) {
655            existing.when = existing.when.max(refresh.when);
656            continue;
657        }
658        plan.push(refresh);
659    }
660    plan
661}
662
663pub(crate) fn controller_github_token() -> Option<String> {
664    for name in ["GH_TOKEN", "GITHUB_TOKEN"] {
665        if let Ok(token) = std::env::var(name)
666            && let Some(token) = usable_github_token(&token)
667        {
668            return Some(token.to_owned());
669        }
670    }
671    let output = match Command::new("gh")
672        .args(["auth", "token", "--hostname", "github.com"])
673        .stdin(Stdio::null())
674        .stderr(Stdio::null())
675        .output()
676    {
677        Ok(output) => output,
678        Err(error) => {
679            tracing::debug!(%error, "could not query the GitHub CLI for a token");
680            return None;
681        }
682    };
683    if !output.status.success() {
684        tracing::debug!(status = ?output.status, "GitHub CLI did not return an authenticated token");
685        return None;
686    }
687    let token = match std::str::from_utf8(&output.stdout) {
688        Ok(token) => token,
689        Err(error) => {
690            tracing::debug!(%error, "GitHub CLI returned a non-UTF-8 token");
691            return None;
692        }
693    };
694    let Some(token) = usable_github_token(token) else {
695        tracing::debug!("GitHub CLI returned an empty or invalid token");
696        return None;
697    };
698    Some(token.to_owned())
699}
700
701fn usable_github_token(token: &str) -> Option<&str> {
702    let token = token.trim();
703    (!token.is_empty() && !token.chars().any(char::is_whitespace)).then_some(token)
704}
705
706pub(super) fn configure_github_token_environment(target: &mut targets::TargetTemplate) -> bool {
707    let container = match target {
708        targets::TargetTemplate::LocalPodman(container)
709        | targets::TargetTemplate::LocalDocker(container)
710        | targets::TargetTemplate::AppleContainer(container)
711        | targets::TargetTemplate::SshPodman { container, .. }
712        | targets::TargetTemplate::SshDocker { container, .. } => container,
713        targets::TargetTemplate::LocalBare
714        | targets::TargetTemplate::AwsEc2(_)
715        | targets::TargetTemplate::SshBare { .. } => return false,
716    };
717    container
718        .extra_run_args
719        .extend(["--env".to_owned(), "GH_TOKEN".to_owned()]);
720    true
721}
722
723pub(super) fn use_github_https_urls(bundle: &mut targets::ProjectBundleSpec) {
724    for repository in &mut bundle.repositories {
725        for source in repository
726            .url
727            .iter_mut()
728            .chain(repository.push_urls.iter_mut())
729        {
730            if let Some(github) = crate::setup::github_repository_from_origin(source) {
731                *source = format!(
732                    "https://github.com/{}/{}.git",
733                    github.owner, github.repository
734                );
735            }
736        }
737    }
738}
739
740fn backend_container(
741    container: &mj_core::config::ContainerTemplate,
742    allocation: Option<&SessionResourceAllocation>,
743    overrides: ContainerOverrides<'_>,
744) -> ContainerTemplate {
745    let mut extra_run_args = Vec::new();
746    if let Some(platform) = &container.platform {
747        extra_run_args.push(format!("--platform={platform}"));
748    }
749    let (cpus, memory) = match allocation {
750        Some(SessionResourceAllocation::Container { cpus, memory_bytes }) => {
751            (Some(cpus.to_string()), Some(memory_bytes.to_string()))
752        }
753        _ => (container.cpus.clone(), container.memory.clone()),
754    };
755    // The session's own overrides are the last word on size.
756    let cpus = overrides.cpus.map(str::to_owned).or(cpus);
757    let memory = overrides.memory.map(str::to_owned).or(memory);
758    if let Some(cpus) = cpus {
759        extra_run_args.push(format!("--cpus={cpus}"));
760    }
761    if let Some(memory) = memory {
762        extra_run_args.push(format!("--memory={memory}"));
763    }
764    for (key, value) in &container.environment {
765        extra_run_args.extend(["--env".to_string(), format!("{key}={value}")]);
766    }
767    ContainerTemplate {
768        image: container.image.clone(),
769        pull_policy: container.pull_policy,
770        extra_run_args,
771        workspace_storage: targets::PodmanWorkspaceStorage::ContainerLayer,
772        build_cache: container.build_cache.clone(),
773    }
774}
775
776pub(super) fn validate_resource_allocation(
777    template: &TargetTemplate,
778    allocation: Option<&SessionResourceAllocation>,
779) -> Result<()> {
780    if let Some(allocation) = allocation {
781        allocation.validate()?;
782    }
783    match (template, allocation) {
784        (_, None)
785        | (
786            TargetTemplate::LocalPodman { .. }
787            | TargetTemplate::LocalDocker { .. }
788            | TargetTemplate::AppleContainer { .. }
789            | TargetTemplate::SshPodman { .. }
790            | TargetTemplate::SshDocker { .. },
791            Some(SessionResourceAllocation::Container { .. }),
792        )
793        | (TargetTemplate::AwsEc2 { .. }, Some(SessionResourceAllocation::AwsEc2 { .. })) => Ok(()),
794        (TargetTemplate::LocalBare | TargetTemplate::SshBare { .. }, Some(_)) => {
795            bail!("bare targets have fixed host resources")
796        }
797        _ => bail!("resource allocation does not match the selected target kind"),
798    }
799}
800
801/// How long a freshly launched EC2 instance may take to accept SSH.
802const AWS_SSH_READY_TIMEOUT: Duration = Duration::from_secs(300);
803
804const AWS_SSH_READY_RETRY_DELAY: Duration = Duration::from_secs(3);
805
806/// Poll a remote host until it accepts SSH, or until the deadline passes.
807///
808/// `now` and `sleep` are injected so tests can drive the deadline without
809/// waiting in real time.
810fn wait_for_ssh_ready(
811    executor: &impl CommandExecutor,
812    probe: &CommandSpec,
813    timeout: Duration,
814    mut now: impl FnMut() -> Instant,
815    mut sleep: impl FnMut(Duration),
816) -> Result<()> {
817    let started = now();
818    loop {
819        if executor.cancellation_requested() {
820            bail!("cancelled while waiting for SSH on the new instance");
821        }
822        let failure = match executor.execute(probe) {
823            Ok(output) if output.status == 0 => return Ok(()),
824            Ok(output) => String::from_utf8_lossy(&output.stderr).trim().to_string(),
825            Err(error) => error.to_string(),
826        };
827        if now().duration_since(started) >= timeout {
828            bail!(
829                "{} timed out after {}s: {}",
830                probe.purpose,
831                timeout.as_secs(),
832                if failure.is_empty() {
833                    "the SSH probe reported no error output"
834                } else {
835                    failure.as_str()
836                }
837            );
838        }
839        sleep(AWS_SSH_READY_RETRY_DELAY);
840    }
841}
842
843pub(super) fn locator_after_provision(
844    canonical: &TargetTemplate,
845    backend: &targets::TargetTemplate,
846    session_id: &str,
847    first_output: Option<&CommandOutput>,
848    executor: &(impl CommandExecutor + Sync),
849) -> Result<TargetLocator> {
850    let generated = targets::resource_name(session_id)?;
851    Ok(match canonical {
852        TargetTemplate::LocalBare => TargetLocator::LocalBare {
853            worker_root: data_dir().join("workers").join(session_id),
854        },
855        TargetTemplate::LocalPodman { .. } => {
856            let targets::TargetTemplate::LocalPodman(container) = backend else {
857                bail!("session locator/template mismatch")
858            };
859            TargetLocator::LocalPodman {
860                borrowed_from: None,
861                container_id: generated,
862                workspace_storage: PodmanWorkspaceLocator::from(targets::podman_workspace_locator(
863                    container, session_id,
864                )?),
865            }
866        }
867        TargetTemplate::LocalDocker { .. } => TargetLocator::LocalDocker {
868            borrowed_from: None,
869            container_id: generated,
870        },
871        TargetTemplate::AppleContainer { .. } => TargetLocator::AppleContainer {
872            borrowed_from: None,
873            container_id: generated,
874        },
875        TargetTemplate::SshBare { ssh, .. } => TargetLocator::SshBare {
876            host: ssh.host.clone(),
877            workspace: PathBuf::from(targets::workspace_for(backend, session_id)?),
878            worker_id: None,
879        },
880        TargetTemplate::SshPodman { ssh, .. } => {
881            let targets::TargetTemplate::SshPodman { container, .. } = backend else {
882                bail!("session locator/template mismatch")
883            };
884            TargetLocator::SshPodman {
885                borrowed_from: None,
886                host: ssh.host.clone(),
887                container_id: generated,
888                workspace_storage: PodmanWorkspaceLocator::from(targets::podman_workspace_locator(
889                    container, session_id,
890                )?),
891            }
892        }
893        TargetTemplate::SshDocker { ssh, .. } => TargetLocator::SshDocker {
894            borrowed_from: None,
895            host: ssh.host.clone(),
896            container_id: generated,
897        },
898        TargetTemplate::AwsEc2 {
899            aws_profile,
900            region,
901            ssh_user,
902            address_source,
903            identity_file,
904            ssh_args,
905            ..
906        } => {
907            let output = first_output.context("AWS launch produced no output")?;
908            let json: serde_json::Value = serde_json::from_slice(&output.stdout)
909                .context("parse aws ec2 run-instances response")?;
910            let instance_id = json
911                .pointer("/Instances/0/InstanceId")
912                .and_then(serde_json::Value::as_str)
913                .context("AWS response omitted instance ID")?
914                .to_string();
915            let profile = aws_profile.clone().unwrap_or_else(|| "default".into());
916            execute_checked(
917                executor,
918                CommandSpec::new(
919                    "aws",
920                    [
921                        "--profile".into(),
922                        profile.clone(),
923                        "--region".into(),
924                        region.clone(),
925                        "ec2".into(),
926                        "wait".into(),
927                        "instance-running".into(),
928                        "--instance-ids".into(),
929                        instance_id.clone(),
930                    ],
931                )
932                .purpose("wait for EC2 session instance to run")
933                .stage(ProvisionStage::Booting),
934            )?;
935            let field = match address_source {
936                AwsAddressSource::PublicDns => "PublicDnsName",
937                AwsAddressSource::PublicIp => "PublicIpAddress",
938                AwsAddressSource::PrivateDns => "PrivateDnsName",
939                AwsAddressSource::PrivateIp => "PrivateIpAddress",
940            };
941            let address = execute_checked(
942                executor,
943                CommandSpec::new(
944                    "aws",
945                    [
946                        "--profile".into(),
947                        profile.clone(),
948                        "--region".into(),
949                        region.clone(),
950                        "ec2".into(),
951                        "describe-instances".into(),
952                        "--instance-ids".into(),
953                        instance_id.clone(),
954                        "--query".into(),
955                        format!("Reservations[0].Instances[0].{field}"),
956                        "--output".into(),
957                        "text".into(),
958                    ],
959                )
960                .purpose("resolve EC2 session address")
961                .stage(ProvisionStage::Booting),
962            )?;
963            let address = String::from_utf8(address.stdout)
964                .context("AWS address was not UTF-8")?
965                .trim()
966                .to_string();
967            if address.is_empty() || address == "None" {
968                bail!("AWS instance {instance_id} has no configured address");
969            }
970            let ssh = SshTarget {
971                destination: format!("{ssh_user}@{address}"),
972                ssh_args: targets::ssh_args_with_identity(ssh_args, identity_file.as_deref()),
973            };
974            wait_for_ssh_ready(
975                executor,
976                &crate::targets::ssh_command(&ssh, ["true"])
977                    .purpose("wait for EC2 SSH availability")
978                    .stage(ProvisionStage::Booting),
979                AWS_SSH_READY_TIMEOUT,
980                Instant::now,
981                std::thread::sleep,
982            )?;
983            TargetLocator::AwsEc2 {
984                instance_id,
985                address: Some(address),
986            }
987        }
988    })
989}
990
991/// The execution-plan locator for a session's stored target.
992///
993/// The mapping itself lives in `mj_core::targets`; this only pairs the stored
994/// locator with the target template the session was created against.
995pub(super) fn backend_locator(
996    locator: &TargetLocator,
997    session: &SessionRecord,
998    config: &Config,
999) -> Result<targets::TargetLocator> {
1000    let template = config
1001        .targets
1002        .get(&session.target_template_id)
1003        .context("session target template is missing")?;
1004    Ok(targets::TargetLocator::try_from(targets::StoredTarget {
1005        locator,
1006        template,
1007        session_id: &session.id,
1008    })?)
1009}
1010
1011#[cfg(test)]
1012mod tests;