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