rusty-stack 0.3.0

A comprehensive ML environment installer and platform toolkit optimized for AMD GPUs with ROCm support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! MPI4Py installer — ports `scripts/install_mpi4py.sh`.
//!
//! Detects system MPI implementation, constructs pip install with correct
//! MPICC/MPICXX environment variables.
//!
//! # Validation Assertion
//!
//! - **VAL-INSTALL-005**: MPI4Py installer detects system MPI

use crate::installers::common::{command_exists, DistroFacade};
use std::fmt;
use std::path::PathBuf;

// ===========================================================================
// Types
// ===========================================================================

/// Detected MPI implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MpiImplementation {
    /// OpenMPI (most common).
    OpenMPI,
    /// MPICH.
    MPICH,
    /// Intel MPI.
    IntelMPI,
    /// No MPI detected.
    None,
}

impl fmt::Display for MpiImplementation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MpiImplementation::OpenMPI => write!(f, "OpenMPI"),
            MpiImplementation::MPICH => write!(f, "MPICH"),
            MpiImplementation::IntelMPI => write!(f, "IntelMPI"),
            MpiImplementation::None => write!(f, "None"),
        }
    }
}

/// Configuration for the MPI4Py installer.
#[derive(Debug, Clone)]
pub struct Mpi4PyConfig {
    /// Python binary to use.
    pub python_bin: String,
    /// Whether to force reinstall.
    pub force_reinstall: bool,
    /// Whether to run in dry-run mode.
    pub dry_run: bool,
    /// Whether ROCm is enabled.
    pub rocm_enabled: bool,
}

impl Default for Mpi4PyConfig {
    fn default() -> Self {
        Self {
            python_bin: "python3".to_string(),
            force_reinstall: false,
            dry_run: false,
            rocm_enabled: true,
        }
    }
}

/// A constructed shell command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellCommand {
    /// The program to run.
    pub program: String,
    /// Arguments to pass.
    pub args: Vec<String>,
    /// Environment variables to set.
    pub env: Vec<(String, String)>,
}

impl ShellCommand {
    /// Format as a shell command string.
    pub fn to_command_string(&self) -> String {
        let env_prefix = self
            .env
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect::<Vec<_>>()
            .join(" ");
        let cmd = if self.args.is_empty() {
            self.program.clone()
        } else {
            format!("{} {}", self.program, self.args.join(" "))
        };
        if env_prefix.is_empty() {
            cmd
        } else {
            format!("{env_prefix} {cmd}")
        }
    }
}

/// The MPI4Py installer.
pub struct Mpi4PyInstaller {
    config: Mpi4PyConfig,
}

impl Mpi4PyInstaller {
    /// Create a new MPI4Py installer with the given config.
    pub fn new(config: Mpi4PyConfig) -> Self {
        Self { config }
    }

    /// Create with default config.
    pub fn with_defaults() -> Self {
        Self::new(Mpi4PyConfig::default())
    }

    // -----------------------------------------------------------------------
    // MPI detection (VAL-INSTALL-005)
    // -----------------------------------------------------------------------

    /// Detect the MPI implementation on the system.
    ///
    /// Checks for mpirun/mpiexec and identifies the implementation.
    pub fn detect_mpi(&self) -> MpiImplementation {
        if command_exists("mpirun") || command_exists("mpiexec") {
            // Try to identify which MPI
            if self.is_openmpi() {
                MpiImplementation::OpenMPI
            } else if self.is_mpich() {
                MpiImplementation::MPICH
            } else {
                // Default to OpenMPI if we can't determine
                MpiImplementation::OpenMPI
            }
        } else {
            MpiImplementation::None
        }
    }

    /// Check if the detected MPI is OpenMPI.
    fn is_openmpi(&self) -> bool {
        // Check for ompi_info which is OpenMPI-specific
        command_exists("ompi_info")
            || std::path::Path::new("/usr/lib/x86_64-linux-gnu/openmpi").exists()
            || std::path::Path::new("/usr/lib64/openmpi").exists()
    }

    /// Check if the detected MPI is MPICH.
    fn is_mpich(&self) -> bool {
        command_exists("mpichversion")
            || std::path::Path::new("/usr/lib/x86_64-linux-gnu/mpich").exists()
    }

    /// Detect the MPI installation path.
    ///
    /// Checks common paths in order:
    /// 1. /usr/lib64/openmpi
    /// 2. /opt/openmpi
    /// 3. /usr/lib/openmpi
    /// 4. Derived from mpirun location
    pub fn detect_mpi_path(&self) -> PathBuf {
        let candidates = [
            "/usr/lib64/openmpi",
            "/opt/openmpi",
            "/usr/local/openmpi",
            "/usr/lib/openmpi",
        ];

        for path_str in &candidates {
            let path = PathBuf::from(path_str);
            if path.join("bin/mpirun").exists() || path.join("bin").exists() {
                return path;
            }
        }

        // Try to derive from mpirun location
        if let Ok(output) = std::process::Command::new("which").arg("mpirun").output() {
            if output.status.success() {
                let mpirun = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if !mpirun.is_empty() {
                    if let Some(parent) = PathBuf::from(&mpirun).parent() {
                        if let Some(grandparent) = parent.parent() {
                            return grandparent.to_path_buf();
                        }
                    }
                }
            }
        }

        PathBuf::from("/usr/lib64/openmpi")
    }

    // -----------------------------------------------------------------------
    // System MPI package installation
    // -----------------------------------------------------------------------

    /// Construct the system package install command for MPI.
    ///
    /// Returns the correct command based on distro family:
    /// - apt: `sudo apt-get install -y libopenmpi-dev openmpi-bin`
    /// - dnf: `sudo dnf install -y openmpi openmpi-devel`
    /// - pacman: `sudo pacman -S --noconfirm openmpi`
    /// - zypper: `sudo zypper install -y openmpi openmpi-devel`
    pub fn build_system_mpi_install_command(&self, distro: &DistroFacade) -> ShellCommand {
        if distro.uses_apt() {
            ShellCommand {
                program: "sudo".to_string(),
                args: vec![
                    "apt-get".to_string(),
                    "update".to_string(),
                    "&&".to_string(),
                    "sudo".to_string(),
                    "apt-get".to_string(),
                    "install".to_string(),
                    "-y".to_string(),
                    "libopenmpi-dev".to_string(),
                    "openmpi-bin".to_string(),
                ],
                env: vec![],
            }
        } else if distro.uses_dnf() {
            ShellCommand {
                program: "sudo".to_string(),
                args: vec![
                    "dnf".to_string(),
                    "install".to_string(),
                    "-y".to_string(),
                    "openmpi".to_string(),
                    "openmpi-devel".to_string(),
                ],
                env: vec![],
            }
        } else if distro.uses_yum() {
            ShellCommand {
                program: "sudo".to_string(),
                args: vec![
                    "yum".to_string(),
                    "install".to_string(),
                    "-y".to_string(),
                    "openmpi".to_string(),
                    "openmpi-devel".to_string(),
                ],
                env: vec![],
            }
        } else if distro.uses_pacman() {
            ShellCommand {
                program: "sudo".to_string(),
                args: vec![
                    "pacman".to_string(),
                    "-S".to_string(),
                    "--noconfirm".to_string(),
                    "openmpi".to_string(),
                ],
                env: vec![],
            }
        } else if distro.uses_zypper() {
            ShellCommand {
                program: "sudo".to_string(),
                args: vec![
                    "zypper".to_string(),
                    "install".to_string(),
                    "-y".to_string(),
                    "openmpi".to_string(),
                    "openmpi-devel".to_string(),
                ],
                env: vec![],
            }
        } else {
            ShellCommand {
                program: "sudo".to_string(),
                args: vec![
                    "apt-get".to_string(),
                    "update".to_string(),
                    "&&".to_string(),
                    "sudo".to_string(),
                    "apt-get".to_string(),
                    "install".to_string(),
                    "-y".to_string(),
                    "libopenmpi-dev".to_string(),
                    "openmpi-bin".to_string(),
                ],
                env: vec![],
            }
        }
    }

    // -----------------------------------------------------------------------
    // mpi4py pip install command
    // -----------------------------------------------------------------------

    /// Construct the pip install command for mpi4py with correct env vars.
    ///
    /// Sets MPICC and MPICXX environment variables pointing to the MPI
    /// installation's compiler wrappers.
    pub fn build_pip_install_command(&self, mpi_path: &std::path::Path) -> ShellCommand {
        let mpicc = mpi_path.join("bin/mpicc");
        let mpicxx = mpi_path.join("bin/mpicxx");

        let env = vec![
            ("MPICC".to_string(), mpicc.to_string_lossy().to_string()),
            ("MPICXX".to_string(), mpicxx.to_string_lossy().to_string()),
            (
                "PATH".to_string(),
                format!(
                    "{}:{}",
                    mpi_path.join("bin").to_string_lossy(),
                    std::env::var("PATH").unwrap_or_default()
                ),
            ),
            (
                "LD_LIBRARY_PATH".to_string(),
                format!(
                    "{}:{}",
                    mpi_path.join("lib").to_string_lossy(),
                    std::env::var("LD_LIBRARY_PATH").unwrap_or_default()
                ),
            ),
        ];

        let mut args = vec![
            "-m".to_string(),
            "pip".to_string(),
            "install".to_string(),
            "--break-system-packages".to_string(),
        ];
        if self.config.force_reinstall {
            args.push("--force-reinstall".to_string());
        }
        args.push("mpi4py".to_string());

        ShellCommand {
            program: self.config.python_bin.clone(),
            args,
            env,
        }
    }

    /// Construct the ROCm environment exports for MPI.
    pub fn rocm_env_exports(&self) -> Vec<(String, String)> {
        if self.config.rocm_enabled {
            vec![
                ("HSA_OVERRIDE_GFX_VERSION".to_string(), "11.0.0".to_string()),
                ("PYTORCH_ROCM_ARCH".to_string(), "gfx1100".to_string()),
                ("ROCM_PATH".to_string(), "/opt/rocm".to_string()),
            ]
        } else {
            vec![]
        }
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::platform::detection::{DistroFamily, DistroInfo, PackageManager};

    fn ubuntu_distro() -> DistroFacade {
        DistroFacade::from_info(DistroInfo {
            id: "ubuntu".to_string(),
            name: "Ubuntu 24.04".to_string(),
            version: "24.04".to_string(),
            codename: "noble".to_string(),
            family: DistroFamily::Debian,
            pkg_manager: PackageManager::Apt,
            id_like: "debian".to_string(),
        })
    }

    fn fedora_distro() -> DistroFacade {
        DistroFacade::from_info(DistroInfo {
            id: "fedora".to_string(),
            name: "Fedora 41".to_string(),
            version: "41".to_string(),
            codename: String::new(),
            family: DistroFamily::Rhel,
            pkg_manager: PackageManager::Dnf,
            id_like: "fedora".to_string(),
        })
    }

    fn arch_distro() -> DistroFacade {
        DistroFacade::from_info(DistroInfo {
            id: "arch".to_string(),
            name: "Arch Linux".to_string(),
            version: "rolling".to_string(),
            codename: String::new(),
            family: DistroFamily::Arch,
            pkg_manager: PackageManager::Pacman,
            id_like: "arch".to_string(),
        })
    }

    // --- VAL-INSTALL-005: MPI4Py installer detects system MPI ---

    #[test]
    fn test_detect_mpi() {
        let installer = Mpi4PyInstaller::with_defaults();
        // Just verify it doesn't panic
        let mpi = installer.detect_mpi();
        // On this system, it may or may not have MPI
        assert!(matches!(
            mpi,
            MpiImplementation::OpenMPI | MpiImplementation::MPICH | MpiImplementation::None
        ));
    }

    #[test]
    fn test_detect_mpi_path() {
        let installer = Mpi4PyInstaller::with_defaults();
        let path = installer.detect_mpi_path();
        // Should return a path, even if it's the default
        assert!(!path.to_string_lossy().is_empty());
    }

    #[test]
    fn test_system_mpi_install_apt() {
        let installer = Mpi4PyInstaller::with_defaults();
        let distro = ubuntu_distro();
        let cmd = installer.build_system_mpi_install_command(&distro);
        assert!(cmd.args.contains(&"libopenmpi-dev".to_string()));
        assert!(cmd.args.contains(&"openmpi-bin".to_string()));
    }

    #[test]
    fn test_system_mpi_install_dnf() {
        let installer = Mpi4PyInstaller::with_defaults();
        let distro = fedora_distro();
        let cmd = installer.build_system_mpi_install_command(&distro);
        assert!(cmd.args.contains(&"openmpi".to_string()));
        assert!(cmd.args.contains(&"openmpi-devel".to_string()));
    }

    #[test]
    fn test_system_mpi_install_pacman() {
        let installer = Mpi4PyInstaller::with_defaults();
        let distro = arch_distro();
        let cmd = installer.build_system_mpi_install_command(&distro);
        assert!(cmd.args.contains(&"openmpi".to_string()));
        assert!(cmd.args.contains(&"--noconfirm".to_string()));
    }

    #[test]
    fn test_pip_install_command() {
        let installer = Mpi4PyInstaller::with_defaults();
        let mpi_path = PathBuf::from("/usr/lib64/openmpi");
        let cmd = installer.build_pip_install_command(&mpi_path);

        assert_eq!(cmd.program, "python3");
        assert!(cmd.args.contains(&"mpi4py".to_string()));
        assert!(cmd.args.contains(&"--break-system-packages".to_string()));

        // Verify MPICC/MPICXX env vars
        assert!(cmd
            .env
            .iter()
            .any(|(k, v)| k == "MPICC" && v.contains("mpicc")));
        assert!(cmd
            .env
            .iter()
            .any(|(k, v)| k == "MPICXX" && v.contains("mpicxx")));
        assert!(cmd
            .env
            .iter()
            .any(|(k, v)| k == "PATH" && v.contains("openmpi/bin")));
    }

    #[test]
    fn test_pip_install_command_force_reinstall() {
        let installer = Mpi4PyInstaller::new(Mpi4PyConfig {
            force_reinstall: true,
            ..Default::default()
        });
        let mpi_path = PathBuf::from("/usr/lib64/openmpi");
        let cmd = installer.build_pip_install_command(&mpi_path);
        assert!(cmd.args.contains(&"--force-reinstall".to_string()));
    }

    #[test]
    fn test_rocm_env_exports_enabled() {
        let installer = Mpi4PyInstaller::new(Mpi4PyConfig {
            rocm_enabled: true,
            ..Default::default()
        });
        let exports = installer.rocm_env_exports();
        assert!(exports.iter().any(|(k, _)| k == "HSA_OVERRIDE_GFX_VERSION"));
        assert!(exports.iter().any(|(k, _)| k == "ROCM_PATH"));
    }

    #[test]
    fn test_rocm_env_exports_disabled() {
        let installer = Mpi4PyInstaller::new(Mpi4PyConfig {
            rocm_enabled: false,
            ..Default::default()
        });
        let exports = installer.rocm_env_exports();
        assert!(exports.is_empty());
    }

    #[test]
    fn test_mpi_implementation_display() {
        assert_eq!(format!("{}", MpiImplementation::OpenMPI), "OpenMPI");
        assert_eq!(format!("{}", MpiImplementation::MPICH), "MPICH");
        assert_eq!(format!("{}", MpiImplementation::None), "None");
    }
}