-
Notifications
You must be signed in to change notification settings - Fork 0
/
watchgateway.go
92 lines (79 loc) · 2 KB
/
watchgateway.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
package bridge
import (
"path/filepath"
"github.com/deltaswapio/swaprouter/v3/log"
"github.com/deltaswapio/swaprouter/v3/params"
"github.com/deltaswapio/swaprouter/v3/router"
"github.com/deltaswapio/swaprouter/v3/tokens"
"github.com/fsnotify/fsnotify"
)
// WatchGatewayConfig watch and update gateway config
func WatchGatewayConfig() {
if params.GatewayConfigFile == "" {
return
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Error("fsnotify: new watcher failed", "err", err)
return
}
go startWatcher(watcher)
file := filepath.Clean(params.GatewayConfigFile)
dir := filepath.Dir(file)
err = watcher.Add(dir)
if err != nil {
log.Error("fsnotify: add gateway path failed", "err", err)
return
}
log.Infof("fsnotify: start to watch gateway config file %v", file)
}
func startWatcher(watcher *fsnotify.Watcher) {
defer watcher.Close()
ops := []fsnotify.Op{
fsnotify.Write,
}
for {
select {
case ev, ok := <-watcher.Events:
if !ok { // Channel was closed
log.Error("fsnotify: channel was closed")
return
}
if filepath.Clean(ev.Name) != filepath.Clean(params.GatewayConfigFile) {
continue
}
log.Trace("fsnotify: watcher event", "file", ev.Name, "op", ev.Op)
for _, op := range ops {
if ev.Has(op) {
err := updateGateway(ev.Name)
if err == nil {
log.Info("fsnotify: updateGateway success")
} else {
log.Warn("fsnotify: updateGateway failed", "err", err)
}
break
}
}
case err, ok := <-watcher.Errors:
if !ok { // Channel was closed
log.Error("fsnotify: channel was closed")
return
}
log.Warn("fsnotify: watcher error", "err", err)
}
}
}
func updateGateway(fileName string) error {
gateways, err := params.LoadGatewayConfigs()
if err != nil {
return err
}
params.GetRouterConfig().GatewayConfigs = gateways
router.RouterBridges.Range(func(k, v interface{}) bool {
chainID := k.(string)
bridge := v.(tokens.IBridge)
SetGatewayConfig(bridge, chainID)
return true
})
return nil
}