-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlaunchctl.go
280 lines (230 loc) · 6.1 KB
/
launchctl.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package launchctlutil
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/user"
"runtime"
"strconv"
"strings"
)
const (
Unknown Status = "unknown"
NotInstalled Status = "not_installed"
Running Status = "running"
NotRunning Status = "not_running"
)
// Status represents the status of a launchd service.
type Status string
// StatusDetails provides detailed information about the status of
// a launchd service.
type StatusDetails struct {
Status Status
Pid int
LastExitStatus int
PidErr error
LastExitStatusErr error
}
// GotLastExitStatus returns true if the launchd service provided an
// exit status.
func (o StatusDetails) GotLastExitStatus() bool {
return o.LastExitStatusErr == nil
}
// GotPid returns true if the launchd service provided a PID.
func (o StatusDetails) GotPid() bool {
return o.PidErr == nil
}
const (
defaultLaunchctl = "launchctl"
couldNotFindServicePrefix = "Could not find service "
lastExitStatusPrefix = "\"LastExitStatus\" = "
pidPrefix = "\"PID\" = "
serviceListLineSuffix = ";"
)
var (
// ExePath is the path to the launchctl CLI application.
ExePath = defaultLaunchctl
)
// Install installs the provided service Configuration.
func Install(configuration Configuration) error {
if configuration.GetKind() == Daemon {
err := isRoot()
if err != nil {
return err
}
}
configPath, err := configuration.GetFilePath()
if err != nil {
return err
}
// Try to remove the LaunchAgent first because it may already exist.
// Ignore errors because this may create false positives.
Remove(configPath, configuration.GetKind())
err = ioutil.WriteFile(configPath, []byte(configuration.GetContents()), 0600)
if err != nil {
return err
}
_, err = run("load", configPath)
if err != nil {
return err
}
// Check that the LaunchAgent was installed using special logic because
// launchctl seems to return exit status 0 even when an error occurs.
isInstalled, err := IsInstalled(configuration)
if err != nil {
return err
}
if !isInstalled {
// Try to remove the config file if the installation fails.
// Ignore errors because this may create false positives.
os.Remove(configPath)
return fmt.Errorf("an unknown error occurred installing the laucnctl config")
}
return nil
}
// Remove unloads and removes the specified service configuration file.
func Remove(configPath string, kind Kind) error {
if kind == Daemon {
err := isRoot()
if err != nil {
return err
}
}
_, err := run("unload", configPath)
if err != nil {
return err
}
err = os.Remove(configPath)
if err != nil {
return err
}
return nil
}
// RemoveService unloads the specified service by label. Note, the service will
// be loaded again after rebooting or logging out.
//
// Warning: This call does not error if the specified service does not exist.
func RemoveService(label string) error {
_, err := run("remove", label)
if err != nil {
return err
}
return nil
}
// IsInstalled is a wrapper for Configuration.IsInstalled().
func IsInstalled(configuration Configuration) (isInstalled bool, err error) {
return configuration.IsInstalled()
}
// Start starts the specified launchd service.
func Start(label string, kind Kind) error {
if kind == Daemon {
err := isRoot()
if err != nil {
return err
}
}
_, err := run("start", label)
if err != nil {
return err
}
return nil
}
// Stop stops the specified launchd service.
func Stop(label string, kind Kind) error {
if kind == Daemon {
err := isRoot()
if err != nil {
return err
}
}
_, err := run("stop", label)
if err != nil {
return err
}
return nil
}
// CurrentStatus returns the current status of the specified launchd service.
func CurrentStatus(label string) (StatusDetails, error) {
output, err := run("list", label)
if err != nil {
if strings.HasPrefix(output, couldNotFindServicePrefix) {
return StatusDetails{
Status: NotInstalled,
}, nil
}
return StatusDetails{
Status: Unknown,
}, err
}
details := StatusDetails{
Status: NotRunning,
}
for _, l := range strings.Split(output, "\n") {
l = strings.TrimSpace(l)
if strings.HasPrefix(l, lastExitStatusPrefix) {
exit, err := getLastExitStatus(l)
if err != nil {
details.LastExitStatusErr = err
continue
}
details.LastExitStatus = exit
}
if strings.HasPrefix(l, pidPrefix) {
pid, err := getPid(l)
if err != nil {
details.PidErr = err
continue
}
details.Pid = pid
details.Status = Running
}
}
return details, nil
}
func getPid(lineWithoutLeadingSpaces string) (int, error) {
lineWithoutLeadingSpaces = strings.TrimPrefix(lineWithoutLeadingSpaces, pidPrefix)
lineWithoutLeadingSpaces = strings.TrimSuffix(lineWithoutLeadingSpaces, serviceListLineSuffix)
pid, err := strconv.Atoi(lineWithoutLeadingSpaces)
if err != nil {
return 0, err
}
return pid, nil
}
func getLastExitStatus(lineWithoutLeadingSpaces string) (int, error) {
lineWithoutLeadingSpaces = strings.TrimPrefix(lineWithoutLeadingSpaces, lastExitStatusPrefix)
lineWithoutLeadingSpaces = strings.TrimSuffix(lineWithoutLeadingSpaces, serviceListLineSuffix)
exit, err := strconv.Atoi(lineWithoutLeadingSpaces)
if err != nil {
return 0, err
}
return exit, nil
}
func isRoot() error {
currentUser, err := user.Current()
if err != nil {
// For whatever reason, 'user.Current()' throws a "not
// implemented error" when running as a launch service
// on macOS.
if runtime.GOOS == "darwin" && strings.Contains(err.Error(), "Current not implemented on") {
return nil
}
return fmt.Errorf("failed to check if current user is root - %s", err.Error())
}
if currentUser.Username == "root" {
return nil
}
return fmt.Errorf("root privileges are required to do this")
}
func run(args... string) (output string, err error) {
command := exec.Command(ExePath, args...)
raw, err := command.CombinedOutput()
output = string(raw)
if err != nil {
return output, fmt.Errorf("%s - output: %s", err.Error(), output)
}
if strings.Contains(output, ": Invalid property list") {
return output, fmt.Errorf("invalid property list")
}
return output, nil
}