-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstop.go
61 lines (58 loc) · 1.73 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
package main
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"os"
"path"
"strconv"
"syscall"
"tiny-docker/constant"
"tiny-docker/container"
)
func stopContainer(containerId string) {
// 1. 根据id查询容器的详细信息
containerInfo, err := getInfoByContainerId(containerId)
if err != nil {
log.Errorf("Get container %s info error %v", containerId, err)
return
}
pidInt, err := strconv.Atoi(containerInfo.Pid)
if err != nil {
log.Errorf("Conver pid from string to int error %v", err)
return
}
// 2.发送SIGTERM信号
if err = syscall.Kill(pidInt, syscall.SIGTERM); err != nil {
log.Errorf("Stop container %s error %v", containerId, err)
return
}
// 3.修改容器信息,将容器置为STOP状态,并清空PID
containerInfo.Status = container.STOP
containerInfo.Pid = " "
newContentBytes, err := json.Marshal(containerInfo)
if err != nil {
log.Errorf("Json marshal %s error %v", containerId, err)
return
}
//重新写回存储器信息的文件
dirPath := fmt.Sprintf(container.InfoLocFormat, containerId)
configFilePath := path.Join(dirPath, container.ConfigName)
if err := os.WriteFile(configFilePath, newContentBytes, constant.Perm0622); err != nil {
log.Errorf("Write file %s error:%v", configFilePath, err)
}
}
func getInfoByContainerId(containerId string) (*container.Info, error) {
dirPath := fmt.Sprintf(container.InfoLocFormat, containerId)
configFilePath := path.Join(dirPath, container.ConfigName)
contentBytes, err := os.ReadFile(configFilePath)
if err != nil {
return nil, errors.Wrapf(err, "read file %s", configFilePath)
}
var info container.Info
if err = json.Unmarshal(contentBytes, &info); err != nil {
return nil, err
}
return &info, nil
}