runtime-rs: add a public method to support process entering netns.

The enter_netns function is designed as a public method to help
VMMs running as a independent process enter a network namespace,
reducing duplicate code.

Fixes: #8865

Signed-off-by: Alex Lyn <alex.lyn@antgroup.com>
This commit is contained in:
Alex Lyn 2024-03-11 15:55:52 +08:00
parent 4176fcc3c6
commit f571ec84d2

View File

@ -4,11 +4,18 @@
// SPDX-License-Identifier: Apache-2.0
//
use std::{collections::HashSet, os::fd::RawFd};
use std::{
collections::HashSet,
fs::File,
os::fd::{AsRawFd, RawFd},
};
use anyhow::Result;
use anyhow::{anyhow, Context, Result};
use kata_types::config::KATA_PATH;
use nix::fcntl;
use nix::{
fcntl,
sched::{setns, CloneFlags},
};
use crate::{DEFAULT_HYBRID_VSOCK_NAME, JAILER_ROOT};
@ -64,3 +71,13 @@ pub fn clear_fd_flags(rawfd: RawFd) -> Result<()> {
Ok(())
}
pub fn enter_netns(netns_path: &str) -> Result<()> {
if !netns_path.is_empty() {
let netns =
File::open(netns_path).context(anyhow!("open netns path {:?} failed.", netns_path))?;
setns(netns.as_raw_fd(), CloneFlags::CLONE_NEWNET).context("set netns failed")?;
}
Ok(())
}