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.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.Maps;
15 import com.google.common.net.InetAddresses;
16 import com.google.common.primitives.UnsignedInts;
17 import io.netty.buffer.ByteBuf;
18 import io.netty.buffer.Unpooled;
19 import java.net.Inet4Address;
20 import java.net.Inet6Address;
21 import java.net.InetAddress;
22 import java.net.InetSocketAddress;
23 import java.net.SocketAddress;
24 import java.util.List;
26 import javax.annotation.concurrent.GuardedBy;
27 import javax.annotation.concurrent.ThreadSafe;
28 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
29 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
30 import org.opendaylight.protocol.bgp.parser.BGPError;
31 import org.opendaylight.protocol.bgp.parser.impl.message.open.As4CapabilityHandler;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
34 import org.opendaylight.protocol.bgp.rib.impl.spi.ReusableBGPPeer;
35 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParameters;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapability;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * BGP peer registry that allows only 1 session per BGP peer.
51 * If second session with peer is established, one of the sessions will be dropped.
52 * The session with lower source BGP id will be dropped.
55 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
57 private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
59 // TODO remove backwards compatibility
60 public static final StrictBGPPeerRegistry GLOBAL = new StrictBGPPeerRegistry();
63 private final Map<IpAddress, ReusableBGPPeer> peers = Maps.newHashMap();
65 private final Map<IpAddress, BGPSessionId> sessionIds = Maps.newHashMap();
67 private final Map<IpAddress, BGPSessionPreferences> peerPreferences = Maps.newHashMap();
70 public synchronized void addPeer(final IpAddress ip, final ReusableBGPPeer peer, final BGPSessionPreferences preferences) {
71 Preconditions.checkNotNull(ip);
72 Preconditions.checkArgument(!this.peers.containsKey(ip), "Peer for %s already present", ip);
73 this.peers.put(ip, Preconditions.checkNotNull(peer));
74 Preconditions.checkNotNull(preferences.getMyAs());
75 Preconditions.checkNotNull(preferences.getHoldTime());
76 Preconditions.checkNotNull(preferences.getParams());
77 Preconditions.checkNotNull(preferences.getBgpId());
78 this.peerPreferences.put(ip, preferences);
82 public synchronized void removePeer(final IpAddress ip) {
83 Preconditions.checkNotNull(ip);
84 this.peers.remove(ip);
88 public synchronized void removePeerSession(final IpAddress ip) {
89 Preconditions.checkNotNull(ip);
90 this.sessionIds.remove(ip);
94 public boolean isPeerConfigured(final IpAddress ip) {
95 Preconditions.checkNotNull(ip);
96 return this.peers.containsKey(ip);
99 private void checkPeerConfigured(final IpAddress ip) {
100 Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, this.peers.keySet());
104 public synchronized BGPSessionListener getPeer(final IpAddress ip, final Ipv4Address sourceId,
105 final Ipv4Address remoteId, final Open openObj) throws BGPDocumentedException {
106 Preconditions.checkNotNull(ip);
107 Preconditions.checkNotNull(sourceId);
108 Preconditions.checkNotNull(remoteId);
109 final AsNumber remoteAsNumber = AsNumberUtil.advertizedAsNumber(openObj);
110 Preconditions.checkNotNull(remoteAsNumber);
112 final BGPSessionPreferences prefs = getPeerPreferences(ip);
114 checkPeerConfigured(ip);
116 final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId, remoteAsNumber);
117 final BGPSessionListener p = this.peers.get(ip);
119 final BGPSessionId previousConnection = this.sessionIds.get(ip);
121 if (previousConnection != null) {
123 LOG.warn("Duplicate BGP session established with {}", ip);
125 // Session reestablished with different ids
126 if (!previousConnection.equals(currentConnection)) {
127 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
128 throw new BGPDocumentedException(
129 String.format("BGP session with %s %s has to be dropped. Same session already present %s",
130 ip, currentConnection, previousConnection),
133 // Session reestablished with lower source bgp id, dropping current
134 } else if (previousConnection.isHigherDirection(currentConnection)) {
135 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
136 throw new BGPDocumentedException(
137 String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
138 ip, currentConnection),
141 // Session reestablished with higher source bgp id, dropping previous
142 } else if (currentConnection.isHigherDirection(previousConnection)) {
143 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
144 this.peers.get(ip).releaseConnection();
145 return this.peers.get(ip);
147 } else if (previousConnection.hasHigherAsNumber(currentConnection)) {
148 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
149 throw new BGPDocumentedException(
150 String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
151 ip, currentConnection),
153 } else if (currentConnection.hasHigherAsNumber(previousConnection)) {
154 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
155 this.peers.get(ip).releaseConnection();
156 return this.peers.get(ip);
157 // Session reestablished with same source bgp id, dropping current as duplicate
159 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
160 throw new BGPDocumentedException(
161 String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
162 ip, currentConnection),
166 validateAs(remoteAsNumber, openObj, prefs);
168 // Map session id to peer IP address
169 this.sessionIds.put(ip, currentConnection);
173 private void validateAs(final AsNumber remoteAs, final Open openObj, final BGPSessionPreferences localPref) throws BGPDocumentedException {
174 if (!remoteAs.equals(localPref.getExpectedRemoteAs())) {
175 LOG.warn("Unexpected remote AS number. Expecting {}, got {}", remoteAs, localPref.getExpectedRemoteAs());
176 throw new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS);
179 // https://tools.ietf.org/html/rfc6286#section-2.2
180 if (openObj.getBgpIdentifier() != null && openObj.getBgpIdentifier().equals(localPref.getBgpId())) {
181 LOG.warn("Remote and local BGP Identifiers are the same: {}", openObj.getBgpIdentifier());
182 throw new BGPDocumentedException("Remote and local BGP Identifiers are the same.", BGPError.BAD_BGP_ID);
184 final List<BgpParameters> prefs = openObj.getBgpParameters();
186 if (getAs4BytesCapability(localPref.getParams()).isPresent() && !getAs4BytesCapability(prefs).isPresent()) {
187 throw new BGPDocumentedException("The peer must advertise AS4Bytes capability.", BGPError.UNSUPPORTED_CAPABILITY, serializeAs4BytesCapability(getAs4BytesCapability(localPref.getParams()).get()));
189 if (!prefs.containsAll(localPref.getParams())) {
190 LOG.info("BGP Open message session parameters differ, session still accepted.");
193 throw new BGPDocumentedException("Open message unacceptable. Check the configuration of BGP speaker.", BGPError.UNSPECIFIC_OPEN_ERROR);
197 private static Optional<As4BytesCapability> getAs4BytesCapability(final List<BgpParameters> prefs) {
198 for (final BgpParameters param : prefs) {
199 for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
200 final CParameters cParam = capa.getCParameters();
201 if (cParam.getAs4BytesCapability() != null) {
202 return Optional.of(cParam.getAs4BytesCapability());
206 return Optional.absent();
209 private static byte[] serializeAs4BytesCapability(final As4BytesCapability as4Capability) {
210 final ByteBuf buffer = Unpooled.buffer(1 /*CODE*/ + 1 /*LENGTH*/ + Integer.SIZE / Byte.SIZE /*4 byte value*/);
211 final As4CapabilityHandler serializer = new As4CapabilityHandler();
212 serializer.serializeCapability(new CParametersBuilder().setAs4BytesCapability(as4Capability).build(), buffer);
213 return buffer.array();
217 public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
218 Preconditions.checkNotNull(ip);
219 checkPeerConfigured(ip);
220 return this.peerPreferences.get(ip);
224 * Creates IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
226 * @param socketAddress socket address to transform
227 * @return IpAddress equivalent to given socket address
228 * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
230 public static IpAddress getIpAddress(final SocketAddress socketAddress) {
231 Preconditions.checkNotNull(socketAddress);
232 Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
233 final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
235 Preconditions.checkArgument(inetAddress instanceof Inet4Address || inetAddress instanceof Inet6Address, "Expecting %s or %s but was %s", Inet4Address.class, Inet6Address.class, inetAddress.getClass());
236 if(inetAddress instanceof Inet4Address) {
237 return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
239 return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
243 public synchronized void close() {
245 this.sessionIds.clear();
249 public String toString() {
250 return MoreObjects.toStringHelper(this)
251 .add("peers", this.peers.keySet())
256 * Session identifier that contains (source Bgp Id) -> (destination Bgp Id) AsNumber is the remoteAs coming from
257 * remote Open message
259 private static final class BGPSessionId {
261 private final Ipv4Address from, to;
262 private final AsNumber asNumber;
264 BGPSessionId(final Ipv4Address from, final Ipv4Address to, final AsNumber asNumber) {
265 this.from = Preconditions.checkNotNull(from);
266 this.to = Preconditions.checkNotNull(to);
267 this.asNumber = Preconditions.checkNotNull(asNumber);
271 * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
274 public boolean equals(final Object o) {
278 if (o == null || getClass() != o.getClass()) {
282 final BGPSessionId bGPSessionId = (BGPSessionId) o;
284 if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
287 if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
295 public int hashCode() {
296 final int prime = 31;
297 int result = this.from.hashCode() + this.to.hashCode();
298 result = prime * result;
303 * Check if this connection is equal to other and if it contains higher source bgp id
305 boolean isHigherDirection(final BGPSessionId other) {
306 return toLong(this.from) > toLong(other.from);
309 boolean hasHigherAsNumber(final BGPSessionId other) {
310 return this.asNumber.getValue() > other.asNumber.getValue();
313 private static long toLong(final Ipv4Address from) {
314 final int i = InetAddresses.coerceToInteger(InetAddresses.forString(from.getValue()));
315 return UnsignedInts.toLong(i);
319 public String toString() {
320 return MoreObjects.toStringHelper(this)
321 .add("from", this.from)