/
rmt.go
228 lines (184 loc) · 5.27 KB
/
rmt.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
package main
import (
"bufio"
"bytes"
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"text/template"
"time"
"github.com/denkhaus/rancher-meta-template/config"
"github.com/denkhaus/rancher-meta-template/logging"
"github.com/denkhaus/rancher-meta-template/scratch"
"github.com/juju/errors"
"github.com/rancher/go-rancher-metadata/metadata"
"gopkg.in/pipe.v2"
)
const (
DEFAULT_TEMPLATE_DIR = "/etc/rancher-meta-template/templates"
)
//////////////////////////////////////////////////////////////////////////////
func createTemplateCtx(meta *metadata.Client) (interface{}, error) {
services, err := meta.GetServices()
if err != nil {
return nil, errors.Annotate(err, "get services")
}
containers, err := meta.GetContainers()
if err != nil {
return nil, errors.Annotate(err, "get containers")
}
containersW := make([]ContainerWrap, 0)
for _, container := range containers {
cw := ContainerWrap{container}
containersW = append(containersW, cw)
}
servicesW := make([]ServiceWrap, 0)
for _, service := range services {
sw := ServiceWrap{service}
servicesW = append(servicesW, sw)
}
ctx := map[string]interface{}{
"Services": servicesW,
"Containers": containersW,
}
return ctx, nil
}
//////////////////////////////////////////////////////////////////////////////
func computeMd5(filePath string) (string, error) {
if _, err := os.Stat(filePath); err != nil {
return "", nil
}
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
//////////////////////////////////////////////////////////////////////////////////
func appendCommandPipe(cmd config.Command, pipes []pipe.Pipe) []pipe.Pipe {
if cmd.Cmd != "" {
if cmd.Args != nil {
return append(pipes, pipe.Exec(cmd.Cmd, cmd.Args...))
}
return append(pipes, pipe.Exec(cmd.Cmd))
}
return pipes
}
//////////////////////////////////////////////////////////////////////////////////
func processTemplateSet(meta *metadata.Client, set config.TemplateSet) error {
if _, err := os.Stat(set.TemplatePath); err != nil {
logging.Warning("template path %q is not available: skip", set.TemplatePath)
return nil
}
buf, err := ioutil.ReadFile(set.TemplatePath)
if err != nil {
return errors.Annotate(err, "read template file")
}
templ := template.New(set.Name).Funcs(newFuncMap())
tmpl, err := templ.Parse(string(buf))
if err != nil {
return errors.Annotate(err, "parse template")
}
lastMd5 := ""
if _, err = os.Stat(set.DestinationPath); err == nil {
lmd5, err := computeMd5(set.DestinationPath)
if err != nil {
return errors.Annotate(err, "get last md5 hash")
}
lastMd5 = lmd5
}
ctx, err := createTemplateCtx(meta)
if err != nil {
return errors.Annotate(err, "create template context")
}
var newBuf bytes.Buffer
wr := bufio.NewWriter(&newBuf)
if err := tmpl.Execute(wr, ctx); err != nil {
return errors.Annotate(err, "execute template")
}
if err := wr.Flush(); err != nil {
return errors.Annotate(err, "flush tmpl writer")
}
hash := md5.New()
hash.Write(newBuf.Bytes())
currentMd5 := fmt.Sprintf("%x", hash.Sum(nil))
if lastMd5 == currentMd5 {
return nil
}
if lastMd5 == "" {
logging.Info("create output file")
} else {
logging.Info("last md5 sum is %q", lastMd5)
logging.Info("current md5 sum is %q", currentMd5)
logging.Info("output file needs refresh")
}
f, err := os.Create(set.DestinationPath)
if err != nil {
return errors.Annotate(err, "create destination file")
}
w := bufio.NewWriter(f)
if _, err := w.Write(newBuf.Bytes()); err != nil {
return errors.Annotate(err, "write to output")
}
if err := w.Flush(); err != nil {
return errors.Annotate(err, "flush out writer")
}
if err := f.Close(); err != nil {
return errors.Annotate(err, "outfile close")
}
logging.Info("process check & generate")
pipes := make([]pipe.Pipe, 0)
pipes = appendCommandPipe(set.Check, pipes)
pipes = appendCommandPipe(set.Run, pipes)
script := pipe.Script(pipes...)
if output, err := pipe.CombinedOutput(script); err != nil {
logging.Info(string(output))
return errors.Annotate(err, "check & run")
}
return nil
}
//////////////////////////////////////////////////////////////////////////////////
func processTemplates(cnf *config.Config) error {
apiURL := cnf.Host + cnf.Prefix
meta, err := metadata.NewClientAndWait(apiURL)
if err != nil {
return errors.Annotate(err, "get meta client")
}
logging.Info("connect rancher metadata url: %q", apiURL)
//expand template paths
logging.Debug("expand template paths")
for idx, set := range cnf.Sets {
if !path.IsAbs(set.TemplatePath) {
cnf.Sets[idx].TemplatePath = path.Join(DEFAULT_TEMPLATE_DIR, set.TemplatePath)
}
}
version := "init"
for {
newVersion, err := meta.GetVersion()
if err != nil {
return errors.Annotate(err, "get version")
}
if newVersion == version {
time.Sleep(5 * time.Second)
continue
}
version = newVersion
logging.Info("metadata changed - refresh config")
for _, set := range cnf.Sets {
scratch.Reset()
if err := processTemplateSet(meta, set); err != nil {
return errors.Annotate(err, "process template set")
}
}
time.Sleep(time.Duration(cnf.Repeat) * time.Second)
}
return nil
}