• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Write a docker with go in seven days

King Wang

1 月 3, 2022

Today is the last day , We finally stop the container , Delete function to achieve

Container stop

In the last section , We go through config.json The basic information of the container is recorded , One of them status Field is used to record the state of the container , And a PID Field record container init Process on the host Pid, We stop the container , That is to say pid The process to kill , And update the status Status can be

// Stop container , Modify the container state 
func StopContainer(containerName string) {

info, err := getContainerInfo(containerName)
if err != nil {

logrus.Errorf("get container info, err: %v", err)
return
}
if info.Pid != "" {

pid, _ := strconv.Atoi(info.Pid)
// Kill process 
if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {

logrus.Errorf("stop container, pid: %d, err: %v", pid, err)
return
}
// Modify the container state 
info.Status = common.Stop
info.Pid = ""
bs, _ := json.Marshal(info)
fileName := path.Join(common.DefaultContainerInfoPath, containerName, common.ContainerInfoFileName)
err := ioutil.WriteFile(fileName, bs, 0622)
if err != nil {

logrus.Errorf("write container config.json, err: %v", err)
}
}
}

Delete container

First of all, it needs to be clear , We can’t delete running containers , That is to say status by Running The container of , So we must stop the container before we delete it , Then we delete a series of folders generated by the container

// Delete container 
func RemoveContainer(containerName string) {

info, err := getContainerInfo(containerName)
if err != nil {

logrus.Errorf("get container info, err: %v", err)
return
}
// You can only delete containers in the stopped state 
if info.Status != common.Stop {

logrus.Errorf("can't remove running container")
return
}
dir := path.Join(common.DefaultContainerInfoPath, containerName)
err = os.RemoveAll(dir)
if err != nil {

logrus.Errorf("remove container dir: %s, err: %v", dir, err)
return
}
}

Here we are 《 For seven days Go Write a docker》 The system article is over , Finally, thank you for your attention and support ! All the source code of the article has been in GitHub Open source , Click here

发表回复