Skip to main content

zombienet_provider/shared/
types.rs

1use std::{
2    collections::HashMap,
3    path::{Path, PathBuf},
4    process::ExitStatus,
5};
6
7use configuration::shared::resources::Resources;
8
9use crate::ProviderError;
10
11pub type Port = u16;
12
13pub type ExecutionResult = Result<String, (ExitStatus, String)>;
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct ProviderCapabilities {
17    // default ports internal
18    /// Ensure that we have an image for each node (k8s/podman/docker)
19    pub requires_image: bool,
20    /// Allow to customize the resources through manifest (k8s).
21    pub has_resources: bool,
22    /// Used in native to prefix filepath with fullpath
23    pub prefix_with_full_path: bool,
24    /// Use default ports in node cmd/args.
25    /// NOTE: generally used in k8s/dockers since the images expose those ports.
26    pub use_default_ports_in_cmd: bool,
27    /// An env value may be read from a `Secret` in the namespace (k8s).
28    pub has_secrets: bool,
29    /// A `db_snapshot` given as a URL is fetched by the namespace's
30    /// fileserver, inside the cluster, rather than downloaded on this host
31    /// and uploaded to it (k8s). See
32    /// [`ProviderNamespace::fetch_into_fileserver`](crate::ProviderNamespace::fetch_into_fileserver).
33    pub fileserver_fetches_db_snapshot_url: bool,
34}
35
36/// A database snapshot a node starts from, as the orchestrator hands it to
37/// the provider.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum DbSnapshot {
40    /// A local `.tgz` the orchestrator has already downloaded or copied.
41    Local(PathBuf),
42    /// A `.tgz` already in the namespace's fileserver, at this URL, which
43    /// the fileserver fetched itself. Only handed to a provider whose
44    /// capabilities set
45    /// [`ProviderCapabilities::fileserver_fetches_db_snapshot_url`], so a
46    /// large snapshot never passes through the host running zombienet.
47    InFileserver(url::Url),
48}
49
50impl std::fmt::Display for DbSnapshot {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        match self {
53            DbSnapshot::Local(path) => write!(f, "{}", path.display()),
54            DbSnapshot::InFileserver(url) => write!(f, "{url}"),
55        }
56    }
57}
58
59impl DbSnapshot {
60    /// The local file, for a provider without a fileserver. Anything else
61    /// means the orchestrator skipped resolving it, which is a bug.
62    pub fn local_path(&self, node: &str) -> Result<&Path, ProviderError> {
63        match self {
64            DbSnapshot::Local(path) => Ok(path),
65            DbSnapshot::InFileserver(url) => Err(ProviderError::InvalidConfig(format!(
66                "{}: node {node} was handed db_snapshot {url} in a fileserver, \
67                 which this provider does not have",
68                support::constants::THIS_IS_A_BUG
69            ))),
70        }
71    }
72}
73
74/// An environment variable read from the `key` of the `Secret` named
75/// `secret` in the namespace, by the pod itself (k8s only).
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct SecretEnvVar {
78    pub name: String,
79    pub secret: String,
80    pub key: String,
81}
82
83/// Role of a node in the network, exposed by providers that support labels
84/// (k8s) as the `zombie-role` label with the values zombienet v1 used
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum NodeRole {
87    /// Relay chain node, validator or not
88    Node,
89    /// Dedicated bootnode
90    Bootnode,
91    /// Collator of a parachain that is not cumulus based (e.g adder/undying)
92    Collator,
93    /// Collator of a cumulus based parachain
94    CumulusCollator,
95    /// Short-lived helper node (e.g used to generate chain-specs)
96    Temp,
97    /// A custom process declared in the network config, running next to the nodes
98    CustomProcess,
99}
100
101impl NodeRole {
102    pub fn as_label(&self) -> &'static str {
103        match self {
104            NodeRole::Node => "node",
105            NodeRole::Bootnode => "bootnode",
106            NodeRole::Collator => "collator",
107            NodeRole::CumulusCollator => "cumulus-collator",
108            NodeRole::Temp => "temp",
109            NodeRole::CustomProcess => "custom-process",
110        }
111    }
112}
113
114/// How a provider tells that a node spawned without the wrapper is ready.
115/// On kubernetes it becomes the pod's readiness probe.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct ReadinessProbe {
118    pub target: ReadinessTarget,
119    /// Seconds between two attempts.
120    pub period_secs: u64,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum ReadinessTarget {
125    /// The port accepts a TCP connection.
126    Tcp(Port),
127    /// `GET <path>` on the port answers 2xx.
128    Http { port: Port, path: String },
129}
130
131/// What a provider knows about a node's process.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub enum ProcessStatus {
134    /// The process runs. `ready` is what the provider's own check says, where
135    /// it has one (kubernetes: the pod's Ready condition); `None` otherwise.
136    Running { ready: Option<bool> },
137    /// The process exited, with its code where the provider knows it (not for
138    /// a process attached by pid that is gone).
139    Exited { code: Option<i32> },
140}
141
142#[derive(Debug, Clone)]
143pub struct SpawnNodeOptions {
144    /// Name of the node
145    pub name: String,
146    /// Image of the node (IFF is supported by the provider)
147    pub image: Option<String>,
148    /// Resources to apply to the node (IFF is supported by the provider)
149    pub resources: Option<Resources>,
150    /// Main command to execute
151    pub program: String,
152    /// Arguments to pass to the main command
153    pub args: Vec<String>,
154    /// Environment to set when running the `program`
155    pub env: Vec<(String, String)>,
156    /// Environment read from `Secret`s in the namespace (k8s only).
157    pub secret_env: Vec<SecretEnvVar>,
158    // TODO: rename startup_files
159    /// Files to inject at startup. On native, where a file's `remote_path`
160    /// stands in `program`, `args` or `env` it becomes the file's full path.
161    pub injected_files: Vec<TransferedFile>,
162    /// Paths to create before start the node (e.g keystore)
163    /// should be created with `create_dir_all` in order
164    /// to create the full path even when we have missing parts
165    pub created_paths: Vec<PathBuf>,
166    /// Database snapshot to be injected: a local `.tgz` resolved by the
167    /// orchestrator before spawn, or (only for a provider whose fileserver
168    /// fetches them) one already in the namespace's fileserver. See
169    /// `orchestrator::generators::resolve_db_snapshots`.
170    pub db_snapshot: Option<DbSnapshot>,
171    pub port_mapping: Option<HashMap<Port, Port>>,
172    /// Named ports the process listens on. On k8s they are the pod's container
173    /// ports and its `Service` ports (none gives a headless Service); the other
174    /// providers ignore them.
175    pub ports: Vec<(String, Port)>,
176    /// How the provider may check readiness itself; on k8s the pod's probe.
177    pub readiness: Option<ReadinessProbe>,
178    /// Optionally specify a log path for the node
179    pub node_log_path: Option<PathBuf>,
180    /// Role of the node in the network
181    pub role: Option<NodeRole>,
182    /// Run `program` through zombienet's wrapper script, which gives the
183    /// pause/resume/restart controls nodes have. The wrapper needs `bash` in
184    /// the image and replaces the image's entrypoint, so a custom process that
185    /// is just an off-the-shelf image runs without it.
186    pub wrapper: bool,
187}
188
189impl SpawnNodeOptions {
190    pub fn new<S>(name: S, program: S) -> Self
191    where
192        S: AsRef<str>,
193    {
194        Self {
195            name: name.as_ref().to_string(),
196            image: None,
197            resources: None,
198            program: program.as_ref().to_string(),
199            args: vec![],
200            env: vec![],
201            secret_env: vec![],
202            injected_files: vec![],
203            created_paths: vec![],
204            db_snapshot: None,
205            port_mapping: None,
206            ports: vec![],
207            readiness: None,
208            node_log_path: None,
209            role: None,
210            wrapper: true,
211        }
212    }
213
214    pub fn image<S>(mut self, image: S) -> Self
215    where
216        S: AsRef<str>,
217    {
218        self.image = Some(image.as_ref().to_string());
219        self
220    }
221
222    pub fn resources(mut self, resources: Resources) -> Self {
223        self.resources = Some(resources);
224        self
225    }
226
227    pub fn db_snapshot(mut self, db_snap: Option<DbSnapshot>) -> Self {
228        self.db_snapshot = db_snap;
229        self
230    }
231
232    pub fn args<S, I>(mut self, args: I) -> Self
233    where
234        S: AsRef<str>,
235        I: IntoIterator<Item = S>,
236    {
237        self.args = args.into_iter().map(|s| s.as_ref().to_string()).collect();
238        self
239    }
240
241    pub fn env<S, I>(mut self, env: I) -> Self
242    where
243        S: AsRef<str>,
244        I: IntoIterator<Item = (S, S)>,
245    {
246        self.env = env
247            .into_iter()
248            .map(|(name, value)| (name.as_ref().to_string(), value.as_ref().to_string()))
249            .collect();
250        self
251    }
252
253    pub fn injected_files<I>(mut self, injected_files: I) -> Self
254    where
255        I: IntoIterator<Item = TransferedFile>,
256    {
257        self.injected_files = injected_files.into_iter().collect();
258        self
259    }
260
261    pub fn created_paths<P, I>(mut self, created_paths: I) -> Self
262    where
263        P: AsRef<Path>,
264        I: IntoIterator<Item = P>,
265    {
266        self.created_paths = created_paths
267            .into_iter()
268            .map(|path| path.as_ref().into())
269            .collect();
270        self
271    }
272
273    pub fn port_mapping(mut self, ports: HashMap<Port, Port>) -> Self {
274        self.port_mapping = Some(ports);
275        self
276    }
277
278    pub fn node_log_path(mut self, path: Option<PathBuf>) -> Self {
279        self.node_log_path = path;
280        self
281    }
282
283    pub fn role(mut self, role: NodeRole) -> Self {
284        self.role = Some(role);
285        self
286    }
287
288    pub fn ports<S, I>(mut self, ports: I) -> Self
289    where
290        S: AsRef<str>,
291        I: IntoIterator<Item = (S, Port)>,
292    {
293        self.ports = ports
294            .into_iter()
295            .map(|(name, port)| (name.as_ref().to_string(), port))
296            .collect();
297        self
298    }
299
300    pub fn readiness(mut self, probe: Option<ReadinessProbe>) -> Self {
301        self.readiness = probe;
302        self
303    }
304
305    pub fn secret_env<I>(mut self, secret_env: I) -> Self
306    where
307        I: IntoIterator<Item = SecretEnvVar>,
308    {
309        self.secret_env = secret_env.into_iter().collect();
310        self
311    }
312
313    /// Run `program` directly instead of through the zombie wrapper script.
314    ///
315    /// The wrapper needs `bash` in the image and is what pause, resume and
316    /// restart talk to, so those return an error for a node spawned this way
317    /// on docker and kubernetes (native signals the process and needs no
318    /// wrapper). The wrapper holds the program back until the injected files
319    /// are copied in; without it they are mounted in before the program
320    /// starts, read-only.
321    pub fn without_wrapper(mut self) -> Self {
322        self.wrapper = false;
323        self
324    }
325}
326
327#[derive(Debug)]
328pub struct GenerateFileCommand {
329    pub program: String,
330    pub args: Vec<String>,
331    pub env: Vec<(String, String)>,
332    pub local_output_path: PathBuf,
333}
334
335impl GenerateFileCommand {
336    pub fn new<S, P>(program: S, local_output_path: P) -> Self
337    where
338        S: AsRef<str>,
339        P: AsRef<Path>,
340    {
341        Self {
342            program: program.as_ref().to_string(),
343            args: vec![],
344            env: vec![],
345            local_output_path: local_output_path.as_ref().into(),
346        }
347    }
348
349    pub fn args<S, I>(mut self, args: I) -> Self
350    where
351        S: AsRef<str>,
352        I: IntoIterator<Item = S>,
353    {
354        self.args = args.into_iter().map(|s| s.as_ref().to_string()).collect();
355        self
356    }
357
358    pub fn env<S, I>(mut self, env: I) -> Self
359    where
360        S: AsRef<str>,
361        I: IntoIterator<Item = (S, S)>,
362    {
363        self.env = env
364            .into_iter()
365            .map(|(name, value)| (name.as_ref().to_string(), value.as_ref().to_string()))
366            .collect();
367        self
368    }
369}
370
371#[derive(Debug)]
372pub struct GenerateFilesOptions {
373    pub commands: Vec<GenerateFileCommand>,
374    pub image: Option<String>,
375    pub injected_files: Vec<TransferedFile>,
376    // Allow to control the name of the node used to create the files.
377    pub temp_name: Option<String>,
378    pub expected_path: Option<PathBuf>,
379}
380
381impl GenerateFilesOptions {
382    pub fn new<I>(commands: I, image: Option<String>, expected_path: Option<PathBuf>) -> Self
383    where
384        I: IntoIterator<Item = GenerateFileCommand>,
385    {
386        Self {
387            commands: commands.into_iter().collect(),
388            injected_files: vec![],
389            image,
390            temp_name: None,
391            expected_path,
392        }
393    }
394
395    pub fn with_files<I>(
396        commands: I,
397        image: Option<String>,
398        injected_files: &[TransferedFile],
399        expected_path: Option<PathBuf>,
400    ) -> Self
401    where
402        I: IntoIterator<Item = GenerateFileCommand>,
403    {
404        Self {
405            commands: commands.into_iter().collect(),
406            injected_files: injected_files.into(),
407            image,
408            temp_name: None,
409            expected_path,
410        }
411    }
412
413    pub fn image<S>(mut self, image: S) -> Self
414    where
415        S: AsRef<str>,
416    {
417        self.image = Some(image.as_ref().to_string());
418        self
419    }
420
421    pub fn injected_files<I>(mut self, injected_files: I) -> Self
422    where
423        I: IntoIterator<Item = TransferedFile>,
424    {
425        self.injected_files = injected_files.into_iter().collect();
426        self
427    }
428
429    pub fn temp_name(mut self, name: impl Into<String>) -> Self {
430        self.temp_name = Some(name.into());
431        self
432    }
433}
434
435#[derive(Debug)]
436pub struct RunCommandOptions {
437    pub program: String,
438    pub args: Vec<String>,
439    pub env: Vec<(String, String)>,
440}
441
442impl RunCommandOptions {
443    pub fn new<S>(program: S) -> Self
444    where
445        S: AsRef<str>,
446    {
447        Self {
448            program: program.as_ref().to_string(),
449            args: vec![],
450            env: vec![],
451        }
452    }
453
454    pub fn args<S, I>(mut self, args: I) -> Self
455    where
456        S: AsRef<str>,
457        I: IntoIterator<Item = S>,
458    {
459        self.args = args.into_iter().map(|s| s.as_ref().to_string()).collect();
460        self
461    }
462
463    pub fn env<S, I>(mut self, env: I) -> Self
464    where
465        S: AsRef<str>,
466        I: IntoIterator<Item = (S, S)>,
467    {
468        self.env = env
469            .into_iter()
470            .map(|(name, value)| (name.as_ref().to_string(), value.as_ref().to_string()))
471            .collect();
472        self
473    }
474}
475
476pub struct RunScriptOptions {
477    pub local_script_path: PathBuf,
478    pub args: Vec<String>,
479    pub env: Vec<(String, String)>,
480}
481
482impl RunScriptOptions {
483    pub fn new<P>(local_script_path: P) -> Self
484    where
485        P: AsRef<Path>,
486    {
487        Self {
488            local_script_path: local_script_path.as_ref().into(),
489            args: vec![],
490            env: vec![],
491        }
492    }
493
494    pub fn args<S, I>(mut self, args: I) -> Self
495    where
496        S: AsRef<str>,
497        I: IntoIterator<Item = S>,
498    {
499        self.args = args.into_iter().map(|s| s.as_ref().to_string()).collect();
500        self
501    }
502
503    pub fn env<S, I>(mut self, env: I) -> Self
504    where
505        S: AsRef<str>,
506        I: IntoIterator<Item = (S, S)>,
507    {
508        self.env = env
509            .into_iter()
510            .map(|(name, value)| (name.as_ref().to_string(), value.as_ref().to_string()))
511            .collect();
512        self
513    }
514}
515
516pub use configuration::TransferedFile;
517
518/// Result of [`ProviderNode::snapshot_db`].
519/// return the filename, hash and bytes of the generated `{node.name}.tgz`
520pub struct InnerSnapshotDb {
521    /// local filename (scoped in node base_dir)
522    pub filename: String,
523    /// Hex-encoded SHA-256 of the archive contents.
524    pub sha256: String,
525    /// Size of the archive in bytes.
526    pub size: u64,
527}