-
Notifications
You must be signed in to change notification settings - Fork 0
/
heliumd.go
executable file
·404 lines (318 loc) · 9.86 KB
/
heliumd.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package main
import (
"bytes"
"errors"
"flag"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"github.com/coreos/go-etcd/etcd"
)
var prefix = flag.String("key", "/varnish", "etcd key to watch. Include the leading slash")
var templates = flag.String("templates", "./templates", "Path to the varnish templates")
var directorsOut = flag.String("directors", "/etc/varnish/directors.vcl", "The file to write the directors to")
var varnishSecret = flag.String("secret", "/etc/varnish/secret", "The secret to use when connecting to varnish")
var varnishServer = flag.String("varnish", "127.0.0.1:6082", "Varnish server to connect to, with admin port")
var varnishAdmin = flag.String("varnishadm", "/usr/bin/varnishadm", "The varnishadm program")
var vclOut = flag.String("vcl", "/etc/varnish/default.vcl", "The file to write the main VCL to")
var Error *log.Logger
var Info *log.Logger
var Warning *log.Logger
var nameRegexp *regexp.Regexp
type Def struct {
Hosts []*Host
Directors map[string]*Director
}
type Host struct {
Name string
Paths []*HostPath
}
type HostPath struct {
Director string
Path string
VCL string
}
type Director struct {
Backends []*Backend
Name string
}
type Backend struct {
Address string
Name string
Port int
}
func assert(err error) {
if err != nil {
Error.Fatal(err)
}
}
func parse(hosts *etcd.Response, upstreams *etcd.Response) *Def {
def := &Def{
Hosts: make([]*Host, 0),
Directors: make(map[string]*Director),
}
// read in all the configured hosts
for i := 0; i < len(hosts.Node.Nodes); i++ {
parsedHost := parseHost(hosts.Node.Nodes[i])
if parsedHost != nil && len(parsedHost.Paths) > 0 {
def.Hosts = append(def.Hosts, parsedHost)
// create an entry for each upstream the host uses
for j := 0; j < len(parsedHost.Paths); j++ {
directorName := parsedHost.Paths[j].Director
if _, state := def.Directors[directorName]; state == false {
def.Directors[directorName] = &Director{
Backends: make([]*Backend, 0),
Name: directorName,
}
}
}
}
}
// read in all the registered backends
for i := 0; i < len(upstreams.Node.Nodes); i++ {
node := upstreams.Node.Nodes[i]
directorName := formatNameForVarnish(path.Base(node.Key))
if director, state := def.Directors[directorName]; state == true {
for j := 0; j < len(node.Nodes); j++ {
if path.Base(node.Nodes[j].Key) == "endpoints" {
for k := 0; k < len(node.Nodes[j].Nodes); k++ {
endpointNode := node.Nodes[j].Nodes[k]
address, port, err := parseEndpoint(endpointNode.Value)
if err != nil {
Error.Printf("Invalid endpoint address, %s, expected http://address:port", endpointNode.Value)
} else {
backend := &Backend{
Name: director.Name + "_" + strconv.Itoa(len(director.Backends)),
Address: address,
Port: port,
}
director.Backends = append(director.Backends, backend)
}
}
}
}
}
}
return def
}
func parseHost(host *etcd.Node) *Host {
templateHost := &Host{
Name: path.Base(host.Key),
Paths: make([]*HostPath, 0),
}
for i := 0; i < len(host.Nodes); i++ {
if path.Base(host.Nodes[i].Key) == "locations" {
for j := 0; j < len(host.Nodes[i].Nodes); j++ {
hostPath := parseHostPath(host.Nodes[i].Nodes[j], templateHost)
if hostPath != nil {
templateHost.Paths = append(templateHost.Paths, hostPath)
}
}
}
}
return templateHost
}
func parseHostPath(pathNode *etcd.Node, host *Host) *HostPath {
hostPath := &HostPath{}
pathKey := path.Base(pathNode.Key)
missingComponents := make([]string, 0)
for i := 0; i < len(pathNode.Nodes); i++ {
node := pathNode.Nodes[i]
key := path.Base(node.Key)
switch key {
case "path":
hostPath.Path = node.Value
case "upstream":
hostPath.Director = node.Value
case "vcl":
hostPath.VCL = node.Value
}
}
if len(hostPath.Path) == 0 {
missingComponents = append(missingComponents, "path")
}
if len(hostPath.Director) == 0 {
missingComponents = append(missingComponents, "upstream")
}
if len(hostPath.VCL) == 0 {
missingComponents = append(missingComponents, "vcl")
}
if len(missingComponents) > 0 {
Warning.Printf("Found %s/%s but missing components [%s], ignoring", host.Name, pathKey, strings.Join(missingComponents, ","))
} else {
hostPath.Director = formatNameForVarnish(hostPath.Director)
return hostPath
}
return nil
}
func writeHosts(t *template.Template, hosts []*Host) error {
var buf bytes.Buffer
err := t.Execute(&buf, hosts)
if err != nil {
return err
}
return ioutil.WriteFile(*vclOut, buf.Bytes(), 0700)
}
func writeDirectors(t *template.Template, directors map[string]*Director) error {
var buf bytes.Buffer
err := t.Execute(&buf, directors)
if err != nil {
return err
}
return ioutil.WriteFile(*directorsOut, buf.Bytes(), 0700)
}
func reloadVarnish() error {
vclName := "vcl" + strconv.FormatInt(time.Now().Unix(), 10)
load := exec.Command(*varnishAdmin, "-T"+*varnishServer, "-S"+*varnishSecret, "vcl.load "+vclName+" "+*vclOut)
use := exec.Command(*varnishAdmin, "-T"+*varnishServer, "-S"+*varnishSecret, "vcl.use "+vclName)
var err error
var out []byte
if out, err = load.CombinedOutput(); err != nil {
Error.Println("Problem compiling new VCL,", err.Error(), string(out))
} else if err = use.Run(); err != nil {
Error.Println("Problem switching to new VCL, ", err.Error())
} else {
Info.Println("Configuration updated")
}
return nil
}
func formatNameForVarnish(name string) string {
return nameRegexp.ReplaceAllString(name, "")
}
func parseEndpoint(endpoint string) (address string, port int, err error) {
uri, err := url.Parse(endpoint)
if err != nil {
return "", 0, errors.New("Invalid address")
} else if uri.Host == "" {
return "", 0, errors.New("Must provide a host")
}
parts := strings.Split(uri.Host, ":")
address = parts[0]
if len(parts) == 1 {
port = 80
} else {
port, _ = strconv.Atoi(parts[1])
}
return
}
func process(client *etcd.Client) *Def {
if hosts, err := client.Get(*prefix+"/hosts", true, true); err != nil {
Error.Println("Reading hosts from etcd,", err.Error())
} else if upstreams, err := client.Get(*prefix+"/upstreams", true, true); err != nil {
Error.Println("Reading upstreams from etcd,", err.Error())
} else {
return parse(hosts, upstreams)
}
return nil
}
func write(def *Def, vclTemplate *template.Template, upstreamTemplate *template.Template) {
if err := writeHosts(vclTemplate, def.Hosts); err != nil {
Error.Println("Writing hosts,", err.Error())
} else if err = writeDirectors(upstreamTemplate, def.Directors); err != nil {
Error.Println("Writing directors,", err.Error())
} else if err = reloadVarnish(); err != nil {
Error.Println("Trying to reload varnish,", err.Error())
}
}
func processAndWrite(client *etcd.Client, vclTemplate *template.Template, upstreamTemplate *template.Template) *Def {
def := process(client)
if def != nil {
write(def, vclTemplate, upstreamTemplate)
}
return def
}
func compare(current *Def, previous *Def) bool {
if previous == nil {
return true
}
if len(current.Hosts) != len(previous.Hosts) {
return true
} else if len(current.Directors) != len(previous.Directors) {
return true
}
// the order of the two defs should always be the same this is safe to test like this
for i := 0; i < len(current.Hosts); i++ {
if current.Hosts[i].Name != previous.Hosts[i].Name {
return true
}
if len(current.Hosts[i].Paths) != len(previous.Hosts[i].Paths) {
return true
}
for j := 0; j < len(current.Hosts[i].Paths); j++ {
if current.Hosts[i].Paths[j].Director != previous.Hosts[i].Paths[j].Director {
return true
}
if current.Hosts[i].Paths[j].Path != previous.Hosts[i].Paths[j].Path {
return true
}
if current.Hosts[i].Paths[j].VCL != previous.Hosts[i].Paths[j].VCL {
return true
}
}
}
for i, _ := range current.Directors {
if current.Directors[i].Name != previous.Directors[i].Name {
return true
}
if len(current.Directors[i].Backends) != len(previous.Directors[i].Backends) {
return true
}
for j := 0; j < len(current.Directors[i].Backends); j++ {
if current.Directors[i].Backends[j].Address != previous.Directors[i].Backends[j].Address {
return true
}
if current.Directors[i].Backends[j].Name != previous.Directors[i].Backends[j].Name {
return true
}
if current.Directors[i].Backends[j].Port != previous.Directors[i].Backends[j].Port {
return true
}
}
}
return false
}
func main() {
Error = log.New(os.Stderr, "ERROR: ", log.Ltime|log.Lshortfile)
Info = log.New(os.Stdout, "INFO: ", log.Ltime|log.Lshortfile)
Warning = log.New(os.Stdout, "WARN: ", log.Ltime|log.Lshortfile)
nameRegexp = regexp.MustCompile(`[\W]`)
flag.Parse()
// arg 0 is the etcd server address
uri, err := url.Parse(flag.Arg(0))
assert(err)
if uri.Host == "" {
Error.Fatal("Invalid etcd host, expected format http://127.0.0.1:4001")
}
// compile the templates, exit early if there's a problem
vclTemplate := template.New("default.vcl")
vclTemplate, err = vclTemplate.ParseFiles(*templates + "/default.vcl")
assert(err)
directorTemplate := template.New("directors.vcl")
directorTemplate, err = directorTemplate.ParseFiles(*templates + "/directors.vcl")
assert(err)
// connect to etcd and start watching
urls := []string{uri.String()}
watchChan := make(chan *etcd.Response)
client := etcd.NewClient(urls)
previousDef := processAndWrite(client, vclTemplate, directorTemplate)
go client.Watch(*prefix, 0, true, watchChan, nil)
Info.Printf("Listening for etcd events from %s%s...", uri.String(), *prefix)
for _ = range watchChan {
def := process(client)
hasDiff := compare(def, previousDef)
if def != nil && hasDiff == true {
Info.Println("Change detected...")
write(def, vclTemplate, directorTemplate)
}
previousDef = def
}
Error.Fatal("etcd watch loop closed")
}