executor.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package executor
  2. import (
  3. pb "github.com/jamesread/OliveTin/gen/grpc"
  4. config "github.com/jamesread/OliveTin/internal/config"
  5. log "github.com/sirupsen/logrus"
  6. "context"
  7. "errors"
  8. "os/exec"
  9. "time"
  10. )
  11. var (
  12. Cfg *config.Config
  13. )
  14. func ExecAction(action string) *pb.StartActionResponse {
  15. res := &pb.StartActionResponse{}
  16. res.TimedOut = false
  17. log.WithFields(log.Fields{
  18. "actionName": action,
  19. }).Infof("StartAction")
  20. actualAction, err := findAction(action)
  21. if err != nil {
  22. log.Errorf("Error finding action %s, %s", err, action)
  23. return res
  24. }
  25. log.WithFields(log.Fields{
  26. "title": actualAction.Title,
  27. "timeout": actualAction.Timeout,
  28. }).Infof("Found action")
  29. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
  30. defer cancel()
  31. cmd := exec.CommandContext(ctx, "sh", "-c", actualAction.Shell)
  32. stdout, stderr := cmd.Output()
  33. res.ExitCode = int32(cmd.ProcessState.ExitCode())
  34. res.Stdout = string(stdout)
  35. if stderr == nil {
  36. res.Stderr = ""
  37. } else {
  38. res.Stderr = stderr.Error()
  39. }
  40. if ctx.Err() == context.DeadlineExceeded {
  41. res.TimedOut = true
  42. }
  43. log.WithFields(log.Fields{
  44. "stdout": res.Stdout,
  45. "stderr": res.Stderr,
  46. "timedOut": res.TimedOut,
  47. "exit": res.ExitCode,
  48. }).Infof("Finished command.")
  49. return res
  50. }
  51. func sanitizeAction(action *config.ActionButton) {
  52. if action.Timeout < 3 {
  53. action.Timeout = 3
  54. }
  55. }
  56. func findAction(actionTitle string) (*config.ActionButton, error) {
  57. for _, action := range Cfg.ActionButtons {
  58. if action.Title == actionTitle {
  59. sanitizeAction(&action)
  60. return &action, nil
  61. }
  62. }
  63. return nil, errors.New("Action not found")
  64. }