summaryrefslogtreecommitdiffhomepage
path: root/table/path.go
blob: 390d5f1dccefc1c2b3ef0ce4eb219140f1bd8f8f (plain)
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
// Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package table

import (
	"encoding/json"
	"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/osrg/gobgp/api"
	"github.com/osrg/gobgp/config"
	"github.com/osrg/gobgp/packet"
	"net"
	"reflect"
	"time"
	"math"
)

type Path interface {
	String() string
	getPathAttrs() []bgp.PathAttributeInterface
	getPathAttr(bgp.BGPAttrType) (int, bgp.PathAttributeInterface)
	updatePathAttrs(global *config.Global, peer *config.Neighbor)
	GetRouteFamily() bgp.RouteFamily
	GetAsPathLen() int
	GetAsList() []uint32
	GetAsSeqList() []uint32
	GetCommunities() []uint32
	SetCommunities([]uint32, bool)
	RemoveCommunities([]uint32) int
	ClearCommunities()
	GetMed() uint32
	SetMed(int64, bool) error
	setSource(source *PeerInfo)
	GetSource() *PeerInfo
	GetSourceAs() uint32
	GetNexthop() net.IP
	SetNexthop(net.IP)
	setWithdraw(withdraw bool)
	IsWithdraw() bool
	GetNlri() bgp.AddrPrefixInterface
	getPrefix() string
	setMedSetByTargetNeighbor(medSetByTargetNeighbor bool)
	getMedSetByTargetNeighbor() bool
	Clone(IsWithdraw bool) Path
	getTimestamp() time.Time
	setTimestamp(t time.Time)
	isLocal() bool
	ToApiStruct() *api.Path
	MarshalJSON() ([]byte, error)
}

type PathDefault struct {
	routeFamily            bgp.RouteFamily
	source                 *PeerInfo
	withdraw               bool
	nlri                   bgp.AddrPrefixInterface
	pathAttrs              []bgp.PathAttributeInterface
	medSetByTargetNeighbor bool
	timestamp              time.Time
}

func NewPathDefault(rf bgp.RouteFamily, source *PeerInfo, nlri bgp.AddrPrefixInterface, isWithdraw bool, pattrs []bgp.PathAttributeInterface, medSetByTargetNeighbor bool, now time.Time) *PathDefault {
	if !isWithdraw && pattrs == nil {
		log.WithFields(log.Fields{
			"Topic": "Table",
			"Key":   nlri.String(),
			"Peer":  source.Address.String(),
		}).Error("Need to provide patattrs for the path that is not withdraw.")
		return nil
	}

	path := &PathDefault{}
	path.routeFamily = rf
	path.pathAttrs = pattrs
	path.nlri = nlri
	path.source = source
	path.withdraw = isWithdraw
	path.medSetByTargetNeighbor = medSetByTargetNeighbor
	path.timestamp = now
	return path
}

func cloneAsPath(asAttr *bgp.PathAttributeAsPath) *bgp.PathAttributeAsPath {
	newASparams := make([]bgp.AsPathParamInterface, len(asAttr.Value))
	for i, param := range asAttr.Value {
		asParam := param.(*bgp.As4PathParam)
		as := make([]uint32, len(asParam.AS))
		copy(as, asParam.AS)
		newASparams[i] = bgp.NewAs4PathParam(asParam.Type, as)
	}
	return bgp.NewPathAttributeAsPath(newASparams)
}

func (pd *PathDefault) updatePathAttrs(global *config.Global, peer *config.Neighbor) {

	if peer.RouteServer.RouteServerClient {
		return
	}

	if peer.PeerType == config.PEER_TYPE_EXTERNAL {
		// NEXTHOP handling
		pd.SetNexthop(peer.LocalAddress)

		// AS_PATH handling
		//
		//  When a given BGP speaker advertises the route to an external
		//  peer, the advertising speaker updates the AS_PATH attribute
		//  as follows:
		//  1) if the first path segment of the AS_PATH is of type
		//     AS_SEQUENCE, the local system prepends its own AS num as
		//     the last element of the sequence (put it in the left-most
		//     position with respect to the position of  octets in the
		//     protocol message).  If the act of prepending will cause an
		//     overflow in the AS_PATH segment (i.e.,  more than 255
		//     ASes), it SHOULD prepend a new segment of type AS_SEQUENCE
		//     and prepend its own AS number to this new segment.
		//
		//  2) if the first path segment of the AS_PATH is of type AS_SET
		//     , the local system prepends a new path segment of type
		//     AS_SEQUENCE to the AS_PATH, including its own AS number in
		//     that segment.
		//
		//  3) if the AS_PATH is empty, the local system creates a path
		//     segment of type AS_SEQUENCE, places its own AS into that
		//     segment, and places that segment into the AS_PATH.
		idx, originalAsPath := pd.getPathAttr(bgp.BGP_ATTR_TYPE_AS_PATH)
		if idx < 0 {
			log.Fatal("missing AS_PATH mandatory attribute")
		}
		asPath := cloneAsPath(originalAsPath.(*bgp.PathAttributeAsPath))
		pd.pathAttrs[idx] = asPath
		fst := asPath.Value[0].(*bgp.As4PathParam)
		if len(asPath.Value) > 0 && fst.Type == bgp.BGP_ASPATH_ATTR_TYPE_SEQ &&
			fst.ASLen() < 255 {
			fst.AS = append([]uint32{global.As}, fst.AS...)
			fst.Num += 1
		} else {
			p := bgp.NewAs4PathParam(bgp.BGP_ASPATH_ATTR_TYPE_SEQ, []uint32{global.As})
			asPath.Value = append([]bgp.AsPathParamInterface{p}, asPath.Value...)
		}

		// MED Handling
		idx, _ = pd.getPathAttr(bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC)
		if idx >= 0 {
			pd.pathAttrs = append(pd.pathAttrs[:idx], pd.pathAttrs[idx+1:]...)
		}
	} else if peer.PeerType == config.PEER_TYPE_INTERNAL {
		// For iBGP peers we are required to send local-pref attribute
		// for connected or local prefixes.
		// We set default local-pref 100.
		p := bgp.NewPathAttributeLocalPref(100)
		idx, _ := pd.getPathAttr(bgp.BGP_ATTR_TYPE_LOCAL_PREF)
		if idx < 0 {
			pd.pathAttrs = append(pd.pathAttrs, p)
		} else {
			pd.pathAttrs[idx] = p
		}
	} else {
		log.WithFields(log.Fields{
			"Topic": "Peer",
			"Key":   peer.NeighborAddress,
		}).Warnf("invalid peer type: %d", peer.PeerType)
	}
}

func (pd *PathDefault) getTimestamp() time.Time {
	return pd.timestamp
}

func (pd *PathDefault) setTimestamp(t time.Time) {
	pd.timestamp = t
}

func (pd *PathDefault) isLocal() bool {
	var ret bool
	if pd.source.Address == nil {
		ret = true
	}
	return ret
}

func (pd *PathDefault) ToApiStruct() *api.Path {
	pathAttrs := func(arg []bgp.PathAttributeInterface) []*api.PathAttr {
		ret := make([]*api.PathAttr, 0, len(arg))
		for _, a := range arg {
			ret = append(ret, a.ToApiStruct())
		}
		return ret
	}(pd.getPathAttrs())
	return &api.Path{
		Nlri:       pd.GetNlri().ToApiStruct(),
		Nexthop:    pd.GetNexthop().String(),
		Attrs:      pathAttrs,
		Age:        int64(time.Now().Sub(pd.timestamp).Seconds()),
		IsWithdraw: pd.IsWithdraw(),
	}
}

func (pd *PathDefault) MarshalJSON() ([]byte, error) {
	return json.Marshal(pd.ToApiStruct())
}

// create new PathAttributes
func (pd *PathDefault) Clone(isWithdraw bool) Path {
	nlri := pd.nlri
	if pd.GetRouteFamily() == bgp.RF_IPv4_UC && isWithdraw {
		if pd.IsWithdraw() {
			nlri = pd.nlri
		} else {
			nlri = &bgp.WithdrawnRoute{pd.nlri.(*bgp.NLRInfo).IPAddrPrefix}
		}
	}

	newPathAttrs := make([]bgp.PathAttributeInterface, len(pd.pathAttrs))
	for i, v := range pd.pathAttrs {
		newPathAttrs[i] = v
	}

	path, _ := CreatePath(pd.source, nlri, newPathAttrs, isWithdraw, pd.timestamp)
	return path
}

func (pd *PathDefault) GetRouteFamily() bgp.RouteFamily {
	return pd.routeFamily
}

func (pd *PathDefault) setSource(source *PeerInfo) {
	pd.source = source
}
func (pd *PathDefault) GetSource() *PeerInfo {
	return pd.source
}

func (pd *PathDefault) GetSourceAs() uint32 {
	_, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_AS_PATH)
	if attr != nil {
		asPathParam := attr.(*bgp.PathAttributeAsPath).Value
		if len(asPathParam) == 0 {
			return 0
		}
		asPath := asPathParam[len(asPathParam)-1].(*bgp.As4PathParam)
		if asPath.Num == 0 {
			return 0
		}
		return asPath.AS[asPath.Num-1]
	}
	return 0
}

func (pd *PathDefault) GetNexthop() net.IP {
	_, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_NEXT_HOP)
	if attr != nil {
		return attr.(*bgp.PathAttributeNextHop).Value
	}
	_, attr = pd.getPathAttr(bgp.BGP_ATTR_TYPE_MP_REACH_NLRI)
	if attr != nil {
		return attr.(*bgp.PathAttributeMpReachNLRI).Nexthop
	}
	return net.IP{}
}

func (pd *PathDefault) SetNexthop(nexthop net.IP) {
	idx, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_NEXT_HOP)
	if attr != nil {
		newNexthop := bgp.NewPathAttributeNextHop(nexthop.String())
		pd.pathAttrs[idx] = newNexthop
	}
	idx, attr = pd.getPathAttr(bgp.BGP_ATTR_TYPE_MP_REACH_NLRI)
	if attr != nil {
		oldNlri := attr.(*bgp.PathAttributeMpReachNLRI)
		newNlri := bgp.NewPathAttributeMpReachNLRI(nexthop.String(), oldNlri.Value)
		pd.pathAttrs[idx] = newNlri
	}
}

func (pd *PathDefault) setWithdraw(withdraw bool) {
	pd.withdraw = withdraw
}

func (pd *PathDefault) IsWithdraw() bool {
	return pd.withdraw
}

func (pd *PathDefault) GetNlri() bgp.AddrPrefixInterface {
	return pd.nlri
}

func (pd *PathDefault) setMedSetByTargetNeighbor(medSetByTargetNeighbor bool) {
	pd.medSetByTargetNeighbor = medSetByTargetNeighbor
}

func (pd *PathDefault) getMedSetByTargetNeighbor() bool {
	return pd.medSetByTargetNeighbor
}

func (pd *PathDefault) getPathAttrs() []bgp.PathAttributeInterface {
	return pd.pathAttrs
}

func (pd *PathDefault) getPathAttr(pattrType bgp.BGPAttrType) (int, bgp.PathAttributeInterface) {
	attrMap := [bgp.BGP_ATTR_TYPE_AS4_AGGREGATOR + 1]reflect.Type{}
	attrMap[bgp.BGP_ATTR_TYPE_ORIGIN] = reflect.TypeOf(&bgp.PathAttributeOrigin{})
	attrMap[bgp.BGP_ATTR_TYPE_AS_PATH] = reflect.TypeOf(&bgp.PathAttributeAsPath{})
	attrMap[bgp.BGP_ATTR_TYPE_NEXT_HOP] = reflect.TypeOf(&bgp.PathAttributeNextHop{})
	attrMap[bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC] = reflect.TypeOf(&bgp.PathAttributeMultiExitDisc{})
	attrMap[bgp.BGP_ATTR_TYPE_LOCAL_PREF] = reflect.TypeOf(&bgp.PathAttributeLocalPref{})
	attrMap[bgp.BGP_ATTR_TYPE_ATOMIC_AGGREGATE] = reflect.TypeOf(&bgp.PathAttributeAtomicAggregate{})
	attrMap[bgp.BGP_ATTR_TYPE_AGGREGATOR] = reflect.TypeOf(&bgp.PathAttributeAggregator{})
	attrMap[bgp.BGP_ATTR_TYPE_COMMUNITIES] = reflect.TypeOf(&bgp.PathAttributeCommunities{})
	attrMap[bgp.BGP_ATTR_TYPE_ORIGINATOR_ID] = reflect.TypeOf(&bgp.PathAttributeOriginatorId{})
	attrMap[bgp.BGP_ATTR_TYPE_CLUSTER_LIST] = reflect.TypeOf(&bgp.PathAttributeClusterList{})
	attrMap[bgp.BGP_ATTR_TYPE_MP_REACH_NLRI] = reflect.TypeOf(&bgp.PathAttributeMpReachNLRI{})
	attrMap[bgp.BGP_ATTR_TYPE_MP_UNREACH_NLRI] = reflect.TypeOf(&bgp.PathAttributeMpUnreachNLRI{})
	attrMap[bgp.BGP_ATTR_TYPE_EXTENDED_COMMUNITIES] = reflect.TypeOf(&bgp.PathAttributeExtendedCommunities{})
	attrMap[bgp.BGP_ATTR_TYPE_AS4_PATH] = reflect.TypeOf(&bgp.PathAttributeAs4Path{})
	attrMap[bgp.BGP_ATTR_TYPE_AS4_AGGREGATOR] = reflect.TypeOf(&bgp.PathAttributeAs4Aggregator{})

	t := attrMap[pattrType]
	for i, p := range pd.pathAttrs {
		if t == reflect.TypeOf(p) {
			return i, p
		}
	}
	return -1, nil
}

// return Path's string representation
func (pi *PathDefault) String() string {
	str := fmt.Sprintf("IPv4Path Source: %v, ", pi.GetSource())
	str = str + fmt.Sprintf(" NLRI: %s, ", pi.getPrefix())
	str = str + fmt.Sprintf(" nexthop: %s, ", pi.GetNexthop().String())
	str = str + fmt.Sprintf(" withdraw: %s, ", pi.IsWithdraw())
	//str = str + fmt.Sprintf(" path attributes: %s, ", pi.getPathAttributeMap())
	return str
}

func (pi *PathDefault) getPrefix() string {
	return pi.nlri.String()
}

// GetAsPathLen returns the number of AS_PATH
func (pd *PathDefault) GetAsPathLen() int {

	var length int = 0
	if _, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_AS_PATH); attr != nil {
		aspath := attr.(*bgp.PathAttributeAsPath)
		for _, paramIf := range aspath.Value {
			segment := paramIf.(*bgp.As4PathParam)
			length += segment.ASLen()
		}
	}
	return length
}

func (pd *PathDefault) GetAsList() []uint32 {
	return pd.getAsListofSpecificType(true, true)

}

func (pd *PathDefault) GetAsSeqList() []uint32 {
	return pd.getAsListofSpecificType(true, false)

}

func (pd *PathDefault) getAsListofSpecificType(getAsSeq, getAsSet bool) []uint32 {
	asList := []uint32{}
	if _, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_AS_PATH); attr != nil {
		aspath := attr.(*bgp.PathAttributeAsPath)
		for _, paramIf := range aspath.Value {
			segment := paramIf.(*bgp.As4PathParam)
			if getAsSeq && segment.Type == bgp.BGP_ASPATH_ATTR_TYPE_SEQ {
				asList = append(asList, segment.AS...)
				continue
			}
			if getAsSet && segment.Type == bgp.BGP_ASPATH_ATTR_TYPE_SET {
				asList = append(asList, segment.AS...)
			}
		}
	}
	return asList
}

func (pd *PathDefault) GetCommunities() []uint32 {
	communityList := []uint32{}
	if _, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES); attr != nil {
		communities := attr.(*bgp.PathAttributeCommunities)
		communityList = append(communityList, communities.Value...)
	}
	return communityList
}

// SetCommunities adds or replaces communities with new ones.
// If the length of communites is 0, it does nothing.
func (pd *PathDefault) SetCommunities(communities []uint32, doReplace bool) {

	if len(communities) == 0 {
		// do nothing
		return
	}

	newList := make([]uint32, 0)
	idx, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
	if attr != nil {
		c := attr.(*bgp.PathAttributeCommunities)
		if doReplace {
			newList = append(newList, communities...)
		} else {
			newList = append(newList, c.Value...)
			newList = append(newList, communities...)
		}
		newCommunities := bgp.NewPathAttributeCommunities(newList)
		pd.pathAttrs[idx] = newCommunities
	} else {
		newList = append(newList, communities...)
		newCommunities := bgp.NewPathAttributeCommunities(newList)
		pd.pathAttrs = append(pd.pathAttrs, newCommunities)
	}

}

// RemoveCommunities removes specific communities.
// If the length of communites is 0, it does nothing.
// If all communities are removed, it removes Communities path attribute itself.
func (pd *PathDefault) RemoveCommunities(communities []uint32) int {

	if len(communities) == 0 {
		// do nothing
		return 0
	}

	find := func(val uint32) bool {
		for _, com := range communities {
			if com == val {
				return true
			}
		}
		return false
	}

	count := 0
	idx, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
	if attr != nil {
		newList := make([]uint32, 0)
		c := attr.(*bgp.PathAttributeCommunities)

		for _, value := range c.Value {
			if find(value) {
				count += 1
			} else {
				newList = append(newList, value)
			}
		}

		if len(newList) != 0 {
			newCommunities := bgp.NewPathAttributeCommunities(newList)
			pd.pathAttrs[idx] = newCommunities
		} else {
			pd.pathAttrs = append(pd.pathAttrs[:idx], pd.pathAttrs[idx+1:]...)
		}
	}
	return count
}

// ClearCommunities removes Communities path attribute.
func (pd *PathDefault) ClearCommunities() {
	idx, _ := pd.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
	if idx >= 0 {
		pd.pathAttrs = append(pd.pathAttrs[:idx], pd.pathAttrs[idx+1:]...)
	}
}

func (pd *PathDefault) GetMed() uint32 {
	_, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC)
	med := attr.(*bgp.PathAttributeMultiExitDisc).Value
	return med
}

// SetMed replace, add or subtraction med with new ones.
func (pd *PathDefault) SetMed(med int64, doReplace bool) error {

	parseMed := func(orgMed uint32, med int64, doReplace bool) (*bgp.PathAttributeMultiExitDisc, error) {
		newMed := &bgp.PathAttributeMultiExitDisc{}
		if doReplace {
			newMed = bgp.NewPathAttributeMultiExitDisc(uint32(med))
		} else {
			if int64(orgMed) + med < 0 {
				return nil, fmt.Errorf("med value invalid. it's underflow threshold.")
			} else if int64(orgMed) + med > int64(math.MaxUint32) {
				return nil, fmt.Errorf("med value invalid. it's overflow threshold.")
			}
			newMed = bgp.NewPathAttributeMultiExitDisc(uint32(int64(orgMed) + med))
		}
		return newMed, nil
	}

	idx, attr := pd.getPathAttr(bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC)
	if attr != nil{
		m := attr.(*bgp.PathAttributeMultiExitDisc)
		newMed, err := parseMed(m.Value, med, doReplace)
		if err !=  nil{
			return err
		}
		pd.pathAttrs[idx] = newMed
	} else {
		m := 0
		newMed, err := parseMed(uint32(m), med, doReplace)
		if err !=  nil{
			pd.pathAttrs = append(pd.pathAttrs, &bgp.PathAttributeMultiExitDisc{})
			return err
		}
		pd.pathAttrs = append(pd.pathAttrs, newMed)
	}
	return nil
}

// create Path object based on route family
func CreatePath(source *PeerInfo, nlri bgp.AddrPrefixInterface, attrs []bgp.PathAttributeInterface, isWithdraw bool, now time.Time) (Path, error) {

	rf := bgp.RouteFamily(int(nlri.AFI())<<16 | int(nlri.SAFI()))
	log.Debugf("CreatePath afi: %d, safi: %d ", int(nlri.AFI()), nlri.SAFI())
	var path Path

	switch rf {
	case bgp.RF_IPv4_UC:
		log.Debugf("CreatePath RouteFamily : %s", bgp.RF_IPv4_UC.String())
		path = NewIPv4Path(source, nlri, isWithdraw, attrs, false, now)
	case bgp.RF_IPv6_UC:
		log.Debugf("CreatePath RouteFamily : %s", bgp.RF_IPv6_UC.String())
		path = NewIPv6Path(source, nlri, isWithdraw, attrs, false, now)
	case bgp.RF_IPv4_VPN:
		log.Debugf("CreatePath RouteFamily : %s", bgp.RF_IPv4_VPN.String())
		path = NewIPv4VPNPath(source, nlri, isWithdraw, attrs, false, now)
	case bgp.RF_EVPN:
		log.Debugf("CreatePath RouteFamily : %s", bgp.RF_EVPN.String())
		path = NewEVPNPath(source, nlri, isWithdraw, attrs, false, now)
	case bgp.RF_ENCAP:
		log.Debugf("CreatePath RouteFamily : %s", bgp.RF_ENCAP.String())
		path = NewEncapPath(source, nlri, isWithdraw, attrs, false, now)
	case bgp.RF_RTC_UC:
		log.Debugf("CreatePath RouteFamily : %s", bgp.RF_RTC_UC)
		path = NewRouteTargetPath(source, nlri, isWithdraw, attrs, false, now)
	default:
		return path, fmt.Errorf("Unsupported RouteFamily: %s", rf)
	}
	return path, nil
}

/*
* 	Definition of inherited Path  interface
 */
type IPv4Path struct {
	*PathDefault
}

func NewIPv4Path(source *PeerInfo, nlri bgp.AddrPrefixInterface, isWithdraw bool, attrs []bgp.PathAttributeInterface, medSetByTargetNeighbor bool, now time.Time) *IPv4Path {
	ipv4Path := &IPv4Path{}
	ipv4Path.PathDefault = NewPathDefault(bgp.RF_IPv4_UC, source, nlri, isWithdraw, attrs, medSetByTargetNeighbor, now)
	return ipv4Path
}

func (ipv4p *IPv4Path) setPathDefault(pd *PathDefault) {
	ipv4p.PathDefault = pd
}
func (ipv4p *IPv4Path) getPathDefault() *PathDefault {
	return ipv4p.PathDefault
}

type IPv6Path struct {
	*PathDefault
}

func NewIPv6Path(source *PeerInfo, nlri bgp.AddrPrefixInterface, isWithdraw bool, attrs []bgp.PathAttributeInterface, medSetByTargetNeighbor bool, now time.Time) *IPv6Path {
	ipv6Path := &IPv6Path{}
	ipv6Path.PathDefault = NewPathDefault(bgp.RF_IPv6_UC, source, nlri, isWithdraw, attrs, medSetByTargetNeighbor, now)
	return ipv6Path
}

func (ipv6p *IPv6Path) setPathDefault(pd *PathDefault) {
	ipv6p.PathDefault = pd
}

func (ipv6p *IPv6Path) getPathDefault() *PathDefault {
	return ipv6p.PathDefault
}

// return IPv6Path's string representation
func (ipv6p *IPv6Path) String() string {
	str := fmt.Sprintf("IPv6Path Source: %v, ", ipv6p.GetSource())
	str = str + fmt.Sprintf(" NLRI: %s, ", ipv6p.getPrefix())
	str = str + fmt.Sprintf(" nexthop: %s, ", ipv6p.GetNexthop().String())
	str = str + fmt.Sprintf(" withdraw: %s, ", ipv6p.IsWithdraw())
	//str = str + fmt.Sprintf(" path attributes: %s, ", ipv6p.getPathAttributeMap())
	return str
}

type IPv4VPNPath struct {
	*PathDefault
}

func NewIPv4VPNPath(source *PeerInfo, nlri bgp.AddrPrefixInterface, isWithdraw bool, attrs []bgp.PathAttributeInterface, medSetByTargetNeighbor bool, now time.Time) *IPv4VPNPath {
	ipv4VPNPath := &IPv4VPNPath{}
	ipv4VPNPath.PathDefault = NewPathDefault(bgp.RF_IPv4_VPN, source, nlri, isWithdraw, attrs, medSetByTargetNeighbor, now)
	return ipv4VPNPath
}

func (ipv4vpnp *IPv4VPNPath) setPathDefault(pd *PathDefault) {
	ipv4vpnp.PathDefault = pd
}

func (ipv4vpnp *IPv4VPNPath) getPathDefault() *PathDefault {
	return ipv4vpnp.PathDefault
}

// return IPv4VPNPath's string representation
func (ipv4vpnp *IPv4VPNPath) String() string {
	str := fmt.Sprintf("IPv4VPNPath Source: %v, ", ipv4vpnp.GetSource())
	str = str + fmt.Sprintf(" NLRI: %s, ", ipv4vpnp.getPrefix())
	str = str + fmt.Sprintf(" nexthop: %s, ", ipv4vpnp.GetNexthop().String())
	str = str + fmt.Sprintf(" withdraw: %s, ", ipv4vpnp.IsWithdraw())
	//str = str + fmt.Sprintf(" path attributes: %s, ", ipv4vpnp.getPathAttributeMap())
	return str
}

func (ipv4vpnp *IPv4VPNPath) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Network string
		Nexthop string
		Attrs   []bgp.PathAttributeInterface
		Age     int64
	}{
		Network: ipv4vpnp.getPrefix(),
		Nexthop: ipv4vpnp.PathDefault.GetNexthop().String(),
		Attrs:   ipv4vpnp.PathDefault.getPathAttrs(),
		Age:     int64(time.Now().Sub(ipv4vpnp.PathDefault.timestamp).Seconds()),
	})
}

type EVPNPath struct {
	*PathDefault
}

func NewEVPNPath(source *PeerInfo, nlri bgp.AddrPrefixInterface, isWithdraw bool, attrs []bgp.PathAttributeInterface, medSetByTargetNeighbor bool, now time.Time) *EVPNPath {
	EVPNPath := &EVPNPath{}
	EVPNPath.PathDefault = NewPathDefault(bgp.RF_EVPN, source, nlri, isWithdraw, attrs, medSetByTargetNeighbor, now)
	return EVPNPath
}

func (evpnp *EVPNPath) setPathDefault(pd *PathDefault) {
	evpnp.PathDefault = pd
}

func (evpnp *EVPNPath) getPathDefault() *PathDefault {
	return evpnp.PathDefault
}

// return EVPNPath's string representation
func (evpnp *EVPNPath) String() string {
	str := fmt.Sprintf("EVPNPath Source: %v, ", evpnp.GetSource())
	str = str + fmt.Sprintf(" NLRI: %s, ", evpnp.getPrefix())
	str = str + fmt.Sprintf(" nexthop: %s, ", evpnp.GetNexthop().String())
	str = str + fmt.Sprintf(" withdraw: %s, ", evpnp.IsWithdraw())
	//str = str + fmt.Sprintf(" path attributes: %s, ", evpnp.getPathAttributeMap())
	return str
}

func (evpnp *EVPNPath) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Network string
		Nexthop string
		Attrs   []bgp.PathAttributeInterface
		Age     int64
	}{
		Network: evpnp.getPrefix(),
		Nexthop: evpnp.PathDefault.GetNexthop().String(),
		Attrs:   evpnp.PathDefault.getPathAttrs(),
		Age:     int64(time.Now().Sub(evpnp.PathDefault.timestamp).Seconds()),
	})
}

type EncapPath struct {
	*PathDefault
}

func NewEncapPath(source *PeerInfo, nlri bgp.AddrPrefixInterface, isWithdraw bool, attrs []bgp.PathAttributeInterface, medSetByTargetNeighbor bool, now time.Time) *EncapPath {
	return &EncapPath{
		PathDefault: NewPathDefault(bgp.RF_ENCAP, source, nlri, isWithdraw, attrs, medSetByTargetNeighbor, now),
	}
}

func (p *EncapPath) setPathDefault(pd *PathDefault) {
	p.PathDefault = pd
}
func (p *EncapPath) getPathDefault() *PathDefault {
	return p.PathDefault
}

type RouteTargetPath struct {
	*PathDefault
}

func NewRouteTargetPath(source *PeerInfo, nlri bgp.AddrPrefixInterface, isWithdraw bool, attrs []bgp.PathAttributeInterface, medSetByTargetNeighbor bool, now time.Time) *RouteTargetPath {
	return &RouteTargetPath{
		PathDefault: NewPathDefault(bgp.RF_RTC_UC, source, nlri, isWithdraw, attrs, medSetByTargetNeighbor, now),
	}
}

func (p *RouteTargetPath) setPathDefault(pd *PathDefault) {
	p.PathDefault = pd
}
func (p *RouteTargetPath) getPathDefault() *PathDefault {
	return p.PathDefault
}