netns_rs/
lib.rs

1// Copyright 2022 Alibaba Cloud. All Rights Reserved.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5
6//! This crate provides an ultra-simple interface for handling network namespaces
7//! in Rust. Changing namespaces requires elevated privileges, so in most cases this
8//! code needs to be run as root.
9//!
10//! We can simply create a NetNs using [`NetNs::new`]. Once created, the netns
11//! instance can be used.
12//!
13//! # Examples
14//!
15//!```no_run
16//!use netns_rs::NetNs;
17//!
18//!// create a new netns in `/var/run/netns` by default.
19//!let mut ns = NetNs::new("my_netns").unwrap();
20//!
21//!ns.run(|_| {
22//!    // do something in the new netns. eg. ip link add.
23//!}).unwrap();
24//!
25//!// removes netns.
26//!ns.remove().unwrap();
27//!```
28//! To get a Netns that already exists, you can use the [`NetNs::get`] series of functions.
29//!```no_run
30//!use netns_rs::NetNs;
31//!
32//!let ns = NetNs::get("my_netns").unwrap();
33//!```
34//! Or use [`get_from_current_thread`] to get the netns of the current thread.
35//!```no_run
36//!use netns_rs::get_from_current_thread;
37//!
38//!let ns = get_from_current_thread().unwrap();
39//!```
40//! [`NetNs::new`]: NetNs::new
41//! [`NetNs::get`]: NetNs::get
42//! [`get_from_current_thread`]: get_from_current_thread
43
44mod netns;
45pub use self::netns::*;
46
47pub type Result<T> = std::result::Result<T, Error>;
48
49#[derive(Debug, thiserror::Error)]
50pub enum Error {
51    #[error("Can not create netns directory, {0}")]
52    CreateNsDirError(std::io::Error),
53
54    #[error("Can not create netns,{0}")]
55    CreateNsError(std::io::Error),
56
57    #[error("Can not open netns {0},{1}")]
58    OpenNsError(std::path::PathBuf, std::io::Error),
59
60    #[error("Failed to close netns,{0}")]
61    CloseNsError(nix::Error),
62
63    #[error("Failed to mount {0}, {1}")]
64    MountError(String, nix::Error),
65
66    #[error("Failed to unmount {0}, {1}")]
67    UnmountError(std::path::PathBuf, nix::Error),
68
69    #[error("Failed to unshare, {0}")]
70    UnshareError(nix::Error),
71
72    #[error("Failed to join thread, {0}")]
73    JoinThreadError(String),
74
75    #[error("Can not setns, {0}")]
76    SetnsError(nix::Error),
77}