-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
main.go
325 lines (282 loc) · 7.03 KB
/
main.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
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"os/exec"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"github.com/joho/godotenv"
"gopkg.in/yaml.v3"
)
// version is the git tag at the time of build and is used to denote the
// binary's current version. This value is supplied as an ldflag at compile
// time by goreleaser (see .goreleaser.yml).
const (
name = "goreman"
version = "0.3.16"
revision = "HEAD"
)
func usage() {
fmt.Fprint(os.Stderr, `Tasks:
goreman check # Show entries in Procfile
goreman help [TASK] # Show this help
goreman export [FORMAT] [LOCATION] # Export the apps to another process
(upstart)
goreman run COMMAND [PROCESS...] # Run a command
start
stop
stop-all
restart
restart-all
list
status
goreman start [PROCESS] # Start the application
goreman version # Display Goreman version
Options:
`)
flag.PrintDefaults()
os.Exit(0)
}
// -- process information structure.
type procInfo struct {
name string
cmdline string
cmd *exec.Cmd
port uint
setPort bool
colorIndex int
// True if we called stopProc to kill the process, in which case an
// *os.ExitError is not the fault of the subprocess
stoppedBySupervisor bool
mu sync.Mutex
cond *sync.Cond
waitErr error
}
var mu sync.Mutex
// process informations named with proc.
var procs []*procInfo
// filename of Procfile.
var procfile = flag.String("f", "Procfile", "proc file")
// rpc port number.
var port = flag.Uint("p", defaultPort(), "port")
var startRPCServer = flag.Bool("rpc-server", true, "Start an RPC server listening on "+defaultAddr())
// base directory
var basedir = flag.String("basedir", "", "base directory")
// base of port numbers for app
var baseport = flag.Uint("b", 5000, "base number of port")
var setPorts = flag.Bool("set-ports", true, "False to avoid setting PORT env var for each subprocess")
// true to exit the supervisor
var exitOnError = flag.Bool("exit-on-error", false, "Exit goreman if a subprocess quits with a nonzero return code")
// true to exit the supervisor when all processes stop
var exitOnStop = flag.Bool("exit-on-stop", true, "Exit goreman if all subprocesses stop")
// show timestamp in log
var logTime = flag.Bool("logtime", true, "show timestamp in log")
var maxProcNameLength = 0
var re = regexp.MustCompile(`\$([a-zA-Z]+[a-zA-Z0-9_]+)`)
type config struct {
Procfile string `yaml:"procfile"`
// Port for RPC server
Port uint `yaml:"port"`
BaseDir string `yaml:"basedir"`
BasePort uint `yaml:"baseport"`
Args []string
// If true, exit the supervisor process if a subprocess exits with an error.
ExitOnError bool `yaml:"exit_on_error"`
}
func readConfig() *config {
var cfg config
flag.Parse()
if flag.NArg() == 0 {
usage()
}
cfg.Procfile = *procfile
cfg.Port = *port
cfg.BaseDir = *basedir
cfg.BasePort = *baseport
cfg.ExitOnError = *exitOnError
cfg.Args = flag.Args()
b, err := os.ReadFile(".goreman")
if err == nil {
yaml.Unmarshal(b, &cfg)
}
return &cfg
}
// read Procfile and parse it.
func readProcfile(cfg *config) error {
content, err := os.ReadFile(cfg.Procfile)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
procs = []*procInfo{}
index := 0
for _, line := range strings.Split(string(content), "\n") {
tokens := strings.SplitN(line, ":", 2)
if len(tokens) != 2 || tokens[0][0] == '#' {
continue
}
k, v := strings.TrimSpace(tokens[0]), strings.TrimSpace(tokens[1])
if runtime.GOOS == "windows" {
v = re.ReplaceAllStringFunc(v, func(s string) string {
return "%" + s[1:] + "%"
})
}
proc := &procInfo{name: k, cmdline: v, colorIndex: index}
if *setPorts {
proc.setPort = true
proc.port = cfg.BasePort
cfg.BasePort += 100
}
proc.cond = sync.NewCond(&proc.mu)
procs = append(procs, proc)
if len(k) > maxProcNameLength {
maxProcNameLength = len(k)
}
index = (index + 1) % len(colors)
}
if len(procs) == 0 {
return errors.New("no valid entry")
}
return nil
}
func defaultServer(serverPort uint) string {
if s, ok := os.LookupEnv("GOREMAN_RPC_SERVER"); ok {
return s
}
return fmt.Sprintf("127.0.0.1:%d", defaultPort())
}
func defaultAddr() string {
if s, ok := os.LookupEnv("GOREMAN_RPC_ADDR"); ok {
return s
}
return "0.0.0.0"
}
// default port
func defaultPort() uint {
s := os.Getenv("GOREMAN_RPC_PORT")
if s != "" {
i, err := strconv.Atoi(s)
if err == nil {
return uint(i)
}
}
return 8555
}
// command: check. show Procfile entries.
func check(cfg *config) error {
err := readProcfile(cfg)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
keys := make([]string, len(procs))
i := 0
for _, proc := range procs {
keys[i] = proc.name
i++
}
sort.Strings(keys)
fmt.Printf("valid procfile detected (%s)\n", strings.Join(keys, ", "))
return nil
}
func findProc(name string) *procInfo {
mu.Lock()
defer mu.Unlock()
for _, proc := range procs {
if proc.name == name {
return proc
}
}
return nil
}
// command: start. spawn procs.
func start(ctx context.Context, sig <-chan os.Signal, cfg *config) error {
err := readProcfile(cfg)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(ctx)
// Cancel the RPC server when procs have returned/errored, cancel the
// context anyway in case of early return.
defer cancel()
if len(cfg.Args) > 1 {
tmp := make([]*procInfo, 0, len(cfg.Args[1:]))
maxProcNameLength = 0
for _, v := range cfg.Args[1:] {
proc := findProc(v)
if proc == nil {
return errors.New("unknown proc: " + v)
}
tmp = append(tmp, proc)
if len(v) > maxProcNameLength {
maxProcNameLength = len(v)
}
}
mu.Lock()
procs = tmp
mu.Unlock()
}
godotenv.Load()
rpcChan := make(chan *rpcMessage, 10)
if *startRPCServer {
go startServer(ctx, rpcChan, cfg.Port)
}
procsErr := startProcs(sig, rpcChan, cfg.ExitOnError)
return procsErr
}
func showVersion() {
fmt.Fprintf(os.Stdout, "%s\n", version)
os.Exit(0)
}
func main() {
var err error
cfg := readConfig()
if cfg.BaseDir != "" {
err = os.Chdir(cfg.BaseDir)
if err != nil {
fmt.Fprintf(os.Stderr, "goreman: %s\n", err.Error())
os.Exit(1)
}
}
cmd := cfg.Args[0]
switch cmd {
case "check":
err = check(cfg)
case "help":
usage()
case "run":
if len(cfg.Args) >= 2 {
cmd, args := cfg.Args[1], cfg.Args[2:]
err = run(cmd, args, cfg.Port)
} else {
usage()
}
case "export":
if len(cfg.Args) == 3 {
format, path := cfg.Args[1], cfg.Args[2]
err = export(cfg, format, path)
} else {
usage()
}
case "start":
c := notifyCh()
err = start(context.Background(), c, cfg)
case "version":
showVersion()
default:
usage()
}
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", os.Args[0], err.Error())
os.Exit(1)
}
}