executor.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package executor
  2. import (
  3. config "github.com/jamesread/OliveTin/pkg/config"
  4. log "github.com/sirupsen/logrus"
  5. pb "github.com/jamesread/OliveTin/gen/grpc"
  6. "errors"
  7. "os/exec"
  8. "context"
  9. "time"
  10. "fmt"
  11. )
  12. var (
  13. Cfg *config.Config;
  14. )
  15. func ExecAction(action string) (*pb.StartActionResponse) {
  16. res := &pb.StartActionResponse{}
  17. res.TimedOut = false;
  18. log.WithFields(log.Fields{
  19. "actionName": action,
  20. }).Infof("StartAction")
  21. actualAction, err := findAction(action)
  22. if err != nil {
  23. log.Errorf("Error finding action %s, %s", err, action)
  24. return res
  25. }
  26. log.Infof("Found action %s", actualAction.Title)
  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.Stdout = string(stdout)
  32. res.Stderr = fmt.Sprintf("%s", stderr)
  33. if ctx.Err() == context.DeadlineExceeded {
  34. res.TimedOut = true
  35. }
  36. log.Infof("Command %v stdout %v", actualAction.Title, res.Stdout)
  37. log.Infof("Command %v stderr %v", actualAction.Title, res.Stderr)
  38. return res
  39. }
  40. func findAction(actionTitle string) (*config.ActionButton, error) {
  41. for _, action := range Cfg.ActionButtons {
  42. if action.Title == actionTitle {
  43. return &action, nil
  44. }
  45. }
  46. return nil, errors.New("Action not found")
  47. }