1. 准备工作
1.1 准备环境
root@nicktming:~/go/src/github.com/nicktming/mydocker# git clone https://github.com/nicktming/mydocker.git
root@nicktming:~/go/src/github.com/nicktming/mydocker# git checkout code-5.1
root@nicktming:~/go/src/github.com/nicktming/mydocker# git checkout -b dev-5.2
1.2 准备busybox.tar
// 前提条件
root@nicktming:/nicktming# pwd
/nicktming
root@nicktming:/nicktming# ls
busybox.tar
1.3 预期效果
root@nicktming:~/go/src/github.com/nicktming/mydocker# git clone https://github.com/nicktming/mydocker.git
root@nicktming:~/go/src/github.com/nicktming/mydocker# git checkout code-5.2
root@nicktming:~/go/src/github.com/nicktming/mydocker# go build .
root@nicktming:~/go/src/github.com/nicktming/mydocker# ./mydocker run -d /bin/top
root@nicktming:~/go/src/github.com/nicktming/mydocker# ./mydocker run -d -name test /bin/top
root@nicktming:~/go/src/github.com/nicktming/mydocker# ./mydocker ps
ID NAME PID STATUS COMMAND CREATED
15549996015865478061 15549996015865478061 1497 running /bin/top 2019-04-12 00:20:01
15549996129084897981 test 1526 running /bin/top 2019-04-12 00:20:12
2. 方法
2.1 一些公共方法
type ContainerInfo struct {
Pid string `json:"pid"`
Id string `json:"id"`
Name string `json:"name"`
Command string `json:"command"`
CreateTime string `json:"createTime"`
Status string `json:"status"`
}
var (
RUNNING string = "running"
STOP string = "stopped"
EXIT string = "exited"
CONTAINS string = "/var/run/mydocker"
INFOLOCATION string = "/var/run/mydocker/%s"
CONFIGNAME string = "config.json"
)
func writeUUID(uuid string) {
ioutil.WriteFile("uuid.txt", []byte(uuid), 0644)
}
func readUUID() string {
data, _ := ioutil.ReadFile("uuid.txt")
return string(data)
}
2.2 生成UUID
生成
containerId
,就是根据当前时间再连上一些随机数. 方法如下:
func ContainerUUID() string {
str := time.Now().UnixNano()
containerId := fmt.Sprintf("%d%d", str, int(math.Abs(float64(rand.Intn(10)))))
log.Printf("containerId:%s\n", containerId)
return containerId
}
func Test001(t *testing.T) {
uuid := ContainerUUID()
//将uuid写入一个文件中 方便测试用一个uuid测试增删改查方法
writeUUID(uuid)
}
测试
Test001
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# pwd
/root/go/src/github.com/nicktming/mydocker/command
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# ls
command.go commit.go init.go models.go run.go utils.go utils_test.go
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# ls
command.go commit.go init.go models.go run.go utils.go utils_test.go
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# go test -v utils_test.go -test.run Test001
=== RUN Test001
2019/04/11 22:24:18 containerId:15549926581106262991
--- PASS: Test001 (0.00s)
PASS
ok command-line-arguments 0.003s
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# cat uuid.txt
15549926581106262991
root@nicktming:~/go/src/github.com/nicktming/mydocker/command#
2.3 保存容器metadata
将一个容器保存到
/var/run/mydocker
目录下:
func RecordContainerInfo(pid, name, id, command string) error {
containerInfo := &ContainerInfo {
Pid: pid,
Id: id,
Name: name,
Command: command,
CreateTime: time.Now().Format("2006-01-02 15:04:05"),
Status: RUNNING,
}
jsonInfo, _ := json.Marshal(containerInfo)
log.Printf("jsonInfo:%s\n", string(jsonInfo))
location := fmt.Sprintf(INFOLOCATION, name)
file := location + "/" + CONFIGNAME
if err := os.MkdirAll(location, 0622); err != nil {
return fmt.Errorf("create %s error : %v\n", location, err)
}
if err := ioutil.WriteFile(file, []byte(jsonInfo), 0622); err != nil {
return fmt.Errorf("write %s to %s error:%v\n", jsonInfo, file, err)
}
return nil
}
func Test002(t *testing.T) {
uuid := readUUID()
if err := RecordContainerInfo(uuid, uuid, uuid, "/bin/top"); err != nil {
log.Printf("RecordContainerInfo error : %v\n", err)
} else {
log.Printf("write successfully!\n")
}
}
测试
Test002
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# go test -v utils_test.go -test.run Test002
=== RUN Test002
2019/04/11 22:25:36 jsonInfo:{"pid":"15549926581106262991","id":"15549926581106262991","name":"15549926581106262991","command":"/bin/top","createTime":"2019-04-11 22:25:36","status":"running"}
2019/04/11 22:25:36 write successfully!
--- PASS: Test002 (0.00s)
PASS
ok command-line-arguments 0.003s
----------------------------terminal 02-------------------------------
root@nicktming:/var/run/mydocker# pwd
/var/run/mydocker
root@nicktming:/var/run/mydocker# cat 15549926581106262991/config.json
{"pid":"15549926581106262991","id":"15549926581106262991","name":"15549926581106262991","command":"/bin/top","createTime":"2019-04-11 22:25:36","status":"running"}
root@nicktming:/var/run/mydocker#
2.4 获取容器metadata
根据容器名读取容器的
metadata
func GetContainerInfo(name string) (*ContainerInfo, error) {
location := fmt.Sprintf(INFOLOCATION, name)
file := location + "/" + CONFIGNAME
containerInfo := &ContainerInfo {}
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("read data %s error:%s\n", data, err)
}
json.Unmarshal(data, containerInfo)
return containerInfo, nil
}
func Test003(t *testing.T) {
uuid := readUUID()
containerInfo, _ := GetContainerInfo(uuid)
if containerInfo != nil {
log.Printf("Pid:%s, Id:%s, Name:%s, Command:%s, CreateTime:%s, Status:%s\n",
containerInfo.Pid, containerInfo.Id, containerInfo.Name, containerInfo.Command, containerInfo.CreateTime, containerInfo.Status)
}
}
测试
Test003
如下:
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# go test -v utils_test.go -test.run Test003
=== RUN Test003
2019/04/11 22:26:06 Pid:15549926581106262991, Id:15549926581106262991, Name:15549926581106262991, Command:/bin/top, CreateTime:2019-04-11 22:25:36, Status:running
--- PASS: Test003 (0.00s)
PASS
ok command-line-arguments 0.003s
2.5 显示所有容器metadata
显示所有容器的
metadata
并格式打印
func Test004(t *testing.T) {
ShowAllContainers()
}
func ShowAllContainers() {
files, err := ioutil.ReadDir(CONTAINS)
if err != nil {
fmt.Errorf("readDir error : %v\n", err)
return
}
var containers []*ContainerInfo
for _, file := range files {
container, err := GetContainerInfo(file.Name())
if err != nil {
log.Printf("ERROR: %v\n", err)
continue
}
containers = append(containers, container)
}
w := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)
fmt.Fprint(w, "ID\tNAME\tPID\tSTATUS\tCOMMAND\tCREATED\n")
for _, item := range containers {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",
item.Id,
item.Name,
item.Pid,
item.Status,
item.Command,
item.CreateTime)
}
if err := w.Flush(); err != nil {
fmt.Errorf("Flush error %v", err)
}
}
测试
Test004
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# go test -v utils_test.go -test.run Test004
=== RUN Test004
ID NAME PID STATUS COMMAND CREATED
15549926581106262991 15549926581106262991 15549926581106262991 running /bin/top 2019-04-11 22:25:36
--- PASS: Test004 (0.00s)
PASS
ok command-line-arguments 0.003s
2.6 删除容器metadata
根据容器名删除某个容器的
metadata
func DeleteContainerInfo(name string) error {
location := fmt.Sprintf(INFOLOCATION, name)
if err := os.RemoveAll(location); err != nil {
return fmt.Errorf("RemoveAll %s error:%v\n", location, err)
}
return nil
}
func Test005(t *testing.T) {
uuid := readUUID()
if err := DeleteContainerInfo(uuid); err != nil {
log.Printf("DeleteContainerInfo error %v\n", err)
}
}
测试
Test005
----------------------------terminal 01-------------------------------
root@nicktming:/var/run/mydocker# pwd
/var/run/mydocker
root@nicktming:/var/run/mydocker# cat 15549926581106262991/config.json
{"pid":"15549926581106262991","id":"15549926581106262991","name":"15549926581106262991","command":"/bin/top","createTime":"2019-04-11 22:25:36","status":"running"}
root@nicktming:/var/run/mydocker#
----------------------------terminal 02-------------------------------
root@nicktming:~/go/src/github.com/nicktming/mydocker/command# go test -v utils_test.go -test.run Test005
=== RUN Test005
--- PASS: Test005 (0.00s)
PASS
ok command-line-arguments 0.002s
----------------------------terminal 01-------------------------------
root@nicktming:/var/run/mydocker# ls
root@nicktming:/var/run/mydocker#
3. 实现
有了
2
中的方法后实现起来就很简单了
3.1 增加参数容器名字
在
command/command.go
中增加参数name
var RunCommand = cli.Command{
Name: "run",
Flags: []cli.Flag {
...
cli.StringFlag{
Name: "name",
Usage: "container name",
},
...
},
Action: func(c *cli.Context) error {
...
containerName := c.String("name")
...
Run(command, tty, &cg, rootPath, volumes, containerName)
return nil
},
}
3.2 修改Run
方法
修改
command/run.go
中的Run
方法.
func Run(command string, tty bool, cg *cgroups.CroupManger, rootPath string, volumes []string, containerName string) {
...
id := ContainerUUID()
if containerName == "" {
containerName = id
}
RecordContainerInfo(strconv.Itoa(cmd.Process.Pid), containerName, id, command)
// false 表明父进程(Run程序)无须等待子进程(Init程序,Init进程后续会被用户程序覆盖)
if tty {
cmd.Wait()
// -it 交互式的时候退出容器时删除容器metadata
DeleteContainerInfo(containerName)
}
}
3.3 增加ps命令
增加
ps
命令列出所有正在运行的容器.
//command/command.go
var ListCommand = cli.Command{
Name: "ps",
Action: func(c *cli.Context) error {
List()
return nil
},
}
// command/list.go
func List() {
ShowAllContainers()
}
// main.go
func main() {
...
app.Commands = []cli.Command{
command.RunCommand,
command.InitCommand,
command.CommitCommand,
command.ListCommand,
}
...
}
3.4 测试
root@nicktming:~/go/src/github.com/nicktming/mydocker# go build .
root@nicktming:~/go/src/github.com/nicktming/mydocker# ./mydocker run -d /bin/top
2019/04/11 23:18:01 volume:[]
2019/04/11 23:18:01 rootPath:
2019/04/11 23:18:01 rootPath is empaty, set cmd.Dir by default: /nicktming/mnt
2019/04/11 23:18:02 containerId:15549958821549242021
2019/04/11 23:18:02 jsonInfo:{"pid":"28396","id":"15549958821549242021","name":"15549958821549242021","command":"/bin/top","createTime":"2019-04-11 23:18:02","status":"running"}
2019/04/11 23:18:02 remove /nicktming/writerLayer, err:remove /nicktming/writerLayer: device or resource busy
root@nicktming:~/go/src/github.com/nicktming/mydocker#
root@nicktming:~/go/src/github.com/nicktming/mydocker# ./mydocker ps
ID NAME PID STATUS COMMAND CREATED
15549958821549242021 15549958821549242021 28396 running /bin/top 2019-04-11 23:18:02
root@nicktming:~/go/src/github.com/nicktming/mydocker#
root@nicktming:~/go/src/github.com/nicktming/mydocker# ./mydocker run -d -name test /bin/top
2019/04/11 23:18:42 volume:[]
2019/04/11 23:18:42 rootPath:
2019/04/11 23:18:42 rootPath is empaty, set cmd.Dir by default: /nicktming/mnt
2019/04/11 23:18:42 mkdir /nicktming/busybox err:mkdir /nicktming/busybox: file exists, set cmd.Dir by default: /nicktming/mnt
2019/04/11 23:18:42 mkdir /nicktming/writerLayer err:mkdir /nicktming/writerLayer: file exists
2019/04/11 23:18:42 containerId:15549959221141642621
2019/04/11 23:18:42 jsonInfo:{"pid":"28451","id":"15549959221141642621","name":"test","command":"/bin/top","createTime":"2019-04-11 23:18:42","status":"running"}
2019/04/11 23:18:42 mount -f /nicktming/mnt, err:exit status 1
2019/04/11 23:18:42 remove /nicktming/writerLayer, err:remove /nicktming/writerLayer: device or resource busy
root@nicktming:~/go/src/github.com/nicktming/mydocker# ./mydocker ps
ID NAME PID STATUS COMMAND CREATED
15549958821549242021 15549958821549242021 28396 running /bin/top 2019-04-11 23:18:02
15549959221141642621 test 28451 running /bin/top 2019-04-11 23:18:42
root@nicktming:~/go/src/github.com/nicktming/mydocker#
root@nicktming:~/go/src/github.com/nicktming/mydocker# tree /var/run/mydocker/
/var/run/mydocker/
|-- 15549958821549242021
| `-- config.json
`-- test
`-- config.json
2 directories, 2 files
可以看到列出了所有正在运行的容器.
4. 时序图
图片.png
图片.png
5. 参考
1. 自己动手写docker.(基本参考此书,加入一些自己的理解,加深对
docker
的理解)
6. 全部内容
mydocker.png
1. [mydocker]---环境说明
2. [mydocker]---urfave cli 理解
3. [mydocker]---Linux Namespace
4. [mydocker]---Linux Cgroup
5. [mydocker]---构造容器01-实现run命令
6. [mydocker]---构造容器02-实现资源限制01
7. [mydocker]---构造容器02-实现资源限制02
8. [mydocker]---构造容器03-实现增加管道
9. [mydocker]---通过例子理解存储驱动AUFS
10. [mydocker]---通过例子理解chroot 和 pivot_root
11. [mydocker]---一步步实现使用busybox创建容器
12. [mydocker]---一步步实现使用AUFS包装busybox
13. [mydocker]---一步步实现volume操作
14. [mydocker]---实现保存镜像
15. [mydocker]---实现容器的后台运行
16. [mydocker]---实现查看运行中容器
17. [mydocker]---实现查看容器日志
18. [mydocker]---实现进入容器Namespace
19. [mydocker]---实现停止容器
20. [mydocker]---实现删除容器
21. [mydocker]---实现容器层隔离
22. [mydocker]---实现通过容器制作镜像
23. [mydocker]---实现cp操作
24. [mydocker]---实现容器指定环境变量
25. [mydocker]---网际协议IP
26. [mydocker]---网络虚拟设备veth bridge iptables
27. [mydocker]---docker的四种网络模型与原理实现(1)
28. [mydocker]---docker的四种网络模型与原理实现(2)
29. [mydocker]---容器地址分配
30. [mydocker]---网络net/netlink api 使用解析
31. [mydocker]---网络实现
32. [mydocker]---网络实现测试
网友评论