279958b77cc8235b37317f606734e3377b85da92
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BestPathSelector.java
1 /*
2  * Copyright (c) 2015 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.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.primitives.UnsignedInteger;
14 import java.util.Collection;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OriginatorId;
17 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpOrigin;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
21 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
25
26 final class BestPathSelector {
27     private static final Collection<PathArgument> ORIGINATOR_ID = ImmutableList.<PathArgument>of(new NodeIdentifier(OriginatorId.QNAME), new NodeIdentifier(QName.create(OriginatorId.QNAME, "originator")));
28
29     private final Long ourAs;
30     private UnsignedInteger bestOriginatorId = null;
31     private UnsignedInteger bestRouterId = null;
32     private BestPathState bestState = null;
33
34     BestPathSelector(final Long ourAs) {
35         this.ourAs = Preconditions.checkNotNull(ourAs);
36     }
37
38     void processPath(final UnsignedInteger routerId, final ContainerNode attrs) {
39         Preconditions.checkNotNull(routerId, "Router ID may not be null");
40
41         // Consider only non-null attributes
42         if (attrs != null) {
43             /*
44              * RFC 4456 mandates the use of Originator IDs instead of Router ID for
45              * selection purposes.
46              */
47             final Optional<NormalizedNode<?, ?>> maybeOriginatorId = NormalizedNodes.findNode(attrs, ORIGINATOR_ID);
48             final UnsignedInteger originatorId;
49             if (maybeOriginatorId.isPresent()) {
50                 originatorId = RouterIds.routerIdForAddress((String) ((LeafNode<?>)maybeOriginatorId.get()).getValue());
51             } else {
52                 originatorId = routerId;
53             }
54
55             /*
56              * Store the new details if we have nothing stored or when the selection algorithm indicates new details
57              * are better.
58              */
59             final BestPathState state = new BestPathState(attrs);
60             if (this.bestOriginatorId == null || selectPath(originatorId, state)) {
61                 this.bestOriginatorId = originatorId;
62                 this.bestRouterId = routerId;
63                 this.bestState = state;
64             }
65         }
66     }
67
68     BestPath result() {
69         return this.bestRouterId == null ? null : new BestPath(this.bestRouterId, this.bestState);
70     }
71
72     /**
73      * Chooses best route according to BGP best path selection.
74      *
75      * @param originatorId of the new route
76      * @param state attributes of the new route
77      * @return true if the existing path is better, false if the new path is better
78      */
79     private boolean selectPath(@Nonnull final UnsignedInteger originatorId, @Nonnull final BestPathState state) {
80         // 1. prefer path with accessible nexthop
81         // - we assume that all nexthops are accessible
82
83         /*
84          * 2. prefer path with higher LOCAL_PREF
85          *
86          * FIXME: for eBGP cases (when the LOCAL_PREF is missing), we should assign a policy-based preference
87          *        before we ever get here.
88          */
89         if (this.bestState.getLocalPref() == null && state.getLocalPref() != null) {
90             return true;
91         }
92         if (this.bestState.getLocalPref() != null && state.getLocalPref() == null) {
93             return false;
94         }
95         if (state.getLocalPref() != null && state.getLocalPref() > this.bestState.getLocalPref()) {
96             return true;
97         }
98
99         // 3. prefer learned path
100         // - we assume that all paths are learned
101
102         // 4. prefer the path with the shortest AS_PATH.
103         if (this.bestState.getAsPathLength() > state.getAsPathLength()) {
104             return true;
105         }
106
107         // 5. prefer the path with the lowest origin type
108         // - IGP is lower than Exterior Gateway Protocol (EGP), and EGP is lower than INCOMPLETE
109         if (!this.bestState.getOrigin().equals(state.getOrigin())) {
110             final BgpOrigin bo = this.bestState.getOrigin();
111             final BgpOrigin no = state.getOrigin();
112
113             // This trick relies on the order in which the values are declared in the model.
114             if (no.ordinal() < bo.ordinal()) {
115                 return true;
116             }
117         }
118
119         // FIXME: we should be able to cache the best AS
120         final Long bestAs = this.bestState.getPeerAs();
121         final Long newAs = state.getPeerAs();
122
123         /*
124          * Checks 6 and 7 are mutually-exclusive, as MEDs are comparable
125          * only when the routes originated from the same AS. On the other
126          * hand, when they are from the same AS, they are in the same iBGP/eBGP
127          * relationship.
128          *
129          */
130         if (bestAs.equals(newAs)) {
131             // 6. prefer the path with the lowest multi-exit discriminator (MED)
132             if (this.bestState.getMultiExitDisc() != null || state.getMultiExitDisc() != null) {
133                 final Long bmed = this.bestState.getMultiExitDisc();
134                 final Long nmed = state.getMultiExitDisc();
135                 if (nmed < bmed) {
136                     return true;
137                 }
138             }
139         } else {
140             /*
141              * 7. prefer eBGP over iBGP paths
142              *
143              * EBGP is peering between two different AS, whereas IBGP is between same AS (Autonomous System),
144              * so we just compare the AS numbers to our AS.
145              *
146              * FIXME: we should know this information from the peer directly.
147              */
148             if (!this.ourAs.equals(bestAs) && this.ourAs.equals(newAs)) {
149                 return true;
150             }
151         }
152
153         // 8. Prefer the path with the lowest IGP metric to the BGP next hop.
154         // - no next hop metric is advertised
155
156         /*
157          * 9. When both paths are external, prefer the path that was received first (the oldest one).
158          *
159          * FIXME: we do not want to store an explicit timer for each set due to performance/memory
160          *        constraints. Our caller has the information about which attributes have changed
161          *        since the selection process has ran last time, which may be a good enough approximation,
162          *        but its properties need to be analyzed.
163          */
164
165         /*
166          * 10. Prefer the route that comes from the BGP router with the lowest router ID.
167          *
168          * This is normally guaranteed by the iteration order of our caller, which runs selection
169          * in the order of increasing router ID, but RFC-4456 Route Reflection throws a wrench into that.
170          *
171          * With RFC-5004, this gets a bit easier, because it completely eliminates step f) and later :-)
172          *
173          * RFC-5004 states that this algorithm should end here and select existing path over new path in the
174          * best path selection process. Benefits are listed in the RFC: @see http://tools.ietf.org/html/rfc500
175          * - This algorithm SHOULD NOT be applied when either path is from a BGP Confederation peer.
176          *  - not applicable, we don't deal with confederation peers
177          * - The algorithm SHOULD NOT be applied when both paths are from peers with an identical BGP identifier
178          *   (i.e., there exist parallel BGP sessions between two BGP speakers).
179          *  - not applicable, BUG-2631 prevents parallel sessions to be created.
180          */
181         return true;
182     }
183 }