BUG-2823: Simplify AS_PATH encoding
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AttributeOperations.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.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableSet;
16 import java.util.Iterator;
17 import org.opendaylight.protocol.util.Values;
18 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.AsPath;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.ClusterId;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.Communities;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.ExtendedCommunities;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.Origin;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.OriginatorId;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.UnrecognizedAttributes;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.as.path.Segments;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.CNextHop;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.QNameModule;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
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.opendaylight.yangtools.yang.data.impl.schema.Builders;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
48 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * Utility class for working with route attributes in binding independent form. An instance
54  * is always bound to a certain namespace, so it maintains cached attribute identifiers.
55  */
56 final class AttributeOperations {
57     private static final Logger LOG = LoggerFactory.getLogger(AttributeOperations.class);
58     private static final LoadingCache<QNameModule, AttributeOperations> ATTRIBUTES_CACHE = CacheBuilder.newBuilder().weakKeys().weakValues().build(
59         new CacheLoader<QNameModule, AttributeOperations>() {
60             @Override
61             public AttributeOperations load(final QNameModule key) throws Exception {
62                 return new AttributeOperations(key);
63             }
64         });
65     private static final LoadingCache<QNameModule, ImmutableSet<QName>> TRANSITIVE_CACHE = CacheBuilder.newBuilder()
66         .weakKeys()
67         .weakValues().build(
68             new CacheLoader<QNameModule, ImmutableSet<QName>>() {
69                 @Override
70                 public ImmutableSet<QName> load(final QNameModule key) {
71                     return ImmutableSet.of(QName.cachedReference(QName.create(key, Origin.QNAME.getLocalName())),
72                         QName.cachedReference(QName.create(key, AsPath.QNAME.getLocalName())),
73                         QName.cachedReference(QName.create(key, CNextHop.QNAME.getLocalName())),
74                         QName.cachedReference(QName.create(key, Communities.QNAME.getLocalName())),
75                         QName.cachedReference(QName.create(key, ExtendedCommunities.QNAME.getLocalName())));
76                 }
77             });
78     private final ImmutableSet<QName> transitiveCollection;
79     private final Iterable<PathArgument> originatorIdPath;
80     private final Iterable<PathArgument> clusterListPath;
81     private final NodeIdentifier originatorIdContainer;
82     private final NodeIdentifier originatorIdLeaf;
83     private final NodeIdentifier clusterListContainer;
84     private final NodeIdentifier clusterListLeaf;
85     private final NodeIdentifier asPathContainer;
86     private final NodeIdentifier asPathSegments;
87     private final NodeIdentifier asPathSequence;
88     private final QName asNumberQname;
89     private final NodeIdentifier transitiveLeaf;
90
91     private AttributeOperations(final QNameModule namespace) {
92         this.asPathContainer = new NodeIdentifier(QName.cachedReference(QName.create(namespace, AsPath.QNAME.getLocalName())));
93         this.asPathSegments = new NodeIdentifier(QName.cachedReference(QName.create(namespace, Segments.QNAME.getLocalName())));
94         this.asPathSequence = new NodeIdentifier(QName.cachedReference(QName.create(namespace, "as-sequence")));
95         this.asNumberQname = QName.cachedReference(QName.create(namespace, "as-number"));
96
97         this.clusterListContainer = new NodeIdentifier(QName.cachedReference(QName.create(namespace, ClusterId.QNAME.getLocalName())));
98         this.clusterListLeaf = new NodeIdentifier(QName.cachedReference(QName.create(namespace, "cluster")));
99         this.clusterListPath = ImmutableList.<PathArgument>of(this.clusterListContainer, this.clusterListLeaf);
100         this.originatorIdContainer = new NodeIdentifier(QName.cachedReference(QName.create(namespace, OriginatorId.QNAME.getLocalName())));
101         this.originatorIdLeaf = new NodeIdentifier(QName.cachedReference(QName.create(namespace, "originator")));
102         this.originatorIdPath = ImmutableList.<PathArgument>of(this.originatorIdContainer, this.originatorIdLeaf);
103
104         this.transitiveLeaf = new NodeIdentifier(QName.cachedReference(QName.create(UnrecognizedAttributes.QNAME, "transitive")));
105         this.transitiveCollection = TRANSITIVE_CACHE.getUnchecked(namespace);
106     }
107
108     static AttributeOperations getInstance(final ContainerNode attributes) {
109         return ATTRIBUTES_CACHE.getUnchecked(attributes.getNodeType().getModule());
110     }
111
112     private LeafSetNode<?> reusableSegment(final UnkeyedListEntryNode segment) {
113         final Optional<NormalizedNode<?, ?>> maybeAsSequence = NormalizedNodes.findNode(segment, this.asPathSequence);
114         if (maybeAsSequence.isPresent()) {
115             final LeafSetNode<?> asList = (LeafSetNode<?>) maybeAsSequence.get();
116             if (asList.getValue().size() < Values.UNSIGNED_BYTE_MAX_VALUE) {
117                 return asList;
118             }
119         }
120         return null;
121     }
122
123     ContainerNode exportedAttributes(final ContainerNode attributes, final Long localAs) {
124         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders.containerBuilder();
125         containerBuilder.withNodeIdentifier(attributes.getIdentifier());
126
127         // First filter out non-transitive attributes
128         // FIXME: removes MULTI_EXIT_DISC, too.
129         spliceTransitives(containerBuilder, attributes);
130
131         final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> segmentsBuilder = Builders.unkeyedListBuilder();
132         segmentsBuilder.withNodeIdentifier(this.asPathSegments);
133
134         final Optional<NormalizedNode<?, ?>> maybeOldAsSegments = NormalizedNodes.findNode(attributes, this.asPathContainer, this.asPathSegments);
135         if (maybeOldAsSegments.isPresent() && !((UnkeyedListNode) maybeOldAsSegments.get()).getValue().isEmpty()) {
136
137             /*
138              * We need to check the first segment.
139              * If it has as-set then new as-sequence with local AS is prepended.
140              * If it has as-sequence, we may add local AS when it has less than 255 elements.
141              * Otherwise we need to create new as-sequence for local AS.
142              */
143
144             final ListNodeBuilder<Object,LeafSetEntryNode<Object>> asSequenceBuilder = Builders.orderedLeafSetBuilder();
145             // add local AS
146             asSequenceBuilder.withNodeIdentifier(this.asPathSequence).addChild(Builders.leafSetEntryBuilder().withNodeIdentifier(new NodeWithValue(this.asNumberQname, localAs)).withValue(localAs).build());
147
148             final Iterator<UnkeyedListEntryNode> oldAsSegments = ((UnkeyedListNode) maybeOldAsSegments.get()).getValue().iterator();
149             final UnkeyedListEntryNode firstSegment = oldAsSegments.next();
150             final LeafSetNode<?> reusableAsSeq = reusableSegment(firstSegment);
151             // first segment contains as-sequence with less then 255 elements and it's append to local AS
152             if (reusableAsSeq != null) {
153                 for (final LeafSetEntryNode<?> child : reusableAsSeq.getValue())  {
154                     asSequenceBuilder.withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(new NodeWithValue(this.asNumberQname, child.getValue())).withValue(child.getValue()).build());
155                 }
156             }
157             // Add the new first segment
158             segmentsBuilder.withChild(Builders.unkeyedListEntryBuilder().withNodeIdentifier(this.asPathSegments).withChild(asSequenceBuilder.build()).build());
159
160             // When first segment contains as-set or full as-sequence, append it
161             if (reusableAsSeq == null) {
162                 segmentsBuilder.withChild(firstSegment);
163             }
164
165             // Add all subsequent segments
166             while (oldAsSegments.hasNext()) {
167                 segmentsBuilder.withChild(oldAsSegments.next());
168             }
169         } else {
170             // Segments are completely empty, create a completely new AS_PATH container with
171             // a single entry
172             segmentsBuilder.withChild(Builders.unkeyedListEntryBuilder().withNodeIdentifier(this.asPathSegments).withChild(
173                 Builders.orderedLeafSetBuilder().withNodeIdentifier(this.asPathSequence).addChild(
174                     Builders.leafSetEntryBuilder().withNodeIdentifier(new NodeWithValue(this.asNumberQname, localAs)).withValue(localAs).build()).build()).build());
175         }
176
177         containerBuilder.withChild(Builders.containerBuilder().withNodeIdentifier(this.asPathContainer).withChild(segmentsBuilder.build()).build());
178         return containerBuilder.build();
179     }
180
181     // Attributes when reflecting a route
182     ContainerNode reflectedAttributes(final ContainerNode attributes, final Ipv4Address originatorId, final ClusterIdentifier clusterId) {
183         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> b = Builders.containerBuilder(attributes);
184
185         // Create a new CLUSTER_LIST builder
186         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> clb = Builders.orderedLeafSetBuilder();
187         clb.withNodeIdentifier(this.clusterListLeaf);
188
189         // prepend local CLUSTER_ID
190         clb.withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(new NodeWithValue(ClusterId.QNAME, clusterId)).withValue(clusterId).build());
191
192         // if there was a CLUSTER_LIST attribute, add all other entries
193         final Optional<NormalizedNode<?, ?>> maybeClusterList = NormalizedNodes.findNode(attributes, this.clusterListPath);
194         if (maybeClusterList.isPresent()) {
195             final NormalizedNode<?, ?> clusterList = maybeClusterList.get();
196             if (clusterList instanceof LeafSetNode) {
197                 for (final LeafSetEntryNode<?> n : ((LeafSetNode<?>)clusterList).getValue()) {
198                     // There's no way we can safely avoid this cast
199                     @SuppressWarnings("unchecked")
200                     final LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)n;
201                     clb.addChild(child);
202                 }
203             } else {
204                 LOG.warn("Ignoring malformed CLUSTER_LIST {}", clusterList);
205             }
206         } else {
207             LOG.debug("Creating fresh CLUSTER_LIST attribute");
208         }
209
210         // Now wrap it in a container and add it to attributes
211         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> cb = Builders.containerBuilder();
212         cb.withNodeIdentifier(this.clusterListContainer);
213         cb.withChild(clb.build());
214         b.withChild(cb.build());
215
216         // add ORIGINATOR_ID if not present
217         final Optional<NormalizedNode<?, ?>> maybeOriginatorId = NormalizedNodes.findNode(attributes, this.originatorIdPath);
218         if (!maybeOriginatorId.isPresent()) {
219             final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> oib = Builders.containerBuilder();
220             oib.withNodeIdentifier(this.originatorIdContainer);
221             oib.withChild(ImmutableNodes.leafNode(this.originatorIdLeaf, originatorId.getValue()));
222             b.withChild(oib.build());
223         }
224
225         return b.build();
226     }
227
228     private boolean isTransitiveAttribute(final DataContainerChild<? extends PathArgument, ?> child) {
229         if (child.getIdentifier() instanceof AugmentationIdentifier) {
230             final AugmentationIdentifier ai = (AugmentationIdentifier) child.getIdentifier();
231             for (final QName name : ai.getPossibleChildNames()) {
232                 LOG.trace("Augmented QNAME {}", name);
233                 if (this.transitiveCollection.contains(name)) {
234                     return true;
235                 }
236             }
237             return false;
238         }
239         if (this.transitiveCollection.contains(child.getNodeType())) {
240             return true;
241         }
242         if (UnrecognizedAttributes.QNAME.equals(child.getNodeType())) {
243             final Optional<NormalizedNode<?, ?>> maybeTransitive = NormalizedNodes.findNode(child, this.transitiveLeaf);
244             if (maybeTransitive.isPresent()) {
245                 return (Boolean) maybeTransitive.get().getValue();
246             }
247         }
248         return false;
249     }
250
251     private boolean spliceTransitives(final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> target, final ContainerNode attributes) {
252         // We want to reuse attributes as much as possible, so the result of the loop
253         // indicates whether we performed a modification. If we have not modified the
254         // attributes, we can reuse them.
255         boolean ret = false;
256         for (final DataContainerChild<? extends PathArgument, ?> child : attributes.getValue()) {
257             if (isTransitiveAttribute(child)) {
258                 target.withChild(child);
259             } else {
260                 ret = true;
261             }
262         }
263
264         return ret;
265     }
266
267     /**
268      * Filter out all non-transitive attributes.
269      *
270      * @param attributes Input attributes
271      * @return Output attributes, transitive only.
272      */
273     ContainerNode transitiveAttributes(final ContainerNode attributes) {
274         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
275         b.withNodeIdentifier(attributes.getIdentifier());
276
277         final boolean modified = spliceTransitives(b, attributes);
278         return modified ? b.build() : attributes;
279     }
280
281     LeafSetNode<?> getClusterList(final ContainerNode attributes) {
282         final Optional<NormalizedNode<?, ?>> maybeClusterList = NormalizedNodes.findNode(attributes, this.clusterListPath);
283         if (maybeClusterList.isPresent()) {
284             final NormalizedNode<?, ?> clusterList = maybeClusterList.get();
285             if (clusterList instanceof LeafSetNode) {
286                 return (LeafSetNode<?>) clusterList;
287             }
288
289             LOG.warn("Unexpected CLUSTER_LIST node {}, ignoring it", clusterList);
290         }
291
292         return null;
293     }
294
295     Object getOriginatorId(final ContainerNode attributes) {
296         final Optional<NormalizedNode<?, ?>> maybeOriginatorId = NormalizedNodes.findNode(attributes, this.originatorIdPath);
297         if (!maybeOriginatorId.isPresent()) {
298             LOG.debug("No ORIGINATOR_ID present");
299             return null;
300         }
301
302         final NormalizedNode<?, ?> originatorId = maybeOriginatorId.get();
303         if (originatorId instanceof LeafNode) {
304             return ((LeafNode<?>) originatorId).getValue();
305         }
306
307         LOG.warn("Unexpected ORIGINATOR_ID node {}, ignoring it", originatorId);
308         return null;
309     }
310 }