-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstart.go
78 lines (68 loc) · 1.46 KB
/
start.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
package winservice
import (
"context"
"time"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/mgr"
)
// Start issues a start command to a service and waits for it to start. It returns
// an error if it fails or the context is cancelled.
//
// Start returns without error if the service is already started.
func Start(ctx context.Context, name string) error {
m, err := mgr.Connect()
if err != nil {
return OpError{Op: "start", Service: name, Err: err}
}
defer m.Disconnect()
if err := startService(ctx, m, name); err != nil {
return OpError{Op: "start", Service: name, Err: err}
}
return nil
}
func startService(ctx context.Context, m *mgr.Mgr, name string) error {
s, err := m.OpenService(name)
if err != nil {
return err
}
defer s.Close()
ticker := time.NewTicker(PollingInterval)
defer ticker.Stop()
for {
status, err := s.Query()
if err != nil {
return err
}
if status.State == svc.Stopped {
// The service has stopped
break
} else if status.State != svc.StopPending {
// The service is already running
return nil
} else {
// The service is stopping (wait for it)
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}
if err := s.Start(); err != nil {
return err
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
status, err := s.Query()
if err != nil {
return err
}
if status.State != svc.StartPending {
return nil
}
}
}
}