mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-04-24 04:58:31 -05:00
timeout command execution
This commit is contained in:
@@ -2,6 +2,7 @@ package ocis
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -219,7 +220,17 @@ func waitUntilCompleteShutdown() (bool, string) {
|
||||
}
|
||||
|
||||
func RunCommand(command string) (int, string) {
|
||||
c := exec.Command(config.Get("bin"), command)
|
||||
out, _ := c.CombinedOutput()
|
||||
return c.ProcessState.ExitCode(), string(out)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
c := exec.CommandContext(ctx, config.Get("bin"), command)
|
||||
output, err := c.CombinedOutput()
|
||||
if err != nil {
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
message := "Command timed out:\n" + string(output)
|
||||
return c.ProcessState.ExitCode(), message
|
||||
}
|
||||
}
|
||||
|
||||
return c.ProcessState.ExitCode(), string(output)
|
||||
}
|
||||
|
||||
@@ -52,18 +52,20 @@ func sendResponse(res http.ResponseWriter, success bool, message string) {
|
||||
}
|
||||
|
||||
func sendCmdResponse(res http.ResponseWriter, exitCode int, message string) {
|
||||
var resBody CommandResponse
|
||||
resBody := CommandResponse{
|
||||
BasicResponse: &BasicResponse{
|
||||
Message: message,
|
||||
},
|
||||
ExitCode: exitCode,
|
||||
}
|
||||
|
||||
if exitCode == 0 {
|
||||
resBody.BasicResponse.Status = "OK"
|
||||
} else {
|
||||
resBody.BasicResponse.Status = "ERROR"
|
||||
}
|
||||
|
||||
res.WriteHeader(http.StatusOK)
|
||||
if exitCode == 0 {
|
||||
resBody.Status = "OK"
|
||||
resBody.ExitCode = exitCode
|
||||
resBody.Message = message
|
||||
} else {
|
||||
resBody.Status = "ERROR"
|
||||
resBody.ExitCode = exitCode
|
||||
resBody.Message = message
|
||||
}
|
||||
res.Header().Set("Content-Type", "application/json")
|
||||
|
||||
jsonResponse, _ := json.Marshal(resBody)
|
||||
@@ -128,23 +130,18 @@ func CommandHandler(res http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
body, err := parseJsonBody(req.Body)
|
||||
if req.Body == nil {
|
||||
http.Error(res, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
http.Error(res, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body["command"] == nil {
|
||||
http.Error(res, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
command, ok := body["command"].(string)
|
||||
if !ok || command == "" {
|
||||
http.Error(res, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
exitCode, output := ocis.RunCommand(string(body))
|
||||
|
||||
exitCode, out := ocis.RunCommand(command)
|
||||
|
||||
sendCmdResponse(res, exitCode, out)
|
||||
sendCmdResponse(res, exitCode, output)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user