-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.go
More file actions
115 lines (101 loc) · 2.49 KB
/
Copy pathroute.go
File metadata and controls
115 lines (101 loc) · 2.49 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
//
// Copyright (c) 2025 Cedrik Pischem
// SPDX-License-Identifier: BSD-2-Clause
//
// route.go - Per-host route management with rate limiting
//
// Installs /128 host routes using the platform-specific route implementation
// so the kernel forwards traffic to learned clients. Rate-limited using
// golang.org/x/time/rate to prevent route table thrashing.
//
// Without per-host routes, the kernel doesn't know clients exist on
// downstream interfaces and won't forward their traffic.
//
package main
import (
"context"
"log"
"strings"
"time"
"golang.org/x/time/rate"
)
// routeOp describes a single route add or delete operation.
type routeOp struct {
add bool
ip string
iface string
}
// RouteWorker manages per-host route operations with rate limiting.
type RouteWorker struct {
ch chan routeOp
limiter *rate.Limiter
done chan struct{}
config *Config
}
// NewRouteWorker creates a rate-limited route worker.
func NewRouteWorker(qps int, config *Config) *RouteWorker {
if config.NoRoutes {
return nil
}
if err := initializeRoutePlatform(); err != nil {
log.Fatalf("route management unavailable: %v (use --no-routes to disable it)", err)
}
r := &RouteWorker{
ch: make(chan routeOp, 4096),
limiter: rate.NewLimiter(rate.Limit(qps), qps),
done: make(chan struct{}),
config: config,
}
// Worker goroutine
go func() {
for {
select {
case <-r.done:
return
case op := <-r.ch:
// Wait for rate limiter token
if err := r.limiter.Wait(context.Background()); err != nil {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
action := "delete"
if op.add {
action = "add"
}
out, err := executeRouteOperation(ctx, op)
cancel()
if err != nil {
r.config.DebugLog("route %s err: %v (out: %s)", action, err, strings.TrimSpace(string(out)))
} else {
if op.add {
r.config.DebugLog("route installed: %s via %s", op.ip, op.iface)
} else {
r.config.DebugLog("route deleted: %s", op.ip)
}
}
}
}
}()
return r
}
// Add enqueues a route add operation.
func (r *RouteWorker) Add(ip, iface string) {
if r == nil {
return
}
r.ch <- routeOp{add: true, ip: ip, iface: iface}
}
// Delete enqueues a route delete operation.
func (r *RouteWorker) Delete(ip, iface string) {
if r == nil {
return
}
r.ch <- routeOp{add: false, ip: ip, iface: iface}
}
// Stop shuts down the route worker.
func (r *RouteWorker) Stop() {
if r == nil {
return
}
close(r.done)
}