-
Notifications
You must be signed in to change notification settings - Fork 13
/
utils.go
285 lines (253 loc) · 6.38 KB
/
utils.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
package gonittest
import (
"bytes"
"fmt"
"html/template"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"syscall"
"github.com/bitnami/gonit/utils"
)
var (
tmplExtension = ".tmpl"
tmplData = make(map[string]string)
searchPath = []string{}
)
// CfgOpts defines the set of available configuration templates options
type CfgOpts struct {
Name string
RootDir string
Timeout string
ConfFile string
PidFile string
ScriptsDir string
ScriptFile string
TempDir string
ConfDir string
TimeoutUnits string
StopCmd string
StartCmd string
}
type tmplResolver struct {
Data string
Error error
}
func (r *tmplResolver) LoadFile(path string) error {
if r.Error == nil {
data, err := os.ReadFile(path)
r.Data, r.Error = string(data), err
}
return r.Error
}
func (r *tmplResolver) Load(data string) {
r.Data = data
}
func (r *tmplResolver) WriteToFile(path string) error {
if r.Error == nil {
r.Error = os.WriteFile(path, []byte(r.Data), os.FileMode(0755))
}
return r.Error
}
func (r *tmplResolver) Subst(opts *CfgOpts) (string, error) {
r.do(opts)
return r.Data, r.Error
}
func (r *tmplResolver) do(opts *CfgOpts) {
if r.Error != nil {
return
}
buff := bytes.NewBufferString("")
tmpl, err := template.New("tmpl").Parse(r.Data)
if err != nil {
r.Error = err
return
}
err = tmpl.Execute(buff, opts)
if err != nil {
r.Error = err
return
}
if buff.String() != r.Data {
r.Data = buff.String()
r.do(opts)
}
}
// SubstText renders a template text into a file with the provided opts settings
func SubstText(text string, file string, opts CfgOpts) error {
r := new(tmplResolver)
r.Load(text)
r.Subst(fillupCfgOpts(&opts))
return r.WriteToFile(file)
}
// Subst copies the template file at origint into the destination dest with the provided opts settings
func Subst(origin string, dest string, opts CfgOpts) error {
r := new(tmplResolver)
r.LoadFile(origin)
r.Subst(fillupCfgOpts(&opts))
return r.WriteToFile(dest)
}
// AddDirToTemplateSearchPath allows adding an extra dir to look for templates
func AddDirToTemplateSearchPath(dir string) {
searchPath = append(searchPath, dir)
}
func findTemplate(id string) string {
for _, p := range searchPath {
tplFile := filepath.Join(p, id)
if utils.FileExists(tplFile) {
return tplFile
}
if !strings.HasSuffix(tplFile, tmplExtension) {
tplFile += tmplExtension
if utils.FileExists(tplFile) {
return tplFile
}
}
}
return ""
}
// RenderTemplate renders a built-in template into the destination dest with the provided opts settings
func RenderTemplate(id string, dest string, opts CfgOpts) error {
if data, ok := tmplData[id]; ok {
return SubstText(data, dest, opts)
}
tplFile := findTemplate(id)
if tplFile == "" {
return fmt.Errorf("Cannot find template file for id %s", id)
}
return Subst(tplFile, dest, opts)
}
// TODO: This deserves its own function in utils, but it would require
// some more work to get a final version
func copyFile(src string, dest string) error {
var srcFh, destFh *os.File
var err error
info, err := os.Lstat(src)
if err != nil {
return err
}
if srcFh, err = os.Open(src); err == nil {
defer srcFh.Close()
} else {
return err
}
if destFh, err = os.OpenFile(dest, syscall.O_TRUNC|syscall.O_RDWR|syscall.O_CREAT, info.Mode()); err == nil {
defer destFh.Close()
} else {
return err
}
len, err := io.Copy(destFh, srcFh)
if err != nil {
return err
}
if len != info.Size() {
return fmt.Errorf("Size mismatch. Got %d bytes but expected %d", len, info.Size())
}
return nil
}
// RenderSampleProcessCheck writes a sample process check configuration file into file with the provided opts settings
func RenderSampleProcessCheck(file string, opts CfgOpts) error {
return RenderTemplate("service-check", file, opts)
}
// RenderConfiguration copies the files at origin into destDir, replacing templates in the process
func RenderConfiguration(origin string, destDir string, opts CfgOpts) error {
matches, err := filepath.Glob(origin)
if err != nil {
return err
}
for _, p := range matches {
rootDir := filepath.Dir(filepath.Clean(p))
err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
relative, _ := filepath.Rel(rootDir, path)
destFile := filepath.Join(destDir, relative)
if info.Mode().IsRegular() {
if strings.HasSuffix(path, tmplExtension) {
destFile = strings.TrimSuffix(destFile, tmplExtension)
if err := Subst(
path,
destFile,
opts,
); err != nil {
return err
}
} else {
err := copyFile(path, destFile)
if err != nil {
return err
}
}
} else if info.IsDir() {
os.MkdirAll(destFile, info.Mode())
} else {
return fmt.Errorf("Unknown file type (%s)", path)
}
os.Chmod(destFile, info.Mode().Perm())
return nil
})
if err != nil {
return err
}
}
return nil
}
func fillupCfgOpts(cfg *CfgOpts) *CfgOpts {
defautlOpts := CfgOpts{
RootDir: "",
Name: "sample",
TimeoutUnits: "seconds",
ScriptsDir: "{{.RootDir}}/scripts",
ScriptFile: "{{.ScriptsDir}}/ctl.sh",
ConfDir: "{{.RootDir}}/conf",
TempDir: "{{.RootDir}}/temp",
PidFile: "{{.TempDir}}/{{.Name}}.pid",
ConfFile: "{{.ConfDir}}/{{.Name}}.cnf",
StartCmd: "{{.ScriptFile}} start",
StopCmd: "{{.ScriptFile}} stop",
}
defaultValue := reflect.ValueOf(defautlOpts)
v := reflect.ValueOf(cfg)
for i := 0; i < v.Elem().NumField(); i++ {
if v.Elem().Field(i).Interface().(string) == "" {
v.Elem().Field(i).Set(defaultValue.Field(i))
}
}
return cfg
}
func init() {
if cwd, err := os.Getwd(); err == nil {
searchPath = append(searchPath, filepath.Join(cwd, "testdata"))
}
// Built-in templates
tmplData["sample-ctl-script"] = `#!/bin/bash
PID=$$
PID_FILE="{{.PidFile}}"
STOP_FILE="{{.RootDir}}/{{.Name}}.stop"
ERROR_FILE="{{.RootDir}}/{{.Name}}.doerror"
function kill_self {
kill -0 $PID
if [[ $? == 0 ]]; then
kill $PID
fi
}
if [[ -f $ERROR_FILE ]]; then
exit 1
fi
echo $PID > $PID_FILE
rm $STOP_FILE
(sleep 30; kill_self)&
while [[ ! -f $STOP_FILE ]]; do
sleep 0.1
done
rm $PID_FILE
rm $STOP_FILE
echo TERMINATED
`
tmplData["service-check"] = `
check process {{.Name}}
with pidfile "{{.PidFile}}"
start program = "{{.StartCmd}}" with timeout {{.Timeout}} {{.TimeoutUnits}}
stop program = "{{.StopCmd}}" with timeout {{.Timeout}} {{.TimeoutUnits}}
`
}