process.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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, args ...string) *process.Process {
  31. return process.New(
  32. process.WithName(a.BinaryPath(p)),
  33. process.WithArgs(args...),
  34. process.WithStateDir(filepath.Join(a.stateDir, "proc", state)),
  35. )
  36. }
  37. // BinaryPath returns the binary path of the program requested as argument.
  38. // The binary path is relative to the process state directory
  39. func (a *ProcessController) BinaryPath(b string) string {
  40. return filepath.Join(a.stateDir, "bin", b)
  41. }
  42. // Run simply runs a command from a binary in the state directory
  43. func (a *ProcessController) Run(command string, args ...string) (string, error) {
  44. cmd := exec.Command(a.BinaryPath(command), args...)
  45. out, err := cmd.CombinedOutput()
  46. return string(out), err
  47. }