`ip netns exec` 命令如何创建挂载命名空间?

How does `ip netns exec` command create mount namespace?

ip netns exec 命令如何创建挂载命名空间并防止更改传播到其他挂载命名空间?

以下是 ip-netns 的手册页:

For applications that are aware of network namespaces, the convention is to look for global network configuration files first in /etc/netns/NAME/ then in /etc/. For example, if you want a different version of /etc/resolv.conf for a network namespace used to isolate your vpn you would name it /etc/netns/myvpn/resolv.conf.

ip netns exec automates handling of this configuration, file convention for network namespace unaware applications, by creating a mount namespace and bind mounting all of the per network namespace configure files into their traditional location in /etc.

但是,它如何管理仅在特定命名空间中可见的绑定安装?

让我举个例子。 在一个终端中,我创建了一个网络命名空间 ns3,并为 ns3 创建了一个特定的 resolv.conf。

# ip netns add ns3
# mkdir /etc/netns/ns3
# echo "ns3 conf" > /etc/netns/ns3/resolv.conf
# ip netns exec ns3 sleep 36000

现在在另一个终端中,我检查 /etc/resolv.conf.

# cat /etc/resolv.conf
default conf

这里没有反映绑定挂载所做的更改。 仅当我输入由 ip netns 命令创建的挂载命名空间时,更改才可见。

# lsns | grep mnt
4026533472 mnt        1 13016 root             sleep 36000
# nsenter -m -t 13016
# cat /etc/resolv.conf
ns3 conf

所以一切都按预期工作。

现在让我尝试直接使用 unshare 命令来执行此操作,而不是使用 ip netns exec.

我又创建了一个命名空间。使用 unshare,我正在创建一个挂载命名空间并在该挂载命名空间内进行绑定挂载。我假设这就是 ip netns exec 命令在内部所做的。

# ip netns add ns4
# mkdir /etc/netns/ns4
# echo "ns4 conf" > /etc/netns/ns4/resolv.conf
# unshare -m --propagation unchanged /bin/bash
# mount --bind /etc/netns/ns4/resolv.conf /etc/resolv.conf

但是这次当我从另一个终端检查时,更改已经传回,这是不希望的。

# cat /etc/resolv.conf
ns4 conf

那么 ip netns exec 防止这种更改传播的额外步骤是什么?我假设它与使用 make-sharedmake-slave 标志有关,但无法确切地弄清楚。

发现如果我使用 # unshare -m --propagation slave /bin/bash,传播就会被阻止。

ip netns exec 命令在 unshare(CLONE_NEWNS) 完成后似乎是 运行 mount --make-rslave /。 即,在创建新的挂载命名空间后,/ 在该命名空间中作为从属挂载。