forked from chai2010/winsvc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
371 lines (322 loc) · 8.24 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
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
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
/*
Package winsvc provids easy windows service support.
Example
This a simple windows service example:
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
"github.com/chai2010/winsvc"
)
var (
appPath string
flagServiceName = flag.String("service-name", "hello-winsvc", "Set service name")
flagServiceDesc = flag.String("service-desc", "hello windows service", "Set service description")
flagServiceInstall = flag.Bool("service-install", false, "Install service")
flagServiceUninstall = flag.Bool("service-remove", false, "Remove service")
flagServiceStart = flag.Bool("service-start", false, "Start service")
flagServiceStop = flag.Bool("service-stop", false, "Stop service")
flagHelp = flag.Bool("help", false, "Show usage and exit.")
)
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, `Usage:
hello [options]...
Options:
`)
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "%s\n", `
Example:
# run hello server
$ go build -o hello.exe hello.go
$ hello.exe
# install hello as windows service
$ hello.exe -service-install
# start/stop hello service
$ hello.exe -service-start
$ hello.exe -service-stop
# remove hello service
$ hello.exe -service-remove
# help
$ hello.exe -h
Report bugs to <chaishushan{AT}gmail.com>.`)
}
// change to current dir
var err error
if appPath, err = winsvc.GetAppPath(); err != nil {
log.Fatal(err)
}
if err := os.Chdir(filepath.Dir(appPath)); err != nil {
log.Fatal(err)
}
}
func main() {
flag.Parse()
// install service
if *flagServiceInstall {
if err := winsvc.InstallService(appPath, *flagServiceName, *flagServiceDesc); err != nil {
log.Fatalf("installService(%s, %s): %v\n", *flagServiceName, *flagServiceDesc, err)
}
fmt.Printf("Done\n")
return
}
// remove service
if *flagServiceUninstall {
if err := winsvc.RemoveService(*flagServiceName); err != nil {
log.Fatalln("removeService:", err)
}
fmt.Printf("Done\n")
return
}
// start service
if *flagServiceStart {
if err := winsvc.StartService(*flagServiceName); err != nil {
log.Fatalln("startService:", err)
}
fmt.Printf("Done\n")
return
}
// stop service
if *flagServiceStop {
if err := winsvc.StopService(*flagServiceName); err != nil {
log.Fatalln("stopService:", err)
}
fmt.Printf("Done\n")
return
}
// run as service
if !winsvc.InServiceMode() {
log.Println("main:", "runService")
if err := winsvc.RunAsService(*flagServiceName, StartServer, StopServer, false); err != nil {
log.Fatalf("svc.Run: %v\n", err)
}
return
}
// run as normal
StartServer()
}
func StartServer() {
log.Println("StartServer, port = 8080")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "winsrv server", time.Now())
})
http.ListenAndServe(":8080", nil)
}
func StopServer() {
log.Println("StopServer")
}
BUGS
Report bugs to <[email protected]>.
Thanks!
*/
package winsvc
import (
"fmt"
"log"
"os"
"path/filepath"
"time"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/debug"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"
)
func GetAppPath() (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("winsvc.GetAppPath: %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("winsvc.GetAppPath: %s is directory", p)
}
}
return "", err
}
func InServiceMode() bool {
isIntSess, err := svc.IsAnInteractiveSession()
if err != nil {
log.Fatalf("winsvc.InServiceMode: svc.IsAnInteractiveSession(): err = %v", err)
}
return isIntSess
}
func InstallService(appPath, name, desc string) error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(name)
if err == nil {
s.Close()
return fmt.Errorf("winsvc.InstallService: service %s already exists", name)
}
s, err = m.CreateService(name, appPath, mgr.Config{
DisplayName: desc,
StartType: windows.SERVICE_AUTO_START,
})
if err != nil {
return err
}
defer s.Close()
err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)
if err != nil {
s.Delete()
return fmt.Errorf("winsvc.InstallService: InstallAsEventCreate failed, err = %v", err)
}
return nil
}
func RemoveService(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("winsvc.RemoveService: service %s is not installed", name)
}
defer s.Close()
err = s.Delete()
if err != nil {
return err
}
err = eventlog.Remove(name)
if err != nil {
return fmt.Errorf("winsvc.RemoveService: eventlog.Remove failed: %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("winsvc.StartService: could not access service: %v", err)
}
defer s.Close()
err = s.Start("p1", "p2", "p3")
if err != nil {
return fmt.Errorf("winsvc.StartService: could not start service: %v", err)
}
return nil
}
func StopService(name string) error {
if err := controlService(name, svc.Stop, svc.Stopped); err != nil {
return 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("winsvc.controlService: could not access service: %v", err)
}
defer s.Close()
status, err := s.Control(c)
if err != nil {
return fmt.Errorf("winsvc.controlService: could not send control=%d: %v", c, err)
}
timeout := time.Now().Add(10 * time.Second)
for status.State != to {
if timeout.Before(time.Now()) {
return fmt.Errorf("winsvc.controlService: timeout waiting for service to go to state=%d", to)
}
time.Sleep(300 * time.Millisecond)
status, err = s.Query()
if err != nil {
return fmt.Errorf("winsvc.controlService: could not retrieve service status: %v", err)
}
}
return nil
}
var elog debug.Log
func RunAsService(name string, start, stop func(), isDebug bool) (err error) {
if isDebug {
elog = debug.New(name)
} else {
elog, err = eventlog.Open(name)
if err != nil {
return
}
}
defer elog.Close()
run := svc.Run
if isDebug {
run = debug.Run
}
elog.Info(1, fmt.Sprintf("winsvc.RunAsService: starting %s service", name))
if err = run(name, &winService{Start: start, Stop: stop}); err != nil {
elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err))
return
}
elog.Info(1, fmt.Sprintf("winsvc.RunAsService: %s service stopped", name))
return
}
type winService struct {
Start func()
Stop func()
}
func (p *winService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
elog.Info(1, "winsvc.Execute:"+"begin")
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
changes <- svc.Status{State: svc.StartPending}
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
go p.Start()
loop:
for {
select {
case c := <-r:
switch c.Cmd {
case svc.Interrogate:
changes <- c.CurrentStatus
// testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4
time.Sleep(100 * time.Millisecond)
changes <- c.CurrentStatus
case svc.Stop, svc.Shutdown:
break loop
case svc.Pause:
changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
case svc.Continue:
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
default:
elog.Error(1, fmt.Sprintf("winsvc.Execute:: unexpected control request #%d", c))
}
}
}
changes <- svc.Status{State: svc.StopPending}
p.Stop()
elog.Info(1, "winsvc.Execute:"+"end")
return
}