-
Notifications
You must be signed in to change notification settings - Fork 14
/
app.go
116 lines (96 loc) · 2.22 KB
/
app.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
package command
import (
"io"
"sync/atomic"
"github.com/caddyserver/caddy/v2"
"go.uber.org/zap"
)
// Interface guards
var (
_ caddy.App = (*App)(nil)
_ caddy.Module = (*App)(nil)
_ caddy.Provisioner = (*App)(nil)
_ caddy.Validator = (*App)(nil)
)
// lifeCycle is used to keep track of startup/shutdown
var lifeCycle int32
// loggers keeps track of loggers to prevent recreation.
var loggers = map[string]io.WriteCloser{}
func init() {
caddy.RegisterModule(App{})
}
// App is top level module that runs shell commands.
type App struct {
Commands []Cmd `json:"commands,omitempty"`
commands map[string][]Runner
log *zap.Logger
}
// Provision implements caddy.Provisioner
func (a *App) Provision(ctx caddy.Context) error {
if a.commands == nil {
a.commands = map[string][]Runner{}
}
a.log = ctx.Logger(a)
repl := caddy.NewReplacer()
for _, cmd := range a.Commands {
if err := cmd.provision(ctx, a); err != nil {
return err
}
// replace global placeholders
argv := make([]string, len(cmd.Args))
for index, argument := range cmd.Args {
argv[index] = repl.ReplaceAll(argument, "")
}
runner := runnerFunc(func() error {
return cmd.run(argv)
})
for at := range cmd.at {
a.commands[at] = append(a.commands[at], runner)
}
}
return nil
}
// Validate implements caddy.Validator
func (a App) Validate() error {
for _, cmd := range a.Commands {
if err := cmd.validate(); err != nil {
return err
}
}
return nil
}
// Start starts the app.
func (a App) Start() error {
count := atomic.AddInt32(&lifeCycle, 1)
if count > 1 {
// not the first startup, maybe a reload
return nil
}
for _, runner := range a.commands["startup"] {
if err := runner.Run(); err != nil {
return err
}
}
return nil
}
// Stop stops the app.
func (a *App) Stop() error {
count := atomic.AddInt32(&lifeCycle, -1)
if count > 0 {
// not shutdown, maybe a prior config reload.
return nil
}
for _, runner := range a.commands["shutdown"] {
if err := runner.Run(); err != nil {
return err
}
}
return nil
}
// CaddyModule implements caddy.ModuleInfo
func (a App) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "exec",
New: func() caddy.Module { return new(App) },
}
}