forked from megaease/easeprobe
/
main.go
278 lines (241 loc) · 7.74 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
/*
* Copyright (c) 2022, MegaEase
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package main is the entry point for the easeprobe command.
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"runtime/debug"
"strings"
"sync"
"syscall"
"time"
"github.com/wfusion/easeprobe/channel"
"github.com/wfusion/easeprobe/conf"
"github.com/wfusion/easeprobe/daemon"
"github.com/wfusion/easeprobe/global"
"github.com/wfusion/easeprobe/probe"
"github.com/wfusion/easeprobe/web"
log "github.com/sirupsen/logrus"
)
func getEnvOrDefault(key, defaultValue string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return defaultValue
}
func showVersion() {
var v = global.Ver
bi, ok := debug.ReadBuildInfo()
if !ok {
v = fmt.Sprintf("%v %v", global.DefaultProg, v)
fmt.Println(v)
return
}
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
v = fmt.Sprintf("%v %v", v, s.Value[:9])
case "vcs.time":
v = fmt.Sprintf("%v %v", v, s.Value)
}
}
v = fmt.Sprintf("%v %v %v", global.DefaultProg, v, bi.GoVersion)
fmt.Println(v)
}
func main() {
////////////////////////////////////////////////////////////////////////////
// Parse command line arguments and config file settings //
////////////////////////////////////////////////////////////////////////////
dryNotify := flag.Bool("d", os.Getenv("PROBE_DRY") == "true", "dry notification mode")
yamlFile := flag.String("f", getEnvOrDefault("PROBE_CONFIG", "config.yaml"), "configuration file")
jsonSchema := flag.Bool("j", false, "show JSON schema")
version := flag.Bool("v", false, "prints version")
flag.Parse()
if *version {
showVersion()
os.Exit(0)
}
if *jsonSchema {
schema, err := conf.JSONSchema()
if err != nil {
log.Fatalf("failed to show JSON schema: %v", err)
}
fmt.Println(schema)
os.Exit(0)
}
c, err := conf.New(yamlFile)
if err != nil {
log.Errorln("Fatal: Cannot read the YAML configuration file!")
os.Exit(-1)
}
// Create the pid file if the file name is not empty
c.Settings.PIDFile = strings.TrimSpace(c.Settings.PIDFile)
if len(c.Settings.PIDFile) > 0 && c.Settings.PIDFile != "-" {
d, err := daemon.NewPIDFile(c.Settings.PIDFile)
if err != nil {
log.Errorf("Fatal: Cannot create the PID file: %s!", err)
os.Exit(-1)
}
log.Infof("Successfully created the PID file: %s", d.PIDFile)
defer d.RemovePIDFile()
} else {
if len(c.Settings.PIDFile) == 0 {
log.Info("Skipping PID file creation (pid file is empty).")
} else {
log.Info("Skipping PID file creation (pid file is set to '-').")
}
}
c.InitAllLogs()
// if dry notification mode is specified in command line, overwrite the configuration
if *dryNotify {
c.Settings.Notify.Dry = *dryNotify
log.Infoln("Dry Notification Mode...")
}
// set the dry notify flag to channel
channel.SetDryNotify(c.Settings.Notify.Dry)
////////////////////////////////////////////////////////////////////////////
// Start the HTTP Server //
////////////////////////////////////////////////////////////////////////////
// if error happens, the EaseProbe will exit
web.Server()
////////////////////////////////////////////////////////////////////////////
// Configure all of Probers and Notifiers //
////////////////////////////////////////////////////////////////////////////
// Probers
probers := c.AllProbers()
// Notification
notifies := c.AllNotifiers()
// Configure the Probes
probers = configProbers(probers)
if len(probers) == 0 {
log.Fatal("No probes configured, exiting...")
}
// Configure the Notifiers
notifies = configNotifiers(notifies)
if len(notifies) == 0 {
log.Warning("No notifies configured, exiting...")
}
// configure channels
configChannels(probers, notifies)
////////////////////////////////////////////////////////////////////////////
// Start the EaseProbe //
////////////////////////////////////////////////////////////////////////////
// wait group for probers
var wg sync.WaitGroup
// the exit channel for all probers
doneProbe := make(chan bool, len(probers))
// the exit channel for saving the data
doneSave := make(chan bool)
// the channel for saving the probe result data
saveChannel := make(chan probe.Result, len(probers))
// 1) SLA Data Save process
probe.CleanData(probers) // remove the data not in probers
go saveData(doneSave, saveChannel) // save the data to file
// 2) Start the Probers
runProbers(probers, &wg, doneProbe, saveChannel)
// 3) Start the Event Watching
channel.WatchForAllEvents()
// 4) Set probers into web server
web.SetProbers(probers)
// 5) Set the Cron Job for SLA Report
if conf.Get().Settings.SLAReport.Schedule != conf.None {
scheduleSLA(probers)
} else {
log.Info("No SLA Report would be sent!!")
}
runMetric(doneSave)
////////////////////////////////////////////////////////////////////////////
// Rotate the log file //
////////////////////////////////////////////////////////////////////////////
rotateLog := make(chan os.Signal, 1)
doneRotate := make(chan bool, 1)
signal.Notify(rotateLog, syscall.SIGHUP)
go func() {
for {
c := conf.Get()
select {
case <-doneRotate:
log.Info("Received the exit signal, Rotating log file process exiting...")
c.Settings.Log.Close()
c.Settings.HTTPServer.AccessLog.Close()
return
case <-rotateLog:
log.Info("Received SIGHUP, rotating the log file...")
c.Settings.Log.Rotate()
c.Settings.HTTPServer.AccessLog.Rotate()
}
}
}()
////////////////////////////////////////////////////////////////////////////
// Graceful Shutdown / Re-Run //
////////////////////////////////////////////////////////////////////////////
done := make(chan os.Signal, 1)
signal.Notify(done, syscall.SIGTERM)
// the graceful shutdown process
exit := func() {
web.Shutdown()
for i := 0; i < len(probers); i++ {
if probers[i].Result().Status != probe.StatusBad {
doneProbe <- true
}
}
wg.Wait()
channel.AllDone()
doneSave <- true
doneRotate <- true
}
// the graceful restart process
reRun := func() {
exit()
p, e := os.StartProcess(os.Args[0], os.Args, &os.ProcAttr{
Env: os.Environ(),
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
})
if e != nil {
log.Errorf("!!! FAILED TO RESTART THE EASEPROBE: %v !!!", e)
return
}
log.Infof("!!! RESTART THE EASEPROBE SUCCESSFULLY - PID=[%d] !!!", p.Pid)
}
// Monitor the configuration file
monConf := make(chan bool, 1)
go monitorYAMLFile(*yamlFile, monConf)
// wait for the exit and restart signal
select {
case <-done:
log.Info("!!! RECEIVED THE SIGTERM EXIT SIGNAL, EXITING... !!!")
exit()
case <-monConf:
log.Info("!!! RECEIVED THE RESTART EVENT, RESTARTING... !!!")
reRun()
}
log.Info("Graceful Exit Successfully!")
}
func monitorYAMLFile(path string, monConf chan bool) {
for {
if conf.IsConfigModified(path) {
log.Infof("The configuration file [%s] has been modified, restarting...", path)
monConf <- true
break
}
log.Debugf("The configuration file [%s] has not been modified", path)
time.Sleep(global.DefaultConfigFileCheckInterval)
}
}