-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathservice.go
227 lines (205 loc) · 6.25 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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"golang.org/x/net/context"
"fmt"
"os"
"path/filepath"
"time"
"flag"
"github.com/google/cabbie/cablib"
"github.com/google/deck"
"golang.org/x/sys/windows/registry"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"
"golang.org/x/sys/windows/svc"
"github.com/google/subcommands"
"github.com/google/glazier/go/helpers"
)
// Available flags.
type serviceCmd struct {
install bool
uninstall bool
}
func (serviceCmd) Name() string { return "service" }
func (serviceCmd) Synopsis() string { return "Manage the installation status of the Cabbie service." }
func (serviceCmd) Usage() string {
return fmt.Sprintf("%s service [--install | --uninstall]\n", filepath.Base(os.Args[0]))
}
func (c *serviceCmd) SetFlags(f *flag.FlagSet) {
f.BoolVar(&c.install, "install", false, "Install the Cabbie service.")
f.BoolVar(&c.uninstall, "uninstall", false, "Uninstall the Cabbie service.")
}
func (c serviceCmd) Execute(ctx context.Context, flags *flag.FlagSet, args ...any) subcommands.ExitStatus {
rc := subcommands.ExitSuccess
if c.install && c.uninstall {
fmt.Println("Install and Uninstall flags can not be passed at the same time.")
return subcommands.ExitFailure
}
if c.install {
if err := installService(cablib.SvcName, cablib.SvcName+" Update Manager"); err != nil {
msg := fmt.Sprintf("Failed to install service: %v\n", err)
deck.ErrorA(msg).With(eventID(cablib.EvtErrSvcInstall)).Go()
fmt.Println(msg)
rc = subcommands.ExitFailure
}
deck.InfoA("Successfully installed Cabbie service.").With(eventID(cablib.EvtSvcInstall)).Go()
}
if c.uninstall {
if err := removeService(cablib.SvcName); err != nil {
msg := fmt.Sprintf("Failed to uninstall service: %v\n", err)
deck.ErrorA(msg).With(eventID(cablib.EvtErrSvcInstall)).Go()
fmt.Println(msg)
rc = subcommands.ExitFailure
}
deck.InfoA("Successfully uninstalled Cabbie service.").With(eventID(cablib.EvtSvcInstall)).Go()
}
if !(c.install || c.uninstall) {
fmt.Printf("%s\nUsage: %s\n", c.Synopsis(), c.Usage())
rc = subcommands.ExitUsageError
}
return rc
}
func configureEventLog() error {
// Assemble the path to the event DLL file on the disk.
dllpath, err := filepath.Abs(cablib.CabbiePath + cablib.EventDLL)
if err != nil {
return err
}
// Determine if the event DLL file exists on the disk.
hasDLL, err := helpers.PathExists(dllpath)
if err != nil {
return err
}
// Define the supported event types.
supports := uint32(eventlog.Error | eventlog.Warning | eventlog.Info)
// Attempt to remove the Cabbie event log registry key.
err = eventlog.Remove(cablib.LogSrcName)
// Proceed if the Cabbie event log registry key doesn't exist.
if err != nil && err != registry.ErrNotExist {
// If we get here, an unexpected error occurred.
return fmt.Errorf("eventLog.Remove(%s): %v", cablib.LogSrcName, err)
}
// Configure event logging.
if hasDLL {
if err := eventlog.Install(cablib.LogSrcName, dllpath, false, supports); err != nil {
return fmt.Errorf("event log source (%s) creation failed: %+v", dllpath, err)
}
return nil
}
if err := eventlog.InstallAsEventCreate(cablib.LogSrcName, supports); err != nil {
return fmt.Errorf("event log source (default) creation failed: %+v", err)
}
return nil
}
func installService(name, desc string) error {
exepath, err := filepath.Abs(cablib.CabbiePath + cablib.CabbieExe)
if err != nil {
return err
}
// Check that cabbie.exe is a file & exists at exepath
isFile, err := cablib.FileExists(exepath)
if err != nil {
return err
}
if !isFile {
return fmt.Errorf("%v does not exist or is a directory", exepath)
}
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
// Generate cabbie service config.
config := mgr.Config{
DisplayName: desc,
StartType: mgr.StartAutomatic,
}
// Configure event logging.
if err := configureEventLog(); err != nil {
return fmt.Errorf("configuring event log: %v", err)
}
// Install or update Cabbie service.
s, err := m.OpenService(name)
if err == nil {
msg := fmt.Sprintf("service %q already exists. Updating service config and ensuring service is running...\n", name)
deck.InfoA(msg).With(eventID(cablib.EvtSvcInstall)).Go()
fmt.Println(msg)
s.UpdateConfig(config)
} else {
s, err = m.CreateService(name, exepath, config)
if err != nil {
return err
}
}
defer s.Close()
// Set service recovery actions.
ra := []mgr.RecoveryAction{
{
Type: mgr.ServiceRestart,
Delay: 5 * time.Second,
},
{
Type: mgr.ServiceRestart,
Delay: 5 * time.Second,
},
{
Type: mgr.ServiceRestart,
Delay: 5 * time.Second,
},
}
if err := s.SetRecoveryActions(ra, 60); err != nil {
msg := fmt.Sprintf("Failed to set service recovery actions:\n%v", err)
deck.ErrorA(msg).With(eventID(cablib.EvtErrSvcInstall)).Go()
fmt.Println(msg)
}
status, err := s.Query()
if err != nil {
return fmt.Errorf("failed to query service: %v", err)
}
if status.State == svc.Running {
return nil
}
fmt.Println("Starting service...")
return s.Start()
}
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 {
msg := fmt.Sprintf("service %q is not installed.", name)
deck.InfoA(msg).With(eventID(cablib.EvtSvcInstall)).Go()
fmt.Println(msg)
return nil
}
defer s.Close()
if err = s.Delete(); err != nil {
return err
}
_, err = s.Control(svc.Stop)
if err != nil {
msg := fmt.Sprintf("Failed to stop service:\n%v", err)
deck.ErrorA(msg).With(eventID(cablib.EvtErrService)).Go()
fmt.Println(msg)
}
if err = eventlog.Remove(name); err != nil {
return fmt.Errorf("event log removal failed: %s", err)
}
return nil
}