forked from kardianos/service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_windows.go
510 lines (446 loc) · 11.3 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
509
510
// Copyright 2015 Daniel Theophanes.
// Use of this source code is governed by a zlib-style
// license that can be found in the LICENSE file.
package service
import (
"fmt"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"
)
const (
version = "windows-service"
StartType = "StartType"
ServiceStartManual = "manual"
ServiceStartDisabled = "disabled"
ServiceStartAutomatic = "automatic"
OnFailure = "OnFailure"
OnFailureRestart = "restart"
OnFailureReboot = "reboot"
OnFailureNoAction = "noaction"
OnFailureDelayDuration = "OnFailureDelayDuration"
OnFailureResetPeriod = "OnFailureResetPeriod"
errnoServiceDoesNotExist syscall.Errno = 1060
)
type windowsService struct {
i Interface
*Config
errSync sync.Mutex
stopStartErr error
}
// WindowsLogger allows using windows specific logging methods.
type WindowsLogger struct {
ev *eventlog.Log
errs chan<- error
}
type windowsSystem struct{}
func (windowsSystem) String() string {
return version
}
func (windowsSystem) Detect() bool {
return true
}
func (windowsSystem) Interactive() bool {
return interactive
}
func (windowsSystem) New(i Interface, c *Config) (Service, error) {
ws := &windowsService{
i: i,
Config: c,
}
return ws, nil
}
func init() {
ChooseSystem(windowsSystem{})
}
func (l WindowsLogger) send(err error) error {
if err == nil {
return nil
}
if l.errs != nil {
l.errs <- err
}
return err
}
// Error logs an error message.
func (l WindowsLogger) Error(v ...interface{}) error {
return l.send(l.ev.Error(3, fmt.Sprint(v...)))
}
// Warning logs an warning message.
func (l WindowsLogger) Warning(v ...interface{}) error {
return l.send(l.ev.Warning(2, fmt.Sprint(v...)))
}
// Info logs an info message.
func (l WindowsLogger) Info(v ...interface{}) error {
return l.send(l.ev.Info(1, fmt.Sprint(v...)))
}
// Errorf logs an error message.
func (l WindowsLogger) Errorf(format string, a ...interface{}) error {
return l.send(l.ev.Error(3, fmt.Sprintf(format, a...)))
}
// Warningf logs an warning message.
func (l WindowsLogger) Warningf(format string, a ...interface{}) error {
return l.send(l.ev.Warning(2, fmt.Sprintf(format, a...)))
}
// Infof logs an info message.
func (l WindowsLogger) Infof(format string, a ...interface{}) error {
return l.send(l.ev.Info(1, fmt.Sprintf(format, a...)))
}
// NError logs an error message and an event ID.
func (l WindowsLogger) NError(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Error(eventID, fmt.Sprint(v...)))
}
// NWarning logs an warning message and an event ID.
func (l WindowsLogger) NWarning(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Warning(eventID, fmt.Sprint(v...)))
}
// NInfo logs an info message and an event ID.
func (l WindowsLogger) NInfo(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Info(eventID, fmt.Sprint(v...)))
}
// NErrorf logs an error message and an event ID.
func (l WindowsLogger) NErrorf(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Error(eventID, fmt.Sprintf(format, a...)))
}
// NWarningf logs an warning message and an event ID.
func (l WindowsLogger) NWarningf(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Warning(eventID, fmt.Sprintf(format, a...)))
}
// NInfof logs an info message and an event ID.
func (l WindowsLogger) NInfof(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Info(eventID, fmt.Sprintf(format, a...)))
}
var interactive = false
func init() {
var err error
interactive, err = svc.IsAnInteractiveSession()
if err != nil {
panic(err)
}
}
func (ws *windowsService) String() string {
if len(ws.DisplayName) > 0 {
return ws.DisplayName
}
return ws.Name
}
func (ws *windowsService) Platform() string {
return version
}
func (ws *windowsService) setError(err error) {
ws.errSync.Lock()
defer ws.errSync.Unlock()
ws.stopStartErr = err
}
func (ws *windowsService) getError() error {
ws.errSync.Lock()
defer ws.errSync.Unlock()
return ws.stopStartErr
}
func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
changes <- svc.Status{State: svc.StartPending}
if err := ws.i.Start(ws); err != nil {
ws.setError(err)
return true, 1
}
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
loop:
for {
c := <-r
switch c.Cmd {
case svc.Interrogate:
changes <- c.CurrentStatus
case svc.Stop:
changes <- svc.Status{State: svc.StopPending}
if err := ws.i.Stop(ws); err != nil {
ws.setError(err)
return true, 2
}
break loop
case svc.Shutdown:
changes <- svc.Status{State: svc.StopPending}
var err error
if wsShutdown, ok := ws.i.(Shutdowner); ok {
err = wsShutdown.Shutdown(ws)
} else {
err = ws.i.Stop(ws)
}
if err != nil {
ws.setError(err)
return true, 2
}
break loop
default:
continue loop
}
}
return false, 0
}
func (ws *windowsService) Install() error {
exepath, err := ws.execPath()
if err != nil {
return err
}
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(ws.Name)
if err == nil {
s.Close()
return fmt.Errorf("service %s already exists", ws.Name)
}
var startType int32
switch ws.Option.string(StartType, ServiceStartAutomatic) {
case ServiceStartAutomatic:
startType = mgr.StartAutomatic
case ServiceStartManual:
startType = mgr.StartManual
case ServiceStartDisabled:
startType = mgr.StartDisabled
}
serviceType := windows.SERVICE_WIN32_OWN_PROCESS
if ws.Option.bool("Interactive", false) {
serviceType = serviceType | windows.SERVICE_INTERACTIVE_PROCESS
}
s, err = m.CreateService(ws.Name, exepath, mgr.Config{
DisplayName: ws.DisplayName,
Description: ws.Description,
StartType: uint32(startType),
ServiceStartName: ws.UserName,
Password: ws.Option.string("Password", ""),
Dependencies: ws.Dependencies,
DelayedAutoStart: ws.Option.bool("DelayedAutoStart", false),
ServiceType: uint32(serviceType),
}, ws.Arguments...)
if err != nil {
return err
}
if onFailure := ws.Option.string(OnFailure, ""); onFailure != "" {
var delay = 1 * time.Second
if d, err := time.ParseDuration(ws.Option.string(OnFailureDelayDuration, "1s")); err == nil {
delay = d
}
var actionType int
switch onFailure {
case OnFailureReboot:
actionType = mgr.ComputerReboot
case OnFailureRestart:
actionType = mgr.ServiceRestart
case OnFailureNoAction:
actionType = mgr.NoAction
default:
actionType = mgr.ServiceRestart
}
if err := s.SetRecoveryActions([]mgr.RecoveryAction{
{
Type: actionType,
Delay: delay,
},
}, uint32(ws.Option.int(OnFailureResetPeriod, 10))); err != nil {
return err
}
}
defer s.Close()
err = eventlog.InstallAsEventCreate(ws.Name, eventlog.Error|eventlog.Warning|eventlog.Info)
if err != nil {
if !strings.Contains(err.Error(), "exists") {
s.Delete()
return fmt.Errorf("SetupEventLogSource() failed: %s", err)
}
}
return nil
}
func (ws *windowsService) Uninstall() error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(ws.Name)
if err != nil {
return fmt.Errorf("service %s is not installed", ws.Name)
}
defer s.Close()
err = s.Delete()
if err != nil {
return err
}
err = eventlog.Remove(ws.Name)
if err != nil {
return fmt.Errorf("RemoveEventLogSource() failed: %s", err)
}
return nil
}
func (ws *windowsService) Run() error {
ws.setError(nil)
if !interactive {
// Return error messages from start and stop routines
// that get executed in the Execute method.
// Guarded with a mutex as it may run a different thread
// (callback from windows).
runErr := svc.Run(ws.Name, ws)
startStopErr := ws.getError()
if startStopErr != nil {
return startStopErr
}
if runErr != nil {
return runErr
}
return nil
}
err := ws.i.Start(ws)
if err != nil {
return err
}
sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt)
<-sigChan
return ws.i.Stop(ws)
}
func (ws *windowsService) Status() (Status, error) {
m, err := mgr.Connect()
if err != nil {
return StatusUnknown, err
}
defer m.Disconnect()
s, err := m.OpenService(ws.Name)
if err != nil {
if errno, ok := err.(syscall.Errno); ok && errno == errnoServiceDoesNotExist {
return StatusUnknown, ErrNotInstalled
}
return StatusUnknown, err
}
defer s.Close()
status, err := s.Query()
if err != nil {
return StatusUnknown, err
}
switch status.State {
case svc.StartPending:
fallthrough
case svc.Running:
return StatusRunning, nil
case svc.PausePending:
fallthrough
case svc.Paused:
fallthrough
case svc.ContinuePending:
fallthrough
case svc.StopPending:
fallthrough
case svc.Stopped:
return StatusStopped, nil
default:
return StatusUnknown, fmt.Errorf("unknown status %v", status)
}
}
func (ws *windowsService) Start() error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(ws.Name)
if err != nil {
return err
}
defer s.Close()
return s.Start()
}
func (ws *windowsService) Stop() error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(ws.Name)
if err != nil {
return err
}
defer s.Close()
return ws.stopWait(s)
}
func (ws *windowsService) Restart() error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(ws.Name)
if err != nil {
return err
}
defer s.Close()
err = ws.stopWait(s)
if err != nil {
return err
}
return s.Start()
}
func (ws *windowsService) stopWait(s *mgr.Service) error {
// First stop the service. Then wait for the service to
// actually stop before starting it.
status, err := s.Control(svc.Stop)
if err != nil {
return err
}
timeDuration := time.Millisecond * 50
timeout := time.After(getStopTimeout() + (timeDuration * 2))
tick := time.NewTicker(timeDuration)
defer tick.Stop()
for status.State != svc.Stopped {
select {
case <-tick.C:
status, err = s.Query()
if err != nil {
return err
}
case <-timeout:
break
}
}
return nil
}
// getStopTimeout fetches the time before windows will kill the service.
func getStopTimeout() time.Duration {
// For default and paths see https://support.microsoft.com/en-us/kb/146092
defaultTimeout := time.Millisecond * 20000
key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control`, registry.READ)
if err != nil {
return defaultTimeout
}
sv, _, err := key.GetStringValue("WaitToKillServiceTimeout")
if err != nil {
return defaultTimeout
}
v, err := strconv.Atoi(sv)
if err != nil {
return defaultTimeout
}
return time.Millisecond * time.Duration(v)
}
func (ws *windowsService) Logger(errs chan<- error) (Logger, error) {
if interactive {
return ConsoleLogger, nil
}
return ws.SystemLogger(errs)
}
func (ws *windowsService) SystemLogger(errs chan<- error) (Logger, error) {
el, err := eventlog.Open(ws.Name)
if err != nil {
return nil, err
}
return WindowsLogger{el, errs}, nil
}