/
main_other.go
104 lines (95 loc) · 2.07 KB
/
main_other.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
//go:build !windows
// +build !windows
package main
import (
"context"
"sync"
"syscall"
"time"
"github.com/go-logr/logr"
"github.com/wzshiming/bridge/chain"
"github.com/wzshiming/bridge/config"
"github.com/wzshiming/notify"
)
func runWithReload(ctx context.Context, log logr.Logger, tasks []config.Chain, configs []string) {
reloadCn := make(chan struct{}, 1)
notify.On(syscall.SIGHUP, func() {
select {
case reloadCn <- struct{}{}:
default:
}
})
wg := sync.WaitGroup{}
defer wg.Wait()
var lastWorking = map[string]func(){}
var cleanups []func()
count := 1
reloadCn <- struct{}{}
for {
select {
case <-ctx.Done():
return
case <-reloadCn:
}
log := log.WithValues("reload_count", count)
tasks, err := config.LoadConfig(configs...)
if err != nil {
for {
log.Error(err, "LoadConfig")
log.Info("Try reload again after 1 second")
time.Sleep(time.Second)
tasks, err = config.LoadConfig(configs...)
if err == nil {
break
}
}
}
working := map[string]func(){}
for _, task := range tasks {
uniq := task.Unique()
cleanup := lastWorking[uniq]
if cleanup != nil {
working[uniq] = cleanup
continue
}
ctx, cancel := context.WithCancel(ctx)
working[uniq] = cancel
wg.Add(1)
go func(ctx context.Context, task config.Chain) {
defer wg.Done()
log := log.WithValues("chains", task)
log.Info(chain.ShowChainWithConfig(task))
for ctx.Err() == nil {
b := chain.NewBridge(log, dump)
err := b.BridgeWithConfig(ctx, task)
if err != nil {
log.Error(err, "BridgeWithConfig")
}
time.Sleep(time.Second)
}
}(ctx, task)
}
for uniq := range lastWorking {
if _, ok := working[uniq]; !ok {
cancel := lastWorking[uniq]
if cancel != nil {
cleanups = append(cleanups, cancel)
}
}
}
lastWorking = working
// TODO: wait for all task is working
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
if len(cleanups) > 0 {
for _, cleanup := range cleanups {
cleanup()
}
cleanups = cleanups[:0]
}
count++
}
}