Skip to main content

elemental_core/runtime/
distribution.rs

1use std::collections::HashSet;
2use std::env::consts::EXE_SUFFIX;
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use futures::future::join_all;
7use futures::stream::{self, StreamExt};
8use tokio::fs;
9use tokio::process::Command;
10
11use crate::runtime::{
12    RuntimeValidationMode,
13    error::{Error, Result},
14    provider::RuntimeProvider,
15};
16
17const JAVA_INFO_PROBE_TIMEOUT: Duration = Duration::from_secs(15);
18const JAVA_INFO_PROBE_CONCURRENCY: usize = 8;
19const JAVA_PROBE_ENV_VARIABLES: &[&str] = &[
20    "JAVA_HOME",
21    "JRE_HOME",
22    "JAVA_ARGS",
23    "CLASSPATH",
24    "JAVA_TOOL_OPTIONS",
25    "_JAVA_OPTIONS",
26    "JAVA_OPTIONS",
27    "JDK_JAVA_OPTIONS",
28];
29
30#[derive(Debug, Default, Clone)]
31pub struct DistributionReleaseData {
32    /// java.vm.vendor e.g. Eclipse Adoptium
33    pub implementor: Option<String>,
34    //? impl version may need ?
35    /// os.arch e.g. x86_64
36    pub architecture: Option<String>,
37    /// java.specification.version e.g. 1.8
38    pub major_version: Option<String>,
39    /// java.version e.g. 1.8.0_452
40    pub jre_version: Option<String>,
41    /// java.vm.version e.g. 24.0.1+9
42    pub jvm_version: Option<String>,
43}
44
45#[derive(Debug, Clone)]
46pub struct Distribution {
47    // Release Data (when available)
48    release: Option<DistributionReleaseData>,
49
50    // Physical Data
51    /// Path to the runtime installation
52    path: PathBuf,
53
54    // Discovery Data
55    /// Elemental Provider used to discover this runtime
56    provider: &'static str,
57}
58
59impl DistributionReleaseData {
60    pub fn java_major_version(&self) -> Option<usize> {
61        self.major_version
62            .as_deref()
63            .and_then(Self::parse_java_major_version)
64    }
65
66    pub fn matches_java_major_version(&self, major_version: usize) -> bool {
67        self.java_major_version()
68            .is_some_and(|current| current == major_version)
69    }
70
71    pub async fn parse_from_commandline(root: &Path) -> Result<Self> {
72        let java_exe = root.join("bin").join(format!("java{EXE_SUFFIX}"));
73        let mut command = Command::new(&java_exe);
74        command.arg("-XshowSettings:properties").kill_on_drop(true);
75        for variable_name in JAVA_PROBE_ENV_VARIABLES {
76            command.env_remove(variable_name);
77        }
78
79        let output = tokio::time::timeout(JAVA_INFO_PROBE_TIMEOUT, command.output())
80            .await
81            .map_err(|_| Error::ProbeTimeout {
82                executable: java_exe.clone(),
83                timeout_secs: JAVA_INFO_PROBE_TIMEOUT.as_secs(),
84            })?
85            .map_err(|source| Error::ProbeSpawn {
86                executable: java_exe.clone(),
87                source,
88            })?;
89
90        if !output.status.success() {
91            return Err(Error::ProbeFailed {
92                executable: java_exe,
93                status: output.status,
94            });
95        }
96
97        let release = Self::parse_properties(&String::from_utf8_lossy(&output.stderr));
98        if release.java_major_version().is_none() {
99            return Err(Error::ProbeMissingVersion {
100                executable: java_exe,
101            });
102        }
103
104        Ok(release)
105    }
106
107    pub async fn parse_from_release(root: &Path) -> Result<Self> {
108        let release_path = root.join("release");
109        let content =
110            fs::read_to_string(&release_path)
111                .await
112                .map_err(|source| Error::ReadRelease {
113                    path: release_path.clone(),
114                    source,
115                })?;
116        let release = Self::parse_release_properties(&content);
117        if release.java_major_version().is_none() {
118            return Err(Error::ReleaseMissingVersion { path: release_path });
119        }
120
121        Ok(release)
122    }
123
124    pub async fn parse(root: &Path) -> Result<Self> {
125        let release_path = root.join("release");
126        let release_exists =
127            fs::try_exists(&release_path)
128                .await
129                .map_err(|source| Error::CheckRelease {
130                    path: release_path.clone(),
131                    source,
132                })?;
133
134        if release_exists {
135            Self::parse_from_release(root).await
136        } else {
137            Self::parse_from_commandline(root).await
138        }
139    }
140
141    pub fn is_lts(&self) -> bool {
142        self.major_version
143            .as_deref()
144            .and_then(Self::parse_java_major_version)
145            .is_some_and(|version| matches!(version, 8 | 11 | 17 | 21))
146    }
147
148    fn parse_properties(output: &str) -> Self {
149        let mut implementor = None;
150        let mut architecture = None;
151        let mut major_version = None;
152        let mut jre_version = None;
153        let mut jvm_version = None;
154
155        for (key, value) in Self::property_pairs(output) {
156            match key {
157                "java.vm.vendor" => implementor = Some(value.to_string()),
158                "os.arch" => architecture = Some(value.to_string()),
159                "java.specification.version" => major_version = Some(value.to_string()),
160                "java.version" => jre_version = Some(value.to_string()),
161                "java.vm.version" => jvm_version = Some(value.to_string()),
162                _ => {}
163            }
164        }
165
166        Self {
167            implementor,
168            architecture,
169            major_version,
170            jre_version,
171            jvm_version,
172        }
173    }
174
175    fn parse_release_properties(output: &str) -> Self {
176        let mut implementor = None;
177        let mut architecture = None;
178        let mut major_version = None;
179        let mut jre_version = None;
180        let mut jvm_version = None;
181
182        for (key, value) in Self::property_pairs(output) {
183            let value = value.trim_matches('"');
184            match key {
185                "IMPLEMENTOR" => implementor = Some(value.to_string()),
186                "OS_ARCH" => architecture = Some(value.to_string()),
187                "JAVA_VERSION" => jre_version = Some(value.to_string()),
188                "JAVA_RUNTIME_VERSION" => jvm_version = Some(value.to_string()),
189                _ => {}
190            }
191        }
192
193        // Extract major version from jre_version
194        if let Some(ref ver) = jre_version {
195            major_version = Self::parse_java_major_version(ver).map(|value| value.to_string());
196        }
197
198        Self {
199            implementor,
200            architecture,
201            major_version,
202            jre_version,
203            jvm_version,
204        }
205    }
206
207    fn property_pairs(output: &str) -> impl Iterator<Item = (&str, &str)> {
208        output.lines().filter_map(|line| {
209            let (key, value) = line.trim().split_once('=')?;
210            Some((key.trim(), value.trim()))
211        })
212    }
213
214    fn parse_java_major_version(version: &str) -> Option<usize> {
215        let normalized = version.trim();
216        if let Some(legacy) = normalized.strip_prefix("1.") {
217            return legacy
218                .split(['.', '_', '-'])
219                .next()
220                .and_then(|value| value.parse::<usize>().ok());
221        }
222
223        normalized
224            .split(['.', '_', '-'])
225            .next()
226            .and_then(|value| value.parse::<usize>().ok())
227    }
228}
229
230impl Distribution {
231    pub(crate) async fn build_from_root(root: PathBuf, provider: &'static str) -> Result<Self> {
232        let requested_root = root.clone();
233        let root =
234            fs::canonicalize(&root)
235                .await
236                .map_err(|source| Error::CanonicalizeRuntimeRoot {
237                    path: root.clone(),
238                    source,
239                })?;
240        let release = DistributionReleaseData::parse(&root)
241            .await
242            .map_err(|source| Error::DetermineRuntimeProperties {
243                path: requested_root,
244                source: Box::new(source),
245            })?;
246
247        Ok(Self {
248            release: Some(release),
249            path: root,
250            provider,
251        })
252    }
253
254    pub async fn from_providers<O>(providers: Vec<std::sync::Arc<dyn RuntimeProvider>>) -> O
255    where
256        O: FromIterator<Self>,
257    {
258        let provider_lists = join_all(
259            providers
260                .into_iter()
261                .map(|provider| async move { (provider.name(), provider.list().await) }),
262        )
263        .await;
264
265        let mut probes = Vec::new();
266        for (name, paths) in provider_lists {
267            for path in paths {
268                let candidate_path = path.clone();
269                probes.push(async move {
270                    Distribution::build_from_root(path, name)
271                        .await
272                        .map_err(|source| Error::BuildDistribution {
273                            provider: name,
274                            path: candidate_path,
275                            source: Box::new(source),
276                        })
277                });
278            }
279        }
280
281        let distributions: Vec<Self> = stream::iter(probes)
282            .buffer_unordered(JAVA_INFO_PROBE_CONCURRENCY)
283            .filter_map(|result| async move {
284                match result {
285                    Ok(distribution) => Some(distribution),
286                    Err(error) => {
287                        tracing::warn!(%error, "skip invalid Java runtime candidate");
288                        None
289                    }
290                }
291            })
292            .collect()
293            .await;
294
295        let mut seen_paths = HashSet::with_capacity(distributions.len());
296        let mut unique_distributions: Vec<Self> = distributions
297            .into_iter()
298            .filter(|distribution| seen_paths.insert(distribution.path.clone()))
299            .collect();
300        unique_distributions.sort_by(ordering::compare_distributions);
301        unique_distributions.into_iter().collect()
302    }
303
304    pub fn matches_java_major_version(&self, major_version: usize) -> bool {
305        self.release
306            .as_ref()
307            .is_some_and(|release| release.matches_java_major_version(major_version))
308    }
309
310    pub fn java_major_version(&self) -> Option<usize> {
311        self.release
312            .as_ref()
313            .and_then(DistributionReleaseData::java_major_version)
314    }
315
316    pub fn release(&self) -> Option<&DistributionReleaseData> {
317        self.release.as_ref()
318    }
319
320    pub fn path(&self) -> &Path {
321        &self.path
322    }
323
324    pub fn provider(&self) -> &'static str {
325        self.provider
326    }
327
328    pub fn executable(&self) -> PathBuf {
329        self.path.join("bin").join(format!("java{EXE_SUFFIX}"))
330    }
331
332    pub fn require_compatible(
333        &self,
334        required_major_version: usize,
335        validation_mode: RuntimeValidationMode,
336    ) -> Result<()> {
337        if validation_mode == RuntimeValidationMode::Disabled {
338            return Ok(());
339        }
340
341        let actual_major_version =
342            self.java_major_version()
343                .ok_or_else(|| Error::RuntimeVersionUnknown {
344                    path: self.path.clone(),
345                })?;
346        if actual_major_version != required_major_version {
347            return Err(Error::VersionMismatch {
348                actual: actual_major_version,
349                expected: required_major_version,
350                path: self.path.clone(),
351            });
352        }
353
354        Ok(())
355    }
356}
357
358mod ordering {
359    use std::cmp::Ordering;
360
361    use super::Distribution;
362
363    pub(super) fn compare_distributions(left: &Distribution, right: &Distribution) -> Ordering {
364        let left_version = left
365            .release
366            .as_ref()
367            .and_then(|release| release.jre_version.as_deref());
368        let right_version = right
369            .release
370            .as_ref()
371            .and_then(|release| release.jre_version.as_deref());
372
373        right
374            .java_major_version()
375            .cmp(&left.java_major_version())
376            .then_with(|| compare_release_versions(right_version, left_version))
377            .then_with(|| left.path.cmp(&right.path))
378    }
379
380    fn compare_release_versions(left: Option<&str>, right: Option<&str>) -> Ordering {
381        match (left, right) {
382            (Some(left), Some(right)) => {
383                let mut left_components = version_components(left).peekable();
384                let mut right_components = version_components(right).peekable();
385                if left_components.peek().is_none() || right_components.peek().is_none() {
386                    left.cmp(right)
387                } else {
388                    left_components.cmp(right_components)
389                }
390            }
391            (Some(_), None) => Ordering::Greater,
392            (None, Some(_)) => Ordering::Less,
393            (None, None) => Ordering::Equal,
394        }
395    }
396
397    fn version_components(version: &str) -> impl Iterator<Item = u64> + '_ {
398        version
399            .split(|character: char| !character.is_ascii_digit())
400            .filter(|component| !component.is_empty())
401            .filter_map(|component| component.parse::<u64>().ok())
402    }
403}
404
405#[tokio::test]
406async fn default_providers_return_deduplicated_distributions_sorted_by_major_version() {
407    use super::provider::default_providers;
408
409    let distributions: Vec<_> = Distribution::from_providers(default_providers()).await;
410    let mut paths: Vec<_> = distributions
411        .iter()
412        .map(|distribution| distribution.path.clone())
413        .collect();
414    let path_count = paths.len();
415    paths.sort();
416    paths.dedup();
417
418    assert_eq!(paths.len(), path_count);
419    assert!(
420        distributions
421            .iter()
422            .all(|distribution| distribution.java_major_version().is_some())
423    );
424    assert!(
425        distributions
426            .windows(2)
427            .all(|pair| { pair[0].java_major_version() >= pair[1].java_major_version() })
428    );
429    println!("{:#?}", distributions);
430}
431
432#[test]
433fn parse_properties_uses_exact_keys_and_unquotes_release_values() {
434    let diagnostic = r#"
435        java.vm.vendor = Eclipse Adoptium
436        os.arch = amd64
437        java.specification.version = 21
438        java.version = 21.0.5
439        java.version.date = 2024-10-15
440        java.vm.version = 21.0.5+11-LTS
441    "#;
442    let release = DistributionReleaseData::parse_properties(diagnostic);
443    assert_eq!(release.jre_version.as_deref(), Some("21.0.5"));
444    assert_eq!(release.jvm_version.as_deref(), Some("21.0.5+11-LTS"));
445    assert_eq!(release.java_major_version(), Some(21));
446
447    let release_file = r#"
448        IMPLEMENTOR="Eclipse Adoptium"
449        OS_ARCH="x86_64"
450        JAVA_VERSION="1.8.0_452"
451        JAVA_VERSION_DATE="2025-01-21"
452        JAVA_RUNTIME_VERSION="1.8.0_452-b09"
453    "#;
454    let release = DistributionReleaseData::parse_release_properties(release_file);
455    assert_eq!(release.implementor.as_deref(), Some("Eclipse Adoptium"));
456    assert_eq!(release.jre_version.as_deref(), Some("1.8.0_452"));
457    assert_eq!(release.java_major_version(), Some(8));
458}