timeout command execution

This commit is contained in:
Saw-jan
2024-07-05 14:55:03 +05:45
parent d1d25ae940
commit 3306a1f277
2 changed files with 34 additions and 26 deletions
+14 -3
View File
@@ -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)
}
+20 -23
View File
@@ -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)
}