executor.go 1.7 KB

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