-
Notifications
You must be signed in to change notification settings - Fork 55
/
service_windows.go
232 lines (217 loc) · 5.51 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
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"time"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"
)
var (
winSvcCmd = flag.String("winsvc", "", "install, uninstall, start, stop a Windows service")
winSvcRunning = false
)
func manageService() {
const winSvcName = "exporter_exporter"
var err error
switch *winSvcCmd {
case "start":
err = startService(winSvcName)
case "install":
err = installService(winSvcName, "Reverse proxy for Prometheus exporters")
case "uninstall":
err = uninstallService(winSvcName)
case "stop":
err = controlService(winSvcName, svc.Stop, svc.Stopped)
case "":
isIntSess, err := svc.IsAnInteractiveSession()
if err != nil {
log.Fatalf("Failed to determine if we are running in an interactive session: %v", err)
}
if !isIntSess {
go runService(winSvcName)
for {
time.Sleep(time.Millisecond * 200)
if winSvcRunning {
break
}
}
}
return
default:
log.Fatalf("Unknown command '%v' for -winsvc", *winSvcCmd)
}
if err != nil {
log.Fatalf("Failed to %s %s: %v", *winSvcCmd, winSvcName, err)
}
os.Exit(0)
}
func exePath() (string, error) {
prog := os.Args[0]
p, err := filepath.Abs(prog)
if err != nil {
return "", err
}
fi, err := os.Stat(p)
if err == nil {
if !fi.Mode().IsDir() {
return p, nil
}
err = fmt.Errorf("%s is directory", p)
}
if filepath.Ext(p) == "" {
p += ".exe"
fi, err := os.Stat(p)
if err == nil {
if !fi.Mode().IsDir() {
return p, nil
}
err = fmt.Errorf("%s is directory", p)
}
}
return "", err
}
func installService(name, desc string) error {
exepath, err := exePath()
if err != nil {
return fmt.Errorf("Unable to determine path of exe: %v", err)
}
var serviceArgs []string
flag.Visit(func(f *flag.Flag) {
if f.Name != "winsvc" {
serviceArgs = append(serviceArgs, fmt.Sprintf("-%s", f.Name))
if f.Value.String() != "true" {
serviceArgs = append(serviceArgs, f.Value.String())
}
}
})
if len(serviceArgs) <= 0 {
serviceArgs = append(serviceArgs, "-config.file", fmt.Sprintf("%s\\expexp.yaml", filepath.Dir(exepath)))
}
m, err := mgr.Connect()
if err != nil {
return fmt.Errorf("Failed while connecting to service control manager: %v", err)
}
defer m.Disconnect()
s, err := m.OpenService(name)
if err == nil {
s.Close()
return fmt.Errorf("Service with the name '%s' already exists", name)
}
s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: name,
StartType: mgr.StartAutomatic,
Description: desc}, serviceArgs...,
)
if err != nil {
return fmt.Errorf("Failed while creating a new service: %v", err)
}
defer s.Close()
err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)
if err != nil {
s.Delete()
return fmt.Errorf("Failed while creating eventlog source: %v", err)
}
log.Infof("Installed service %s with args: %v", name, serviceArgs)
return nil
}
func uninstallService(name string) error {
controlService(name, svc.Stop, svc.Stopped)
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(name)
if err != nil {
return fmt.Errorf("Failed while retrieving access to the service: %v", err)
}
defer s.Close()
err = s.Delete()
if err != nil {
return err
}
err = eventlog.Remove(name)
if err != nil {
return fmt.Errorf("Failed while removing eventlog source: %v", err)
}
return nil
}
func startService(name string) error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(name)
if err != nil {
return fmt.Errorf("Failed while retrieving access to the service: %v", err)
}
defer s.Close()
err = s.Start()
if err != nil {
return fmt.Errorf("Failed while trying to start the service: %v", err)
}
return nil
}
func controlService(name string, c svc.Cmd, to svc.State) error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(name)
if err != nil {
return fmt.Errorf("Failed while retrieving access to the service: %v", err)
}
defer s.Close()
status, err := s.Control(c)
if err != nil {
return fmt.Errorf("Failed while sending control %d: %v", c, err)
}
timeout := time.Now().Add(35 * time.Second)
for status.State != to {
if timeout.Before(time.Now()) {
return fmt.Errorf("Failed while waiting for the service to change state to %d", to)
}
time.Sleep(300 * time.Millisecond)
status, err = s.Query()
if err != nil {
return fmt.Errorf("Failed while attempting to retrieve service status: %v", err)
}
}
return nil
}
type exporterExporterService struct {
}
func (s *exporterExporterService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
changes <- svc.Status{State: svc.StartPending}
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
winSvcRunning = true
loop:
for c := range r {
switch c.Cmd {
case svc.Interrogate:
changes <- c.CurrentStatus
case svc.Stop, svc.Shutdown:
break loop
default:
log.Errorf("Unexpected control request #%d", c)
}
}
changes <- svc.Status{State: svc.StopPending}
return
}
func runService(name string) {
log.Infof("Starting service %s %s", name, Version)
err := svc.Run(name, &exporterExporterService{})
if err != nil {
log.Errorf("%s service failed: %v", name, err)
return
}
log.Infof("%s service stopped", name)
os.Exit(0)
}