-
Notifications
You must be signed in to change notification settings - Fork 0
/
stop.go
84 lines (79 loc) · 2.23 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
84
package main
import (
"Mydockker/container"
"Mydockker/meta"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
"syscall"
log "github.com/sirupsen/logrus"
)
func StopContainer(containerName string) {
// get pid of containerProcess
info, err := getContainerInfoByName(containerName)
if err != nil {
log.Errorf("Get containerInfo %s failed %v", containerName, err)
return
}
pid, err := strconv.Atoi(info.Pid)
if err != nil {
log.Errorf("Convert containerPid %s failed %v", containerName, err)
return
}
// send SIGTERM to containerProcess
if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
log.Errorf("Send SIGTERM to %s failed %v", containerName, err)
return
}
// update and cleanup containerStatus
info.Status = container.STOP
info.Pid = " "
content, err := json.Marshal(info)
if err != nil {
log.Errorf("Json marshal %s failed %v", containerName, err)
return
}
dirUrl := fmt.Sprintf(container.JsonFormat, containerName)
configPath := dirUrl + container.ConfigName
if err := ioutil.WriteFile(configPath, content, container.Perm0622); err != nil {
log.Errorf("Write file %s failed %v", configPath, err)
}
}
/**
* get containerInfo by containerName
*/
func getContainerInfoByName(containerName string) (*container.Info, error) {
dirUrl := fmt.Sprintf(container.JsonFormat, containerName)
configFilePath := dirUrl + container.ConfigName
content, err := ioutil.ReadFile(configFilePath)
if err != nil {
return nil, meta.NewError(meta.ErrRead, "Read configFile failed", err)
}
var info container.Info
if err = json.Unmarshal(content, &info); err != nil {
return nil, meta.NewError(meta.ErrRead, "Unmarshal containerInfo failed", err)
}
return &info, nil
}
/**
* remove unused container
*/
func RemoveContainer(containerName string) {
info, err := getContainerInfoByName(containerName)
if err != nil {
log.Errorf("Get container %s info failed %v", containerName, err)
return
}
if info.Status != container.STOP {
log.Errorf("Can't remove running container")
return
}
dirUrl := fmt.Sprintf(container.JsonFormat, containerName)
if err := os.RemoveAll(dirUrl); err != nil {
log.Errorf("Remove containerInfoFile %s failed", containerName)
return
}
container.DeleteWorkSpace(info.Volume, containerName)
}