2 * Copyright (c) 2014 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.bgp.rib.impl;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Maps;
14 import com.google.common.net.InetAddresses;
15 import com.google.common.primitives.UnsignedInts;
16 import java.net.Inet4Address;
17 import java.net.Inet6Address;
18 import java.net.InetAddress;
19 import java.net.InetSocketAddress;
20 import java.net.SocketAddress;
22 import javax.annotation.concurrent.GuardedBy;
23 import javax.annotation.concurrent.ThreadSafe;
24 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
25 import org.opendaylight.protocol.bgp.parser.BGPError;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
28 import org.opendaylight.protocol.bgp.rib.impl.spi.ReusableBGPPeer;
29 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
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.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * BGP peer registry that allows only 1 session per BGP peer.
39 * If second session with peer is established, one of the sessions will be dropped.
40 * The session with lower source BGP id will be dropped.
43 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
45 private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
47 // TODO remove backwards compatibility
48 public static final StrictBGPPeerRegistry GLOBAL = new StrictBGPPeerRegistry();
51 private final Map<IpAddress, ReusableBGPPeer> peers = Maps.newHashMap();
53 private final Map<IpAddress, BGPSessionId> sessionIds = Maps.newHashMap();
55 private final Map<IpAddress, BGPSessionPreferences> peerPreferences = Maps.newHashMap();
58 public synchronized void addPeer(final IpAddress ip, final ReusableBGPPeer peer, final BGPSessionPreferences preferences) {
59 Preconditions.checkNotNull(ip);
60 Preconditions.checkArgument(!this.peers.containsKey(ip), "Peer for %s already present", ip);
61 this.peers.put(ip, Preconditions.checkNotNull(peer));
62 Preconditions.checkNotNull(preferences.getMyAs());
63 Preconditions.checkNotNull(preferences.getHoldTime());
64 Preconditions.checkNotNull(preferences.getParams());
65 Preconditions.checkNotNull(preferences.getBgpId());
66 this.peerPreferences.put(ip, preferences);
70 public synchronized void removePeer(final IpAddress ip) {
71 Preconditions.checkNotNull(ip);
72 this.peers.remove(ip);
76 public synchronized void removePeerSession(final IpAddress ip) {
77 Preconditions.checkNotNull(ip);
78 this.sessionIds.remove(ip);
82 public boolean isPeerConfigured(final IpAddress ip) {
83 Preconditions.checkNotNull(ip);
84 return this.peers.containsKey(ip);
87 private void checkPeerConfigured(final IpAddress ip) {
88 Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, this.peers.keySet());
92 public synchronized BGPSessionListener getPeer(final IpAddress ip, final Ipv4Address sourceId,
93 final Ipv4Address remoteId, final AsNumber asNumber) throws BGPDocumentedException {
94 Preconditions.checkNotNull(ip);
95 Preconditions.checkNotNull(sourceId);
96 Preconditions.checkNotNull(remoteId);
97 Preconditions.checkNotNull(asNumber);
99 checkPeerConfigured(ip);
101 final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId, asNumber);
102 final BGPSessionListener p = this.peers.get(ip);
104 final BGPSessionId previousConnection = this.sessionIds.get(ip);
106 if (previousConnection != null) {
108 LOG.warn("Duplicate BGP session established with {}", ip);
110 // Session reestablished with different ids
111 if (!previousConnection.equals(currentConnection)) {
112 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
113 throw new BGPDocumentedException(
114 String.format("BGP session with %s %s has to be dropped. Same session already present %s",
115 ip, currentConnection, previousConnection),
118 // Session reestablished with lower source bgp id, dropping current
119 } else if (previousConnection.isHigherDirection(currentConnection)) {
120 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
121 throw new BGPDocumentedException(
122 String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
123 ip, currentConnection),
126 // Session reestablished with higher source bgp id, dropping previous
127 } else if (currentConnection.isHigherDirection(previousConnection)) {
128 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
129 this.peers.get(ip).releaseConnection();
130 return this.peers.get(ip);
132 } else if (previousConnection.hasHigherAsNumber(currentConnection)) {
133 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
134 throw new BGPDocumentedException(
135 String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
136 ip, currentConnection),
138 } else if (currentConnection.hasHigherAsNumber(previousConnection)) {
139 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
140 this.peers.get(ip).releaseConnection();
141 return this.peers.get(ip);
142 // Session reestablished with same source bgp id, dropping current as duplicate
144 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
145 throw new BGPDocumentedException(
146 String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
147 ip, currentConnection),
151 if (!getPeerPreferences(ip).getMyAs().equals(asNumber)) {
152 LOG.warn("Unexpected remote AS number. Expecting {}, got {}", asNumber, getPeerPreferences(ip).getMyAs());
153 throw new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS);
157 // Map session id to peer IP address
158 this.sessionIds.put(ip, currentConnection);
163 public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
164 Preconditions.checkNotNull(ip);
165 checkPeerConfigured(ip);
166 return this.peerPreferences.get(ip);
170 * Creates IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
172 * @param socketAddress socket address to transform
173 * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
175 public static IpAddress getIpAddress(final SocketAddress socketAddress) {
176 Preconditions.checkNotNull(socketAddress);
177 Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
178 final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
180 if(inetAddress instanceof Inet4Address) {
181 return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
182 } else if(inetAddress instanceof Inet6Address) {
183 return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
186 throw new IllegalArgumentException("Expecting " + Inet4Address.class + " or " + Inet6Address.class + " but was " + inetAddress.getClass());
190 public synchronized void close() {
192 this.sessionIds.clear();
196 public String toString() {
197 return MoreObjects.toStringHelper(this)
198 .add("peers", this.peers.keySet())
203 * Session identifier that contains (source Bgp Id) -> (destination Bgp Id)
205 private static final class BGPSessionId {
207 private final Ipv4Address from, to;
208 private final AsNumber asNumber;
210 BGPSessionId(final Ipv4Address from, final Ipv4Address to, final AsNumber asNumber) {
211 this.from = Preconditions.checkNotNull(from);
212 this.to = Preconditions.checkNotNull(to);
213 this.asNumber = Preconditions.checkNotNull(asNumber);
217 * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
220 public boolean equals(final Object o) {
224 if (o == null || getClass() != o.getClass()) {
228 final BGPSessionId bGPSessionId = (BGPSessionId) o;
230 if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
233 if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
241 public int hashCode() {
242 final int prime = 31;
243 int result = this.from.hashCode() + this.to.hashCode();
244 result = prime * result;
249 * Check if this connection is equal to other and if it contains higher source bgp id
251 boolean isHigherDirection(final BGPSessionId other) {
252 return toLong(this.from) > toLong(other.from);
255 boolean hasHigherAsNumber(final BGPSessionId other) {
256 return this.asNumber.getValue() > other.asNumber.getValue();
259 private static long toLong(final Ipv4Address from) {
260 final int i = InetAddresses.coerceToInteger(InetAddresses.forString(from.getValue()));
261 return UnsignedInts.toLong(i);
265 public String toString() {
266 return MoreObjects.toStringHelper(this)
267 .add("from", this.from)