-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
345 lines (297 loc) · 9.72 KB
/
service.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package service
import (
"os"
"path/filepath"
"strings"
"time"
"github.com/juju/clock"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/juju/os/v2/series"
"github.com/juju/retry"
"github.com/juju/juju/service/common"
"github.com/juju/juju/service/snap"
"github.com/juju/juju/service/systemd"
"github.com/juju/juju/service/upstart"
"github.com/juju/juju/service/windows"
)
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination mocks/service.go github.com/juju/juju/service Service
var logger = loggo.GetLogger("juju.service")
// These are the names of the init systems recognized by juju.
const (
InitSystemSystemd = "systemd"
InitSystemUpstart = "upstart"
InitSystemWindows = "windows"
InitSystemSnap = "snap"
)
// linuxInitSystems lists the names of the init systems that juju might
// find on a linux host.
var linuxInitSystems = []string{
InitSystemSystemd,
InitSystemUpstart,
// InitSystemSnap is not part of this list, so that
// the discovery machinery can't select snap over systemd
}
// ServiceActions represents the actions that may be requested for
// an init system service.
type ServiceActions interface {
// Start will try to start the service.
Start() error
// Stop will try to stop the service.
Stop() error
// Install installs a service.
Install() error
// Remove will remove the service.
Remove() error
}
// Service represents a service in the init system running on a host.
type Service interface {
ServiceActions
// Name returns the service's name.
Name() string
// Conf returns the service's conf data.
Conf() common.Conf
// Running returns a boolean value that denotes
// whether or not the service is running.
Running() (bool, error)
// Exists returns whether the service configuration exists in the
// init directory with the same content that this Service would have
// if installed.
Exists() (bool, error)
// Installed will return a boolean value that denotes
// whether or not the service is installed.
Installed() (bool, error)
// TODO(ericsnow) Move all the commands into a separate interface.
// InstallCommands returns the list of commands to run on a
// (remote) host to install the service.
InstallCommands() ([]string, error)
// StartCommands returns the list of commands to run on a
// (remote) host to start the service.
StartCommands() ([]string, error)
}
// ConfigurableService performs tasks that need to occur between the software
// has been installed and when has started
type ConfigurableService interface {
// Configure performs any necessary configuration steps
Configure() error
// ReConfigureDuringRestart indicates whether Configure
// should be called during a restart
ReConfigureDuringRestart() bool
}
// RestartableService is a service that directly supports restarting.
type RestartableService interface {
// Restart restarts the service.
Restart() error
}
// UpgradableService describes a service that can be upgraded.
// It is assumed that such a service is not being upgraded across different
// init systems; rather taking a new form for the same init system.
type UpgradableService interface {
// Remove old service deletes old files made obsolete by upgrade.
RemoveOldService() error
// WriteService writes the service conf data. If the service is
// running, WriteService adds links to allow for manual and automatic
// starting of the service.
WriteService() error
}
// TODO(ericsnow) bug #1426458
// Eliminate the need to pass an empty conf for most service methods
// and several helper functions.
// NewService returns a new Service based on the provided info.
var NewService = func(name string, conf common.Conf, series string) (Service, error) {
if name == "" {
return nil, errors.New("missing name")
}
initSystem, err := versionInitSystem(series)
if err != nil {
return nil, errors.Trace(err)
}
return newService(name, conf, initSystem)
}
// this needs to be stubbed out in some tests
func newService(name string, conf common.Conf, initSystem string) (Service, error) {
var svc Service
var err error
switch initSystem {
case InitSystemWindows:
svc, err = windows.NewService(name, conf)
case InitSystemUpstart:
svc, err = upstart.NewService(name, conf), nil
case InitSystemSystemd:
svc, err = systemd.NewServiceWithDefaults(name, conf)
case InitSystemSnap:
svc, err = snap.NewServiceFromName(name, conf)
default:
return nil, errors.NotFoundf("init system %q", initSystem)
}
if err != nil {
return nil, errors.Annotatef(err, "failed to wrap service %q", name)
}
return svc, nil
}
// ListServices lists all installed services on the running system
var ListServices = func() ([]string, error) {
hostSeries, err := series.HostSeries()
if err != nil {
return nil, errors.Trace(err)
}
initName, err := VersionInitSystem(hostSeries)
if err != nil {
return nil, errors.Trace(err)
}
var services []string
switch initName {
case InitSystemWindows:
services, err = windows.ListServices()
case InitSystemSnap:
services, err = snap.ListServices()
case InitSystemUpstart:
services, err = upstart.ListServices()
case InitSystemSystemd:
services, err = systemd.ListServices()
default:
return nil, errors.NotFoundf("init system %q", initName)
}
if err != nil {
return nil, errors.Annotatef(err, "failed to list %s services", initName)
}
return services, nil
}
// ListServicesScript returns the commands that should be run to get
// a list of service names on a host.
func ListServicesScript() string {
commands := []string{
"init_system=$(" + DiscoverInitSystemScript() + ")",
// If the init system is not identified then the script will
// "exit 1". This is correct since the script should fail if no
// init system can be identified.
newShellSelectCommand("init_system", "exit 1", listServicesCommand),
}
return strings.Join(commands, "\n")
}
func listServicesCommand(initSystem string) (string, bool) {
switch initSystem {
case InitSystemWindows:
return windows.ListCommand(), true
case InitSystemUpstart:
return upstart.ListCommand(), true
case InitSystemSystemd:
return systemd.ListCommand(), true
case InitSystemSnap:
return snap.ListCommand(), true
default:
return "", false
}
}
// installStartRetryAttempts defines how much InstallAndStart retries
// upon Start failures.
var installStartRetryStrategy = retry.CallArgs{
Clock: clock.WallClock,
MaxDuration: 1 * time.Second,
Delay: 250 * time.Millisecond,
}
// InstallAndStart installs the provided service and tries starting it.
// The first few Start failures are ignored.
func InstallAndStart(svc ServiceActions) error {
service, ok := svc.(Service)
if !ok {
return errors.Errorf("specified service has no name %+v", svc)
}
logger.Infof("Installing and starting service %s", service.Name())
logger.Debugf("Installing and starting service %+v", svc)
if err := svc.Install(); err != nil {
return errors.Trace(err)
}
// For various reasons the init system may take a short time to
// realise that the service has been installed.
retryStrategy := installStartRetryStrategy
retryStrategy.Func = func() error { return ManuallyRestart(svc) }
retryStrategy.NotifyFunc = func(lastError error, _ int) {
logger.Errorf("retrying start request (%v)", errors.Cause(lastError))
}
err := retry.Call(retryStrategy)
if err != nil {
err = retry.LastError(err)
return errors.Trace(err)
}
return nil
}
// discoverService is patched out during some tests.
var discoverService = func(name string) (Service, error) {
return DiscoverService(name, common.Conf{})
}
// TODO(ericsnow) Add one-off helpers for Start and Stop too?
// Restart restarts the named service.
func Restart(name string) error {
svc, err := discoverService(name)
if err != nil {
return errors.Annotatef(err, "failed to find service %q", name)
}
if err := ManuallyRestart(svc); err != nil {
return errors.Annotatef(err, "failed to restart service %q", name)
}
return nil
}
// ManuallyRestart restarts the service by applying
// its Restart method or by falling back to calling Stop and Start
func ManuallyRestart(svc ServiceActions) error {
// TODO(tsm): fix service.upstart behaviour to match other implementations
// if restartableService, ok := svc.(RestartableService); ok {
// if err := restartableService.Restart(); err != nil {
// return errors.Trace(err)
// }
// return nil
// }
if err := svc.Stop(); err != nil {
logger.Errorf("could not stop service: %v", err)
}
configureableService, ok := svc.(ConfigurableService)
if ok && configureableService.ReConfigureDuringRestart() {
if err := configureableService.Configure(); err != nil {
return errors.Trace(err)
}
return nil
}
if err := svc.Start(); err != nil {
return errors.Trace(err)
}
return nil
}
// FindAgents finds all the agents available on the machine.
func FindAgents(dataDir string) (string, []string, []string, error) {
var (
machineAgent string
unitAgents []string
errAgentNames []string
)
agentDir := filepath.Join(dataDir, "agents")
dir, err := os.Open(agentDir)
if err != nil {
return "", nil, nil, errors.Annotate(err, "opening agents dir")
}
defer func() { _ = dir.Close() }()
entries, err := dir.Readdir(-1)
if err != nil {
return "", nil, nil, errors.Annotate(err, "reading agents dir")
}
for _, info := range entries {
name := info.Name()
tag, err := names.ParseTag(name)
if err != nil {
continue
}
switch tag.Kind() {
case names.MachineTagKind:
machineAgent = name
case names.UnitTagKind:
unitAgents = append(unitAgents, name)
default:
errAgentNames = append(errAgentNames, name)
logger.Infof("%s is not of type Machine nor Unit, ignoring", name)
}
}
return machineAgent, unitAgents, errAgentNames, nil
}