-
Notifications
You must be signed in to change notification settings - Fork 162
/
utils.go
85 lines (75 loc) · 1.67 KB
/
utils.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
// Package utils provides common sub commands and command flags.
package utils
import (
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
"github.com/anyswap/CrossChain-Bridge/log"
"github.com/anyswap/CrossChain-Bridge/params"
"github.com/urfave/cli/v2"
)
var (
clientIdentifier string
gitCommit string
gitDate string
)
// catch signal and cleanup related
var (
CleanupChan = make(chan struct{})
TopWaitGroup = new(sync.WaitGroup)
)
// NewApp creates an app with sane defaults.
func NewApp(identifier, gitcommit, gitdate, usage string) *cli.App {
notifySignals()
clientIdentifier = identifier
gitCommit = gitcommit
gitDate = gitdate
app := cli.NewApp()
app.Name = filepath.Base(os.Args[0])
app.Version = params.VersionWithCommit(gitCommit, gitDate)
app.Usage = usage
return app
}
func notifySignals() {
signal.Reset() // to cancal imported mod (eg. okex) to catch signal and call os.Exit
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan,
os.Interrupt,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGHUP,
)
go func() {
sig := <-signalChan
log.Info("receive signal", "signal", sig)
log.Info("notify others to do clean up")
close(CleanupChan)
go func() {
for i := 1; i <= 5; i++ {
sig := <-signalChan
log.Info("receive multiple (5) signals to exit", "signal", sig, "count", i)
}
os.Exit(1)
}()
<-time.After(5 * time.Second)
os.Exit(1)
}()
}
// IsCleanuping is cleanuping
func IsCleanuping() bool {
select {
case <-CleanupChan:
return true
default:
return false
}
}
// WaitAndCleanup wait and cleanup
func WaitAndCleanup(doCleanup func()) {
<-CleanupChan
doCleanup()
}