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;
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;
23 import javax.annotation.concurrent.GuardedBy;
24 import javax.annotation.concurrent.ThreadSafe;
26 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
27 import org.opendaylight.protocol.bgp.parser.BGPError;
28 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
29 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
30 import org.opendaylight.protocol.bgp.rib.impl.spi.ReusableBGPPeer;
31 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * BGP peer registry that allows only 1 session per BGP peer.
40 * If second session with peer is established, one of the sessions will be dropped.
41 * The session with lower source BGP id will be dropped.
44 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
46 private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
48 private static final CharMatcher NONDIGIT = CharMatcher.inRange('0', '9').negate();
50 // TODO remove backwards compatibility
51 public static final StrictBGPPeerRegistry GLOBAL = new StrictBGPPeerRegistry();
54 private final Map<IpAddress, ReusableBGPPeer> peers = Maps.newHashMap();
56 private final Map<IpAddress, BGPSessionId> sessionIds = Maps.newHashMap();
58 private final Map<IpAddress, BGPSessionPreferences> peerPreferences = Maps.newHashMap();
61 public synchronized void addPeer(final IpAddress ip, final ReusableBGPPeer peer, final BGPSessionPreferences preferences) {
62 Preconditions.checkNotNull(ip);
63 Preconditions.checkArgument(!this.peers.containsKey(ip), "Peer for %s already present", ip);
64 this.peers.put(ip, Preconditions.checkNotNull(peer));
65 this.peerPreferences.put(ip, Preconditions.checkNotNull(preferences));
69 public synchronized void removePeer(final IpAddress ip) {
70 Preconditions.checkNotNull(ip);
71 this.peers.remove(ip);
75 public boolean isPeerConfigured(final IpAddress ip) {
76 Preconditions.checkNotNull(ip);
77 return this.peers.containsKey(ip);
80 private void checkPeerConfigured(final IpAddress ip) {
81 Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, this.peers.keySet());
85 public synchronized BGPSessionListener getPeer(final IpAddress ip,
86 final Ipv4Address sourceId, final Ipv4Address remoteId)
87 throws BGPDocumentedException {
88 Preconditions.checkNotNull(ip);
89 Preconditions.checkNotNull(sourceId);
90 Preconditions.checkNotNull(remoteId);
92 checkPeerConfigured(ip);
94 final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId);
96 if (this.sessionIds.containsKey(ip)) {
97 LOG.warn("Duplicate BGP session established with {}", ip);
99 final BGPSessionId previousConnection = this.sessionIds.get(ip);
101 // Session reestablished with different ids
102 if (!previousConnection.equals(currentConnection)) {
103 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
104 throw new BGPDocumentedException(
105 String.format("BGP session with %s %s has to be dropped. Same session already present %s",
106 ip, currentConnection, previousConnection),
109 // Session reestablished with lower source bgp id, dropping current
110 } else if (previousConnection.isHigherDirection(currentConnection)) {
111 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
112 throw new BGPDocumentedException(
113 String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
114 ip, currentConnection),
117 // Session reestablished with higher source bgp id, dropping previous
118 } else if (currentConnection.isHigherDirection(previousConnection)) {
119 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
120 this.peers.get(ip).releaseConnection();
121 return this.peers.get(ip);
123 // Session reestablished with same source bgp id, dropping current as duplicate
125 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
126 throw new BGPDocumentedException(
127 String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
128 ip, currentConnection),
133 // Map session id to peer IP address
134 this.sessionIds.put(ip, currentConnection);
135 return this.peers.get(ip);
139 public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
140 Preconditions.checkNotNull(ip);
141 checkPeerConfigured(ip);
142 return this.peerPreferences.get(ip);
146 * Create IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
148 * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
149 * @param socketAddress socket address to transform
151 public static IpAddress getIpAddress(final SocketAddress socketAddress) {
152 Preconditions.checkNotNull(socketAddress);
153 Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
154 final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
156 if(inetAddress instanceof Inet4Address) {
157 return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
158 } else if(inetAddress instanceof Inet6Address) {
159 return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
162 throw new IllegalArgumentException("Expecting " + Inet4Address.class + " or " + Inet6Address.class + " but was " + inetAddress.getClass());
166 public synchronized void close() {
168 this.sessionIds.clear();
172 public String toString() {
173 return Objects.toStringHelper(this)
174 .add("peers", this.peers.keySet())
179 * Session identifier that contains (source Bgp Id) -> (destination Bgp Id)
181 private static final class BGPSessionId {
182 private final Ipv4Address from, to;
184 BGPSessionId(final Ipv4Address from, final Ipv4Address to) {
185 this.from = Preconditions.checkNotNull(from);
186 this.to = Preconditions.checkNotNull(to);
190 * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
193 public boolean equals(final Object o) {
197 if (o == null || getClass() != o.getClass()) {
201 final BGPSessionId bGPSessionId = (BGPSessionId) o;
203 if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
206 if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
214 public int hashCode() {
215 final int prime = 31;
216 int result = this.from.hashCode() + this.to.hashCode();
217 result = prime * result;
222 * Check if this connection is equal to other and if it contains higher source bgp id
224 boolean isHigherDirection(final BGPSessionId other) {
225 Preconditions.checkState(!this.isSameDirection(other), "Equal sessions with same direction");
226 return toLong(this.from) > toLong(other.from);
229 private long toLong(final Ipv4Address from) {
230 return Long.parseLong(NONDIGIT.removeFrom(from.getValue()));
234 * Check if 2 connections are equal and face same direction
236 boolean isSameDirection(final BGPSessionId other) {
237 Preconditions.checkState(this.equals(other), "Only equal sessions can be compared");
238 return this.from.equals(other.from);
242 public String toString() {
243 return Objects.toStringHelper(this)
244 .add("from", this.from)