likes
comments
collection
share

自己动手写Docker系列 -- 5.6实现删除容器

作者站长头像
站长
· 阅读数 10

简介

在上篇中我们实现了stop命令,停止正在运行的容器,本篇将实现rm命令,删除已经停止的容器

源码说明

同时放到了Gitee和Github上,都可进行获取

本章节对应的版本标签是:5.6,防止后面代码过多,不好查看,可切换到标签版本进行查看

代码实现

实现该功能的主要思路如下:

这部分的实现可以说非常简单了,主要是找到容器的配置文件,将配置文件删除即可

因为我们的ps命令就是读取指定目录下的容器配置信息命令,进行容器列表展示的

我们把对应的容器的配置信息目录一删,就完事了

rm命令添加

在main.go中添加相关的命令:

func main() {
	......
	
	app.Commands = []cli.Command{
		command.InitCommand,
		command.RunCommand,
		command.CommitCommand,
		command.ListCommand,
		command.LogCommand,
		command.ExecCommand,
		command.StopCommand,
		command.RemoveCommand,
	}
	......
}

在main_command.go中添加相关的命令:

var RemoveCommand = cli.Command{
	Name:  "rm",
	Usage: "remove container",
	Action: func(context *cli.Context) {
		if len(context.Args()) < 1 {
			log.Errorf("missing container name")
			return
		}
		containerName := context.Args().Get(0)
		if err := run.RemoveContainer(containerName); err != nil {
			log.Errorf("%v", err)
		}
	},
}

rm命令的具体实现

根据容器名称,找到对应的容器目录,将其进行删除即可

新增stop.go文件

func StopContainer(containerName string) error {
	pid, err := getContainerPidByName(containerName)
	if err != nil {
		return err
	}

	pidInt, err := strconv.Atoi(pid)
	if err != nil {
		return fmt.Errorf("convert pid %s to int err: %v", pid, err)
	}

	if err := syscall.Kill(pidInt, syscall.SIGTERM); err != nil {
		return fmt.Errorf("send sigterm %d, err: %v", pid, err)
	}

	containerInfo, err := getContainerInfoByName(containerName)
	if err != nil {
		return fmt.Errorf("get container info err: %v", err)
	}

	containerInfo.Status = container.STOP
	containerInfo.Pid = ""
	newContainerInfo, err := json.Marshal(containerInfo)
	if err != nil {
		return fmt.Errorf("json marshal %v,err: %v", containerInfo, err)
	}

	dirUrl := fmt.Sprintf(container.DefaultInfoLocation, containerName)
	configPath := dirUrl + container.ConfigName
	if err := ioutil.WriteFile(configPath, newContainerInfo, 0622); err != nil {
		return fmt.Errorf("write file %s err: %v", configPath, err)
	}
	return nil
}

测试运行

在上一篇的测试基础上,我们运行rm命令,看看是否对应的删除了

  • 启动一个后台运行的top命令容器
  • ps查看状态:看到有一个预期的running的容器
  • 查看是否有对应的宿主机进程,看到有一个对应的top进程
  • 使用stop命令
  • ps查看状态:看到已经停止了
  • 查看宿主机是否有top进程,看到没有了
  • 使用rm命令,删除进程
  • ps查看,已经没有了
root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ./main run --name bird -d top                                                                                       ✔  ⚡  417  07:28:53
{"level":"info","msg":"memory cgroup path: /sys/fs/cgroup/memory/mydocker-cgroup","time":"2022-04-09T07:29:00+08:00"}
{"level":"info","msg":"memory cgroup path: /sys/fs/cgroup/memory/mydocker-cgroup","time":"2022-04-09T07:29:00+08:00"}
{"level":"info","msg":"all command is : top","time":"2022-04-09T07:29:00+08:00"}
{"level":"info","msg":"parent process run","time":"2022-04-09T07:29:00+08:00"}

root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ./main ps                                                                                                  SIG(127) ↵  ⚡  418  07:29:00
ID           NAME        PID         STATUS      COMMAND     CREATED
1808352378   bird        126298      running     top         9000-04-04 00:00:00

root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ps -ef|grep top                                                                                                     ✔  ⚡  419  07:29:05
root        2751    1776  0 4月07 ?       00:00:01 /usr/libexec/xdg-desktop-portal
root        2778    1776  0 4月07 ?       00:00:00 /usr/libexec/xdg-desktop-portal-gtk
root      126298       1  0 07:28 pts/2    00:00:00 top
root      126537   22616  0 07:29 pts/2    00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn --exclude-dir=.idea --exclude-dir=.tox top

root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ./main stop bird                                                                                                    ✔  ⚡  420  07:29:09
 
root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ./main ps                                                                                                           ✔  ⚡  421  07:29:20
ID           NAME        PID         STATUS      COMMAND     CREATED
1808352378   bird                    stop        top         9000-04-04 00:00:00

root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ps -ef|grep top                                                                                                     ✔  ⚡  422  07:29:24
root        2751    1776  0 4月07 ?       00:00:01 /usr/libexec/xdg-desktop-portal
root        2778    1776  0 4月07 ?       00:00:00 /usr/libexec/xdg-desktop-portal-gtk
root      126883   22616  0 07:29 pts/2    00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn --exclude-dir=.idea --exclude-dir=.tox top

root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ./main rm bird                                                                                                      ✔  ⚡  423  07:29:26

root@lw-Code-01-Series-PF5NU1G  ~/code/go/dockerDemo   main ●  ./main ps                                                                                                           ✔  ⚡  424  07:40:56
ID          NAME        PID         STATUS      COMMAND     CREATED