From bb6ed73b4542c19038829d3247e3beb8d5be524c Mon Sep 17 00:00:00 2001 From: rodley82 Date: Mon, 20 Jun 2022 02:32:56 -0300 Subject: [PATCH] Mejorado el manejo de timeout para comando ping en general ahora espera 5 --- internal/slack/handler.go | 41 ++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/internal/slack/handler.go b/internal/slack/handler.go index b7c5b7d..6474eb6 100644 --- a/internal/slack/handler.go +++ b/internal/slack/handler.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "os" + "time" "os/exec" "rodleyserverbot/slack-bot/config" "github.com/slack-go/slack" @@ -64,9 +65,11 @@ func Start() { //fmt.Println("Value:", action.Value) var output string var err error + + replyToAction(callback.Channel.ID, "Chi Chi Chi Chi Amo, trabajando, tenga paciencia :pray:", client) output, err = executeAction(action.Value) if err == nil { - finalMessage := fmt.Sprintf("Chi chi chi chi amo!\n*Output*\n```\n%s\n```", output) + finalMessage := fmt.Sprintf("Resultado*\n```\n%s\n```", output) replyToAction(callback.Channel.ID, finalMessage, client) } case slack.InteractionTypeMessageAction: @@ -138,20 +141,48 @@ func handleEventMessage(event slackevents.EventsAPIEvent, client *slack.Client) } func executeAction(actionName string) (string, error) { - fmt.Println("executeAction actionName:", actionName, "actions:", config.Config.Actions) + //fmt.Println("executeAction actionName:", actionName, "actions:", config.Config.Actions) var output_str string + var err error for _, action := range config.Config.Actions { if action.Name == actionName { - cmd := exec.Command("/bin/bash", action.Path) - output, err := cmd.Output() + output_str, err = executeScript(action.Path) if err != nil { fmt.Printf("error %s", err) return "", err } - output_str = string(output) } } + return output_str, err +} + +func executeScript(scriptPath string) (string, error) { + // Create a new context and add a timeout to it + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() // The cancel should be deferred so resources are cleaned up + + // Create the command with our context + cmd := exec.CommandContext(ctx, "/bin/bash", scriptPath) + + // This time we can simply use Output() to get the result. + out, err := cmd.Output() + + // We want to check the context error to see if the timeout was executed. + // The error returned by cmd.Output() will be OS specific based on what + // happens when a process is killed. + if ctx.Err() == context.DeadlineExceeded { + fmt.Println("Command timed out") + return "", context.DeadlineExceeded + } + + // If there's no context error, we know the command completed (or errored). + + if err != nil { + fmt.Println("Non-zero exit code:", err) + } + output_str := string(out) + // fmt.Println("Output:", output_str) return output_str, nil }