-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroot.go
165 lines (142 loc) · 3.61 KB
/
root.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package commands
import (
"context"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/wangfeiping/log"
)
// nolint
const (
CmdRoot = "net_watcher"
CmdStart = "start"
CmdAdd = "add"
CmdCall = "call"
CmdConfig = "config"
CmdVersion = "version"
CmdHelp = "help"
ShortDescription = "Network service availability detection tools"
)
// nolint
const (
FlagLog = "log"
FlagConfig = "config"
FlagListen = "listen"
FlagAlias = "alias"
FlagURL = "url"
FlagBody = "body"
FlagMethod = "method"
FlagRegex = "regex"
FlegDuration = "duration"
FlagService = "service"
FlagVersion = CmdVersion
)
// Runner is command call function
type Runner func() (context.CancelFunc, error)
// NewRootCommand returns root command
func NewRootCommand(versioner Runner) *cobra.Command {
root := &cobra.Command{
Use: CmdRoot,
Short: ShortDescription,
Run: func(cmd *cobra.Command, args []string) {
if viper.GetBool(FlagVersion) {
versioner()
return
}
cmd.Help()
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
if err := viper.BindPFlags(cmd.Flags()); err != nil {
log.Error("bind flags error: ", err)
return err
}
if strings.EqualFold(cmd.Use, CmdRoot) ||
strings.EqualFold(cmd.Use, CmdVersion) {
// doesn't need init config & log
return nil
}
initConfig()
if !strings.EqualFold(cmd.Use, CmdStart) {
// doesn't need init log
return nil
}
initLogger()
return
},
}
root.Flags().BoolP(FlagVersion, "v", false, "Show version info")
root.PersistentFlags().StringP(FlagConfig, "c", "./config.yml", "Config file path")
return root
}
func initConfig() error {
viper.SetConfigFile(viper.GetString(FlagConfig))
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
// stderr, so if we redirect output to json file, this doesn't appear
// fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
} else if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// ignore not found error, return other errors
return err
}
return nil
}
func initLogger() {
log.Config(log.RollingFileConfig())
log.Infof("starting at %s", getExecPath())
}
// getExecPath returns the execution path
func getExecPath() (execPath string) {
file, _ := exec.LookPath(os.Args[0])
execFile := filepath.Base(file)
execPath, _ = filepath.Abs(file)
if len(execPath) > 1 {
rs := []rune(execPath)
execPath = string(rs[0:(len(execPath) - len(execFile))])
}
return
}
func commandRunner(run Runner, isKeepRunning bool) error {
cancel, err := run()
if err != nil {
log.Error("Running error: ", err.Error())
return err
}
if isKeepRunning {
keepRunning(func(sig os.Signal) {
defer log.Flush()
if cancel != nil {
cancel()
}
log.Debug("Stopped by signal: ", sig)
})
}
return nil
}
func keepRunning(callback func(sig os.Signal)) {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
select {
case s, ok := <-signals:
log.Infof("System signal [%v] %t, trying to run callback...", s, ok)
if !ok {
break
}
if callback != nil {
callback(s)
}
log.Flush()
os.Exit(1)
}
}
func serviceFlags(cmd *cobra.Command) {
cmd.Flags().StringP(FlagURL, "u", "", "request url")
cmd.Flags().StringP(FlagBody, "b", "", "request body")
cmd.Flags().StringP(FlagAlias, "a", "", "service alias")
cmd.Flags().StringP(FlagMethod, "m", "GET", "http method")
cmd.Flags().StringP(FlagRegex, "r", "GET", "match regex")
}