forked from phamhongviet/serf-template
/
main.go
100 lines (87 loc) · 1.93 KB
/
main.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
package main
import (
//"encoding/json"
"errors"
//"fmt"
"os"
"os/exec"
//"strconv"
rpc "github.com/hashicorp/serf/client"
"log"
"strings"
//"text/template"
)
// exit codes
/*
const (
OK = iota
SYNTAX_ERROR = iota
CMD_FAILED = iota
TEMPLATE_PARSE_FAILED = iota
)
*/
const (
DEBUG = false
DEBUG_FILE = "/tmp/serf_template.log"
)
func main() {
if DEBUG {
log_file, _ := os.Create(DEBUG_FILE)
defer log_file.Close()
log.SetOutput(log_file)
log.Println("Serf Template starting")
}
if len(os.Args) != 2 {
err := errors.New("No config file")
panic(err)
}
// parse directive from config file
directives, err := ParseDirectives(os.Args[1])
if err != nil {
panic(err)
}
if DEBUG {
log.Printf("directives: %s", directives)
}
// create RPC config
rpc_config := rpc.Config{
Addr: directives.Rpc_addr,
AuthKey: directives.Rpc_auth,
Timeout: directives.Rpc_timeout,
}
// create connection to the RPC interface
rpc_client, err := rpc.ClientFromConfig(&rpc_config)
if err != nil {
panic(err)
}
defer rpc_client.Close()
// create input channel
ch := make(chan map[string]interface{})
_, err = rpc_client.Stream("member-join,member-failed,member-update,member-leave,member-reap", ch)
if err != nil {
panic(err)
}
for {
// wait for signal from serf
<-ch
// get members' information
members, err := rpc_client.MembersFiltered(directives.Tags, directives.Status, directives.Name)
if err != nil {
panic(err)
}
// for each templates:
// - render template
// - execute command if any
for i := 0; i < len(directives.Templates); i++ {
RenderTemplate(directives.Templates[i].Src, directives.Templates[i].Dest, members)
if directives.Templates[i].Cmd != "" {
cmd_args := strings.Split(directives.Templates[i].Cmd, " ")
cmd := exec.Command(cmd_args[0], cmd_args[1:]...)
err := cmd.Run()
if err != nil {
panic(err)
}
}
}
}
}