Skip to main content

zombienet_provider/shared/
helpers.rs

1use std::{
2    env,
3    path::{Path, PathBuf},
4};
5
6use anyhow::anyhow;
7use support::fs::FileSystem;
8use tracing::warn;
9
10use crate::{
11    types::{RunCommandOptions, TransferedFile},
12    DynNode, ProviderError,
13};
14
15/// A namespace's base dir, `custom` or `<tmp_dir>/<name>`: created if
16/// missing, used as it is with a warning if not (a namespace spawned into
17/// again), and made absolute, since nodes run from their own directory and
18/// docker takes a relative bind-mount source for a named volume.
19pub(crate) async fn namespace_base_dir<FS: FileSystem>(
20    filesystem: &FS,
21    tmp_dir: &Path,
22    name: &str,
23    custom: Option<&Path>,
24) -> Result<PathBuf, ProviderError> {
25    let base_dir = custom.map_or_else(|| tmp_dir.join(name), Path::to_path_buf);
26    if filesystem.exists(&base_dir).await {
27        warn!(
28            "⚠️ Using an existing directory {} as base dir",
29            base_dir.display()
30        );
31    } else {
32        filesystem.create_dir_all(&base_dir).await.map_err(|err| {
33            ProviderError::CreateNamespaceFailed(
34                name.to_string(),
35                anyhow!("can't create base dir {}: {err}", base_dir.display()),
36            )
37        })?;
38    }
39    std::path::absolute(&base_dir)
40        .map_err(|err| ProviderError::CreateNamespaceFailed(name.to_string(), err.into()))
41}
42
43/// Check if we are running in `CI` by checking the 'RUN_IN_CI' env var
44pub fn running_in_ci() -> bool {
45    env::var("RUN_IN_CI").unwrap_or_default() == "1"
46}
47
48/// serde default for the fields that older records did not carry.
49pub(crate) fn default_true() -> bool {
50    true
51}
52
53/// The pause/resume/restart controls are messages on the wrapper's pipe. A
54/// process started without the wrapper has no pipe, and `echo` into a path
55/// that is not a pipe would create a file and report success, so refuse.
56pub(crate) fn ensure_wrapper(
57    name: &str,
58    wrapper: bool,
59    action: &str,
60    failed: fn(String, anyhow::Error) -> ProviderError,
61) -> Result<(), ProviderError> {
62    if wrapper {
63        Ok(())
64    } else {
65        Err(failed(
66            name.to_string(),
67            anyhow!("runs without the zombie wrapper, {action} is not available"),
68        ))
69    }
70}
71
72/// Executes a command on a temporary node and extracts the execution result either from the
73/// standard output or a file.
74pub async fn extract_execution_result(
75    temp_node: &DynNode,
76    options: RunCommandOptions,
77    expected_path: Option<&PathBuf>,
78) -> Result<String, ProviderError> {
79    let output_contents = temp_node
80        .run_command(options)
81        .await?
82        .map_err(|(_, msg)| ProviderError::FileGenerationFailed(anyhow!("{msg}")))?;
83
84    // If an expected_path is provided, read the file contents from inside the container
85    if let Some(expected_path) = expected_path.as_ref() {
86        Ok(temp_node
87            .run_command(
88                RunCommandOptions::new("cat")
89                    .args(vec![expected_path.to_string_lossy().to_string()]),
90            )
91            .await?
92            .map_err(|(_, msg)| {
93                ProviderError::FileGenerationFailed(anyhow!(format!(
94                    "failed reading expected_path {}: {}",
95                    expected_path.display(),
96                    msg
97                )))
98            })?)
99    } else {
100        Ok(output_contents)
101    }
102}
103
104pub fn extract_namespace_info(
105    json_value: &serde_json::Value,
106) -> Result<(PathBuf, String), ProviderError> {
107    let base_dir = json_value
108        .get("local_base_dir")
109        .and_then(|v| v.as_str())
110        .map(PathBuf::from)
111        .ok_or(ProviderError::InvalidConfig(
112            "`field local_base_dir` is missing from zombie.json".to_string(),
113        ))?;
114
115    let name =
116        json_value
117            .get("ns")
118            .and_then(|v| v.as_str())
119            .ok_or(ProviderError::InvalidConfig(
120                "field `ns` is missing from zombie.json".to_string(),
121            ))?;
122
123    Ok((base_dir, name.to_string()))
124}
125
126/// A name for the `index`th injected file of a process: unique by the index,
127/// readable by the file name, within what a volume path or a docker mount
128/// may contain.
129pub(crate) fn injected_file_name(index: usize, file: &TransferedFile) -> String {
130    let name: String = file
131        .remote_path
132        .file_name()
133        .map(|name| name.to_string_lossy().into_owned())
134        .unwrap_or_default()
135        .chars()
136        .map(|c| {
137            if c.is_ascii_alphanumeric() || "-_.".contains(c) {
138                c
139            } else {
140                '-'
141            }
142        })
143        .collect();
144    format!("{index}-{name}")
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn check_runing_in_ci_env_var() {
153        assert!(!running_in_ci());
154        // now set the env var
155        env::set_var("RUN_IN_CI", "1");
156        assert!(running_in_ci());
157        // reset
158        env::set_var("RUN_IN_CI", "");
159    }
160}