-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
115 lines (92 loc) · 2.46 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"flag"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/samuel/go-zookeeper/zk"
)
type Property struct {
Key string
Value string
}
var (
zookeeper *string
namespace *string
srcTemplate *string
destConf *string
command *string
aSync *bool
conn *zk.Conn
zookeeperProperties []Property
eventChannel <-chan zk.Event
child []string
)
func flags() {
zookeeper = flag.String("zookeeper", "192.168.120.81:2181,192.168.120.82:2181", "Zookeeper server list example: 192.168.120.1:2181,192.168.120.2:2181,..")
namespace = flag.String("namespace", "/watch", "Namespace to watch on")
srcTemplate = flag.String("template", "", "srcTemplate absolut path")
destConf = flag.String("destConf", "", "Generated config absolut path")
aSync = flag.Bool("aSync", false, "Asyncron command execution")
command = flag.String("cmd", "", "Command execute after regenerate config")
flag.Parse()
}
func main() {
flags()
if *srcTemplate != "" && *destConf == "" {
println("destConf option must be set")
flag.Usage()
os.Exit(2)
}
if *srcTemplate == "" && *destConf != "" {
println("srcTemplate option must be set")
flag.Usage()
os.Exit(2)
}
if *command == "" && *srcTemplate == "" {
println("At least you have to set srcTemplate path or a command to execute after change event")
flag.Usage()
os.Exit(2)
}
splittedCommand := strings.Split(*command, " ")
cmd := &Command{
Cmd: splittedCommand[0],
Args: splittedCommand[1:],
Async: *aSync,
}
conf := &Config{
Template: *srcTemplate,
Dest: *destConf,
}
conf.Init()
defer conf.Close()
conn, _, _ = zk.Connect(strings.Split(*zookeeper, ","), time.Second)
defer conn.Close()
log.Printf("connected to zookeepers: %v", *zookeeper)
log.Printf("Watch on: %s", *namespace)
eventChannel, zookeeperProperties = getChildW(*namespace)
conf.GenerateConfig(zookeeperProperties)
for true {
zookeeperProperties = []Property{}
<-eventChannel
eventChannel, zookeeperProperties = getChildW(*namespace)
conf.GenerateConfig(zookeeperProperties)
cmd.Execute()
}
}
func getChildW(namespace string) (ch <-chan zk.Event, properties []Property) {
child, _, ch, _ = conn.ChildrenW(namespace)
for _, key := range child {
value, _, _ := conn.Get(fmt.Sprintf("%s/%s", namespace, key))
// bypass directory
if string(value) != "" {
properties = append(properties, Property{
Key: key,
Value: string(value),
})
}
}
return
}