forked from Checkmk/csm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
284 lines (260 loc) · 10.6 KB
/
Copy pathmod.rs
File metadata and controls
284 lines (260 loc) · 10.6 KB
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
//! This module deals with `micromamba` - obtaining it, calling it, etc.
mod download;
pub mod result;
use crate::csmrc::Config;
use crate::micromamba::download::download_micromamba;
use crate::micromamba::result::MicromambaResult;
use log::{debug, error, info};
use serde::Deserialize;
use std::collections::HashMap;
use std::io;
use std::path::PathBuf;
use std::process::Command;
#[derive(Deserialize)]
pub struct MicromambaInfo {
#[serde(rename(deserialize = "env location"))]
pub env_location: String,
}
pub struct Micromamba<'a> {
config: &'a Config,
env_vars: HashMap<String, String>,
}
fn block_on_child_exit(child: &mut std::process::Child) -> MicromambaResult {
match child.wait() {
Ok(exit_status) => {
debug!("micromamba exited with status: {}", exit_status);
MicromambaResult::StreamedOutput(exit_status)
}
Err(e) => {
error!("We found a micromamba binary, but failed to wait for it to run");
error!("Error was: {}", e);
MicromambaResult::CouldNotRun
}
}
}
fn exec_micromamba(cmd: &mut Command, stream_output: bool) -> MicromambaResult {
let result = if stream_output {
match cmd.spawn() {
Ok(mut child) => block_on_child_exit(&mut child),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
debug!("Could not run micromamba at specified path: {}", e);
MicromambaResult::NotFound
}
Err(e) => {
error!("We found a micromamba binary, but failed to run it");
error!("Error was: {}", e);
MicromambaResult::CouldNotRun
}
}
} else {
match cmd.output() {
Ok(output) => MicromambaResult::CapturedOutput(output),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
debug!("Could not run micromamba at specified path: {}", e);
MicromambaResult::NotFound
}
Err(e) => {
error!("We found a micromamba binary, but failed to run it");
error!("Error was: {}", e);
MicromambaResult::CouldNotRun
}
}
};
if cfg!(windows)
&& result
.exit_status()
.and_then(|s| s.code())
.is_some_and(|s| s == 0xc0000135u32 as i32)
{
error!("Windows reported a missing DLL required to run micromamba");
error!("This error can very likely be solved by installing the VC++ runtime libraries");
error!(
"See https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170#latest-supported-redistributable-version for more information"
);
}
result
}
impl<'a> Micromamba<'a> {
pub fn new(config: &'a Config) -> Self {
let mut micromamba = Self {
config,
env_vars: HashMap::new(),
};
if let Some(mamba_root_prefix) = &config.mamba_root_prefix {
micromamba.set_env_var("MAMBA_ROOT_PREFIX", mamba_root_prefix);
}
micromamba
}
/// Helper method to insert environment variables with &str for convenience
pub fn set_env_var(&mut self, key: &str, value: &str) {
self.env_vars.insert(key.to_string(), value.to_string());
}
/// Return a [`Command`] ready to shell out to `micromamba` with the appropriate
/// environment variables set based on configuration.
fn micromamba_at(&self, path: &str, args: &Vec<&str>) -> Command {
// On Windows, the env vars don't get shown by the Debug instance for
// Command, so print them ourselves (always, to make testing easier).
debug!(
"Running command with these environment variables: {:?}",
self.env_vars
);
let mut cmd = Command::new(path);
cmd.args(args);
cmd.envs(&self.env_vars);
if self.config.noop_mode {
info!("Would run: {:?}", cmd);
} else {
debug!("About to run: {:?}", cmd);
}
cmd
}
/// Execute micromamba and stream the output to the console.
///
/// Standard input is inherited from the calling console.
pub fn stream(&self, args: Vec<&str>) -> MicromambaResult {
self.micromamba(args, true)
}
/// Execute micromamba and capture the output, to be displayed in the event
/// of an error.
///
/// Standard input is dropped.
pub fn capture(&self, args: Vec<&str>) -> MicromambaResult {
self.micromamba(args, false)
}
/// Execute micromamba and stream the output if we are running in verbose mode.
/// Otherwise, capture the output to be displayed in the event of an error.
pub fn stream_if_verbose(&self, args: Vec<&str>) -> MicromambaResult {
if self.config.verbose {
self.micromamba(args, true)
} else {
self.micromamba(args, false)
}
}
/// Run `micromamba` and return the result, if able.
///
/// We need a `micromamba` binary to work with. If one is not present, attempt
/// to download and install `micromamba` into the user's cache directory.
///
/// 1. If there is already a `micromamba` command in $PATH, we use it.
/// 2. Otherwise, download micromamba and install it somewhere in the user
/// cache directory. (We cannot rely on this - it could be that the user's
/// cache directory is mounted noexec or similar, but we try.)
///
/// Alternative approaches that we do not take here currently:
/// - On Linux, we *could* in theory use memfd_create + fexecve to embed the app
/// and run it from memory. This won't work on Windows.
///
/// - We *could* embed the micromamba binary in our binary (Windows or Linux
/// based on compile target) and write it to the user cache directory rather
/// than downloading it. But this inflates our binary size.
fn micromamba(&self, args: Vec<&str>, stream_output: bool) -> MicromambaResult {
let mut cmd = self.micromamba_at("micromamba", &args);
if self.config.noop_mode {
// Do nothing. micromamba_at() already logged what we're about to run.
return MicromambaResult::Noop;
}
// If we were able to get a result using micromamba found in $PATH, then
// we're done.
match exec_micromamba(&mut cmd, stream_output) {
ok @ (MicromambaResult::StreamedOutput(_) | MicromambaResult::CapturedOutput(_)) => {
debug!("Ran micromamba found in $PATH");
return ok;
}
MicromambaResult::CouldNotRun => {
// In this case, bail out and let the user fix their micromamba
// installation.
debug!("micromamba found in $PATH could not be run, aborting");
return MicromambaResult::CouldNotRun;
}
_ => {}
}
// If we weren't successful there, we download micromamba to the user cache
// directory.
debug!("micromamba not found in $PATH, falling back to cache");
let downloaded_path = match download_micromamba(self.config) {
Ok(path) => path,
Err(e) => {
error!("Could not download micromamba: {}", e);
return MicromambaResult::CouldNotRun;
}
};
let mut cmd = self.micromamba_at(&downloaded_path.to_string_lossy(), &args);
match exec_micromamba(&mut cmd, stream_output) {
ok @ (MicromambaResult::StreamedOutput(_) | MicromambaResult::CapturedOutput(_)) => {
debug!(
"Ran downloaded/cached micromamba at {}",
downloaded_path.display()
);
return ok;
}
MicromambaResult::CouldNotRun => {
debug!(
"Downloaded micromamba at {} could not be run",
downloaded_path.display()
);
}
_ => {}
}
// Finally, if we couldn't run the downloaded one either, just bail out
error!("Could not find a suitable micromamba binary to run");
error!(
"Please install micromamba manually, ensure it is executable, and place it somewhere in $PATH"
);
MicromambaResult::CouldNotRun
}
/// Query micromamba to try to determine the path for an environment
pub fn path_for_env(&self, name: &str) -> Option<PathBuf> {
if self.config.noop_mode {
return Some(PathBuf::from("/no-op/mode/path/for/env"));
}
let result = self.capture(vec!["info", "--name", name, "--json"]);
let MicromambaResult::CapturedOutput(output) = result else {
return None;
};
let stdout = String::from_utf8_lossy(&output.stdout);
let info: MicromambaInfo = serde_json::from_str(&stdout).ok()?;
Some(info.env_location.into())
}
/// Return an OS-specific path to where micromamba stores (most?) binaries.
pub fn bin_path_for_env(&self, name: &str) -> Option<PathBuf> {
let os_specific_bin = if cfg!(windows) { "Scripts" } else { "bin" };
self.path_for_env(name).map(|p| p.join(os_specific_bin))
}
/// Create a directory for a new environment, if it does not already exist.
///
/// If `force` is true, delete any pre-existing environment/directory at this path.
pub fn create_env_dir(&self, name: &str, force: bool) -> Result<PathBuf, std::io::Error> {
if self.config.noop_mode {
info!("Using fake directory path due to no-op mode");
return Ok(PathBuf::from("/no-op/mode/path/for/env"));
}
let env_path = match self.path_for_env(name) {
Some(path) => path,
None => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("Could not determine path for environment '{}'", name),
));
}
};
if env_path.exists() {
if force {
debug!(
"Removing pre-existing directory at '{}'",
env_path.display()
);
std::fs::remove_dir_all(&env_path)?;
} else {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!(
"The target environment directory '{}' already exists",
env_path.display()
),
));
}
}
std::fs::create_dir_all(&env_path)?;
Ok(env_path)
}
}