🐳 通过 docker rm 回收容器

This commit is contained in:
Liang Ding 2019-05-19 00:59:10 +08:00
parent 9a16c9214f
commit 02a809803e
No known key found for this signature in database
GPG Key ID: 136F30F901A2231D
1 changed files with 13 additions and 4 deletions

View File

@ -21,6 +21,7 @@ import (
"net/http" "net/http"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"time" "time"
@ -50,10 +51,12 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
filePath := args["executable"].(string) filePath := args["executable"].(string)
randInt := rand.Int()
rid := strconv.Itoa(randInt)
var cmd *exec.Cmd var cmd *exec.Cmd
if conf.Docker { if conf.Docker {
fileName := filepath.Base(filePath) fileName := filepath.Base(filePath)
cmd = exec.Command("docker", "run", "--rm", "--cpus", "0.1", "-v", filePath+":/"+fileName, conf.DockerImageGo, "/"+fileName) cmd = exec.Command("docker", "run", "--rm", "--cpus", "0.1", "--name", rid, "-v", filePath+":/"+fileName, conf.DockerImageGo, "/"+fileName)
} else { } else {
cmd = exec.Command(filePath) cmd = exec.Command(filePath)
curDir := filepath.Dir(filePath) curDir := filepath.Dir(filePath)
@ -109,8 +112,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
} }
} }
rid := rand.Int() go func(runningId string) {
go func(runningId int) {
defer util.Recover() defer util.Recover()
logger.Debugf("User [%s, %s] is running [id=%d, file=%s]", wSession.UserId, sid, runningId, filePath) logger.Debugf("User [%s, %s] is running [id=%d, file=%s]", wSession.UserId, sid, runningId, filePath)
@ -160,7 +162,14 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
channelRet["cmd"] = "run-done" channelRet["cmd"] = "run-done"
select { select {
case <-after: case <-after:
cmd.Process.Kill() if conf.Docker {
killCmd := exec.Command("docker", "rm", "-f", rid)
if err := killCmd.Run(); nil != err {
logger.Errorf("executes [docker rm -f " + rid + "] failed [" + err.Error() + "], this will cause resource leaking")
}
} else {
cmd.Process.Kill()
}
channelRet["output"] = "\nrun program timeout in 5s\n" channelRet["output"] = "\nrun program timeout in 5s\n"
case <-done: case <-done: