-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
97 lines (89 loc) · 2.34 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
//go:build windows
package service
import (
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/firefart/reboot/server"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/debug"
"golang.org/x/sys/windows/svc/eventlog"
)
var elog debug.Log
type myservice struct{}
// Execute is a method from the Handler interface. It's the main run method of a windows service
func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
changes <- svc.Status{State: svc.StartPending}
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
// nolint: errcheck
elog.Info(1, "reboot service started")
p, err := servicePath()
if err != nil {
// nolint: errcheck
elog.Error(1, fmt.Sprintf("could not get service path: %v", err))
changes <- svc.Status{State: svc.StopPending}
errno = 1
return
}
pwbyte, err := ioutil.ReadFile(fmt.Sprintf("%s\\password.conf", p))
if err != nil {
// nolint: errcheck
elog.Error(1, fmt.Sprintf("could not read password.conf: %v", err))
changes <- svc.Status{State: svc.StopPending}
errno = 1
return
}
password := strings.TrimSpace(string(pwbyte))
go server.Listen(1234, elog, password)
loop:
// nolint: gosimple
for {
select {
case c := <-r:
switch c.Cmd {
// status update
case svc.Interrogate:
changes <- c.CurrentStatus
time.Sleep(100 * time.Millisecond)
changes <- c.CurrentStatus
// stop service
case svc.Stop, svc.Shutdown:
break loop
default:
// nolint: errcheck
elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
}
}
}
changes <- svc.Status{State: svc.StopPending}
return
}
// RunService runs a service. If debug mode is enabled all output will be sent to the terminal
func RunService(name string, isDebug bool) {
var err error
if isDebug {
elog = debug.New(name)
} else {
elog, err = eventlog.Open(name)
if err != nil {
return
}
}
defer elog.Close()
// nolint: errcheck
elog.Info(1, fmt.Sprintf("starting %s service", name))
run := svc.Run
if isDebug {
run = debug.Run
}
err = run(name, &myservice{})
if err != nil {
// nolint: errcheck
elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err))
return
}
// nolint: errcheck
elog.Info(1, fmt.Sprintf("%s service stopped", name))
}