仰望星辰工作室

miaopanel

miaopanel/ internal/waf/collect.go 8.4 KB · 370 行 原始文件
1package waf
2
3import (
4 "bufio"
5 "context"
6 "io"
7 "log/slog"
8 "os"
9 "path/filepath"
10 "regexp"
11 "strconv"
12 "strings"
13 "sync"
14 "time"
15
16 "github.com/miaopanel/miaopanel/internal/config"
17 "github.com/miaopanel/miaopanel/internal/store"
18)
19
20// Collector tails every site access log, aggregates counters and records
21// blocked requests. It never blocks on I/O for more than a few milliseconds
22// per file per cycle.
23type Collector struct {
24 db *store.Store
25 cfg *config.Config
26 log *slog.Logger
27
28 mu sync.Mutex
29 live map[int64]*liveAgg
30 offsets map[string]int64
31 maxRead int64
32 lastCollect int64
33}
34
35// Debug exposes collector internals for operators and smoke tests.
36func (c *Collector) Debug() map[string]any {
37 c.mu.Lock()
38 defer c.mu.Unlock()
39 newest := int64(0)
40 for slot := range c.live {
41 if slot > newest {
42 newest = slot
43 }
44 }
45 return map[string]any{
46 "buckets": len(c.live),
47 "newest_slot": newest,
48 "now": time.Now().Unix(),
49 "last_collect": c.lastCollect,
50 "files": len(c.offsets),
51 }
52}
53
54type liveAgg struct {
55 requests int64
56 blocked int64
57 bytes int64
58 rtSum float64
59 rtCount int64
60}
61
62type minuteAgg struct {
63 requests int64
64 blocked int64
65 throttled int64
66 bytes int64
67 rtSum float64
68 rtCount int64
69}
70
71// NewCollector builds a collector.
72func NewCollector(db *store.Store, cfg *config.Config, log *slog.Logger) *Collector {
73 return &Collector{
74 db: db, cfg: cfg, log: log,
75 live: map[int64]*liveAgg{},
76 offsets: map[string]int64{},
77 maxRead: 8 << 20, // at most 8 MiB per file per cycle
78 }
79}
80
81// Run polls logs until the context is cancelled.
82func (c *Collector) Run(ctx context.Context) {
83 ticker := time.NewTicker(5 * time.Second)
84 defer ticker.Stop()
85 c.collect(ctx)
86 for {
87 select {
88 case <-ctx.Done():
89 return
90 case <-ticker.C:
91 c.collect(ctx)
92 }
93 }
94}
95
96var accessLine = regexp.MustCompile(`^(\S+) \S+ \S+ \[([^\]]+)\] "([^"]*)" (\d{3}) (\d+) "([^"]*)" "([^"]*)" "?([\d.]+)"?`)
97
98const logTimeLayout = "02/Jan/2006:15:04:05 -0700"
99
100func (c *Collector) collect(ctx context.Context) {
101 sites, err := c.db.ListSites(ctx)
102 if err != nil {
103 c.log.Warn("waf collector: list sites", "error", err)
104 return
105 }
106 minuteBuckets := map[string]*minuteAgg{} // key: slug|bucket
107 for _, st := range sites {
108 path := filepath.Join(c.cfg.SiteLogDir(st.Slug), "access.log")
109 c.tailFile(ctx, st.Slug, path, minuteBuckets)
110 }
111 for key, agg := range minuteBuckets {
112 slug, bucketStr, ok := strings.Cut(key, "|")
113 if !ok {
114 continue
115 }
116 bucket, _ := strconv.ParseInt(bucketStr, 10, 64)
117 if err := c.db.WAFMetricAdd(ctx, bucket, slug, agg.requests, agg.blocked, agg.throttled,
118 agg.bytes, agg.rtSum, agg.rtCount); err != nil {
119 c.log.Warn("waf collector: flush metrics", "error", err)
120 break
121 }
122 }
123 c.trimLive(time.Now())
124 c.mu.Lock()
125 c.lastCollect = time.Now().Unix()
126 c.mu.Unlock()
127}
128
129func (c *Collector) tailFile(ctx context.Context, slug, path string, buckets map[string]*minuteAgg) {
130 fi, err := os.Stat(path)
131 if err != nil {
132 return
133 }
134 size := fi.Size()
135
136 c.mu.Lock()
137 offset, seen := c.offsets[path]
138 c.mu.Unlock()
139 if !seen {
140 stored, err := c.db.WAFOffset(ctx, path)
141 if err == nil && stored > 0 {
142 offset = stored
143 } else {
144 // Seed from the last 2 MiB so the dashboard is not empty after a
145 // fresh install on a busy server.
146 offset = size - 2<<20
147 }
148 if offset < 0 {
149 offset = 0
150 }
151 }
152 if size < offset {
153 offset = 0 // log rotated
154 }
155 if size == offset {
156 c.saveOffset(ctx, path, offset)
157 return
158 }
159
160 f, err := os.Open(path)
161 if err != nil {
162 return
163 }
164 defer f.Close()
165 if _, err := f.Seek(offset, io.SeekStart); err != nil {
166 return
167 }
168 reader := bufio.NewReaderSize(f, 64*1024)
169 read := int64(0)
170 events := 0
171 for read < c.maxRead {
172 line, err := reader.ReadString('\n')
173 read += int64(len(line))
174 if line != "" {
175 c.handleLine(ctx, slug, strings.TrimRight(line, "\r\n"), buckets, &events)
176 }
177 if err != nil {
178 break
179 }
180 }
181 c.saveOffset(ctx, path, offset+read)
182}
183
184func (c *Collector) handleLine(ctx context.Context, slug, line string, buckets map[string]*minuteAgg, events *int) {
185 m := accessLine.FindStringSubmatch(line)
186 if m == nil {
187 return
188 }
189 ip, timeStr, request, statusStr, bytesStr, _, ua, rtStr :=
190 m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]
191 ts, err := time.Parse(logTimeLayout, timeStr)
192 if err != nil {
193 ts = time.Now()
194 }
195 status, _ := strconv.Atoi(statusStr)
196 bytesN, _ := strconv.ParseInt(bytesStr, 10, 64)
197 rt, _ := strconv.ParseFloat(rtStr, 64)
198
199 bucket := ts.Truncate(time.Minute).Unix()
200 key := slug + "|" + strconv.FormatInt(bucket, 10)
201 agg := buckets[key]
202 if agg == nil {
203 agg = &minuteAgg{}
204 buckets[key] = agg
205 }
206 agg.requests++
207 agg.bytes += bytesN
208 agg.rtSum += rt
209 agg.rtCount++
210
211 // 429 is throttling (often legitimate bursts), not malicious traffic.
212 blocked := status == 444 || status == 403
213 throttled := status == 429
214 if blocked {
215 agg.blocked++
216 }
217 if throttled {
218 agg.throttled++
219 }
220 method, uri := splitRequest(request)
221 if blocked || throttled {
222 withBlock := int64(0)
223 if blocked {
224 withBlock = 1
225 }
226 c.addLive(ts, 1, withBlock, bytesN, rt)
227 if *events < 20 {
228 *events++
229 ev := &store.WAFEvent{
230 TS: ts.Unix(), Site: slug, IP: ip, Method: method, URI: uri,
231 UA: truncate(ua, 300), Status: status, Rule: ruleForStatus(status),
232 }
233 if err := c.db.WAFEventAdd(ctx, ev); err != nil {
234 c.log.Debug("waf collector: event", "error", err)
235 }
236 }
237 return
238 }
239 c.addLive(ts, 1, 0, bytesN, rt)
240}
241
242func ruleForStatus(status int) string {
243 switch status {
244 case 429:
245 return "rate-limit"
246 case 403:
247 return "waf-block"
248 default:
249 return "scanner"
250 }
251}
252
253func splitRequest(req string) (method, uri string) {
254 parts := strings.SplitN(req, " ", 3)
255 if len(parts) >= 2 {
256 return parts[0], truncate(parts[1], 500)
257 }
258 return "", truncate(req, 500)
259}
260
261func (c *Collector) addLive(ts time.Time, requests, blocked, bytesN int64, rt float64) {
262 slot := ts.Unix() / 10 * 10
263 c.mu.Lock()
264 defer c.mu.Unlock()
265 agg := c.live[slot]
266 if agg == nil {
267 agg = &liveAgg{}
268 c.live[slot] = agg
269 }
270 agg.requests += requests
271 agg.blocked += blocked
272 agg.bytes += bytesN
273 agg.rtSum += rt
274 agg.rtCount++
275}
276
277func (c *Collector) trimLive(now time.Time) {
278 cutoff := now.Unix() - 600
279 c.mu.Lock()
280 defer c.mu.Unlock()
281 for slot := range c.live {
282 if slot < cutoff {
283 delete(c.live, slot)
284 }
285 }
286}
287
288func (c *Collector) saveOffset(ctx context.Context, path string, offset int64) {
289 c.mu.Lock()
290 c.offsets[path] = offset
291 c.mu.Unlock()
292 if err := c.db.SetWAFOffset(ctx, path, offset); err != nil {
293 c.log.Debug("waf collector: offset", "error", err)
294 }
295}
296
297// Live returns current qps, bytes per second and average response time (ms).
298func (c *Collector) Live() (qps, traffic, rt float64) {
299 now := time.Now().Unix()
300 windowStart := now - 10
301 rtStart := now - 60
302 c.mu.Lock()
303 defer c.mu.Unlock()
304 var req, bytesN int64
305 var rtSum float64
306 var rtCount int64
307 for slot, agg := range c.live {
308 if slot >= windowStart {
309 req += agg.requests
310 bytesN += agg.bytes
311 }
312 if slot >= rtStart {
313 rtSum += agg.rtSum
314 rtCount += agg.rtCount
315 }
316 }
317 qps = float64(req) / 10
318 traffic = float64(bytesN) / 10
319 if rtCount > 0 {
320 rt = rtSum / float64(rtCount) * 1000
321 }
322 return
323}
324
325// LiveSeries returns 10 second buckets for the last points*10 seconds.
326func (c *Collector) LiveSeries(points int) map[string][]store.WAFPoint {
327 if points <= 0 || points > 120 {
328 points = 36
329 }
330 now := time.Now().Unix() / 10 * 10
331 out := map[string][]store.WAFPoint{"requests": {}, "blocked": {}, "traffic": {}, "rt": {}}
332 c.mu.Lock()
333 defer c.mu.Unlock()
334 for i := points - 1; i >= 0; i-- {
335 slot := now - int64(i*10)
336 agg := c.live[slot]
337 var qps, traffic, rt float64
338 var blocked float64
339 if agg != nil {
340 qps = float64(agg.requests) / 10
341 traffic = float64(agg.bytes) / 10
342 blocked = float64(agg.blocked)
343 if agg.rtCount > 0 {
344 rt = agg.rtSum / float64(agg.rtCount) * 1000
345 }
346 }
347 out["requests"] = append(out["requests"], store.WAFPoint{TS: slot, Value: qps})
348 out["blocked"] = append(out["blocked"], store.WAFPoint{TS: slot, Value: blocked})
349 out["traffic"] = append(out["traffic"], store.WAFPoint{TS: slot, Value: traffic})
350 out["rt"] = append(out["rt"], store.WAFPoint{TS: slot, Value: rt})
351 }
352 return out
353}
354
355// Prune removes data older than the retention window.
356func (c *Collector) Prune(ctx context.Context, days int) error {
357 if days <= 0 {
358 days = 7
359 }
360 cutoff := time.Now().AddDate(0, 0, -days).Unix()
361 _, err := c.db.PruneWAF(ctx, cutoff)
362 return err
363}
364
365func truncate(s string, n int) string {
366 if len(s) <= n {
367 return s
368 }
369 return s[:n]
370}