forked from lucaslorentz/caddy-supervisor
-
Notifications
You must be signed in to change notification settings - Fork 7
/
options.go
95 lines (77 loc) · 2.41 KB
/
options.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
package supervisor
import (
"bytes"
"errors"
"fmt"
"strings"
"text/template"
"time"
"github.com/Masterminds/sprig/v3"
)
// Options exposes settings to create a process supervisor
type Options struct {
Command string
Replica int
Args []string
Dir string
Env []string
RedirectStdout OutputTarget
RedirectStderr OutputTarget
RestartPolicy RestartPolicy
TerminationGracePeriod time.Duration
User string
}
// RestartPolicy determines when a supervised process should be restarted
type RestartPolicy string
const (
// RestartNever indicates to never restart the process
RestartNever = RestartPolicy("never")
// RestartOnFailure indicates to only restart the process after failures
RestartOnFailure = RestartPolicy("on_failure")
// RestartAlways indicates to always restart the process
RestartAlways = RestartPolicy("always")
)
func (options Options) processTemplates() (Options, error) {
result := Options{}
var err error
var tplErrors []string
handleError := func(option string, e error) {
if e != nil {
tplErrors = append(tplErrors, fmt.Sprintf("%s: %s", option, e))
}
}
result.Command, err = processTemplates(options.Command, options)
handleError("command", err)
result.Args = make([]string, len(options.Args))
for i, arg := range options.Args {
result.Args[i], err = processTemplates(arg, options)
handleError(fmt.Sprintf("args[%d]", i), err)
}
result.Dir, err = processTemplates(options.Dir, options)
handleError("dir", err)
result.Env = make([]string, len(options.Env))
for i, env := range options.Env {
result.Env[i], err = processTemplates(env, options)
handleError(fmt.Sprintf("env[%d]", i), err)
}
result.RedirectStdout = options.RedirectStdout
result.RedirectStderr = options.RedirectStderr
result.RestartPolicy = options.RestartPolicy
result.TerminationGracePeriod = options.TerminationGracePeriod
if len(tplErrors) > 0 {
return result, errors.New("failed to process templates: \n" + strings.Join(tplErrors, "\n"))
}
return result, nil
}
func processTemplates(text string, data interface{}) (string, error) {
tmpl, err := template.New("supervisor").Funcs(sprig.TxtFuncMap()).Parse(text)
if err != nil {
return "", err
}
var writer bytes.Buffer
err = tmpl.Execute(&writer, data)
if err != nil {
return "", err
}
return writer.String(), nil
}