Replace Preconditions.CheckNotNull per RequireNonNull
[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.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.LeafSetEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
41 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 @NotThreadSafe
47 public final class BestPathStateImpl implements BestPathState {
48     private static final class NamespaceSpecificIds {
49         private final Collection<PathArgument> asPath;
50         private final Collection<PathArgument> locPref;
51         private final Collection<PathArgument> med;
52         private final Collection<PathArgument> orig;
53         private final NodeIdentifier asSetNid;
54         private final NodeIdentifier asSeqNid;
55
56         NamespaceSpecificIds(final QName namespace) {
57             NodeIdentifier container = new NodeIdentifier(QName.create(namespace, AsPath.QNAME.getLocalName().intern()));
58             NodeIdentifier leaf = new NodeIdentifier(QName.create(namespace, "segments").intern());
59             this.asPath = ImmutableList.of(container, leaf);
60
61             container = new NodeIdentifier(QName.create(namespace, LocalPref.QNAME.getLocalName()).intern());
62             leaf = new NodeIdentifier(QName.create(namespace, "pref").intern());
63             this.locPref = ImmutableList.of(container, leaf);
64
65             container = new NodeIdentifier(QName.create(namespace, MultiExitDisc.QNAME.getLocalName()).intern());
66             leaf = new NodeIdentifier(QName.create(namespace, "med").intern());
67             this.med = ImmutableList.of(container, leaf);
68
69             container = new NodeIdentifier(QName.create(namespace, Origin.QNAME.getLocalName()).intern());
70             leaf = new NodeIdentifier(QName.create(namespace, "value").intern());
71             this.orig = ImmutableList.of(container, leaf);
72
73             this.asSetNid = new NodeIdentifier(QName.create(namespace, "as-set").intern());
74             this.asSeqNid = new NodeIdentifier(QName.create(namespace, "as-sequence").intern());
75         }
76
77         Collection<PathArgument> getAsPath() {
78             return this.asPath;
79         }
80
81         Collection<PathArgument> getLocPref() {
82             return this.locPref;
83         }
84
85         Collection<PathArgument> getMed() {
86             return this.med;
87         }
88
89         Collection<PathArgument> getOrig() {
90             return this.orig;
91         }
92
93         NodeIdentifier getAsSet() {
94             return this.asSetNid;
95         }
96
97         NodeIdentifier getAsSeq() {
98             return this.asSeqNid;
99         }
100     }
101
102     private static final Logger LOG = LoggerFactory.getLogger(BestPathStateImpl.class);
103     private static final Cache<QNameModule, NamespaceSpecificIds> PATH_CACHE = CacheBuilder.newBuilder().weakKeys().weakValues().build();
104
105     private long peerAs = 0L;
106     private int asPathLength = 0;
107
108     private final ContainerNode attributes;
109     private final NamespaceSpecificIds ids;
110     private Long localPref;
111     private Long multiExitDisc;
112     private BgpOrigin origin;
113     private boolean resolved;
114
115     public BestPathStateImpl(final ContainerNode attributes) {
116         final NamespaceSpecificIds col;
117         try {
118             col = PATH_CACHE.get(attributes.getNodeType().getModule(), () -> new NamespaceSpecificIds(attributes.getNodeType()));
119         } catch (final ExecutionException e) {
120             LOG.error("Error creating namespace-specific attributes collection.", e);
121             throw new IllegalStateException("Error creating namespace-specific attributes collection.", e);
122         }
123
124         this.attributes = requireNonNull(attributes);
125         this.ids = col;
126         resolveValues();
127     }
128
129     private static BgpOrigin fromString(final String originStr) {
130         switch (originStr) {
131         case "igp":
132             return BgpOrigin.Igp;
133         case "egp":
134             return BgpOrigin.Egp;
135         case "incomplete":
136             return BgpOrigin.Incomplete;
137         default:
138             throw new IllegalArgumentException("Unhandled origin value " + originStr);
139         }
140     }
141
142     private void resolveValues() {
143         if (this.resolved) {
144             return;
145         }
146
147         final Optional<NormalizedNode<?, ?>> maybeLocalPref = NormalizedNodes.findNode(this.attributes, this.ids.getLocPref());
148         if (maybeLocalPref.isPresent()) {
149             this.localPref = (Long) maybeLocalPref.get().getValue();
150         } else {
151             this.localPref = null;
152         }
153
154         final Optional<NormalizedNode<?, ?>> maybeMultiExitDisc = NormalizedNodes.findNode(this.attributes, this.ids.getMed());
155         if (maybeMultiExitDisc.isPresent()) {
156             this.multiExitDisc = (Long) maybeMultiExitDisc.get().getValue();
157         } else {
158             this.multiExitDisc = null;
159         }
160
161         final Optional<NormalizedNode<?, ?>> maybeOrigin = NormalizedNodes.findNode(this.attributes, this.ids.getOrig());
162         if (maybeOrigin.isPresent()) {
163             this.origin = fromString((String) maybeOrigin.get().getValue());
164         } else {
165             this.origin = null;
166         }
167
168         final Optional<NormalizedNode<?, ?>> maybeSegments = NormalizedNodes.findNode(this.attributes, this.ids.getAsPath());
169         if (maybeSegments.isPresent()) {
170             final UnkeyedListNode segments = (UnkeyedListNode) maybeSegments.get();
171             final List<Segments> segs = extractSegments(segments);
172             if (!segs.isEmpty()) {
173                 this.peerAs = getPeerAs(segs).getValue();
174                 this.asPathLength = countAsPath(segs);
175             }
176         }
177         this.resolved = true;
178     }
179
180     @Override
181     public Long getLocalPref() {
182         resolveValues();
183         return this.localPref;
184     }
185
186     @Override
187     public Long getMultiExitDisc() {
188         resolveValues();
189         return this.multiExitDisc;
190     }
191
192     @Override
193     public BgpOrigin getOrigin() {
194         resolveValues();
195         return this.origin;
196     }
197
198     @Override
199     public Long getPeerAs() {
200         resolveValues();
201         return this.peerAs;
202     }
203
204     @Override
205     public int getAsPathLength() {
206         resolveValues();
207         return this.asPathLength;
208     }
209
210     private static int countAsPath(final List<Segments> segments) {
211         // an AS_SET counts as 1, no matter how many ASs are in the set.
212         int count = 0;
213         boolean setPresent = false;
214         for (final Segments s : segments) {
215             if (s.getAsSet() != null && !setPresent) {
216                 setPresent = true;
217                 count++;
218             } else if (s.getAsSequence() != null) {
219                 count += s.getAsSequence().size();
220             }
221         }
222         return count;
223     }
224
225     private static AsNumber getPeerAs(final List<Segments> segments) {
226         if (segments.isEmpty()) {
227             return new AsNumber(0L);
228         }
229         for (final Segments seg : segments) {
230             if (seg.getAsSequence() != null && !seg.getAsSequence().isEmpty()) {
231                 return segments.get(0).getAsSequence().get(0);
232             }
233         }
234         return new AsNumber(0L);
235     }
236
237     public List<Segments> extractSegments(final UnkeyedListNode segments) {
238         // list segments
239         final List<Segments> extracted = new ArrayList<>();
240         for (final UnkeyedListEntryNode segment : segments.getValue()) {
241             final SegmentsBuilder sb = new SegmentsBuilder();
242             // We are expecting that segment contains either as-sequence or as-set, so just one of them will be set, other would be null
243             sb.setAsSequence(extractAsList(segment, this.ids.getAsSeq())).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 }