-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice_win.go
161 lines (140 loc) · 4.19 KB
/
service_win.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
// +build windows
package main
import (
"code.google.com/p/winsvc/svc"
"fmt"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"
)
// BUG(brainman): MessageBeep Windows api is broken on Windows 7,
// so this example does not beep when runs as service on Windows 7.
var (
beepFunc = syscall.MustLoadDLL("user32.dll").MustFindProc("MessageBeep")
)
func getLogFilePath() string {
return "c:\\tools\\myservice.log"
}
func beep() {
log.Println("beep\r\n")
beepFunc.Call(0xffffffff)
}
func acceptConnection(listener net.Listener, listen chan<- net.Conn) {
for {
conn, err := listener.Accept()
if err != nil {
continue
}
listen <- conn
}
}
func handleClient(client net.Conn) {
for {
buf := make([]byte, 4096)
numbytes, err := client.Read(buf)
fmt.Printf("numbytes: %d, err: %s, buf: %v \r\n", numbytes, err, buf[:numbytes])
if numbytes == 0 || err != nil {
// EOF, close connection
return
}
if numbytes == 2 && buf[0] == 13 && buf[1] == 10 {
// [13 10] "\r\n"
} else {
now := time.Now()
str := fmt.Sprintf("%s: %s\r\n", now.Local().Format("15:04:05.999999999"), buf)
client.Write([]byte(str))
}
}
}
type myservice struct{}
func (this *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
log.Println("myservice.Execute\r\n")
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
changes <- svc.Status{State: svc.StartPending}
fasttick := time.Tick(500 * time.Millisecond)
slowtick := time.Tick(2 * time.Second)
tick := fasttick
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
// execute Run
go serveConn(args, r, changes)
// major loop for signal processing.
loop:
for {
select {
case <-tick:
beep()
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}
tick = slowtick
case svc.Continue:
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
tick = fasttick
default:
log.Printf("unexpected control request #%d", c)
}
}
}
changes <- svc.Status{State: svc.StopPending}
return
}
func runService(name string, isDebug bool) {
f, err := os.OpenFile(getLogFilePath(), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("error opening file: %v \n", err)
}
defer f.Close()
log.SetOutput(f)
log.Printf("runService: starting %s service \r\n", name)
err = svc.Run(name, &myservice{})
if err != nil {
log.Printf("runService: Error: %s service failed: %v\r\n", name, err)
return
}
log.Printf("runService: %s service stopped\r\n", name)
}
func serveConn(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, error) {
log.Println("serveConn\r\n")
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)
// Set up listener for defined host and port
listener, err := net.Listen("tcp", port)
if err != nil {
return false, err
}
// set up channel on which to send accepted connections
listen := make(chan net.Conn, 100)
go acceptConnection(listener, listen)
// loop work cycle with accept connections or interrupt
// by system signal
log.Println("Manage() loop\r\n")
for {
select {
case conn := <-listen:
go handleClient(conn)
case killSignal := <-interrupt:
log.Println("Got signal:", killSignal, "\r\n")
log.Println("Stoping listening on ", listener.Addr(), "\r\n")
listener.Close()
if killSignal == os.Interrupt {
return false, fmt.Errorf("Daemon was interruped by system signal")
}
return false, fmt.Errorf("Daemon was killed")
}
}
return true, nil
}