-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
consolidating_router.go
59 lines (53 loc) · 1.51 KB
/
consolidating_router.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
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package router
import (
"go4.org/netipx"
"tailscale.com/types/logger"
)
// ConsolidatingRoutes wraps a Router with logic that consolidates Routes
// whenever Set is called. It attempts to consolidate cfg.Routes into the
// smallest possible set.
func ConsolidatingRoutes(logf logger.Logf, router Router) Router {
return &consolidatingRouter{Router: router, logf: logger.WithPrefix(logf, "router: ")}
}
type consolidatingRouter struct {
Router
logf logger.Logf
}
// Set implements Router and attempts to consolidate cfg.Routes into the
// smallest possible set.
func (cr *consolidatingRouter) Set(cfg *Config) error {
return cr.Router.Set(cr.consolidateRoutes(cfg))
}
func (cr *consolidatingRouter) consolidateRoutes(cfg *Config) *Config {
if cfg == nil {
return nil
}
if len(cfg.Routes) < 2 {
return cfg
}
if len(cfg.Routes) == 2 && cfg.Routes[0].Addr().Is4() != cfg.Routes[1].Addr().Is4() {
return cfg
}
var builder netipx.IPSetBuilder
for _, route := range cfg.Routes {
builder.AddPrefix(route)
}
set, err := builder.IPSet()
if err != nil {
cr.logf("consolidateRoutes failed, keeping existing routes: %s", err)
return cfg
}
newRoutes := set.Prefixes()
oldLength := len(cfg.Routes)
newLength := len(newRoutes)
if oldLength == newLength {
// Nothing consolidated, return as-is.
return cfg
}
cr.logf("consolidated %d routes down to %d", oldLength, newLength)
newCfg := *cfg
newCfg.Routes = newRoutes
return &newCfg
}