-
Notifications
You must be signed in to change notification settings - Fork 3
/
application.go
371 lines (304 loc) · 9.67 KB
/
application.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
package clio
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"strings"
"github.com/gookit/color"
"github.com/pborman/indent"
"github.com/pkg/profile"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
"github.com/anchore/fangs"
"github.com/anchore/go-logger"
"github.com/anchore/go-logger/adapter/redact"
)
type Initializer func(*State) error
type PostRun func(*State, error)
type postConstruct func(*application)
type Application interface {
ID() Identification
AddFlags(flags *pflag.FlagSet, cfgs ...any)
SetupCommand(cmd *cobra.Command, cfgs ...any) *cobra.Command
SetupRootCommand(cmd *cobra.Command, cfgs ...any) *cobra.Command
Run()
}
type application struct {
root *cobra.Command
setupConfig SetupConfig `yaml:"-" mapstructure:"-"`
state State `yaml:"-" mapstructure:"-"`
resourcesLoaded bool
}
var _ interface {
Application
fangs.PostLoader
} = (*application)(nil)
func New(cfg SetupConfig) Application {
return &application{
setupConfig: cfg,
state: State{
RedactStore: redact.NewStore(),
},
}
}
func (a *application) ID() Identification {
return a.setupConfig.ID
}
// State returns all application configuration and resources to be either used or replaced by the caller. Note: this is only valid after the application has been setup (cobra PreRunE has run).
func (a *application) State() *State {
return &a.state
}
// TODO: configs of any doesn't lean into the type system enough. Consider a more specific type.
func (a *application) Setup(cfgs ...any) func(_ *cobra.Command, _ []string) error {
return func(cmd *cobra.Command, _ []string) error {
// allow for the all configuration to be loaded first, then allow for the application
// PostLoad() to run, allowing the setup of resources (logger, bus, ui, etc.) and run user initializers
// as early as possible before the final configuration is logged. This allows for a couple of things:
// 1. user initializers to account for taking action before logging the final configuration (such as log redactions).
// 2. other user-facing PostLoad() functions to be able to use the logger, bus, etc. as early as possible. (though it's up to the caller on how these objects are made accessible)
allConfigs, err := a.loadConfigs(cmd, cfgs...)
if err != nil {
return err
}
// show the app version and configuration...
logVersion(a.setupConfig, a.state.Logger)
logConfiguration(a.state.Logger, allConfigs...)
return nil
}
}
func (a *application) loadConfigs(cmd *cobra.Command, cfgs ...any) ([]any, error) {
allConfigs := []any{
&a.state.Config, // 1. process the core application configurations first (logging and development)
a, // 2. enables application.PostLoad() to be called, initializing all state (bus, logger, ui, etc.)
}
allConfigs = append(allConfigs, cfgs...) // 3. allow for all other configs to be loaded + call PostLoad()
if err := fangs.Load(a.setupConfig.FangsConfig, cmd, allConfigs...); err != nil {
return nil, fmt.Errorf("invalid application config: %v", err)
}
return allConfigs, nil
}
func (a *application) PostLoad() error {
if err := a.state.setup(a.setupConfig); err != nil {
return err
}
return a.runInitializers()
}
func (a *application) runInitializers() error {
for _, init := range a.setupConfig.Initializers {
if err := init(&a.state); err != nil {
return err
}
}
a.resourcesLoaded = true
return nil
}
func (a *application) runPostRuns(err error) {
for _, postRun := range a.setupConfig.postRuns {
a.runPostRun(postRun, err)
}
}
func (a *application) runPostRun(fn PostRun, err error) {
defer func() {
// handle panics in each postRun -- the app may already be in a panicking situation,
// this recover should not affect the original panic, as it is being run in a
// different call stack from the original panic, but the original panic should
// return without confusing things when a postRun also fails by panic
if v := recover(); v != nil {
a.state.Logger.Debugf("panic while calling postRun: %v", v)
}
}()
fn(&a.state, err)
}
func (a *application) WrapRunE(fn func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
wrapper := func(cmd *cobra.Command, args []string) (err error) {
defer func() {
// when the worker has completed (or errored) we want to exit the event loop gracefully
if a.state.Bus != nil {
a.state.Bus.Publish(ExitEvent(false))
}
}()
defer a.runPostRuns(err)
err = fn(cmd, args)
return
}
return a.execute(cmd.Context(), async(cmd, args, wrapper))
}
}
func (a *application) execute(ctx context.Context, errs <-chan error) error {
if a.state.Config.Dev != nil {
switch a.state.Config.Dev.Profile {
case ProfileCPU:
defer profile.Start(profile.CPUProfile).Stop()
case ProfileMem:
defer profile.Start(profile.MemProfile).Stop()
}
}
return eventloop(
ctx,
a.state.Logger.Nested("component", "eventloop"),
a.state.Subscription,
errs,
a.state.UI,
)
}
func logVersion(cfg SetupConfig, log logger.Logger) {
if cfg.ID.Version == "" {
log.Infof(cfg.ID.Name)
return
}
log.Infof(
"%s version: %+v",
cfg.ID.Name,
cfg.ID.Version,
)
}
func logConfiguration(log logger.Logger, cfgs ...any) {
var sb strings.Builder
for _, cfg := range cfgs {
if cfg == nil {
continue
}
var str string
if stringer, ok := cfg.(fmt.Stringer); ok {
str = stringer.String()
} else {
// yaml is pretty human friendly (at least when compared to json)
cfgBytes, err := yaml.Marshal(cfg)
if err != nil {
str = fmt.Sprintf("%+v", err)
} else {
str = string(cfgBytes)
}
}
str = strings.TrimSpace(str)
if str != "" && str != "{}" {
sb.WriteString(str + "\n")
}
}
content := sb.String()
if content != "" {
formatted := color.Magenta.Sprint(indent.String(" ", strings.TrimSpace(content)))
log.Debugf("config:\n%+v", formatted)
} else {
log.Debug("config: (none)")
}
}
func (a *application) AddFlags(flags *pflag.FlagSet, cfgs ...any) {
fangs.AddFlags(a.setupConfig.FangsConfig.Logger, flags, cfgs...)
a.state.Config.FromCommands = append(a.state.Config.FromCommands, cfgs...)
}
func (a *application) SetupCommand(cmd *cobra.Command, cfgs ...any) *cobra.Command {
return a.setupCommand(cmd, cmd.Flags(), &cmd.PreRunE, cfgs...)
}
func (a *application) Run() {
if a.root == nil {
panic(errors.New(setupRootCommandNotCalledError))
}
// drive application control from a single context which can be cancelled (notifying the event loop to stop)
ctx, cancel := context.WithCancel(context.Background())
a.root.SetContext(ctx)
// note: it is important to always do signal handling from the main package. In this way if quill is used
// as a lib a refactor would not need to be done (since anything from the main package cannot be imported this
// nicely enforces this constraint)
signals := make(chan os.Signal, 10) // Note: A buffered channel is recommended for this; see https://golang.org/pkg/os/signal/#Notify
signal.Notify(signals, os.Interrupt)
var exitCode int
defer func() {
if exitCode != 0 {
os.Exit(exitCode)
}
}()
defer func() {
signal.Stop(signals)
cancel()
}()
go func() {
select {
case <-signals: // first signal, cancel context
a.state.Logger.Trace("signal interrupt, stop requested")
cancel()
case <-ctx.Done():
}
<-signals // second signal, hard exit
a.state.Logger.Trace("signal interrupt, killing")
exitCode = 1
}()
if err := a.root.Execute(); err != nil {
a.handleExitError(err, os.Stderr)
exitCode = 1
}
}
func (a application) handleExitError(err error, stderr io.Writer) {
msg := color.Red.Render(strings.TrimSpace(err.Error()))
hasLogger := a.state.Logger != nil
shouldLog := hasLogger && a.resourcesLoaded
shouldPrint := !hasLogger || !a.resourcesLoaded
if shouldLog {
a.state.Logger.Error(msg)
}
if shouldPrint {
fmt.Fprintln(stderr, msg)
}
}
func (a *application) SetupRootCommand(cmd *cobra.Command, cfgs ...any) *cobra.Command {
a.root = cmd
return a.setupRootCommand(cmd, cfgs...)
}
func (a *application) setupRootCommand(cmd *cobra.Command, cfgs ...any) *cobra.Command {
if !strings.HasPrefix(cmd.Use, a.setupConfig.ID.Name) {
cmd.Use = a.setupConfig.ID.Name
}
cmd.Version = a.setupConfig.ID.Version
cmd.SetVersionTemplate(fmt.Sprintf("%s {{.Version}}\n", a.setupConfig.ID.Name))
// make a copy of the default configs
a.state.Config.Log = cp(a.setupConfig.DefaultLoggingConfig)
a.state.Config.Dev = cp(a.setupConfig.DefaultDevelopmentConfig)
for _, pc := range a.setupConfig.postConstructs {
pc(a)
}
return a.setupCommand(cmd, cmd.Flags(), &cmd.PreRunE, cfgs...)
}
func cp[T any](value *T) *T {
if value == nil {
return nil
}
t := *value
return &t
}
func (a *application) setupCommand(cmd *cobra.Command, flags *pflag.FlagSet, fn *func(cmd *cobra.Command, args []string) error, cfgs ...any) *cobra.Command {
original := *fn
*fn = func(cmd *cobra.Command, args []string) error {
err := a.Setup(cfgs...)(cmd, args)
if err != nil {
return err
}
if original != nil {
return original(cmd, args)
}
return nil
}
if cmd.RunE != nil {
cmd.RunE = a.WrapRunE(cmd.RunE)
}
cmd.SilenceUsage = true
cmd.SilenceErrors = true
a.state.Config.FromCommands = append(a.state.Config.FromCommands, cfgs...)
fangs.AddFlags(a.setupConfig.FangsConfig.Logger, flags, cfgs...)
return cmd
}
func async(cmd *cobra.Command, args []string, f func(cmd *cobra.Command, args []string) error) <-chan error {
errs := make(chan error)
go func() {
defer close(errs)
if err := f(cmd, args); err != nil {
errs <- err
}
}()
return errs
}
const setupRootCommandNotCalledError = "SetupRootCommand() must be called with the root command"