-
Notifications
You must be signed in to change notification settings - Fork 88
/
main.go
291 lines (255 loc) · 8.4 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
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"regexp"
"runtime"
"strings"
"syscall"
"time"
"github.com/mackerelio/golib/logging"
"github.com/mackerelio/mackerel-agent/command"
"github.com/mackerelio/mackerel-agent/config"
"github.com/mackerelio/mackerel-agent/pidfile"
"github.com/motemen/go-cli"
)
// allow options like -role=... -role=...
type roleFullnamesFlag []string
var roleFullnamePattern = regexp.MustCompile(`^[a-zA-Z0-9][-_a-zA-Z0-9]*:\s*[a-zA-Z0-9][-_a-zA-Z0-9]*$`)
func (r *roleFullnamesFlag) String() string {
return fmt.Sprint(*r)
}
func (r *roleFullnamesFlag) Set(input string) error {
inputRoles := strings.Split(input, ",")
*r = append(*r, inputRoles...)
return nil
}
var logger = logging.GetLogger("main")
func main() {
// although the possibility is very low, mackerel-agent may panic because of
// a race condition in multi-threaded environment on some OS/Arch.
// So fix GOMAXPROCS to 1 just to be safe.
if os.Getenv("GOMAXPROCS") == "" {
runtime.GOMAXPROCS(1)
}
// force disabling http2, because the http/2 connection sometimes unstable
// at a certain data center equipped with particular network switches.
godebug := os.Getenv("GODEBUG")
if godebug != "" {
godebug += ","
}
godebug += "http2client=0"
os.Setenv("GODEBUG", godebug)
cli.Run(os.Args[1:])
}
func printRetireUsage() {
usage := fmt.Sprintf(`Usage of mackerel-agent retire:
-conf string
Config file path (Configs in this file are over-written by command line options)
(default "%s")
-force
force retirement without prompting
-apibase string
API base (default "%s")
-apikey string
(DEPRECATED) API key from mackerel.io web site`,
config.DefaultConfig.Conffile,
config.DefaultConfig.Apibase)
fmt.Fprintln(os.Stderr, usage)
os.Exit(2)
}
func resolveConfigForRetire(fs *flag.FlagSet, argv []string) (*config.Config, bool, error) {
var force = fs.Bool("force", false, "force retirement without prompting")
fs.Usage = printRetireUsage
conf, err := resolveConfig(fs, argv)
return conf, *force, err
}
// resolveConfig parses command line arguments and loads config file to
// return config.Config information.
func resolveConfig(fs *flag.FlagSet, argv []string) (*config.Config, error) {
conf := &config.Config{}
var (
conffile = fs.String("conf", config.DefaultConfig.Conffile, "Config file path (Configs in this file are over-written by command line options)")
apibase = fs.String("apibase", config.DefaultConfig.Apibase, "API base")
pidfile = fs.String("pidfile", config.DefaultConfig.Pidfile, "File containing PID")
root = fs.String("root", config.DefaultConfig.Root, "Directory containing variable state information")
apikey = fs.String("apikey", "", "(DEPRECATED) API key from mackerel.io web site")
diagnostic = fs.Bool("diagnostic", false, "Enables diagnostic features")
autoShutdown = fs.Bool("private-autoshutdown", false, "(internal use) Shutdown automatically if agent is updated")
child = fs.Bool("child", false, "(internal use) child process of the supervise mode")
verbose bool
roleFullnames roleFullnamesFlag
)
fs.BoolVar(&verbose, "verbose", config.DefaultConfig.Verbose, "Toggle verbosity")
fs.BoolVar(&verbose, "v", config.DefaultConfig.Verbose, "Toggle verbosity (shorthand)")
// The value of "role" option is internally "roll fullname",
// but we call it "role" here for ease.
fs.Var(&roleFullnames, "role", "Set this host's roles (format: <service>:<role>)")
err := fs.Parse(argv)
if err != nil {
return nil, err
}
conf, confErr := config.LoadConfig(*conffile)
if confErr != nil {
return nil, fmt.Errorf("failed to load the config file: %s", confErr)
}
conf.Conffile = *conffile
// overwrite config from file by config from args
fs.Visit(func(f *flag.Flag) {
switch f.Name {
case "apibase":
conf.Apibase = *apibase
case "apikey":
conf.Apikey = *apikey
case "pidfile":
conf.Pidfile = *pidfile
case "root":
conf.Root = *root
case "diagnostic":
conf.Diagnostic = *diagnostic
case "private-autoshutdown":
conf.AutoShutdown = *autoShutdown
case "verbose", "v":
conf.Verbose = verbose
case "role":
conf.Roles = roleFullnames
}
})
if *child {
// Child process of supervisor never create pidfile, because supervisor process does create it.
conf.Pidfile = ""
}
r := []string{}
for _, roleFullName := range conf.Roles {
if !roleFullnamePattern.MatchString(roleFullName) {
logger.Errorf("Bad format for role fullname (expecting <service>:<role>. Alphabet, numbers, hyphens and underscores are acceptable, but the first character must not be a hyphen or an underscore.): '%s'", roleFullName)
} else {
r = append(r, roleFullName)
}
}
conf.Roles = r
if conf.Verbose && conf.Silent {
logger.Warningf("both of `verbose` and `silent` option are specified. In this case, `verbose` get preference over `silent`")
}
if conf.Apikey == "" {
return nil, fmt.Errorf("apikey must be specified in the config file (or by the DEPRECATED command-line flag)")
}
setProxy(conf)
return conf, nil
}
func setProxy(conf *config.Config) {
if canEnableProxy(conf.HTTPProxy) {
os.Setenv("HTTP_PROXY", conf.HTTPProxy)
}
if canEnableProxy(conf.HTTPSProxy) {
os.Setenv("HTTPS_PROXY", conf.HTTPSProxy)
}
// Fallback.
// Since Go 1.16, HTTP_PROXY and HTTPS_PROXY are now handled specifically separately.
// https://github.com/golang/go/issues/40909
//
// Originally, the mackerel-agent configuration was for http_proxy, which was
// also handled as https_proxy, so there could be cases where the plugin depends on
// the environment variables set here.
// So, to support the behavior in the old configuration file
if canEnableProxy(conf.HTTPProxy) && conf.HTTPSProxy == "" {
os.Setenv("HTTPS_PROXY", conf.HTTPProxy)
}
}
func canEnableProxy(address string) bool {
return address != "" && address != "direct"
}
func setLogLevel(silent, verbose bool) {
if silent {
logging.SetLogLevel(logging.ERROR)
}
if verbose {
logging.SetLogLevel(logging.DEBUG)
}
}
func start(conf *config.Config, termCh chan struct{}) error {
setLogLevel(conf.Silent, conf.Verbose)
logger.Infof("Starting mackerel-agent version:%s, rev:%s, apibase:%s", version, gitcommit, conf.Apibase)
if err := pidfile.Create(conf.Pidfile); err != nil {
return fmt.Errorf("pidfile.Create(%q) failed: %s", conf.Pidfile, err)
}
defer func() {
err := pidfile.Remove(conf.Pidfile)
if err != nil {
logger.Warningf("pidfile cant remove. : %s", err.Error())
}
}()
app, err := command.Prepare(conf, &command.AgentMeta{
Version: version,
Revision: gitcommit,
})
if err != nil {
return fmt.Errorf("command.Prepare failed: %s", err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
if conf.AutoShutdown {
prog, err := os.Executable()
if err != nil {
return fmt.Errorf("can't get executable file: %v", err)
}
go notifyUpdateFile(c, prog, 10*time.Second)
}
go signalHandler(c, app, termCh)
return command.Run(app, termCh)
}
var maxTerminatingInterval = 30 * time.Second
func signalHandler(c chan os.Signal, app *command.App, termCh chan struct{}) {
received := false
for sig := range c {
if sig == syscall.SIGHUP {
logger.Debugf("Received signal '%v'", sig)
// TODO reload configuration file
app.UpdateHostSpecs()
} else {
if !received {
received = true
logger.Infof(
"Received signal '%v', try graceful shutdown up to %f seconds. If you want force shutdown immediately, send a signal again.",
sig,
maxTerminatingInterval.Seconds())
} else {
logger.Infof("Received signal '%v' again, force shutdown.", sig)
}
termCh <- struct{}{}
go func() {
time.Sleep(maxTerminatingInterval)
logger.Infof("Timed out. force shutdown.")
termCh <- struct{}{}
}()
}
}
}
func notifyUpdateFile(c chan<- os.Signal, file string, interval time.Duration) {
var lastUpdated time.Time
stat, err := os.Stat(file)
if err != nil {
logger.Errorf("Can't stat %s: %v; last modified time is set to now", file, err)
lastUpdated = time.Now()
} else {
lastUpdated = stat.ModTime()
}
for {
time.Sleep(interval)
stat, err := os.Stat(file)
if err != nil {
if os.IsNotExist(err) {
break
}
logger.Errorf("Can't stat %s: %v", file, err)
continue
}
if stat.ModTime().After(lastUpdated) {
break
}
}
logger.Infof("Detected %s was updated; shutting down", file)
c <- os.Interrupt
}