Removed some sonar warnings.
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / LocRibWriter.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.primitives.UnsignedInteger;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import javax.annotation.Nonnull;
19 import javax.annotation.concurrent.NotThreadSafe;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
25 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
28 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
29 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibOut;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
47 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 @NotThreadSafe
52 final class LocRibWriter implements AutoCloseable, DOMDataTreeChangeListener {
53
54     private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
55
56     private final Map<PathArgument, AbstractRouteEntry> routeEntries = new HashMap<>();
57     private final YangInstanceIdentifier locRibTarget;
58     private final DOMTransactionChain chain;
59     private final ExportPolicyPeerTracker peerPolicyTracker;
60     private final NodeIdentifier attributesIdentifier;
61     private final Long ourAs;
62     private final RIBSupport ribSupport;
63     private final NodeIdentifierWithPredicates tableKey;
64     private final RIBSupportContextRegistry registry;
65
66     LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target, final Long ourAs,
67         final DOMDataTreeChangeService service, final PolicyDatabase pd, final TablesKey tablesKey) {
68         this.chain = Preconditions.checkNotNull(chain);
69         this.tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
70         this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(this.tableKey).node(Routes.QNAME).getPathArguments());
71         this.ourAs = Preconditions.checkNotNull(ourAs);
72         this.registry = registry;
73         this.ribSupport = this.registry.getRIBSupportContext(tablesKey).getRibSupport();
74         this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
75         this.peerPolicyTracker = new ExportPolicyPeerTracker(service, target, pd);
76
77         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
78         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget, this.ribSupport.emptyRoutes());
79         tx.submit();
80
81         final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME).node(EffectiveRibIn.QNAME).node(Tables.QNAME).node(this.tableKey);
82         service.registerDataTreeChangeListener(new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId), this);
83     }
84
85     public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain, @Nonnull final YangInstanceIdentifier target,
86         @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final PolicyDatabase pd) {
87         return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, pd, tablesKey);
88     }
89
90     @Override
91     public void close() {
92         this.peerPolicyTracker.close();
93     }
94
95     private AbstractRouteEntry createEntry(final PathArgument routeId) {
96         final AbstractRouteEntry ret = this.ribSupport.isComplexRoute() ? new ComplexRouteEntry() : new SimpleRouteEntry();
97
98         this.routeEntries.put(routeId, ret);
99         LOG.trace("Created new entry for {}", routeId);
100         return ret;
101     }
102
103     @Override
104     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
105         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
106         LOG.trace("Received data change to LocRib {}", Arrays.toString(changes.toArray()));
107         /*
108          * We use two-stage processing here in hopes that we avoid duplicate
109          * calculations when multiple peers have changed a particular entry.
110          */
111         final Map<RouteUpdateKey, AbstractRouteEntry> toUpdate = new HashMap<>();
112         for (final DataTreeCandidate tc : changes) {
113             final YangInstanceIdentifier path = tc.getRootPath();
114             final NodeIdentifierWithPredicates peerKey = IdentifierUtils.peerKey(path);
115             final PeerId peerId = IdentifierUtils.peerId(peerKey);
116             final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
117             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
118                 for (final DataTreeCandidateNode route : this.ribSupport.changedRoutes(child)) {
119                     final PathArgument routeId = route.getIdentifier();
120                     AbstractRouteEntry entry = this.routeEntries.get(routeId);
121
122                     final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
123                     if (maybeData.isPresent()) {
124                         if (entry == null) {
125                             entry = createEntry(routeId);
126                         }
127
128                         entry.addRoute(routerId, this.attributesIdentifier, maybeData.get());
129                     } else if (entry != null && entry.removeRoute(routerId)) {
130                         this.routeEntries.remove(routeId);
131                         entry = null;
132                         LOG.trace("Removed route from {}", routerId);
133                     }
134                     LOG.debug("Updated route {} entry {}", routeId, entry);
135                     toUpdate.put(new RouteUpdateKey(peerId, routeId), entry);
136                 }
137             }
138         }
139
140         // Now walk all updated entries
141         for (final Entry<RouteUpdateKey, AbstractRouteEntry> e : toUpdate.entrySet()) {
142             LOG.trace("Walking through {}", e);
143             final AbstractRouteEntry entry = e.getValue();
144             final NormalizedNode<?, ?> value;
145
146             if (entry != null) {
147                 if (!entry.selectBest(this.ourAs)) {
148                     // Best path has not changed, no need to do anything else. Proceed to next route.
149                     LOG.trace("Continuing");
150                     continue;
151                 }
152                 value = entry.createValue(e.getKey().getRouteId());
153                 LOG.trace("Selected best value {}", value);
154             } else {
155                 value = null;
156             }
157
158             final YangInstanceIdentifier writePath = this.ribSupport.routePath(this.locRibTarget, e.getKey().getRouteId());
159             if (value != null) {
160                 LOG.debug("Write route to LocRib {}", value);
161                 tx.put(LogicalDatastoreType.OPERATIONAL, writePath, value);
162             } else {
163                 LOG.debug("Delete route from LocRib {}", entry);
164                 tx.delete(LogicalDatastoreType.OPERATIONAL, writePath);
165             }
166
167             /*
168              * We need to keep track of routers and populate adj-ribs-out, too. If we do not, we need to
169              * expose from which client a particular route was learned from in the local RIB, and have
170              * the listener perform filtering.
171              *
172              * We walk the policy set in order to minimize the amount of work we do for multiple peers:
173              * if we have two eBGP peers, for example, there is no reason why we should perform the translation
174              * multiple times.
175              */
176             for (final PeerRole role : PeerRole.values()) {
177                 final PeerExportGroup peerGroup = this.peerPolicyTracker.getPeerGroup(role);
178                 if (peerGroup != null) {
179                     final ContainerNode attributes = entry == null ? null : entry.attributes();
180                     final PeerId peerId = e.getKey().getPeerId();
181                     final ContainerNode effectiveAttributes = peerGroup.effectiveAttributes(peerId, attributes);
182                     for (final Entry<PeerId, YangInstanceIdentifier> pid : peerGroup.getPeers()) {
183                         // This points to adj-rib-out for a particular peer/table combination
184                         final RIBSupportContext ribCtx = this.registry.getRIBSupportContext(this.tableKey);
185                         // FIXME: the table should be created for a peer only once
186                         ribCtx.clearTable(tx, pid.getValue().node(AdjRibOut.QNAME).node(Tables.QNAME).node(this.tableKey));
187                         final YangInstanceIdentifier routeTarget = this.ribSupport.routePath(pid.getValue().node(AdjRibOut.QNAME).node(Tables.QNAME).node(this.tableKey).node(Routes.QNAME), e.getKey().getRouteId());
188                         if (effectiveAttributes != null && value != null && !peerId.equals(pid.getKey())) {
189                             LOG.debug("Write route to AdjRibsOut {}", value);
190                             tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget, value);
191                             tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget.node(this.attributesIdentifier), effectiveAttributes);
192                         } else {
193                             LOG.trace("Removing {} from transaction", routeTarget);
194                             tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
195                         }
196                     }
197                 }
198             }
199         }
200         tx.submit();
201     }
202 }