/
service.go
398 lines (336 loc) · 7.81 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package service
import (
"context"
"fmt"
"sync"
"sync/atomic"
"github.com/kardianos/service"
"github.com/spf13/cobra"
"darvaza.org/core"
"darvaza.org/slog"
"darvaza.org/x/config"
)
type cobraCmdE func(*cobra.Command, []string) error
// Service is an application that runs supervised by the OS
type Service struct {
wg sync.WaitGroup
cancelled atomic.Value
cancel context.CancelFunc
ctx context.Context
log slog.Logger
sys service.System
ss service.Service
p program
args []string
run cobraCmdE
root *cobra.Command
serve *cobra.Command
Config Config
}
// MustBuild creates a new service from a given root and serve
// [cobra.Command], and panics if there is a problem.
func MustBuild(rootCmd, serveCmd *cobra.Command) *Service {
s, err := Build(rootCmd, serveCmd)
if err != nil {
panic(err)
}
return s
}
// Build creates a new service from a given root and serve
// [cobra.Command]. [service.Config] parameters can be modified
// until Execute is called or via PersistentPreRunE
// on the root command.
func Build(rootCmd, serveCmd *cobra.Command) (*Service, error) {
s := newService()
err := s.init(cmdRoot(rootCmd), cmdServe(serveCmd))
if err != nil {
return nil, err
}
return s, nil
}
func (s *Service) init(root, serve *cobra.Command) error {
// adapt root actions
if err := s.prepareRootCmd(root); err != nil {
return err
}
// adapt serve actions
run := s.prepareServeCmd(serve)
// store
s.run = run
s.root = root
s.serve = serve
s.root.AddCommand(serve)
// set initial service.Config values
if err := s.prepareConfig(); err != nil {
return err
}
// add extra commands
switch {
case s.sys == nil:
// no service system detected
s.initSolo()
case s.sys.Interactive():
// prepare interactive use integrated with
// the service system.
s.initInteractive()
}
return nil
}
func (s *Service) initInteractive() {
// add service commands
commands := []*cobra.Command{
s.newStartCommand(),
s.newStopCommand(),
s.newRestartCommand(),
s.newInstallCommand(),
s.newUninstallCommand(),
s.newStatusCommand(),
}
s.root.AddCommand(commands...)
}
func (s *Service) initSolo() {
// serve and status commands
commands := []*cobra.Command{
s.newStatusCommand(),
}
s.root.AddCommand(commands...)
}
func (s *Service) prepareServeCmd(serve *cobra.Command) cobraCmdE {
var appRun cobraCmdE
switch {
case serve.RunE != nil:
appRun = serve.RunE
case serve.Run != nil:
run := serve.Run
appRun = func(cmd *cobra.Command, arg []string) error {
run(cmd, arg)
return nil
}
}
serve.Run = nil
serve.RunE = s.runServe
return appRun
}
func (s *Service) runServe(cmd *cobra.Command, args []string) error {
if s.run == nil {
return core.ErrNotImplemented
}
if s.Interactive() {
var c core.Catcher
return c.Do(func() error { return s.run(cmd, args) })
}
s.args = args
return s.ss.Run()
}
func (s *Service) prepareRootCmd(root *cobra.Command) error {
// hook setup
appSetup := root.PersistentPreRunE
setup := func(cmd *cobra.Command, args []string) error {
return s.setup(cmd, args, appSetup)
}
root.PersistentPreRunE = setup
return nil
}
func (s *Service) setup(cmd *cobra.Command, args []string, appSetup cobraCmdE) error {
ctx := cmd.Context()
if err := s.initContext(ctx); err != nil {
return err
}
if appSetup != nil {
// run app's own setup
if err := appSetup(cmd, args); err != nil {
return err
}
}
return s.prepareService()
}
func (s *Service) prepareService() error {
if err := s.prepareConfig(); err != nil {
return core.Wrap(err, "Service.Config")
}
sc := &s.Config.Config
ss, err := service.New(&s.p, sc)
if err != nil {
return err
}
s.ss = ss
return nil
}
func (s *Service) prepareConfig() error {
// Name
name := cmdUseName(s.root, CmdName())
if s.Config.Name == "" {
s.Config.Name = name
}
if s.Config.DisplayName == "" {
s.Config.DisplayName = name
}
// Description
if s.Config.Description == "" {
s.Config.Description = cmdDescription(s.root, "")
}
// TODO: validate
return config.SetDefaults(&s.Config)
}
func (s *Service) newStartCommand() *cobra.Command {
return &cobra.Command{
Use: "start",
Short: "Starts the service",
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
return s.ss.Start()
},
SilenceUsage: true,
}
}
func (s *Service) newStopCommand() *cobra.Command {
return &cobra.Command{
Use: "stop",
Short: "Stops the service",
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
return s.ss.Stop()
},
SilenceUsage: true,
}
}
func (s *Service) newRestartCommand() *cobra.Command {
return &cobra.Command{
Use: "restart",
Short: "Restarts the service",
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
return s.ss.Restart()
},
SilenceUsage: true,
}
}
func (s *Service) newInstallCommand() *cobra.Command {
return &cobra.Command{
Use: "install",
Short: "Installs the service on the system",
Args: s.processInstallArgs,
RunE: func(_ *cobra.Command, _ []string) error {
return s.ss.Install()
},
SilenceUsage: true,
}
}
func (s *Service) processInstallArgs(_ *cobra.Command, args []string) error {
switch {
case len(args) > 0:
// validate
if err := s.serve.ParseFlags(args); err != nil {
return core.Wrap(err, "validate")
}
// override
a := make([]string, len(args)+1)
a[0] = cmdUseName(s.serve, "serve")
copy(a[1:], args)
args = a
case len(s.Config.Arguments) == 0:
// default
a := make([]string, 1)
a[0] = cmdUseName(s.serve, "serve")
args = a
default:
// configured externally
// TODO: validate
return nil
}
s.Config.Arguments = args
return nil
}
func (s *Service) newUninstallCommand() *cobra.Command {
return &cobra.Command{
Use: "uninstall",
Short: "Uninstalls the service from the system",
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
return s.ss.Uninstall()
},
SilenceUsage: true,
}
}
func (s *Service) newStatusCommand() *cobra.Command {
return &cobra.Command{
Use: "status",
Short: "Shows the current service status",
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
plat, err := s.getServicePlatform()
s.printf("%s: %s\n", "Platform", core.Coalesce(plat, "unknown"))
if err != nil {
return err
}
st, err := s.getServiceStatus()
s.printf("%s: %s\n", "Status", core.Coalesce(st, "unknown"))
return err
},
SilenceUsage: true,
}
}
func (s *Service) getServiceStatus() (string, error) {
var res string
st, err := s.ss.Status()
if err == nil {
// success
labels := []string{"unknown", "running", "stopped"}
if int(st) < len(labels) {
res = labels[st]
} else {
res = fmt.Sprintf("%s(%v)", labels[0], int(st))
}
return res, nil
}
// failed, but how?
switch e := err.(type) {
case fmt.Stringer:
res = e.String()
default:
res = e.Error()
}
if res != "" {
res = fmt.Sprintf("%s: %s", "error", res)
} else {
res = "error"
}
return res, core.Wrap(err, "Service.Status")
}
func (*Service) printf(s string, args ...any) {
_, _ = fmt.Printf(s, args...)
}
// Interactive returns false if running under the OS service
// manager and true otherwise.
func (s *Service) Interactive() bool {
if s.sys != nil {
return s.sys.Interactive()
}
return true
}
// Platform returns a description of the system service.
func (s *Service) Platform() string {
plat, _ := s.getServicePlatform()
return plat
}
func (s *Service) getServicePlatform() (string, error) {
if s.sys != nil {
return s.sys.String(), nil
}
return "", service.ErrNoServiceSystemDetected
}
func newService() *Service {
s := new(Service)
s.p.s = s
s.sys = service.ChosenSystem()
return s
}
type program struct {
s *Service
}
func (p *program) Start(_ service.Service) error {
return p.s.doStart()
}
func (p *program) Stop(_ service.Service) error {
return p.s.doStop()
}