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.CharMatcher;
12 import com.google.common.base.Objects;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.Maps;
15 import java.net.Inet4Address;
16 import java.net.Inet6Address;
17 import java.net.InetAddress;
18 import java.net.InetSocketAddress;
19 import java.net.SocketAddress;
21 import javax.annotation.concurrent.GuardedBy;
22 import javax.annotation.concurrent.ThreadSafe;
23 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
24 import org.opendaylight.protocol.bgp.parser.BGPError;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.ReusableBGPPeer;
28 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
36 * BGP peer registry that allows only 1 session per BGP peer.
37 * If second session with peer is established, one of the sessions will be dropped.
38 * The session with lower source BGP id will be dropped.
41 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
43 private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
45 private static final CharMatcher NONDIGIT = CharMatcher.inRange('0', '9').negate();
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 this.peerPreferences.put(ip, Preconditions.checkNotNull(preferences));
66 public synchronized void removePeer(final IpAddress ip) {
67 Preconditions.checkNotNull(ip);
68 this.peers.remove(ip);
71 public synchronized void removePeerSession(final IpAddress ip) {
72 Preconditions.checkNotNull(ip);
73 this.sessionIds.remove(ip);
77 public boolean isPeerConfigured(final IpAddress ip) {
78 Preconditions.checkNotNull(ip);
79 return this.peers.containsKey(ip);
82 private void checkPeerConfigured(final IpAddress ip) {
83 Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, this.peers.keySet());
87 public synchronized BGPSessionListener getPeer(final IpAddress ip,
88 final Ipv4Address sourceId, final Ipv4Address remoteId)
89 throws BGPDocumentedException {
90 Preconditions.checkNotNull(ip);
91 Preconditions.checkNotNull(sourceId);
92 Preconditions.checkNotNull(remoteId);
94 checkPeerConfigured(ip);
96 final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId);
97 final BGPSessionListener p = this.peers.get(ip);
99 if (this.sessionIds.containsKey(ip)) {
100 if (p.isSessionActive()) {
102 LOG.warn("Duplicate BGP session established with {}", ip);
104 final BGPSessionId previousConnection = this.sessionIds.get(ip);
106 // Session reestablished with different ids
107 if (!previousConnection.equals(currentConnection)) {
108 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
109 throw new BGPDocumentedException(
110 String.format("BGP session with %s %s has to be dropped. Same session already present %s",
111 ip, currentConnection, previousConnection),
114 // Session reestablished with lower source bgp id, dropping current
115 } else if (previousConnection.isHigherDirection(currentConnection)) {
116 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
117 throw new BGPDocumentedException(
118 String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
119 ip, currentConnection),
122 // Session reestablished with higher source bgp id, dropping previous
123 } else if (currentConnection.isHigherDirection(previousConnection)) {
124 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
125 this.peers.get(ip).releaseConnection();
126 return this.peers.get(ip);
128 // Session reestablished with same source bgp id, dropping current as duplicate
130 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
131 throw new BGPDocumentedException(
132 String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
133 ip, currentConnection),
137 removePeerSession(ip);
141 // Map session id to peer IP address
142 this.sessionIds.put(ip, currentConnection);
147 public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
148 Preconditions.checkNotNull(ip);
149 checkPeerConfigured(ip);
150 return this.peerPreferences.get(ip);
154 * Create IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
156 * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
157 * @param socketAddress socket address to transform
159 public static IpAddress getIpAddress(final SocketAddress socketAddress) {
160 Preconditions.checkNotNull(socketAddress);
161 Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
162 final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
164 if(inetAddress instanceof Inet4Address) {
165 return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
166 } else if(inetAddress instanceof Inet6Address) {
167 return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
170 throw new IllegalArgumentException("Expecting " + Inet4Address.class + " or " + Inet6Address.class + " but was " + inetAddress.getClass());
174 public synchronized void close() {
176 this.sessionIds.clear();
180 public String toString() {
181 return Objects.toStringHelper(this)
182 .add("peers", this.peers.keySet())
187 * Session identifier that contains (source Bgp Id) -> (destination Bgp Id)
189 private static final class BGPSessionId {
190 private final Ipv4Address from, to;
192 BGPSessionId(final Ipv4Address from, final Ipv4Address to) {
193 this.from = Preconditions.checkNotNull(from);
194 this.to = Preconditions.checkNotNull(to);
198 * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
201 public boolean equals(final Object o) {
205 if (o == null || getClass() != o.getClass()) {
209 final BGPSessionId bGPSessionId = (BGPSessionId) o;
211 if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
214 if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
222 public int hashCode() {
223 final int prime = 31;
224 int result = this.from.hashCode() + this.to.hashCode();
225 result = prime * result;
230 * Check if this connection is equal to other and if it contains higher source bgp id
232 boolean isHigherDirection(final BGPSessionId other) {
233 Preconditions.checkState(!this.isSameDirection(other), "Equal sessions with same direction");
234 return toLong(this.from) > toLong(other.from);
237 private long toLong(final Ipv4Address from) {
238 return Long.parseLong(NONDIGIT.removeFrom(from.getValue()));
242 * Check if 2 connections are equal and face same direction
244 boolean isSameDirection(final BGPSessionId other) {
245 Preconditions.checkState(this.equals(other), "Only equal sessions can be compared");
246 return this.from.equals(other.from);
250 public String toString() {
251 return Objects.toStringHelper(this)
252 .add("from", this.from)