-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (72 loc) · 2.26 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"github.com/mylxsw/asteria/log"
"github.com/philchia/agollo/v4"
)
func main() {
var appID, serverAddr, accessSecret, cluster, namespace, output, format, onChange string
var forever, emtpyValueQuote bool
flag.StringVar(&appID, "app-id", "", "app id")
flag.StringVar(&serverAddr, "server-addr", "http://apollo-config:8080", "apollo server addr")
flag.StringVar(&accessSecret, "secret", "", "apollo access secret")
flag.StringVar(&cluster, "cluster", "default", "apollo cluster")
flag.StringVar(&namespace, "namespace", "application", "apollo namespace")
flag.StringVar(&output, "output", "stdout", "输出文件路径")
flag.StringVar(&format, "format", "%s=%s", "输出格式: %s: %s")
flag.BoolVar(&emtpyValueQuote, "empty-quote", false, "空值是否转换为空字符串,添加双引号")
flag.BoolVar(&forever, "forever", false, "持续运行,监听 key 的变化,实时更新文件")
flag.StringVar(&onChange, "on-change", "", "配置变更时执行的命令")
flag.Parse()
client := agollo.NewClient(&agollo.Conf{
AppID: appID,
MetaAddr: serverAddr,
AccesskeySecret: accessSecret,
Cluster: cluster,
NameSpaceNames: []string{namespace},
CacheDir: os.TempDir(),
})
if err := client.Start(); err != nil {
panic(err)
}
var updateFunc = func() {
lines := make([]string, 0)
for _, k := range client.GetAllKeys() {
val := client.GetString(k)
if emtpyValueQuote && val == "" {
val = `""`
}
lines = append(lines, fmt.Sprintf(format, k, val))
}
if output == "stdout" {
fmt.Println(strings.Join(lines, "\n"))
} else {
if err := ioutil.WriteFile(output, []byte(strings.Join(lines, "\n")), os.ModePerm); err != nil {
panic(err)
}
}
}
updateFunc()
if forever {
client.OnUpdate(func(ce *agollo.ChangeEvent) {
log.With(ce).Debug("change event received")
updateFunc()
if onChange != "" {
cmd := exec.Command("/bin/sh", "-c", onChange)
cmd.Env = os.Environ()
if data, err := cmd.CombinedOutput(); err != nil {
log.Errorf("on-chagne command failed: %v", err)
} else {
log.Infof("on-change data: %s", string(data))
}
}
})
stop := make(chan interface{})
<-stop
}
}