Debian Codegraph @

service_windows.go

raw symbols SCIP
1 package service
2
3 import (
4 "fmt"
5 "golang.org/x/sys/windows/svc"
6 "golang.org/x/sys/windows/svc/mgr"
7 "gopkg.in/hlandau/easyconfig.v1/cflag"
8 "gopkg.in/hlandau/svcutils.v1/exepath"
9 "os"
10 "time"
11 )
12
13 // This is always empty on Windows, as Windows does not support chrooting.
14 // It is present to allow code relying upon it to compile upon all platforms.
15 var EmptyChrootPath = ""
16
17 var (
18 serviceFlag = cflag.String(fg, "do", "", "service command (one of: start, stop, install, remove)")
19 )
20
21 var errNotSupported = fmt.Errorf("not supported")
22
23 func systemdUpdateStatus(status string) error {
24 return errNotSupported
25 }
26
27 // handler is used when running as a service.
28 // Otherwise we use the generic ihandler.
29 type handler struct {
30 info *Info
31 startedChan chan struct{}
32 stopChan chan struct{}
33 status string
34 dropped bool
35 }
36
37 func (h *handler) DropPrivileges() error {
38 h.dropped = true
39 return nil
40 }
41
42 func (h *ihandler) DropPrivileges() error {
43 h.dropped = true
44 return nil
45 }
46
47 func (h *handler) SetStarted() {
48 if !h.dropped {
49 panic("service must call DropPrivileges before calling SetStarted")
50 }
51
52 select {
53 case h.startedChan <- struct{}{}:
54 default:
55 }
56 }
57
58 func (h *handler) StopChan() <-chan struct{} {
59 return h.stopChan
60 }
61
62 func (h *handler) SetStatus(status string) {
63 h.status = status
64 }
65
66 func (h *handler) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) {
67 const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
68 changes <- svc.Status{State: svc.StartPending}
69
70 h.startedChan = make(chan struct{}, 1)
71 h.stopChan = make(chan struct{})
72 doneChan := make(chan error)
73 started := false
74 stopping := false
75
76 go func() {
77 err := h.info.RunFunc(h)
78 doneChan <- err
79 }()
80
81 var err error
82
83 loop:
84 for {
85 select {
86 case c := <-r:
87 switch c.Cmd {
88 case svc.Interrogate:
89 changes <- c.CurrentStatus
90
91 case svc.Stop, svc.Shutdown:
92 // Service stop is pending. Don't accept any more commands while pending.
93 changes <- svc.Status{State: svc.StopPending}
94 if !stopping {
95 stopping = true
96 close(h.stopChan)
97 }
98
99 default:
100 // Unexpected control request
101 }
102
103 case <-h.startedChan:
104 if started {
105 panic("must not call SetStarted() more than once")
106 }
107 started = true
108 changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
109
110 case err = <-doneChan:
111 break loop
112 }
113 }
114
115 if err == nil {
116 changes <- svc.Status{State: svc.Stopped}
117 return false, 0
118 } else {
119 return false, 1
120 }
121 }
122
123 func isInteractive() bool {
124 interactive, err := svc.IsAnInteractiveSession()
125 if err != nil {
126 return false
127 }
128 return interactive
129 }
130
131 func (info *Info) installService() error {
132 svcName := info.Name
133
134 // Connect to the Windows service manager.
135 serviceManager, err := mgr.Connect()
136 if err != nil {
137 return err
138 }
139
140 defer serviceManager.Disconnect()
141
142 // Ensure the service doesn't already exist.
143 service, err := serviceManager.OpenService(svcName)
144 if err == nil {
145 service.Close()
146 return fmt.Errorf("service %s already exists", svcName)
147 }
148
149 // Install the service.
150 service, err = serviceManager.CreateService(svcName, exepath.Abs, mgr.Config{
151 DisplayName: info.Title,
152 Description: info.Description,
153 StartType: mgr.StartAutomatic,
154 ErrorControl: mgr.ErrorNormal,
155 })
156 if err != nil {
157 return err
158 }
159 defer service.Close()
160
161 // TODO: event log
162
163 return nil
164 }
165
166 func (info *Info) removeService() error {
167 svcName := info.Name
168
169 // Connect to the Windows service manager.
170 serviceManager, err := mgr.Connect()
171 if err != nil {
172 return err
173 }
174 defer serviceManager.Disconnect()
175
176 // Ensure the service exists.
177 service, err := serviceManager.OpenService(svcName)
178 if err != nil {
179 return fmt.Errorf("service %s is not installed", svcName)
180 }
181 defer service.Close()
182
183 // Remove the service.
184 err = service.Delete()
185 if err != nil {
186 return err
187 }
188
189 return nil
190 }
191
192 func (info *Info) startService() error {
193 svcName := info.Name
194
195 // Connect to the Windows service manager.
196 serviceManager, err := mgr.Connect()
197 if err != nil {
198 return err
199 }
200 defer serviceManager.Disconnect()
201
202 service, err := serviceManager.OpenService(svcName)
203 if err != nil {
204 return fmt.Errorf("could not access service: %v", err)
205 }
206 defer service.Close()
207
208 err = service.Start(os.Args...)
209 if err != nil {
210 return fmt.Errorf("could not start service: %v", err)
211 }
212
213 return nil
214 }
215
216 func (info *Info) controlService(c svc.Cmd, to svc.State) error {
217 svcName := info.Name
218
219 // Connect to the Windows service manager.
220 serviceManager, err := mgr.Connect()
221 if err != nil {
222 return err
223 }
224 defer serviceManager.Disconnect()
225
226 service, err := serviceManager.OpenService(svcName)
227 if err != nil {
228 return fmt.Errorf("could not access service: %v", err)
229 }
230 defer service.Close()
231
232 // Send the control message.
233 status, err := service.Control(c)
234 if err != nil {
235 return fmt.Errorf("could not send control=%d: %v", c, err)
236 }
237
238 // Wait.
239 for status.State != to {
240 time.Sleep(300 * time.Millisecond)
241 status, err = service.Query()
242 if err != nil {
243 return fmt.Errorf("could not retrieve service status: %v", err)
244 }
245 }
246
247 return nil
248 }
249
250 func (info *Info) stopService() error {
251 return info.controlService(svc.Stop, svc.Stopped)
252 }
253
254 func (info *Info) runAsService() error {
255 // TODO: event log
256
257 err := svc.Run(info.Name, &handler{info: info})
258 if err != nil {
259 return err
260 }
261
262 return nil
263 }
264
265 func (info *Info) serviceMain() error {
266 switch serviceFlag.Value() {
267 case "install":
268 return info.installService()
269 case "remove":
270 return info.removeService()
271 case "start":
272 return info.startService()
273 case "stop":
274 return info.stopService()
275 default:
276 // ...
277 }
278
279 interactive := isInteractive()
280 if !interactive {
281 return info.runAsService()
282 }
283
284 return info.runInteractively()
285 }
286
287 // Copyright © 2013-2014 Conformal Systems LLC.
288 //
289 // Permission to use, copy, modify, and distribute this software for any
290 // purpose with or without fee is hereby granted, provided that the above
291 // copyright notice and this permission notice appear in all copies.
292 //
293 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
294 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
295 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
296 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
297 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
298 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
299 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
300 //
301 // © 2014 Hugo Landau <[email protected]> ISC License