-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
358 lines (305 loc) · 9.03 KB
/
main.go
File metadata and controls
358 lines (305 loc) · 9.03 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// main.go
package main
import (
"bufio"
"bytes"
"context"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"sort"
"strings"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type IPTablesCollector struct {
tables []string
ipv6 bool
timeout time.Duration
descRules *prometheus.Desc
descRulesAction *prometheus.Desc
descRulesTable *prometheus.Desc
descScrapeSuccess *prometheus.Desc
descScrapeDuration *prometheus.Desc
}
func NewIPTablesCollector(tables []string, ipv6 bool, timeout time.Duration) *IPTablesCollector {
return &IPTablesCollector{
tables: tables,
ipv6: ipv6,
timeout: timeout,
descRules: prometheus.NewDesc(
"iptables_rules",
"Number of iptables rules (current)",
[]string{"family", "table", "chain"},
nil,
),
descRulesAction: prometheus.NewDesc(
"iptables_rules_action",
"Number of iptables rules by action (current)",
[]string{"family", "table", "chain", "action"},
nil,
),
descRulesTable: prometheus.NewDesc(
"iptables_rules_table",
"Number of iptables rules in table (current)",
[]string{"family", "table"},
nil,
),
descScrapeSuccess: prometheus.NewDesc(
"iptables_scrape_success",
"Whether the last scrape for a family succeeded (1) or failed (0)",
[]string{"family"},
nil,
),
descScrapeDuration: prometheus.NewDesc(
"iptables_scrape_duration_seconds",
"Duration of last scrape for a family",
[]string{"family"},
nil,
),
}
}
func (c *IPTablesCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.descRules
ch <- c.descRulesAction
ch <- c.descRulesTable
ch <- c.descScrapeSuccess
ch <- c.descScrapeDuration
}
func (c *IPTablesCollector) Collect(ch chan<- prometheus.Metric) {
families := []struct {
family string
bin string
}{
{family: "ipv4", bin: "iptables-save"},
}
if c.ipv6 {
families = append(families, struct {
family string
bin string
}{family: "ipv6", bin: "ip6tables-save"})
}
for _, fam := range families {
start := time.Now()
success := 1.0
if err := c.collectFamily(ch, fam.family, fam.bin); err != nil {
success = 0
log.Printf("collect failed: family=%s bin=%s err=%v", fam.family, fam.bin, err)
}
ch <- prometheus.MustNewConstMetric(c.descScrapeSuccess, prometheus.GaugeValue, success, fam.family)
ch <- prometheus.MustNewConstMetric(c.descScrapeDuration, prometheus.GaugeValue, time.Since(start).Seconds(), fam.family)
}
}
func (c *IPTablesCollector) collectFamily(ch chan<- prometheus.Metric, family, bin string) error {
fullPath, err := exec.LookPath(bin)
if err != nil {
return fmt.Errorf("binary not found: %s: %w", bin, err)
}
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
rules, tableTotals, err := scrapeIPTables(ctx, fullPath, c.tables)
if err != nil {
return err
}
// tableChainRules: map[table][chain]count
tableChainRules := make(map[string]map[string]int)
// tableChainActionRules: map[table][chain][action]count
tableChainActionRules := make(map[string]map[string]map[string]int)
for k, count := range rules {
if tableChainRules[k.table] == nil {
tableChainRules[k.table] = make(map[string]int)
}
tableChainRules[k.table][k.chain] += count
if tableChainActionRules[k.table] == nil {
tableChainActionRules[k.table] = make(map[string]map[string]int)
}
if tableChainActionRules[k.table][k.chain] == nil {
tableChainActionRules[k.table][k.chain] = make(map[string]int)
}
tableChainActionRules[k.table][k.chain][k.action] += count
}
// emit metrics (stable order)
tables := make([]string, 0, len(tableTotals))
for t := range tableTotals {
tables = append(tables, t)
}
sort.Strings(tables)
for _, table := range tables {
ch <- prometheus.MustNewConstMetric(c.descRulesTable, prometheus.GaugeValue, float64(tableTotals[table]), family, table)
chains := make([]string, 0, len(tableChainRules[table]))
for cn := range tableChainRules[table] {
chains = append(chains, cn)
}
sort.Strings(chains)
for _, chain := range chains {
ch <- prometheus.MustNewConstMetric(c.descRules, prometheus.GaugeValue, float64(tableChainRules[table][chain]), family, table, chain)
actions := make([]string, 0, len(tableChainActionRules[table][chain]))
for a := range tableChainActionRules[table][chain] {
actions = append(actions, a)
}
sort.Strings(actions)
for _, action := range actions {
ch <- prometheus.MustNewConstMetric(c.descRulesAction, prometheus.GaugeValue, float64(tableChainActionRules[table][chain][action]), family, table, chain, action)
}
}
}
return nil
}
type ruleKey struct {
table string
chain string
action string
}
func scrapeIPTables(ctx context.Context, bin string, allowedTables []string) (map[ruleKey]int, map[string]int, error) {
cmd := exec.CommandContext(ctx, bin)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, fmt.Errorf("StdoutPipe: %w", err)
}
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return nil, nil, fmt.Errorf("start: %w", err)
}
rules := make(map[ruleKey]int)
tableTotals := make(map[string]int)
allowed := make(map[string]bool)
for _, t := range allowedTables {
allowed[t] = true
}
sc := bufio.NewScanner(stdout)
sc.Buffer(make([]byte, 1024), 1024*1024)
var currentTable string
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if strings.HasPrefix(line, "*") {
currentTable = line[1:]
if allowed[currentTable] && tableTotals[currentTable] == 0 {
tableTotals[currentTable] = 0 // Ensure table exists in totals
}
continue
}
if currentTable == "" || !allowed[currentTable] {
continue
}
if strings.HasPrefix(line, ":") {
// Chain definition: :CHAIN_NAME POLICY [PACKETS:BYTES]
parts := strings.Fields(line)
if len(parts) > 0 {
chain := parts[0][1:]
key := ruleKey{
table: currentTable,
chain: chain,
action: "CONTINUE", // Default for an empty chain
}
if _, exists := rules[key]; !exists {
rules[key] = 0
}
}
continue
}
if strings.HasPrefix(line, "-A ") {
fields := strings.Fields(line)
if len(fields) >= 2 {
chain := fields[1]
tableTotals[currentTable]++
// Extract action (-j or --jump)
action := "CONTINUE"
for i := 0; i < len(fields)-1; i++ {
if fields[i] == "-j" || fields[i] == "--jump" {
if i+1 < len(fields) {
action = fields[i+1]
}
break
}
}
key := ruleKey{
table: currentTable,
chain: chain,
action: action,
}
rules[key]++
}
}
}
if err := sc.Err(); err != nil {
_ = cmd.Wait()
return nil, nil, fmt.Errorf("scan: %w", err)
}
if err := cmd.Wait(); err != nil {
return nil, nil, fmt.Errorf("iptables error: %w: %s", err, strings.TrimSpace(stderr.String()))
}
return rules, tableTotals, nil
}
func splitCSV(s string) []string {
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
out = append(out, p)
}
}
return out
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func main() {
var (
listen = flag.String("listen", getEnv("LISTEN_ADDRESS", ":9105"), "listen address")
metricsPath = flag.String("metrics-path", getEnv("METRICS_PATH", "/metrics"), "metrics path")
enableIPv6 = flag.Bool("ipv6", getEnv("ENABLE_IPV6", "true") == "true", "collect ip6tables too")
tablesCSV = flag.String("tables", getEnv("TABLES", "filter,nat,mangle,raw,security"), "comma-separated tables")
timeout = flag.Duration("timeout", func() time.Duration {
d, err := time.ParseDuration(getEnv("TIMEOUT", "2s"))
if err != nil {
return 2 * time.Second
}
return d
}(), "timeout per iptables command")
)
flag.Parse()
collector := NewIPTablesCollector(splitCSV(*tablesCSV), *enableIPv6, *timeout)
reg := prometheus.NewRegistry()
reg.MustRegister(collector)
reg.MustRegister(prometheus.NewGoCollector())
reg.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
mux := http.NewServeMux()
mux.Handle(*metricsPath, promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok\n")) })
srv := &http.Server{
Addr: *listen,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGTERM)
go func() {
log.Printf("listening on %s, metrics on %s", *listen, *metricsPath)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %s\n", err)
}
}()
<-done
log.Print("stopping server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("server shutdown failed: %+v", err)
}
log.Print("server stopped")
}