Merge changes I21c05c40,Ib6e5362f
[bgpcep.git] / bgp / rib-spi / src / main / java / org / opendaylight / protocol / bgp / rib / spi / BGPObjectComparator.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bgp.rib.spi;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.net.InetAddresses;
13 import java.util.Arrays;
14 import java.util.Comparator;
15 import java.util.List;
16
17 import org.opendaylight.protocol.bgp.rib.spi.AbstractAdjRIBsIn.RIBEntryData;
18 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.PathAttributes;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.as.path.Segments;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpOrigin;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.as.path.segment.c.segment.AListCase;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.as.path.segment.c.segment.ASetCase;
24
25 /**
26  * This comparator is intended to implement BGP Best Path Selection algorithm, as described at
27  *
28  * @see http://www.cisco.com/en/US/tech/tk365/technologies_tech_note09186a0080094431.shtml
29  *
30  * @param <T> Actual object state reference
31  */
32 public final class BGPObjectComparator implements Comparator<RIBEntryData<?, ?>> {
33     private final AsNumber ourAS;
34
35     public BGPObjectComparator(final AsNumber ourAs) {
36         this.ourAS = Preconditions.checkNotNull(ourAs);
37     }
38
39     @Override
40     public int compare(final RIBEntryData<?, ?> e1, final RIBEntryData<?, ?> e2) {
41         if (e1 == e2) {
42             return 0;
43         }
44         if (e1 == null) {
45             return 1;
46         }
47         if (e2 == null) {
48             return -1;
49         }
50
51         final PathAttributes o1 = e1.getPathAttributes();
52         final PathAttributes o2 = e2.getPathAttributes();
53         if (o1.equals(o2) && Arrays.equals(e1.getPeer().getRawIdentifier(), e2.getPeer().getRawIdentifier())) {
54             return 0;
55         }
56
57         // 1. prefer path with accessible nexthop
58         // - we assume that all nexthops are accessible
59
60         // 2. prefer path with higher LOCAL_PREF
61         if ((o1.getLocalPref() != null || o2.getLocalPref() != null)
62             && (o1.getLocalPref() != null && !o1.getLocalPref().equals(o2.getLocalPref()))) {
63             return o1.getLocalPref().getPref().compareTo(o2.getLocalPref().getPref());
64         }
65
66         // 3. prefer learned path
67         // - we assume that all paths are learned
68
69         // 4. prefer the path with the shortest AS_PATH.
70         if (!o1.getAsPath().equals(o2.getAsPath())) {
71             final Integer i1 = countAsPath(o1.getAsPath().getSegments());
72             final Integer i2 = countAsPath(o2.getAsPath().getSegments());
73             return i2.compareTo(i1);
74         }
75
76         // 5. prefer the path with the lowest origin type
77         // - IGP is lower than Exterior Gateway Protocol (EGP), and EGP is lower than INCOMPLETE
78         if (!o1.getOrigin().equals(o2.getOrigin())) {
79             if (o1.getOrigin().getValue().equals(BgpOrigin.Igp)) {
80                 return 1;
81             }
82             if (o2.getOrigin().getValue().equals(BgpOrigin.Igp)) {
83                 return -1;
84             }
85             if (o1.getOrigin().getValue().equals(BgpOrigin.Egp)) {
86                 return 1;
87             } else {
88                 return -1;
89             }
90         }
91
92         // 6. prefer the path with the lowest multi-exit discriminator (MED)
93         if ((o1.getMultiExitDisc() != null || o2.getMultiExitDisc() != null)
94             && (o1.getMultiExitDisc() != null && !o1.getMultiExitDisc().equals(o2.getMultiExitDisc()))) {
95             return o2.getMultiExitDisc().getMed().compareTo(o1.getMultiExitDisc().getMed());
96         }
97
98         // 7. prefer eBGP over iBGP paths
99         // EBGP is peering between two different AS, whereas IBGP is between same AS (Autonomous System).
100         final AsNumber first = getPeerAs(o1.getAsPath().getSegments());
101         final AsNumber second = getPeerAs(o2.getAsPath().getSegments());
102         if ((first != null || second != null) && (first != null && !first.equals(second))) {
103             if (first.equals(this.ourAS)) {
104                 return -1;
105             }
106             if (second == null || second.equals(this.ourAS)) {
107                 return 1;
108             }
109         }
110
111         // 8. Prefer the path with the lowest IGP metric to the BGP next hop.
112         // - no next hop metric is advertized
113
114         // 9. When both paths are external, prefer the path that was received first (the oldest one).
115         // if (first.equals(this.ourAS) && second.equals(this.ourAS)) {
116         // FIXME: do we have a way how to determine which one was received first?
117         // }
118
119         // 10. Prefer the route that comes from the BGP router with the lowest router ID.
120         // The router ID is the highest IP address on the router, with preference given to loopback addresses.
121         // If a path contains route reflector (RR) attributes, the originator ID is substituted for the router ID in the
122         // path selection process.
123         byte[] oid1 = e1.getPeer().getRawIdentifier();
124         byte[] oid2 = e2.getPeer().getRawIdentifier();
125         if (o1.getOriginatorId() != null) {
126             oid1 = InetAddresses.forString(o1.getOriginatorId().getOriginator().getValue()).getAddress();
127         }
128         if (o2.getOriginatorId() != null) {
129             oid2 = InetAddresses.forString(o2.getOriginatorId().getOriginator().getValue()).getAddress();
130         }
131         if (!Arrays.equals(oid1, oid2)) {
132             return compareByteArrays(oid1, oid2);
133         }
134         // 11. prefer the path with the minimum cluster list length
135         int cluster1 = 0;
136         int cluster2 = 0;
137         if (o1.getClusterId() != null) {
138             cluster1 = o1.getClusterId().getCluster().size();
139         }
140         if (o2.getClusterId() != null) {
141             cluster2 = o2.getClusterId().getCluster().size();
142         }
143         if (cluster1 != cluster2) {
144             return ((Integer) cluster1).compareTo(cluster2);
145         }
146
147         // 12. Prefer the path that comes from the lowest neighbor address.
148         // FIXME: do we know this?
149
150         return 0;
151     }
152
153     private static int countAsPath(final List<Segments> segments) {
154         // an AS_SET counts as 1, no matter how many ASs are in the set.
155         int count = 0;
156         boolean setPresent = false;
157         for (final Segments s : segments) {
158             if (s.getCSegment() instanceof ASetCase) {
159                 setPresent = true;
160             } else {
161                 final AListCase list = (AListCase) s.getCSegment();
162                 count += list.getAList().getAsSequence().size();
163             }
164         }
165         return (setPresent) ? ++count : count;
166     }
167
168     private static AsNumber getPeerAs(final List<Segments> segments) {
169         if (segments.size() == 0) {
170             return null;
171         }
172         final AListCase first = (AListCase) segments.get(0).getCSegment();
173         return first.getAList().getAsSequence().get(0).getAs();
174     }
175
176     @VisibleForTesting
177     public static int compareByteArrays(final byte[] byteOne, final byte[] byteTwo) {
178         for (int i = 0; i < byteOne.length; i++) {
179             final int res = Byte.compare(byteOne[i], byteTwo[i]);
180             if (res != 0) {
181                 return res;
182             }
183         }
184         return 0;
185     }
186 }