/
main.go
271 lines (247 loc) · 6.54 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
package main
import (
"cmstop-fsmon/util"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/9466/daemon"
"github.com/9466/goconfig"
"github.com/go-fsnotify/fsnotify"
)
const (
VERSION = "1.0 beta" // 版本
CONFIG_FILE = "/conf/cmstop.conf" // 配置文件
DEF_WPS = 100 // 默认阀值,每秒写入文件大于这个值,就报警
DEF_DELAY = 3 // 延迟发送,等待延时,如果在n秒内没有新的变化,认为该次处理完成,发送报告
)
type mailConf struct {
host string
user string
pass string
from string
to string
title string
serverInfo string
}
type MonitorItem struct {
event string
name string
time time.Time
}
type monitor struct {
mail *mailConf // 邮件配置信息
dirs []string // 监控的目录
wps int // 预警阀值
wpsWarn bool // 阀值预警报告,是否发送,超过阀值即触发
debug bool // 是否调试模式
items []MonitorItem // 被修车或创建的文件列表
logger *log.Logger // 日志处理句柄
markTime time.Time // 标记开始时间
lastTime time.Time // 最后写入时间
}
// 全局实例化
var mon *monitor
func main() {
// Config
config := parseConfig()
isDaemon, err := config.GetBool("log", "daemon")
logfile, err := config.GetString("log", "logfile")
// Daemon
if isDaemon {
_, err := daemon.Daemon(1, 0)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// Log
var logFileHandle *os.File
if isDaemon {
if logfile != "" {
logFileHandle, err = os.OpenFile(logfile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
} else {
logFileHandle, err = os.OpenFile("/dev/null", 0, 0)
}
} else {
logFileHandle = os.Stderr
}
defer logFileHandle.Close()
if err != nil {
log.Fatalln(err.Error())
}
mon.logger = log.New(logFileHandle, "", log.Ldate|log.Ltime)
// Watch
initWatcher()
}
func parseConfig() *goconfig.ConfigFile {
baseDir, err := util.GetDir()
if err != nil {
log.Fatalln("basedir get error: " + err.Error())
}
configFile := baseDir + CONFIG_FILE
conf, err := goconfig.ReadConfigFile(configFile)
if err != nil {
log.Fatalln("ReadConfigFile Err: ", err.Error(), "\nConfigFile:", configFile)
}
mon = new(monitor)
mon.items = make([]MonitorItem, 0)
mondir, err := conf.GetString("common", "monDir")
mon.dirs = strings.Split(mondir, ",")
mon.wps, _ = conf.GetInt("common", "wps")
if mon.wps == 0 {
mon.wps = DEF_WPS
}
mon.debug, _ = conf.GetBool("log", "debug")
mon.mail = &mailConf{}
mon.mail.host, _ = conf.GetString("mail", "mailHost")
mon.mail.user, _ = conf.GetString("mail", "mailUser")
mon.mail.pass, _ = conf.GetString("mail", "mailPass")
mon.mail.from, _ = conf.GetString("mail", "mailFrom")
mon.mail.to, _ = conf.GetString("mail", "mailTo")
mon.mail.title, _ = conf.GetString("mail", "mailTitle")
mon.mail.serverInfo, _ = conf.GetString("mail", "serverInfo")
return conf
}
func initWatcher() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
mon.logger.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Write == fsnotify.Write {
mon.logger.Println("modified file:", event.Name)
handleWatcher("MODIFY", event.Name)
} else if event.Op&fsnotify.Create == fsnotify.Create {
mon.logger.Println("created file:", event.Name)
handleWatcher("CREATE", event.Name)
}
case err := <-watcher.Errors:
mon.logger.Println("error:", err)
}
}
}()
go func() {
for {
select {
case <-time.After(DEF_DELAY * time.Second):
resetWatcher()
}
}
}()
for _, dir := range mon.dirs {
dir = strings.TrimSpace(dir)
if dir == "" {
continue
}
l := make([]string, 0)
l = append(l, dir)
l, err = util.RecursiveDir(dir, l)
if err != nil {
mon.logger.Fatal(err)
}
for _, d := range l {
mon.logger.Println("watcher dir: ", d)
err = watcher.Add(d)
if err != nil {
mon.logger.Fatal(err)
}
}
}
<-done
}
func handleWatcher(event, name string) {
item := MonitorItem{
event: event,
name: name,
time: time.Now(),
}
mon.items = append(mon.items, item)
mon.lastTime = item.time
if mon.markTime.IsZero() {
mon.markTime = item.time
if mon.debug {
mon.logger.Println("set markTime")
}
} else {
if mon.wpsWarn {
return
}
//mon.logger.Println("check wpsWarn")
if mon.markTime.Unix()-mon.lastTime.Unix() == 0 && len(mon.items) >= mon.wps {
body := "<p>发生时间:" + mon.markTime.Format("2006-01-02 15:04:05") + "<br/>" +
"异常信息:在1秒内超过" + strconv.Itoa(mon.wps) + "次文件创建或修改<br/>" +
"服务信息:" + mon.mail.serverInfo + "</p>"
err := mail(body)
if err != nil {
mon.logger.Println(err)
} else {
mon.logger.Println("mail notifaction send.")
mon.wpsWarn = true
}
}
}
}
func resetWatcher() {
if mon.debug {
mon.logger.Println("reset called.")
mon.logger.Println("items", len(mon.items), "wpsWarn", mon.wpsWarn,
"markTime", mon.markTime.IsZero(), "lastTime", mon.lastTime.IsZero())
}
if len(mon.items) == 0 {
return
}
if mon.lastTime.Unix()+DEF_DELAY > time.Now().Unix() {
return
}
if mon.wpsWarn == false {
if len(mon.items) > 0 {
mon.items = make([]MonitorItem, 0)
mon.markTime = time.Time{}
mon.lastTime = time.Time{}
}
return
}
body := "<p>发生时间:" + mon.markTime.Format("2006-01-02 15:04:05") + "<br/>" +
"结束时间:" + mon.lastTime.Format("2006-01-02 15:04:05") + "<br/>" +
"异常信息:在过去" + strconv.Itoa(int(mon.lastTime.Unix()-mon.markTime.Unix())) + "秒内共产生" + strconv.Itoa(len(mon.items)) + "次文件创建或修改<br/>" +
"服务信息:" + mon.mail.serverInfo + "</p>"
lis := ""
for i, item := range mon.items {
lis += "<li style=\"list-style:none\">" + strconv.Itoa(i+1) + ". " + item.time.Format("2006-01-02 15:04:05") + " " + item.event + " " + item.name + "</li>"
}
body += "<ul><h3>文件列表</h3>" + lis + "</ul>"
err := mail(body)
if err != nil {
mon.logger.Println(err)
} else {
mon.logger.Println("mail full report send.")
}
mon.wpsWarn = false
mon.items = make([]MonitorItem, 0)
mon.markTime = time.Time{}
mon.lastTime = time.Time{}
}
func mail(body string) error {
mon.logger.Println("send mail begin.")
conf := &util.MailT{
mon.mail.host,
mon.mail.user,
mon.mail.pass,
mon.mail.from,
mon.mail.to,
mon.mail.title,
body,
"html",
}
err := util.SendMail(conf)
mon.logger.Println("send mail end.")
return err
}