-
Notifications
You must be signed in to change notification settings - Fork 40
/
render.go
108 lines (97 loc) · 2.62 KB
/
render.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
package render
import (
"fmt"
"io/ioutil"
"os"
"path"
"text/template"
"github.com/sirupsen/logrus"
)
const ext = ".tmpl"
var extLen = len(ext)
var log = logrus.New()
func RenderFile(renderPath, templatePath string, cfg interface{}) error {
tmpl, err := template.ParseFiles(templatePath)
if err != nil {
log.WithFields(logrus.Fields{
"path": templatePath,
}).Error("Failed to parse template")
return err
}
renderFile, err := os.Create(renderPath)
if err != nil {
log.WithFields(logrus.Fields{
"path": renderPath,
}).Error("Failed to create file")
return err
}
defer renderFile.Close()
// NOTE For some reason, the template file for keepalived.conf has the
// executable bit set. Let's skip it because keepalived refuses to
// start when its configuration file is executable.
if renderPath != "/etc/keepalived/keepalived.conf" {
// Make sure we propagate any special permissions
templateStat, err := os.Stat(templatePath)
if err != nil {
log.WithFields(logrus.Fields{
"path": templatePath,
}).Error("Failed to stat template")
return err
}
err = os.Chmod(renderPath, templateStat.Mode())
if err != nil {
log.WithFields(logrus.Fields{
"path": renderPath,
}).Error("Failed to set permissions on file")
return err
}
}
log.WithFields(logrus.Fields{
"path": renderPath,
}).Info("Runtimecfg rendering template")
return tmpl.Execute(renderFile, cfg)
}
func Render(outDir string, paths []string, cfg interface{}) error {
tempPaths := paths
if len(paths) == 1 {
fi, err := os.Stat(paths[0])
if err != nil {
log.WithFields(logrus.Fields{
"path": paths[0],
}).Error("Failed to stat file")
}
if fi.Mode().IsDir() {
templateDir := paths[0]
files, err := ioutil.ReadDir(templateDir)
if err != nil {
log.WithFields(logrus.Fields{
"path": templateDir,
}).Error("Failed to read template directory")
return err
}
tempPaths = make([]string, 0)
for _, entryFi := range files {
if entryFi.Mode().IsRegular() {
if path.Ext(entryFi.Name()) == ext {
tempPaths = append(tempPaths, path.Join(templateDir, entryFi.Name()))
}
}
}
}
}
for _, templatePath := range tempPaths {
if path.Ext(templatePath) != ext {
return fmt.Errorf("Template %s does not have the right extension. Must be '%s'", templatePath, ext)
}
baseName := path.Base(templatePath)
renderPath := path.Join(outDir, baseName[:len(baseName)-extLen])
err := RenderFile(renderPath, templatePath, cfg)
if err != nil {
log.WithFields(logrus.Fields{
"path": templatePath,
"err": err,
}).Error("Failed to render template")
}
}
return nil
}