604bb4bf5bcc252066f459bb261d87c73196cb47
[bgpcep.git] / bgp / path-selection-mode / src / main / java / org / opendaylight / protocol / bgp / mode / impl / BestPathStateImpl.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.mode.impl;
9
10 import com.google.common.base.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.cache.Cache;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.collect.ImmutableList;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20 import java.util.concurrent.Callable;
21 import java.util.concurrent.ExecutionException;
22 import javax.annotation.concurrent.NotThreadSafe;
23 import org.opendaylight.protocol.bgp.mode.api.BestPathState;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.AsPath;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.LocalPref;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.MultiExitDisc;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.Origin;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.as.path.Segments;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.as.path.SegmentsBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpOrigin;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.QNameModule;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
42 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 @NotThreadSafe
48 public final class BestPathStateImpl implements BestPathState {
49     private static final class NamespaceSpecificIds {
50         private final Collection<PathArgument> asPath;
51         private final Collection<PathArgument> locPref;
52         private final Collection<PathArgument> med;
53         private final Collection<PathArgument> orig;
54         private final NodeIdentifier asSetNid;
55         private final NodeIdentifier asSeqNid;
56
57         NamespaceSpecificIds(final QName namespace) {
58             NodeIdentifier container = new NodeIdentifier(QName.create(namespace, AsPath.QNAME.getLocalName().intern()));
59             NodeIdentifier leaf = new NodeIdentifier(QName.create(namespace, "segments").intern());
60             this.asPath = ImmutableList.<PathArgument>of(container, leaf);
61
62             container = new NodeIdentifier(QName.create(namespace, LocalPref.QNAME.getLocalName()).intern());
63             leaf = new NodeIdentifier(QName.create(namespace, "pref").intern());
64             this.locPref = ImmutableList.<PathArgument>of(container, leaf);
65
66             container = new NodeIdentifier(QName.create(namespace, MultiExitDisc.QNAME.getLocalName()).intern());
67             leaf = new NodeIdentifier(QName.create(namespace, "med").intern());
68             this.med = ImmutableList.<PathArgument>of(container, leaf);
69
70             container = new NodeIdentifier(QName.create(namespace, Origin.QNAME.getLocalName()).intern());
71             leaf = new NodeIdentifier(QName.create(namespace, "value").intern());
72             this.orig = ImmutableList.<PathArgument>of(container, leaf);
73
74             this.asSetNid = new NodeIdentifier(QName.create(namespace, "as-set").intern());
75             this.asSeqNid = new NodeIdentifier(QName.create(namespace, "as-sequence").intern());
76         }
77
78         Collection<PathArgument> getAsPath() {
79             return this.asPath;
80         }
81
82         Collection<PathArgument> getLocPref() {
83             return this.locPref;
84         }
85
86         Collection<PathArgument> getMed() {
87             return this.med;
88         }
89
90         Collection<PathArgument> getOrig() {
91             return this.orig;
92         }
93
94         NodeIdentifier getAsSet() {
95             return this.asSetNid;
96         }
97
98         NodeIdentifier getAsSeq() {
99             return this.asSeqNid;
100         }
101     }
102
103     private static final Logger LOG = LoggerFactory.getLogger(BestPathStateImpl.class);
104     private static final Cache<QNameModule, NamespaceSpecificIds> PATH_CACHE = CacheBuilder.newBuilder().weakKeys().weakValues().build();
105
106     private long peerAs = 0L;
107     private int asPathLength = 0;
108
109     private final ContainerNode attributes;
110     private final NamespaceSpecificIds ids;
111     private Long localPref;
112     private Long multiExitDisc;
113     private BgpOrigin origin;
114     private boolean resolved;
115
116     public BestPathStateImpl(final ContainerNode attributes) {
117         final NamespaceSpecificIds col;
118         try {
119             col = PATH_CACHE.get(attributes.getNodeType().getModule(), new Callable<NamespaceSpecificIds>() {
120                 @Override
121                 public NamespaceSpecificIds call() {
122                     return new NamespaceSpecificIds(attributes.getNodeType());
123                 }
124             });
125         } catch (final ExecutionException e) {
126             LOG.error("Error creating namespace-specific attributes collection.", e);
127             throw new IllegalStateException("Error creating namespace-specific attributes collection.", e);
128         }
129
130         this.attributes = Preconditions.checkNotNull(attributes);
131         this.ids = col;
132         resolveValues();
133     }
134
135     private static BgpOrigin fromString(final String originStr) {
136         switch (originStr) {
137         case "igp":
138             return BgpOrigin.Igp;
139         case "egp":
140             return BgpOrigin.Egp;
141         case "incomplete":
142             return BgpOrigin.Incomplete;
143         default:
144             throw new IllegalArgumentException("Unhandled origin value " + originStr);
145         }
146     }
147
148     private void resolveValues() {
149         if (this.resolved) {
150             return;
151         }
152
153         final Optional<NormalizedNode<?, ?>> maybeLocalPref = NormalizedNodes.findNode(this.attributes, this.ids.getLocPref());
154         if (maybeLocalPref.isPresent()) {
155             this.localPref = (Long) ((LeafNode<?>)maybeLocalPref.get()).getValue();
156         } else {
157             this.localPref = null;
158         }
159
160         final Optional<NormalizedNode<?, ?>> maybeMultiExitDisc = NormalizedNodes.findNode(this.attributes, this.ids.getMed());
161         if (maybeMultiExitDisc.isPresent()) {
162             this.multiExitDisc = (Long) ((LeafNode<?>)maybeMultiExitDisc.get()).getValue();
163         } else {
164             this.multiExitDisc = null;
165         }
166
167         final Optional<NormalizedNode<?, ?>> maybeOrigin = NormalizedNodes.findNode(this.attributes, this.ids.getOrig());
168         if (maybeOrigin.isPresent()) {
169             this.origin = fromString((String) ((LeafNode<?>)maybeOrigin.get()).getValue());
170         } else {
171             this.origin = null;
172         }
173
174         final Optional<NormalizedNode<?, ?>> maybeSegments = NormalizedNodes.findNode(this.attributes, this.ids.getAsPath());
175         if (maybeSegments.isPresent()) {
176             final UnkeyedListNode segments = (UnkeyedListNode) maybeSegments.get();
177             final List<Segments> segs = extractSegments(segments);
178             if (!segs.isEmpty()) {
179                 this.peerAs = getPeerAs(segs).getValue();
180                 this.asPathLength = countAsPath(segs);
181             }
182         }
183         this.resolved = true;
184     }
185
186     @Override
187     public Long getLocalPref() {
188         resolveValues();
189         return this.localPref;
190     }
191
192     @Override
193     public Long getMultiExitDisc() {
194         resolveValues();
195         return this.multiExitDisc;
196     }
197
198     @Override
199     public BgpOrigin getOrigin() {
200         resolveValues();
201         return this.origin;
202     }
203
204     @Override
205     public Long getPeerAs() {
206         resolveValues();
207         return this.peerAs;
208     }
209
210     @Override
211     public int getAsPathLength() {
212         resolveValues();
213         return this.asPathLength;
214     }
215
216     private static int countAsPath(final List<Segments> segments) {
217         // an AS_SET counts as 1, no matter how many ASs are in the set.
218         int count = 0;
219         boolean setPresent = false;
220         for (final Segments s : segments) {
221             if (s.getAsSet() != null && !setPresent) {
222                 setPresent = true;
223                 count++;
224             } else if (s.getAsSequence() != null) {
225                 count += s.getAsSequence().size();
226             }
227         }
228         return count;
229     }
230
231     private static AsNumber getPeerAs(final List<Segments> segments) {
232         if (segments.isEmpty()) {
233             return new AsNumber(0L);
234         }
235         for (final Segments seg : segments) {
236             if (seg.getAsSequence() != null && !seg.getAsSequence().isEmpty()) {
237                 return segments.get(0).getAsSequence().get(0);
238             }
239         }
240         return new AsNumber(0L);
241     }
242
243     public List<Segments> extractSegments(final UnkeyedListNode segments) {
244         // list segments
245         final List<Segments> extracted = new ArrayList<>();
246         for (final UnkeyedListEntryNode segment : segments.getValue()) {
247             final SegmentsBuilder sb = new SegmentsBuilder();
248             // We are expecting that segment contains either as-sequence or as-set, so just one of them will be set, other would be null
249             sb.setAsSequence(extractAsList(segment, this.ids.getAsSeq())).setAsSet(extractAsList(segment, this.ids.getAsSet()));
250             extracted.add(sb.build());
251         }
252         return extracted;
253     }
254
255     private List<AsNumber> extractAsList(final UnkeyedListEntryNode segment, final NodeIdentifier nid) {
256         final List<AsNumber> ases = new ArrayList<>();
257         final Optional<NormalizedNode<?, ?>> maybeAsList = NormalizedNodes.findNode(segment, nid);
258         if (maybeAsList.isPresent()) {
259             final LeafSetNode<?> list = (LeafSetNode<?>)maybeAsList.get();
260             for (final LeafSetEntryNode<?> as : list.getValue())  {
261                 ases.add(new AsNumber((Long)as.getValue()));
262             }
263             return ases;
264         }
265         return null;
266     }
267
268     @Override
269     public ContainerNode getAttributes() {
270         return this.attributes;
271     }
272
273     private ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
274         toStringHelper.add("attributes", this.attributes);
275         toStringHelper.add("localPref", this.localPref);
276         toStringHelper.add("multiExitDisc", this.multiExitDisc);
277         toStringHelper.add("origin", this.origin);
278         toStringHelper.add("resolved", this.resolved);
279         return toStringHelper;
280     }
281
282     @Override
283     public String toString() {
284         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
285     }
286
287     @Override
288     public int hashCode() {
289         final int prime = 31;
290         int result = 1;
291         result = prime * result + this.attributes.hashCode();
292         result = prime * result + ((this.localPref == null) ? 0 : this.localPref.hashCode());
293         result = prime * result + ((this.multiExitDisc == null) ? 0 : this.multiExitDisc.hashCode());
294         result = prime * result + ((this.origin == null) ? 0 : this.origin.hashCode());
295         return result;
296     }
297
298     @Override
299     public boolean equals(final Object obj) {
300         if (this == obj) {
301             return true;
302         }
303         if (!(obj instanceof BestPathStateImpl)) {
304             return false;
305         }
306         final BestPathStateImpl other = (BestPathStateImpl) obj;
307         if (!this.attributes.equals(other.attributes)) {
308             return false;
309         }
310         if (this.localPref == null) {
311             if (other.localPref != null) {
312                 return false;
313             }
314         } else if (!this.localPref.equals(other.localPref)) {
315             return false;
316         }
317         if (this.multiExitDisc == null) {
318             if (other.multiExitDisc != null) {
319                 return false;
320             }
321         } else if (!this.multiExitDisc.equals(other.multiExitDisc)) {
322             return false;
323         }
324         if (this.origin != other.origin) {
325             return false;
326         }
327         return true;
328     }
329 }