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);
98 if (this.sessionIds.containsKey(ip)) {
99 LOG.warn("Duplicate BGP session established with {}", ip);
101 final BGPSessionId previousConnection = this.sessionIds.get(ip);
103 // Session reestablished with different ids
104 if (!previousConnection.equals(currentConnection)) {
105 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
106 throw new BGPDocumentedException(
107 String.format("BGP session with %s %s has to be dropped. Same session already present %s",
108 ip, currentConnection, previousConnection),
109 BGPError.CONNECTION_COLLISION_RESOLUTION);
111 // Session reestablished with lower source bgp id, dropping current
112 } else if (previousConnection.isHigherDirection(currentConnection)) {
113 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
114 throw new BGPDocumentedException(
115 String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
116 ip, currentConnection),
117 BGPError.CONNECTION_COLLISION_RESOLUTION);
119 // Session reestablished with higher source bgp id, dropping previous
120 } else if (currentConnection.isHigherDirection(previousConnection)) {
121 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
122 this.peers.get(ip).releaseConnection();
123 return this.peers.get(ip);
125 // Session reestablished with same source bgp id, dropping current as duplicate
127 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
128 throw new BGPDocumentedException(
129 String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
130 ip, currentConnection),
131 BGPError.CONNECTION_COLLISION_RESOLUTION);
135 // Map session id to peer IP address
136 this.sessionIds.put(ip, currentConnection);
137 return this.peers.get(ip);
141 public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
142 Preconditions.checkNotNull(ip);
143 checkPeerConfigured(ip);
144 return this.peerPreferences.get(ip);
148 * Create IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
150 * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
151 * @param socketAddress socket address to transform
153 public static IpAddress getIpAddress(final SocketAddress socketAddress) {
154 Preconditions.checkNotNull(socketAddress);
155 Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
156 final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
158 if(inetAddress instanceof Inet4Address) {
159 return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
160 } else if(inetAddress instanceof Inet6Address) {
161 return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
164 throw new IllegalArgumentException("Expecting " + Inet4Address.class + " or " + Inet6Address.class + " but was " + inetAddress.getClass());
168 public synchronized void close() {
170 this.sessionIds.clear();
174 public String toString() {
175 return Objects.toStringHelper(this)
176 .add("peers", this.peers.keySet())
181 * Session identifier that contains (source Bgp Id) -> (destination Bgp Id)
183 private static final class BGPSessionId {
184 private final Ipv4Address from, to;
186 BGPSessionId(final Ipv4Address from, final Ipv4Address to) {
187 this.from = Preconditions.checkNotNull(from);
188 this.to = Preconditions.checkNotNull(to);
192 * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
195 public boolean equals(final Object o) {
199 if (o == null || getClass() != o.getClass()) {
203 final BGPSessionId bGPSessionId = (BGPSessionId) o;
205 if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
208 if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
216 public int hashCode() {
217 final int prime = 31;
218 int result = this.from.hashCode() + this.to.hashCode();
219 result = prime * result;
224 * Check if this connection is equal to other and if it contains higher source bgp id
226 boolean isHigherDirection(final BGPSessionId other) {
227 Preconditions.checkState(!this.isSameDirection(other), "Equal sessions with same direction");
228 return toLong(this.from) > toLong(other.from);
231 private long toLong(final Ipv4Address from) {
232 return Long.parseLong(NONDIGIT.removeFrom(from.getValue()));
236 * Check if 2 connections are equal and face same direction
238 boolean isSameDirection(final BGPSessionId other) {
239 Preconditions.checkState(this.equals(other), "Only equal sessions can be compared");
240 return this.from.equals(other.from);
244 public String toString() {
245 return Objects.toStringHelper(this)
246 .add("from", this.from)