0.前言
首先要知道一個(gè)運(yùn)行的容器埠忘,其實(shí)就是一個(gè)受到隔離和資源限制的Linux進(jìn)程——對(duì)脾拆,它就是一個(gè)進(jìn)程见转。而本文主要來探討Docker容器實(shí)現(xiàn)隔離用到的技術(shù)Linux Namespace观腊。
1.關(guān)于 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分別對(duì)進(jìn)程的 Cgroup root、進(jìn)程間通信县耽、網(wǎng)絡(luò)动羽、文件系統(tǒng)掛載點(diǎn)包帚、進(jìn)程ID渔期、用戶和組运吓、主機(jī)名域名等進(jìn)行隔離。
創(chuàng)建容器(進(jìn)程)主要用到三個(gè)系統(tǒng)調(diào)用:
-
clone()
– 實(shí)現(xiàn)線程的系統(tǒng)調(diào)用疯趟,用來創(chuàng)建一個(gè)新的進(jìn)程拘哨,并可以通過上述參數(shù)達(dá)到隔離 -
unshare()
– 使某進(jìn)程脫離某個(gè)namespace -
setns()
– 把某進(jìn)程加入到某個(gè)namespace
2.舉個(gè)例子(PID namespace)
1) 啟動(dòng)一個(gè)容器
$ docker run -it busybox /bin/sh
/ #
2) 查看容器中的進(jìn)程id(可以看到/bin/sh的pid=1)
/ # ps
PID USER TIME COMMAND
1 root 0:00 /bin/sh
5 root 0:00 ps
3) 查看宿主機(jī)中的該/bin/sh的進(jìn)程id
# ps -ef |grep busy
root 3702 3680 0 15:53 pts/0 00:00:00 docker run -it busybox /bin/sh
可以看到,我們?cè)贒ocker里最開始執(zhí)行的/bin/sh信峻,就是這個(gè)容器內(nèi)部的第1號(hào)進(jìn)程(PID=1)倦青,而在宿主機(jī)上看到它的PID=3702。這就意味著盹舞,前面執(zhí)行的/bin/sh产镐,已經(jīng)被Docker隔離在了一個(gè)跟宿主機(jī)完全不同的世界當(dāng)中。
而這就是Docker在啟動(dòng)一個(gè)容器(創(chuàng)建一個(gè)進(jìn)程)時(shí)使用了PID namespace
int pid = clone(main_function, stack_size, CLONE_NEWPID | SIGCHLD, NULL);
這時(shí)候踢步,Docker就會(huì)在這個(gè)PID=3702的進(jìn)程啟動(dòng)時(shí)給他施一個(gè)“障眼法”癣亚,讓他永遠(yuǎn)看不到不屬于它這個(gè)namespace中的進(jìn)程。這種機(jī)制获印,其實(shí)就是對(duì)被隔離應(yīng)用的進(jìn)程空間做了手腳述雾,使得這些進(jìn)程只能看到重新計(jì)算過的進(jìn)程編號(hào),比如PID=1兼丰〔C希可實(shí)際上,他們?cè)谒拗鳈C(jī)的操作系統(tǒng)里鳍征,還是原來的第3702號(hào)進(jìn)程黍翎。
然后如果你自己只用PID namespace使用上述的clone()
創(chuàng)建一個(gè)進(jìn)程,查看ps或top等命令時(shí)艳丛,卻還是能看到所有進(jìn)程玩敏。說明并沒有完全隔離斗忌,這是因?yàn)椋駊s旺聚、top這些命令會(huì)去讀/proc文件系統(tǒng)织阳,而此時(shí)你創(chuàng)建的隔離了pid的進(jìn)程和宿主機(jī)使用的是同一個(gè)/proc文件系統(tǒng),所以這些命令顯示的東西都是一樣的砰粹。所以唧躲,我們還需要使其它的namespace隔離,如文件系統(tǒng)進(jìn)行隔離碱璃。
3.對(duì)照Docker源碼
當(dāng)啟動(dòng)一個(gè)docker容器時(shí)弄痹,會(huì)調(diào)用到dockerd提供的/containers/{name:.*}/start
接口,然后啟動(dòng)一個(gè)容器嵌器,docker服務(wù)收到請(qǐng)求后肛真,調(diào)用關(guān)系如下:
//注冊(cè)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
接口中創(chuàng)建并啟動(dòng)了容器,而創(chuàng)建容器時(shí)傳入的spec
參數(shù)就包含了namespace爽航,我們?cè)賮砜纯?code>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()會(huì)調(diào)用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中還會(huì)根據(jù)其它配置對(duì)namespace進(jìn)行修改
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)
}
其實(shí)很早以前Docker創(chuàng)建一個(gè)容器蚓让,獲取namespace是通過CloneFlags
函數(shù),后來有了開放容器計(jì)劃(OCI)規(guī)范后讥珍,就改為了以上面代碼中方式創(chuàng)建容器历极。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"
//
//沒錯(cuò),就是這里~
//
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
}
現(xiàn)在衷佃,容器運(yùn)行時(shí)趟卸,通過OCI這個(gè)容器運(yùn)行時(shí)規(guī)范同底層的Linux操作系統(tǒng)進(jìn)行交互,即:把容器操作請(qǐng)求翻譯成對(duì)Linux操作系統(tǒng)的調(diào)用(操作Linux Namespace和Cgroups等)氏义。