/
upstart.go
88 lines (69 loc) · 1.84 KB
/
upstart.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Package upstart provides functions to control upstart jobs.
// Note that this is only usable on systems where upstart is the init system.
package upstart
import (
"fmt"
"github.com/godbus/dbus"
)
var (
hasUpstart = false
)
func init() {
hasUpstart = Detect()
}
// Detect returns true if the system we're running on has an upstart daemon listening on
// its known address and we're able to communicate with it.
func Detect() bool {
versionPropPath := "com.ubuntu.Upstart0_6.version"
// connect to the system bus
conn, err := dbus.SystemBus()
if err != nil {
return false
}
_, err = conn.
Object(upstartServiceDBusPath, upstartManagerObject).
GetProperty(versionPropPath)
if err != nil {
return false
}
return true
}
// StartJob starts the specified job.
func StartJob(name string) error {
if !hasUpstart {
return fmt.Errorf("Unable to communicate with upstart")
}
job := &job{Name: name}
return job.StartWithEnv(map[string]string{})
}
// StopJob stops the specified job.
func StopJob(name string) error {
if !hasUpstart {
return fmt.Errorf("Unable to communicate with upstart")
}
job := &job{Name: name}
return job.Stop()
}
// RestartJob restarts the specified job.
func RestartJob(name string) error {
if !hasUpstart {
return fmt.Errorf("Unable to communicate with upstart")
}
job := &job{Name: name}
return job.Restart()
}
// ListJobInstances lists the instances of the specified job. Unless configured to run
// as multiple instances, a job has a single instance.
func ListJobInstances(name string) ([]string, error) {
if !hasUpstart {
return nil, fmt.Errorf("Unable to communicate with upstart")
}
ret := []string{}
job := &job{Name: name}
printInst := func(_ *dbus.Conn, inst dbus.ObjectPath) error {
ret = append(ret, string(inst))
return nil
}
err := job.foreachInstance(printInst)
return ret, err
}