-
Notifications
You must be signed in to change notification settings - Fork 0
/
stop.go
83 lines (79 loc) · 2.49 KB
/
stop.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"TinyDocker/container"
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
"os"
"strconv"
"syscall"
)
func stopContainer(containerName string) {
//获取PID
pid, err := GetContainerPidByName(containerName)
if err != nil {
log.Errorf("Get contaienr pid by name %s error %v", containerName, err)
return
}
pidInt, err := strconv.Atoi(pid)
if err != nil {
log.Errorf("Conver pid from string to int error %v", err)
return
}
//调用kill发送信号给进程,通过传递syscall.SIGTERM信号,杀掉容器主进程
if err := syscall.Kill(pidInt, syscall.SIGTERM); err != nil {
log.Errorf("Stop container %s error %v", containerName, err)
return
}
//获取容器信息,修改状态为STOP,并覆盖之前的信息
containerInfo, err := getContainerInfoByName(containerName)
if err != nil {
log.Errorf("Get container %s info error %v", containerName, err)
return
}
containerInfo.Status = container.STOP
containerInfo.Pid = " "
newContentBytes, err := json.Marshal(containerInfo)
if err != nil {
log.Errorf("Json marshal %s error %v", containerName, err)
return
}
dirURL := fmt.Sprintf(container.DefaultInfoLocation, containerName)
configFilePath := dirURL + container.ConfigName
if err := ioutil.WriteFile(configFilePath, newContentBytes, 0622); err != nil {
log.Errorf("Write file %s error", configFilePath, err)
}
}
func getContainerInfoByName(containerName string) (*container.ContainerInfo, error) {
dirURL := fmt.Sprintf(container.DefaultInfoLocation, containerName)
configFilePath := dirURL + container.ConfigName
contentBytes, err := ioutil.ReadFile(configFilePath)
if err != nil {
log.Errorf("Read file %s error %v", configFilePath, err)
return nil, err
}
var containerInfo container.ContainerInfo
if err := json.Unmarshal(contentBytes, &containerInfo); err != nil {
log.Errorf("GetContainerInfoByName unmarshal error %v", err)
return nil, err
}
return &containerInfo, nil
}
func removeContainer(containerName string) {
containerInfo, err := getContainerInfoByName(containerName)
if err != nil {
log.Errorf("Get container %s info error %v", containerName, err)
return
}
if containerInfo.Status != container.STOP {
log.Errorf("Couldn't remove running container")
return
}
dirURL := fmt.Sprintf(container.DefaultInfoLocation, containerName)
if err := os.RemoveAll(dirURL); err != nil {
log.Errorf("Remove file %s error %v", dirURL, err)
return
}
container.DeleteWorkSpace(containerInfo.Volume, containerName)
}