2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.protocol.bmp.impl.app;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.Preconditions;
14 import com.google.common.net.InetAddresses;
15 import java.util.HashMap;
16 import java.util.Iterator;
17 import java.util.List;
19 import java.util.Optional;
20 import javax.annotation.concurrent.GuardedBy;
21 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
28 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
30 import org.opendaylight.protocol.bgp.rib.spi.RIBExtensionConsumerContext;
31 import org.opendaylight.protocol.bmp.api.BmpSession;
32 import org.opendaylight.protocol.bmp.impl.spi.BmpRouter;
33 import org.opendaylight.protocol.bmp.impl.spi.BmpRouterPeer;
34 import org.opendaylight.protocol.util.Ipv4Util;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenMessage;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.InitiationMessage;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.PeerDownNotification;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.PeerHeader;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.PeerUpNotification;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev150512.string.informations.StringInformation;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev150512.RouterId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev150512.peers.Peer;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev150512.routers.Router;
45 import org.opendaylight.yangtools.yang.binding.Notification;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class BmpRouterImpl implements BmpRouter, TransactionChainListener {
56 private static final Logger LOG = LoggerFactory.getLogger(BmpRouterImpl.class);
58 private static final QName ROUTER_ID_QNAME = QName.create(Router.QNAME, "router-id").intern();
59 private static final QName ROUTER_STATUS_QNAME = QName.create(Router.QNAME, "status").intern();
60 private static final QName ROUTER_NAME_QNAME = QName.create(Router.QNAME, "name").intern();
61 private static final QName ROUTER_DESCRIPTION_QNAME = QName.create(Router.QNAME, "description").intern();
62 private static final QName ROUTER_INFO_QNAME = QName.create(Router.QNAME, "info").intern();
63 private static final String UP = "up";
64 private static final String DOWN = "down";
66 private final RouterSessionManager sessionManager;
68 private final Map<PeerId, BmpRouterPeer> peers = new HashMap<>();
69 private final DOMTransactionChain domTxChain;
70 private final DOMDataBroker domDataBroker;
71 private final RIBExtensionConsumerContext extensions;
72 private final BindingCodecTree tree;
73 private BmpSession session;
74 private RouterId routerId;
75 private String routerIp;
76 private YangInstanceIdentifier routerYangIId;
77 private YangInstanceIdentifier peersYangIId;
79 public BmpRouterImpl(final RouterSessionManager sessionManager) {
80 this.sessionManager = requireNonNull(sessionManager);
81 this.domDataBroker = sessionManager.getDomDataBroker();
82 this.domTxChain = this.domDataBroker.createTransactionChain(this);
83 this.extensions = sessionManager.getExtensions();
84 this.tree = sessionManager.getCodecTree();
88 public void onSessionUp(final BmpSession session) {
89 this.session = session;
90 this.routerIp = InetAddresses.toAddrString(this.session.getRemoteAddress());
91 this.routerId = new RouterId(Ipv4Util.getIpAddress(this.session.getRemoteAddress()));
92 // check if this session is redundant
93 if (!this.sessionManager.addSessionListener(this)) {
94 LOG.warn("Redundant BMP session with remote router {} ({}) detected. This BMP session will be abandoned.",
95 this.routerIp, this.session);
98 this.routerYangIId = YangInstanceIdentifier.builder(this.sessionManager.getRoutersYangIId())
99 .nodeWithKey(Router.QNAME, ROUTER_ID_QNAME, this.routerIp).build();
100 this.peersYangIId = YangInstanceIdentifier.builder(this.routerYangIId).node(Peer.QNAME).build();
102 LOG.info("BMP session with remote router {} ({}) is up now.", this.routerIp, this.session);
107 public void onSessionDown(final Exception e) {
108 // we want to tear down as we want to do clean up like closing the transaction chain, etc.
109 // even when datastore is not writable (routerYangIId == null / redundant session)
114 public void onMessage(final Notification message) {
115 if (message instanceof InitiationMessage) {
116 onInitiate((InitiationMessage) message);
117 } else if (message instanceof PeerUpNotification) {
118 onPeerUp((PeerUpNotification) message);
119 } else if (message instanceof PeerHeader) {
120 delegateToPeer(message);
125 public RouterId getRouterId() {
126 return this.routerId;
130 public synchronized void close() {
131 if (this.session != null) {
133 this.session.close();
134 } catch (final Exception e) {
135 LOG.error("Fail to close session.", e);
141 private synchronized void tearDown() {
142 // the session has been teared down before
143 if (this.session == null) {
146 // we want to display remote router's IP here, as sometimes this.session.close() is already
147 // invoked before tearDown(), and session channel is null in this case, which leads to unuseful
149 LOG.info("BMP Session with remote router {} ({}) went down.", this.routerIp, this.session);
151 final Iterator<BmpRouterPeer> it = this.peers.values().iterator();
153 while (it.hasNext()) {
157 this.domTxChain.close();
158 } catch(final Exception e) {
159 LOG.error("Failed to properly close BMP application.", e);
161 // remove session only when session is valid, otherwise
162 // we would remove the original valid session when a redundant connection happens
163 // as the routerId is the same for both connection
164 if (isDatastoreWritable()) {
166 // it means the session was closed before it was written to datastore
167 final DOMDataWriteTransaction wTx = this.domDataBroker.newWriteOnlyTransaction();
168 wTx.delete(LogicalDatastoreType.OPERATIONAL, this.routerYangIId);
169 wTx.submit().checkedGet();
170 } catch (final TransactionCommitFailedException e) {
171 LOG.error("Failed to remove BMP router data from DS.", e);
173 this.sessionManager.removeSessionListener(this);
179 public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
180 final Throwable cause) {
181 LOG.error("Transaction chain failed.", cause);
185 public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
186 LOG.debug("Transaction chain {} successfully.", chain);
189 private boolean isDatastoreWritable() {
190 return (this.routerYangIId != null);
193 private synchronized void createRouterEntry() {
194 Preconditions.checkState(isDatastoreWritable());
195 final DOMDataWriteTransaction wTx = this.domTxChain.newWriteOnlyTransaction();
196 wTx.put(LogicalDatastoreType.OPERATIONAL, this.routerYangIId,
197 Builders.mapEntryBuilder()
198 .withNodeIdentifier(new NodeIdentifierWithPredicates(Router.QNAME, ROUTER_ID_QNAME, this.routerIp))
199 .withChild(ImmutableNodes.leafNode(ROUTER_ID_QNAME, this.routerIp))
200 .withChild(ImmutableNodes.leafNode(ROUTER_STATUS_QNAME, DOWN))
201 .withChild(ImmutableNodes.mapNodeBuilder(Peer.QNAME).build()).build());
205 private synchronized void onInitiate(final InitiationMessage initiation) {
206 Preconditions.checkState(isDatastoreWritable());
207 final DOMDataWriteTransaction wTx = this.domTxChain.newWriteOnlyTransaction();
208 wTx.merge(LogicalDatastoreType.OPERATIONAL, this.routerYangIId,
209 Builders.mapEntryBuilder()
210 .withNodeIdentifier(new NodeIdentifierWithPredicates(Router.QNAME, ROUTER_ID_QNAME, this.routerIp))
211 .withChild(ImmutableNodes.leafNode(ROUTER_NAME_QNAME, initiation.getTlvs().getNameTlv().getName()))
212 .withChild(ImmutableNodes.leafNode(ROUTER_DESCRIPTION_QNAME, initiation.getTlvs().getDescriptionTlv().getDescription()))
213 .withChild(ImmutableNodes.leafNode(ROUTER_INFO_QNAME, getStringInfo(initiation.getTlvs().getStringInformation())))
214 .withChild(ImmutableNodes.leafNode(ROUTER_STATUS_QNAME, UP)).build());
218 private void onPeerUp(final PeerUpNotification peerUp) {
219 final PeerId peerId = getPeerIdFromOpen(peerUp.getReceivedOpen());
220 if (!getPeer(peerId).isPresent()) {
221 final BmpRouterPeer peer = BmpRouterPeerImpl.createRouterPeer(this.domTxChain, this.peersYangIId, peerUp,
222 this.extensions, this.tree, peerId);
223 this.peers.put(peerId, peer);
224 LOG.debug("Router {}: Peer {} goes up.", this.routerIp, peerId.getValue());
226 LOG.debug("Peer: {} for Router: {} already exists.", peerId.getValue(), this.routerIp);
230 private void delegateToPeer(final Notification perPeerMessage) {
231 final PeerId peerId = getPeerId((PeerHeader) perPeerMessage);
232 final Optional<BmpRouterPeer> maybePeer = getPeer(peerId);
233 if (maybePeer.isPresent()) {
234 maybePeer.get().onPeerMessage(perPeerMessage);
235 if (perPeerMessage instanceof PeerDownNotification) {
236 this.peers.remove(peerId);
237 LOG.debug("Router {}: Peer {} removed.", this.routerIp, peerId.getValue());
240 LOG.debug("Peer: {} for Router: {} was not found.", peerId.getValue(), this.routerIp);
244 private Optional<BmpRouterPeer> getPeer(final PeerId peerId) {
245 return Optional.ofNullable(this.peers.get(peerId));
248 private static PeerId getPeerId(final PeerHeader peerHeader) {
249 return new PeerId(peerHeader.getPeerHeader().getBgpId().getValue());
252 private static PeerId getPeerIdFromOpen(final OpenMessage open) {
253 return new PeerId(open.getBgpIdentifier().getValue());
256 private static String getStringInfo(final List<StringInformation> info) {
257 final StringBuilder builder = new StringBuilder();
259 for (final StringInformation string : info) {
260 if (string.getStringTlv() != null) {
261 builder.append(string.getStringTlv().getStringInfo());
266 return builder.toString();