-
Notifications
You must be signed in to change notification settings - Fork 1
/
full-routaas.go
executable file
·350 lines (303 loc) · 13.3 KB
/
full-routaas.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
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
package main
import (
"context"
"fmt"
api "github.com/osrg/gobgp/api"
"github.com/BurntSushi/toml"
"github.com/osrg/gobgp/config"
"github.com/osrg/gobgp/packet/bgp"
"github.com/osrg/gobgp/packet/mrt"
gobgp "github.com/osrg/gobgp/server"
"github.com/osrg/gobgp/table"
log "github.com/sirupsen/logrus"
grpc "google.golang.org/grpc"
"io/ioutil"
"os"
"strings"
"io"
"net"
"time"
)
var version string
type tmlConfig struct {
BgpdConfig bgpdConfig
}
type bgpdConfig struct {
As uint32 `toml:"as"`
RouterID string `toml:"router-id"`
NeighborConfig []neighborConfig `toml:"neighbor-config"`
MrtConfig mrtConfig `toml:"mrt-config"`
}
type neighborConfig struct {
PeerAs uint32 `toml:"peer-as"`
NeighborAddress string `toml:"neighbor-address"`
PeerType string `toml:"peer-type"`
}
type mrtConfig struct {
Best bool `toml:"best-path"`
SkipV4 bool `toml:"skip-v4"`
SkipV6 bool `toml:"skip-v6"`
NextHop string `toml:"next-hop"`
}
type mrtOpts struct {
OutputDir string
FileFormat string
Filename string
RecordCount int64
RecordSkip int64
QueueSize int
Best bool
SkipV4 bool
SkipV6 bool
NextHop net.IP
}
func (m *mrtConfig) newmrtOpts() mrtOpts {
var nexthop net.IP
if m.NextHop == "nil" {
nexthop = nil
} else {
nexthop = net.ParseIP(m.NextHop)
}
return mrtOpts{
OutputDir: "./",
FileFormat: "",
Filename: "",
Best: m.Best,
QueueSize: 100000,
SkipV4: m.SkipV4,
SkipV6: m.SkipV6,
NextHop: nexthop,
}
}
func main() {
s := gobgp.NewBgpServer()
go s.Serve()
// start grpc api server. this is not mandatory
// but you will be able to use `gobgp` cmd with this.
g := api.NewGrpcServer(s, ":50051")
go g.Serve()
var tmlconfig tmlConfig
_, err := toml.DecodeFile("./config.tml", &tmlconfig)
if err != nil {
log.Fatal(err)
}
global := &config.Global{
Config: config.GlobalConfig{
As: tmlconfig.BgpdConfig.As,
RouterId: tmlconfig.BgpdConfig.RouterID,
},
}
if err := s.Start(global); err != nil {
log.Fatal(err)
}
for _, v := range tmlconfig.BgpdConfig.NeighborConfig {
peertype := config.PEER_TYPE_INTERNAL
if v.PeerType == "internal" {
peertype = config.PEER_TYPE_INTERNAL
} else if v.PeerType == "external" {
peertype = config.PEER_TYPE_EXTERNAL
}
neighbor := &config.Neighbor{
Config: config.NeighborConfig{
PeerAs: v.PeerAs,
NeighborAddress: v.NeighborAddress,
PeerType: peertype,
},
EbgpMultihop: config.EbgpMultihop{
Config: config.EbgpMultihopConfig{
Enabled: true,
MultihopTtl: 255,
},
},
AfiSafis: []config.AfiSafi{
config.AfiSafi{
Config: config.AfiSafiConfig{
AfiSafiName: "ipv4-unicast",
},
},
},
}
if err := s.AddNeighbor(neighbor); err != nil {
log.Error(err)
}
}
timeout := grpc.WithTimeout(time.Second)
conn, rpcErr := grpc.Dial("localhost:50051", timeout, grpc.WithBlock(), grpc.WithInsecure())
if rpcErr != nil {
log.Fatal("GoBGP is probably not running on the local server ... Please start gobgpd process !\n")
log.Fatal(rpcErr)
return
}
bgpclient := api.NewGobgpApiClient(conn)
m := tmlconfig.BgpdConfig.MrtConfig.newmrtOpts()
var mErr error
m.Filename, mErr = findMrt()
if mErr != nil {
log.Fatal(mErr)
}
log.Info("MRT injection file is ", m.Filename)
go func() {
err := injectMrt(bgpclient, m)
if err != nil {
log.Fatal(fmt.Errorf("failed to add path: %s", err))
return
}
defer log.Info("MRT injection complete!!")
}()
log.Info("Running full-routaas version " + version + " !!")
select {}
}
func findMrt() (mrtFile string, err error) {
files, e := ioutil.ReadDir("./")
if e != nil {
err = e
}
for _, file := range files {
if strings.Contains(file.Name(), "rib") {
mrtFile = "./" + file.Name()
return
}
}
fmt.Errorf("failed to read mib file.", err)
return
}
func injectMrt(bgpclient api.GobgpApiClient, m mrtOpts) error {
file, err := os.Open(m.Filename)
if err != nil {
return fmt.Errorf("failed to open file: %s", err)
}
if m.NextHop != nil && !m.SkipV4 && !m.SkipV6 {
fmt.Println("You should probably specify either --no-ipv4 or --no-ipv6 when overwriting nexthop, unless your dump contains only one type of routes")
}
var idx int64
if m.QueueSize < 1 {
return fmt.Errorf("Specified queue size is smaller than 1, refusing to run with unbounded memory usage")
}
ch := make(chan []*table.Path, m.QueueSize)
go func() {
var peers []*mrt.Peer
for {
buf := make([]byte, mrt.MRT_COMMON_HEADER_LEN)
_, err := file.Read(buf)
if err == io.EOF {
break
} else if err != nil {
log.Fatal(fmt.Errorf("failed to read: %s", err))
}
h := &mrt.MRTHeader{}
err = h.DecodeFromBytes(buf)
if err != nil {
log.Fatal(fmt.Errorf("failed to parse"))
}
buf = make([]byte, h.Len)
_, err = file.Read(buf)
if err != nil {
log.Fatal(fmt.Errorf("failed to read"))
}
msg, err := mrt.ParseMRTBody(h, buf)
if err != nil {
log.Fatal(fmt.Errorf("failed to parse: %s", err))
continue
}
//fmt.Println(msg)
if msg.Header.Type == mrt.TABLE_DUMPv2 {
subType := mrt.MRTSubTypeTableDumpv2(msg.Header.SubType)
switch subType {
case mrt.PEER_INDEX_TABLE:
peers = msg.Body.(*mrt.PeerIndexTable).Peers
continue
case mrt.RIB_IPV4_UNICAST, mrt.RIB_IPV4_UNICAST_ADDPATH:
if m.SkipV4 {
continue
}
case mrt.RIB_IPV6_UNICAST, mrt.RIB_IPV6_UNICAST_ADDPATH:
if m.SkipV6 {
continue
}
case mrt.GEO_PEER_TABLE:
fmt.Printf("WARNING: Skipping GEO_PEER_TABLE: %s", msg.Body.(*mrt.GeoPeerTable))
default:
log.Fatal(fmt.Errorf("unsupported subType: %v", subType))
}
if peers == nil {
log.Fatal(fmt.Errorf("not found PEER_INDEX_TABLE"))
}
rib := msg.Body.(*mrt.Rib)
nlri := rib.Prefix
paths := make([]*table.Path, 0, len(rib.Entries))
for _, e := range rib.Entries {
if len(peers) < int(e.PeerIndex) {
log.Fatal(fmt.Errorf("invalid peer index: %d (PEER_INDEX_TABLE has only %d peers)\n", e.PeerIndex, len(peers)))
}
source := &table.PeerInfo{
AS: peers[e.PeerIndex].AS,
ID: peers[e.PeerIndex].BgpId,
}
t := time.Unix(int64(e.OriginatedTime), 0)
switch subType {
case mrt.RIB_IPV4_UNICAST, mrt.RIB_IPV4_UNICAST_ADDPATH:
paths = append(paths, table.NewPath(source, nlri, false, e.PathAttributes, t, false))
default:
attrs := make([]bgp.PathAttributeInterface, 0, len(e.PathAttributes))
for _, attr := range e.PathAttributes {
if attr.GetType() != bgp.BGP_ATTR_TYPE_MP_REACH_NLRI {
attrs = append(attrs, attr)
} else {
a := attr.(*bgp.PathAttributeMpReachNLRI)
attrs = append(attrs, bgp.NewPathAttributeMpReachNLRI(a.Nexthop.String(), []bgp.AddrPrefixInterface{nlri}))
}
}
paths = append(paths, table.NewPath(source, nlri, false, attrs, t, false))
}
}
if m.NextHop != nil {
for _, p := range paths {
p.SetNexthop(m.NextHop)
}
}
if m.Best {
dst := table.NewDestination(nlri, 0)
for _, p := range paths {
dst.AddNewPath(p)
}
best, _, _ := dst.Calculate().GetChanges(table.GLOBAL_RIB_NAME, false)
if best == nil {
log.Fatal(fmt.Errorf("Can't find the best %v", nlri))
}
paths = []*table.Path{best}
}
if idx >= m.RecordSkip {
ch <- paths
}
idx += 1
if idx == m.RecordCount+m.RecordSkip {
break
}
}
}
close(ch)
}()
bgpmrtclient, err := bgpclient.InjectMrt(context.Background())
if err != nil {
return fmt.Errorf("failed to add path: %s", err)
}
for paths := range ch {
var tables []*api.Path
for _, p := range paths {
tables = append(tables, api.ToPathApi(p))
}
req := &api.InjectMrtRequest{
Resource: api.Resource_GLOBAL,
VrfId: "",
Paths: tables,
}
err = bgpmrtclient.Send(req)
if err != nil {
return fmt.Errorf("failed to send: %s", err)
}
}
if _, err := bgpmrtclient.CloseAndRecv(); err != nil {
return fmt.Errorf("failed to send: %s", err)
}
return nil
}