executor.go 1.6 KB

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