Skip to content

Commit b9d6233

Browse files
committed
Refactor network device namespace handling: streamline network namespace retrieval and improve error handling in move_network_devices_to_container function.
Signed-off-by: nayuta-ai <[email protected]>
1 parent 6de834c commit b9d6233

File tree

1 file changed

+7
-15
lines changed

1 file changed

+7
-15
lines changed

crates/libcontainer/src/process/container_main_process.rs

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -250,26 +250,18 @@ fn move_network_devices_to_container(
250250
) -> Result<()> {
251251
if let Some(namespaces) = linux.namespaces() {
252252
// network devices are not moved for containers running in the host network.
253-
if !namespaces
253+
let net_ns = match namespaces
254254
.iter()
255-
.any(|ns| ns.typ() == LinuxNamespaceType::Network)
255+
.find(|ns| ns.typ() == LinuxNamespaceType::Network)
256256
{
257-
return Ok(());
258-
}
257+
Some(ns) => ns,
258+
None => return Ok(()),
259+
};
259260

260261
// the container init process has already joined the provided net namespace,
261262
// so we can use the process's net ns path directly.
262263
let default_ns_path = PathBuf::from(format!("/proc/{}/ns/net", init_pid.as_raw()));
263-
let ns_path = namespaces
264-
.iter()
265-
.find_map(|ns| {
266-
if ns.typ() == LinuxNamespaceType::Network {
267-
ns.path().as_deref()
268-
} else {
269-
None
270-
}
271-
})
272-
.unwrap_or_else(|| &default_ns_path);
264+
let ns_path = net_ns.path().as_deref().unwrap_or(&default_ns_path);
273265

274266
// If moving any of the network devices fails, we return an error immediately.
275267
// The runtime spec requires that the kernel handles moving back any devices
@@ -281,7 +273,7 @@ fn move_network_devices_to_container(
281273
.iter()
282274
.map(|(name, net_dev)| {
283275
let addrs =
284-
dev_change_net_namespace(name, &ns_path, net_dev).map_err(|err| {
276+
dev_change_net_namespace(name, ns_path, net_dev).map_err(|err| {
285277
tracing::error!("failed to dev_change_net_namespace: {}", err);
286278
err
287279
})?;

0 commit comments

Comments
 (0)