12
var startedRE = regexp.MustCompile("^.* start/running, process (\\d+)\n$")
14
// Service provides visibility into and control over an upstart service.
17
InitDir string // defaults to "/etc/init"
20
func NewService(name string) *Service {
21
return &Service{Name: name, InitDir: "/etc/init"}
24
// path returns the path to the service's configuration file.
25
func (s *Service) path() string {
26
return filepath.Join(s.InitDir, s.Name+".conf")
29
// pid returns the Service's current pid, or -1 if it cannot be determined.
30
func (s *Service) pid() int {
31
cmd := exec.Command("status", s.Name)
32
out, err := cmd.CombinedOutput()
36
match := startedRE.FindStringSubmatch(string(out))
40
pid, err := strconv.Atoi(match[1])
47
// Installed returns true if the Service appears to be installed.
48
func (s *Service) Installed() bool {
49
_, err := os.Stat(s.path())
53
// Running returns true if the Service appears to be running.
54
func (s *Service) Running() bool {
58
// Stable returns true if the Service appears to be running stably, by
59
// checking that the reported pid does not change over the course of 5
60
// checks over 0.4 seconds.
61
func (s *Service) Stable() bool {
66
for i := 0; i < 4; i++ {
67
<-time.After(100 * time.Millisecond)
75
// Start starts the service.
76
func (s *Service) Start() error {
80
return exec.Command("start", s.Name).Run()
83
// Stop stops the service.
84
func (s *Service) Stop() error {
88
return exec.Command("stop", s.Name).Run()
91
// Remove removes the service.
92
func (s *Service) Remove() error {
96
if err := s.Stop(); err != nil {
99
return os.Remove(s.path())