-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
79 lines (67 loc) · 1.81 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
package main
import (
"time"
"github.com/rs/zerolog/log"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/debug"
)
type ServiceWindows struct {
handle ServiceHandled
}
type ServiceHandled interface {
Init() error
Tick() error
Shutdown() error
}
func (w *ServiceWindows) Execute(args []string, r <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
tick := time.Tick(5 * time.Second)
status <- svc.Status{State: svc.StartPending}
status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
if err := w.handle.Init(); err != nil {
log.Fatal().Msgf("Error initializing service. %v", err)
return true, 1
}
loop:
for {
select {
case <-tick:
if err := w.handle.Tick(); err != nil {
log.Error().Msgf("%v", err)
return true, 1
}
case c := <-r:
switch c.Cmd {
case svc.Interrogate:
status <- c.CurrentStatus
case svc.Stop, svc.Shutdown:
if err := w.handle.Shutdown(); err != nil {
log.Error().Msgf("%v", err)
return true, 0
}
break loop
case svc.Pause:
status <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
case svc.Continue:
status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
default:
log.Info().Msgf("Unexpected service control request #%d", c)
}
}
}
status <- svc.Status{State: svc.StopPending}
return false, 1
}
func RunService(name string, isDebug bool, handle ServiceHandled) {
if isDebug {
err := debug.Run(name, &ServiceWindows{handle: handle})
if err != nil {
log.Fatal().Msgf("Error running service in debug mode. %v", err)
}
} else {
err := svc.Run(name, &ServiceWindows{handle: handle})
if err != nil {
log.Fatal().Msg("Error running service in Service Control mode.")
}
}
}