process.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package service
  16. import (
  17. "os/exec"
  18. "path/filepath"
  19. process "github.com/mudler/go-processmanager"
  20. )
  21. // NewProcessController returns a new process controller associated with the state directory
  22. func NewProcessController(statedir string) *ProcessController {
  23. return &ProcessController{stateDir: statedir}
  24. }
  25. // ProcessController syntax sugar around go-processmanager
  26. type ProcessController struct {
  27. stateDir string
  28. }
  29. // Process returns a process associated within binaries inside the state dir
  30. func (a *ProcessController) Process(state, p string, opts ...process.Option) *process.Process {
  31. return process.New(
  32. append(opts,
  33. process.WithName(a.BinaryPath(p)),
  34. process.WithStateDir(filepath.Join(a.stateDir, "proc", state)),
  35. )...,
  36. )
  37. }
  38. // BinaryPath returns the binary path of the program requested as argument.
  39. // The binary path is relative to the process state directory
  40. func (a *ProcessController) BinaryPath(b string) string {
  41. return filepath.Join(a.stateDir, "bin", b)
  42. }
  43. // Run simply runs a command from a binary in the state directory
  44. func (a *ProcessController) Run(command string, args ...string) (string, error) {
  45. cmd := exec.Command(a.BinaryPath(command), args...)
  46. out, err := cmd.CombinedOutput()
  47. return string(out), err
  48. }