Newer
Older
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
package mergedlocrib
import (
"crypto/sha1"
"sync"
"github.com/bio-routing/bio-rd/route"
routeapi "github.com/bio-routing/bio-rd/route/api"
"github.com/bio-routing/bio-rd/routingtable/locRIB"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
)
// MergedLocRIB provides an deduplicated routing table
type MergedLocRIB struct {
routes map[[20]byte]*routeContainer
routesMu sync.Mutex
locRIB *locRIB.LocRIB
}
// New creates a new MergedLocRIB and starts it
func New(locRIB *locRIB.LocRIB) *MergedLocRIB {
return &MergedLocRIB{
routes: make(map[[20]byte]*routeContainer),
locRIB: locRIB,
}
}
// DropAllBySrc drops all routes learned from a source
func (rtm *MergedLocRIB) DropAllBySrc(src interface{}) {
rtm.routesMu.Lock()
defer rtm.routesMu.Unlock()
for h, rc := range rtm.routes {
rtm._delRoute(h, src, rc.route)
}
}
// AddRoute adds a route
func (rtm *MergedLocRIB) AddRoute(cc interface{}, r *routeapi.Route) error {
h, err := hashRoute(r)
if err != nil {
return errors.Wrap(err, "Hashing failed")
}
rtm.routesMu.Lock()
defer rtm.routesMu.Unlock()
if _, exists := rtm.routes[h]; !exists {
s := route.RouteFromProtoRoute(r, true)
rtm.routes[h] = newRouteContainer(r, cc)
rtm.locRIB.AddPath(s.Prefix(), s.Paths()[0])
return nil
}
rtm.routes[h].addSource(cc)
return nil
}
// RemoveRoute deletes a route
func (rtm *MergedLocRIB) RemoveRoute(cc interface{}, r *routeapi.Route) error {
h, err := hashRoute(r)
if err != nil {
return errors.Wrap(err, "Hashing failed")
}
rtm.routesMu.Lock()
defer rtm.routesMu.Unlock()
if _, exists := rtm.routes[h]; !exists {
return nil
}
rtm._delRoute(h, cc, r)
return nil
}
func (rtm *MergedLocRIB) _delRoute(h [20]byte, src interface{}, r *routeapi.Route) {
rtm.routes[h].removeSource(src)
if rtm.routes[h].srcCount() > 0 {
return
}
s := route.RouteFromProtoRoute(r, true)
rtm.locRIB.RemovePath(s.Prefix(), s.Paths()[0])
delete(rtm.routes, h)
}
func hashRoute(route *routeapi.Route) ([20]byte, error) {
m, err := proto.Marshal(route)
if err != nil {
return [20]byte{}, errors.Wrap(err, "Proto marshal failed")
}
h := sha1.New()
_, err = h.Write(m)
if err != nil {
return [20]byte{}, errors.Wrap(err, "Write failed")
}
res := [20]byte{}
x := h.Sum(nil)
copy(res[:], x)
return res, nil
}