Docker技術原理之Linux Namespace(容器隔離)
0.前言
首先要知道一個執行的容器,其實就是一個受到隔離和資源限制的Linux程序——對,它就是一個程序。而本文主要來探討Docker容器實現隔離用到的技術Linux Namespace。
1.關於 Linux Namespace
Linux提供如下Namespace:
Namespace Constant Isolates Cgroup CLONE_NEWCGROUP Cgroup root directory IPC CLONE_NEWIPC System V IPC, POSIX message queues Network CLONE_NEWNET Network devices, stacks, ports, etc. Mount CLONE_NEWNS Mount points PID CLONE_NEWPID Process IDs User CLONE_NEWUSER User and group IDs UTS CLONE_NEWUTS Hostname and NIS domain name
以上Namespace分別對程序的 Cgroup root、程序間通訊、網路、檔案系統掛載點、程序ID、使用者和組、主機名域名等進行隔離。
建立容器(程序)主要用到三個系統呼叫:
clone()
– 實現執行緒的系統呼叫,用來建立一個新的程序,並可以通過上述引數達到隔離unshare()
– 使某程序脫離某個namespacesetns()
– 把某程序加入到某個namespace
2.舉個例子(PID namespace)
1) 啟動一個容器
$ docker run -it busybox /bin/sh
/ #
2) 檢視容器中的程序id(可以看到/bin/sh的pid=1)
/ # ps PID USER TIME COMMAND 1 root 0:00 /bin/sh 5 root 0:00 ps
3) 檢視宿主機中的該/bin/sh的程序id
# ps -ef |grep busy
root 3702 3680 0 15:53 pts/0 00:00:00 docker run -it busybox /bin/sh
可以看到,我們在Docker裡最開始執行的/bin/sh,就是這個容器內部的第1號程序(PID=1),而在宿主機上看到它的PID=3702。這就意味著,前面執行的/bin/sh,已經被Docker隔離在了一個跟宿主機完全不同的世界當中。
而這就是Docker在啟動一個容器(建立一個程序)時使用了PID namespace
int pid = clone(main_function, stack_size, CLONE_NEWPID | SIGCHLD, NULL);
這時候,Docker就會在這個PID=3702的程序啟動時給他施一個“障眼法”,讓他永遠看不到不屬於它這個namespace中的程序。這種機制,其實就是對被隔離應用的程序空間做了手腳,使得這些程序只能看到重新計算過的程序編號,比如PID=1。可實際上,他們在宿主機的作業系統裡,還是原來的第3702號程序。
然後如果你自己只用PID namespace使用上述的clone()
建立一個程序,檢視ps或top等命令時,卻還是能看到所有程序。說明並沒有完全隔離,這是因為,像ps、top這些命令會去讀/proc檔案系統,而此時你建立的隔離了pid的程序和宿主機使用的是同一個/proc檔案系統,所以這些命令顯示的東西都是一樣的。所以,我們還需要使其它的namespace隔離,如檔案系統進行隔離。
3.對照Docker原始碼
當啟動一個docker容器時,會呼叫到dockerd提供的/containers/{name:.*}/start
介面,然後啟動一個容器,docker服務收到請求後,呼叫關係如下:
//註冊http handler
router.NewPostRoute("/containers/{name:.*}/start", r.postContainersStart)
//
func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error
//
func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error
//
func (daemon *Daemon) containerStart(container *container.Container, checkpoint string, checkpointDir string, resetRestartManager bool) (err error) {
//...
spec, err := daemon.createSpec(container)
//...
err = daemon.containerd.Create(context.Background(), container.ID, spec, createOptions)
//...
pid, err := daemon.containerd.Start(context.Background(), container.ID, checkpointDir,
container.StreamConfig.Stdin() != nil || container.Config.Tty,
container.InitializeStdio)
//...
container.SetRunning(pid, true)
//...
}
可以看到在Daemon.containerStart
介面中建立並啟動了容器,而建立容器時傳入的spec
引數就包含了namespace,我們再來看看daemon.createSpec(container)
介面返回的spec
是什麼:
func (daemon *Daemon) createSpec(c *container.Container) (retSpec *specs.Spec, err error) {
s := oci.DefaultSpec()
//...
if err := setUser(&s, c); err != nil {
return nil, fmt.Errorf("linux spec user: %v", err)
}
if err := setNamespaces(daemon, &s, c); err != nil {
return nil, fmt.Errorf("linux spec namespaces: %v", err)
}
//...
return &s
}
//oci.DefaultSpec()會呼叫DefaultLinuxSpec,可以看到返回的spec中包含了namespace
func DefaultLinuxSpec() specs.Spec {
s := specs.Spec{
Version: specs.Version,
Process: &specs.Process{
Capabilities: &specs.LinuxCapabilities{
Bounding: defaultCapabilities(),
Permitted: defaultCapabilities(),
Inheritable: defaultCapabilities(),
Effective: defaultCapabilities(),
},
},
Root: &specs.Root{},
}
s.Mounts = []specs.Mount{
{
Destination: "/proc",
Type: "proc",
Source: "proc",
Options: []string{"nosuid", "noexec", "nodev"},
},
{
Destination: "/sys/fs/cgroup",
Type: "cgroup",
Source: "cgroup",
Options: []string{"ro", "nosuid", "noexec", "nodev"},
},
//...
}
s.Linux = &specs.Linux{
//...
Namespaces: []specs.LinuxNamespace{
{Type: "mount"},
{Type: "network"},
{Type: "uts"},
{Type: "pid"},
{Type: "ipc"},
},
//...
//...
return s
}
//而在setNamespaces中還會根據其它配置對namespace進行修改
func setNamespaces(daemon *Daemon, s *specs.Spec, c *container.Container) error {
userNS := false
// user
if c.HostConfig.UsernsMode.IsPrivate() {
uidMap := daemon.idMapping.UIDs()
if uidMap != nil {
userNS = true
ns := specs.LinuxNamespace{Type: "user"}
setNamespace(s, ns)
s.Linux.UIDMappings = specMapping(uidMap)
s.Linux.GIDMappings = specMapping(daemon.idMapping.GIDs())
}
}
// network
if !c.Config.NetworkDisabled {
ns := specs.LinuxNamespace{Type: "network"}
parts := strings.SplitN(string(c.HostConfig.NetworkMode), ":", 2)
if parts[0] == "container" {
nc, err := daemon.getNetworkedContainer(c.ID, c.HostConfig.NetworkMode.ConnectedContainer())
if err != nil {
return err
}
ns.Path = fmt.Sprintf("/proc/%d/ns/net", nc.State.GetPID())
if userNS {
// to share a net namespace, they must also share a user namespace
nsUser := specs.LinuxNamespace{Type: "user"}
nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", nc.State.GetPID())
setNamespace(s, nsUser)
}
} else if c.HostConfig.NetworkMode.IsHost() {
ns.Path = c.NetworkSettings.SandboxKey
}
setNamespace(s, ns)
}
// ipc
ipcMode := c.HostConfig.IpcMode
switch {
case ipcMode.IsContainer():
ns := specs.LinuxNamespace{Type: "ipc"}
ic, err := daemon.getIpcContainer(ipcMode.Container())
if err != nil {
return err
}
ns.Path = fmt.Sprintf("/proc/%d/ns/ipc", ic.State.GetPID())
setNamespace(s, ns)
if userNS {
// to share an IPC namespace, they must also share a user namespace
nsUser := specs.LinuxNamespace{Type: "user"}
nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", ic.State.GetPID())
setNamespace(s, nsUser)
}
case ipcMode.IsHost():
oci.RemoveNamespace(s, specs.LinuxNamespaceType("ipc"))
case ipcMode.IsEmpty():
// A container was created by an older version of the daemon.
// The default behavior used to be what is now called "shareable".
fallthrough
case ipcMode.IsPrivate(), ipcMode.IsShareable(), ipcMode.IsNone():
ns := specs.LinuxNamespace{Type: "ipc"}
setNamespace(s, ns)
default:
return fmt.Errorf("Invalid IPC mode: %v", ipcMode)
}
// pid
if c.HostConfig.PidMode.IsContainer() {
ns := specs.LinuxNamespace{Type: "pid"}
pc, err := daemon.getPidContainer(c)
if err != nil {
return err
}
ns.Path = fmt.Sprintf("/proc/%d/ns/pid", pc.State.GetPID())
setNamespace(s, ns)
if userNS {
// to share a PID namespace, they must also share a user namespace
nsUser := specs.LinuxNamespace{Type: "user"}
nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", pc.State.GetPID())
setNamespace(s, nsUser)
}
} else if c.HostConfig.PidMode.IsHost() {
oci.RemoveNamespace(s, specs.LinuxNamespaceType("pid"))
} else {
ns := specs.LinuxNamespace{Type: "pid"}
setNamespace(s, ns)
}
// uts
if c.HostConfig.UTSMode.IsHost() {
oci.RemoveNamespace(s, specs.LinuxNamespaceType("uts"))
s.Hostname = ""
}
return nil
}
func setNamespace(s *specs.Spec, ns specs.LinuxNamespace) {
for i, n := range s.Linux.Namespaces {
if n.Type == ns.Type {
s.Linux.Namespaces[i] = ns
return
}
}
s.Linux.Namespaces = append(s.Linux.Namespaces, ns)
}
其實很早以前Docker建立一個容器,獲取namespace是通過CloneFlags
函式,後來有了開放容器計劃(OCI)規範後,就改為了以上面程式碼中方式建立容器。OCI之前程式碼如下:
var namespaceInfo = map[NamespaceType]int{
NEWNET: unix.CLONE_NEWNET,
NEWNS: unix.CLONE_NEWNS,
NEWUSER: unix.CLONE_NEWUSER,
NEWIPC: unix.CLONE_NEWIPC,
NEWUTS: unix.CLONE_NEWUTS,
NEWPID: unix.CLONE_NEWPID,
}
// CloneFlags parses the container's Namespaces options to set the correct
// flags on clone, unshare. This function returns flags only for new namespaces.
func (n *Namespaces) CloneFlags() uintptr {
var flag int
for _, v := range *n {
if v.Path != "" {
continue
}
flag |= namespaceInfo[v.Type]
}
return uintptr(flag)
}
func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*initProcess, error) { t := "_LIBCONTAINER_INITTYPE=standard"
//
//沒錯,就是這裡~
//
cloneFlags := c.config.Namespaces.CloneFlags()
if cloneFlags&syscall.CLONE_NEWUSER != 0 {
if err := c.addUidGidMappings(cmd.SysProcAttr); err != nil {
// user mappings are not supported
return nil, err
}
enableSetgroups(cmd.SysProcAttr)
// Default to root user when user namespaces are enabled.
if cmd.SysProcAttr.Credential == nil {
cmd.SysProcAttr.Credential = &syscall.Credential{}
}
}
cmd.Env = append(cmd.Env, t)
cmd.SysProcAttr.Cloneflags = cloneFlags
return &initProcess{
cmd: cmd,
childPipe: childPipe,
parentPipe: parentPipe,
manager: c.cgroupManager,
config: c.newInitConfig(p),
}, nil
}
現在,容器執行時,通過OCI這個容器執行時規範同底層的Linux作業系統進行互動,即:把容器操作請求翻譯成對Linux作業系統的呼叫(操作Linux Namespace和Cgroups等)。