-
Notifications
You must be signed in to change notification settings - Fork 494
/
service_windows.go
508 lines (463 loc) · 13.4 KB
/
service_windows.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// Copyright 2015 Cloudbase Solutions
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package windows
import (
"reflect"
"syscall"
"unsafe"
// https://bugs.launchpad.net/juju-core/+bug/1470820
"github.com/juju/errors"
"github.com/juju/utils/series"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/mgr"
"github.com/juju/juju/service/common"
)
type SC_ENUM_TYPE int
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v=vs.85).aspx
const (
SC_ENUM_PROCESS_INFO SC_ENUM_TYPE = 0
SERVICE_CONFIG_FAILURE_ACTIONS = 2
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 4
)
//sys enumServicesStatus(h windows.Handle, InfoLevel SC_ENUM_TYPE, dwServiceType uint32, dwServiceState uint32, lpServices uintptr, cbBufSize uint32, pcbBytesNeeded *uint32, lpServicesReturned *uint32, lpResumeHandle *uint32, pszGroupName *uint32) (err error) [failretval==0] = advapi32.EnumServicesStatusExW
const (
SC_ACTION_NONE = iota
SC_ACTION_RESTART
SC_ACTION_REBOOT
SC_ACTION_RUN_COMMAND
)
type serviceAction struct {
actionType uint16
delay uint32
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms685939(v=vs.85).aspx
type serviceFailureActions struct {
dwResetPeriod uint32
lpRebootMsg *uint16
lpCommand *uint16
cActions uint32
scAction *serviceAction
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms685937(v=vs.85).aspx
type serviceFailureActionsFlag struct {
failureActionsOnNonCrashFailures int32
}
// This is done so we can mock this function out
var WinChangeServiceConfig2 = windows.ChangeServiceConfig2
// serviceStatusProcess is used by EnumServicesStatusEx
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms685992%28v=vs.85%29.aspx
type serviceStatusProcess struct {
ServiceType uint32
CurrentState uint32
ControlsAccepted uint32
Win32ExitCode uint32
ServiceSpecificExitCode uint32
CheckPoint uint32
WaitHint uint32
ProcessId uint32
ServiceFlags uint32
}
type enumService struct {
name *uint16
displayName *uint16
Status serviceStatusProcess
}
// Name returns the name of the service stored in enumService.
func (s *enumService) Name() string {
if s.name != nil {
return syscall.UTF16ToString((*[1 << 16]uint16)(unsafe.Pointer(s.name))[:])
}
return ""
}
// windowsManager exposes Mgr methods needed by the windows service package.
type windowsManager interface {
CreateService(name, exepath string, c mgr.Config, args ...string) (windowsService, error)
OpenService(name string) (windowsService, error)
GetHandle(name string) (windows.Handle, error)
CloseHandle(handle windows.Handle) error
}
// windowsService exposes mgr.Service methods needed by the windows service package.
type windowsService interface {
Close() error
Config() (mgr.Config, error)
Control(c svc.Cmd) (svc.Status, error)
Delete() error
Query() (svc.Status, error)
Start(...string) error
UpdateConfig(mgr.Config) error
}
// manager is meant to help stub out winsvc for testing
type manager struct {
m *mgr.Mgr
}
// CreateService wraps Mgr.CreateService method.
func (m *manager) CreateService(name, exepath string, c mgr.Config, args ...string) (windowsService, error) {
// The Create function relies on the fact that this calls Connect(which connects to localhost) and not
// ConnectRemote. If we get to the point where we need to call ConnectRemote we need to stop using
// series.HostSeries inside Create.
s, err := mgr.Connect()
if err != nil {
return nil, err
}
defer s.Disconnect()
return s.CreateService(name, exepath, c, args...)
}
// CreateService wraps Mgr.OpenService method. It returns a windowsService object.
// This allows us to stub out this module for testing.
func (m *manager) OpenService(name string) (windowsService, error) {
s, err := mgr.Connect()
if err != nil {
return nil, err
}
defer s.Disconnect()
return s.OpenService(name)
}
// CreateService wraps Mgr.OpenService method but returns a windows.Handle object.
// This is used to access a lower level function not directly exposed by
// the sys/windows package.
func (m *manager) GetHandle(name string) (handle windows.Handle, err error) {
s, err := mgr.Connect()
if err != nil {
return handle, err
}
defer s.Disconnect()
service, err := s.OpenService(name)
if err != nil {
return handle, err
}
return service.Handle, nil
}
// CloseHandle wraps the windows.CloseServiceHandle method.
// This allows us to stub out this module for testing.
func (m *manager) CloseHandle(handle windows.Handle) error {
return windows.CloseServiceHandle(handle)
}
var newManager = func() (windowsManager, error) {
return &manager{}, nil
}
// getPassword attempts to read the password for the jujud user. We define it as
// a variable to allow us to mock it out for testing
var getPassword = func() (string, error) {
passwd, err := resetJujudPassword()
if err != nil {
return "", errors.Annotate(err, "cannot reset jujud password")
}
return passwd, nil
}
// listServices returns an array of strings containing all the services on
// the current system. It is defined as a variable to allow us to mock it out
// for testing
var listServices = func() (services []string, err error) {
host := syscall.StringToUTF16Ptr(".")
sc, err := windows.OpenSCManager(host, nil, windows.SC_MANAGER_ALL_ACCESS)
defer func() {
// The close service handle error is less important than others
if err == nil {
err = windows.CloseServiceHandle(sc)
}
}()
if err != nil {
return nil, err
}
var needed uint32
var returned uint32
var resume uint32 = 0
var enum []enumService
for {
var buf [512]enumService
err := enumServicesStatus(sc, SC_ENUM_PROCESS_INFO, windows.SERVICE_WIN32,
windows.SERVICE_STATE_ALL, uintptr(unsafe.Pointer(&buf[0])), uint32(unsafe.Sizeof(buf)), &needed, &returned, &resume, nil)
if err != nil {
if err == windows.ERROR_MORE_DATA {
enum = append(enum, buf[:returned]...)
continue
}
return nil, err
}
enum = append(enum, buf[:returned]...)
break
}
services = make([]string, len(enum))
for i, v := range enum {
services[i] = v.Name()
}
return services, nil
}
// SvcManager implements ServiceManager interface
type SvcManager struct {
svc windowsService
mgr windowsManager
serviceConf common.Conf
}
func (s *SvcManager) getService(name string) (windowsService, error) {
service, err := s.mgr.OpenService(name)
if err != nil {
return nil, errors.Trace(err)
}
return service, nil
}
func (s *SvcManager) status(name string) (svc.State, error) {
service, err := s.getService(name)
if err != nil {
return svc.Stopped, errors.Trace(err)
}
defer service.Close()
status, err := service.Query()
if err != nil {
return svc.Stopped, errors.Trace(err)
}
return status.State, nil
}
func (s *SvcManager) exists(name string) (bool, error) {
service, err := s.getService(name)
if err == c_ERROR_SERVICE_DOES_NOT_EXIST {
return false, nil
} else if err != nil {
return false, err
}
defer service.Close()
return true, nil
}
// Start starts a service.
func (s *SvcManager) Start(name string) error {
running, err := s.Running(name)
if err != nil {
return errors.Trace(err)
}
if running {
return nil
}
service, err := s.getService(name)
if err != nil {
return errors.Trace(err)
}
defer service.Close()
err = service.Start()
if err != nil {
return err
}
return nil
}
func (s *SvcManager) escapeExecPath(exePath string, args []string) string {
ret := syscall.EscapeArg(exePath)
for _, v := range args {
ret += " " + syscall.EscapeArg(v)
}
return ret
}
// Exists checks whether the config of the installed service matches the
// config supplied to this function
func (s *SvcManager) Exists(name string, conf common.Conf) (bool, error) {
// We escape and compose BinaryPathName the same way mgr.CreateService does.
execStart := s.escapeExecPath(conf.ServiceBinary, conf.ServiceArgs)
cfg := mgr.Config{
// make this service dependent on WMI service. WMI is needed for almost
// all installers to work properly, and is needed for all of the advanced windows
// instrumentation bits (powershell included). Juju agents must start after this
// service to ensure hooks run properly.
Dependencies: []string{"Winmgmt"},
StartType: mgr.StartAutomatic,
DisplayName: conf.Desc,
ServiceStartName: jujudUser,
BinaryPathName: execStart,
}
currentConfig, err := s.Config(name)
if err != nil {
return false, err
}
if reflect.DeepEqual(cfg, currentConfig) {
return true, nil
}
return false, nil
}
// Stop stops a service.
func (s *SvcManager) Stop(name string) error {
running, err := s.Running(name)
if err != nil {
return errors.Trace(err)
}
if !running {
return nil
}
service, err := s.getService(name)
if err != nil {
return errors.Trace(err)
}
defer service.Close()
_, err = service.Control(svc.Stop)
if err != nil {
return errors.Trace(err)
}
return nil
}
// Delete deletes a service.
func (s *SvcManager) Delete(name string) error {
exists, err := s.exists(name)
if err != nil {
return err
}
if !exists {
return nil
}
service, err := s.getService(name)
if err != nil {
return errors.Trace(err)
}
defer service.Close()
err = service.Delete()
if err == c_ERROR_SERVICE_DOES_NOT_EXIST {
return nil
} else if err != nil {
return errors.Trace(err)
}
return nil
}
// Create creates a service with the given config.
func (s *SvcManager) Create(name string, conf common.Conf) error {
serviceStartName := "LocalSystem"
var passwd string
hostSeries, err := series.HostSeries()
if err != nil {
return errors.Trace(err)
}
if !series.IsWindowsNano(hostSeries) {
password, err := getPassword()
if err != nil {
return errors.Trace(err)
}
passwd = password
serviceStartName = jujudUser
}
cfg := mgr.Config{
Dependencies: []string{"Winmgmt"},
ErrorControl: mgr.ErrorSevere,
StartType: mgr.StartAutomatic,
DisplayName: conf.Desc,
ServiceStartName: serviceStartName,
Password: passwd,
}
// mgr.CreateService actually does correct argument escaping itself. There is no
// need for quoted strings of any kind passed to this function. It takes in
// a binary name, and an array or arguments.
service, err := s.mgr.CreateService(name, conf.ServiceBinary, cfg, conf.ServiceArgs...)
if err != nil {
return errors.Trace(err)
}
defer service.Close()
err = s.ensureRestartOnFailure(name)
if err != nil {
return errors.Trace(err)
}
return nil
}
// Running returns the status of a service.
func (s *SvcManager) Running(name string) (bool, error) {
status, err := s.status(name)
if err != nil {
return false, errors.Trace(err)
}
logger.Infof("Service %q Status %v", name, status)
if status == svc.Running {
return true, nil
}
return false, nil
}
// Config returns the mgr.Config of the service. This config reflects the actual
// service configuration in Windows.
func (s *SvcManager) Config(name string) (mgr.Config, error) {
exists, err := s.exists(name)
if err != nil {
return mgr.Config{}, err
}
if !exists {
return mgr.Config{}, c_ERROR_SERVICE_DOES_NOT_EXIST
}
service, err := s.getService(name)
if err != nil {
return mgr.Config{}, errors.Trace(err)
}
defer service.Close()
return service.Config()
}
func (s *SvcManager) ensureRestartOnFailure(name string) (err error) {
handle, err := s.mgr.GetHandle(name)
if err != nil {
return errors.Trace(err)
}
defer func() {
// The CloseHandle error is less important than another error
closeErr := s.mgr.CloseHandle(handle)
if closeErr != nil {
if err == nil {
err = errors.Annotatef(closeErr, "close %q handle failed", name)
} else {
err = errors.Annotatef(err, "(also close %q handle failed: %s)", name, closeErr)
}
}
}()
action := serviceAction{
actionType: SC_ACTION_RESTART,
delay: 5000,
}
failActions := serviceFailureActions{
dwResetPeriod: 5,
lpRebootMsg: nil,
lpCommand: nil,
cActions: 1,
scAction: &action,
}
err = WinChangeServiceConfig2(handle, SERVICE_CONFIG_FAILURE_ACTIONS, (*byte)(unsafe.Pointer(&failActions)))
if err != nil {
return errors.Trace(err)
}
flag := serviceFailureActionsFlag{
failureActionsOnNonCrashFailures: 1,
}
err = WinChangeServiceConfig2(handle, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, (*byte)(unsafe.Pointer(&flag)))
if err != nil {
return errors.Trace(err)
}
return nil
}
// ChangeServicePassword can change the password of a service
// as long as it belongs to the user defined in this package
func (s *SvcManager) ChangeServicePassword(svcName, newPassword string) error {
currentConfig, err := s.Config(svcName)
if err != nil {
// If access is denied when accessing the service it means
// we can't own it, so there's no reason to return an error
// since we only want to change the password on services started
// by us.
if errors.Cause(err) == syscall.ERROR_ACCESS_DENIED {
return nil
}
return errors.Trace(err)
}
if currentConfig.ServiceStartName == jujudUser {
currentConfig.Password = newPassword
service, err := s.getService(svcName)
if err != nil {
return errors.Trace(err)
}
defer service.Close()
err = service.UpdateConfig(currentConfig)
if err != nil {
return errors.Trace(err)
}
}
if err != nil {
return errors.Trace(err)
}
return nil
}
var NewServiceManager = func() (ServiceManager, error) {
m, err := newManager()
if err != nil {
return nil, errors.Trace(err)
}
return &SvcManager{
mgr: m,
}, nil
}