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
8 package org.opendaylight.protocol.bgp.rib.impl;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.Preconditions;
14 import com.google.common.net.InetAddresses;
15 import com.google.common.primitives.UnsignedInts;
16 import io.netty.buffer.ByteBuf;
17 import io.netty.buffer.Unpooled;
18 import java.net.Inet4Address;
19 import java.net.Inet6Address;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22 import java.net.SocketAddress;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Map.Entry;
28 import java.util.concurrent.ConcurrentHashMap;
29 import org.checkerframework.checker.lock.qual.GuardedBy;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
32 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
33 import org.opendaylight.protocol.bgp.parser.BGPError;
34 import org.opendaylight.protocol.bgp.parser.impl.message.open.As4CapabilityHandler;
35 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
36 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
37 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistryListener;
38 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistrySessionListener;
39 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
40 import org.opendaylight.protocol.util.Ipv6Util;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6AddressNoZone;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.BgpParameters;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.OptionalCapabilities;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.optional.capabilities.CParameters;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapability;
53 import org.opendaylight.yangtools.concepts.AbstractRegistration;
54 import org.opendaylight.yangtools.concepts.Registration;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * BGP peer registry that allows only 1 session per BGP peer. If a second session with peer is established, one of
60 * the sessions will be dropped. The session with lower source BGP id will be dropped. This class is thread-safe.
62 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
63 private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
66 private final Map<IpAddressNoZone, BGPSessionListener> peers = new HashMap<>();
68 private final Map<IpAddressNoZone, BGPSessionId> sessionIds = new HashMap<>();
70 private final Map<IpAddressNoZone, BGPSessionPreferences> peerPreferences = new HashMap<>();
71 private final Set<PeerRegistryListener> listeners = ConcurrentHashMap.newKeySet();
72 private final Set<PeerRegistrySessionListener> sessionListeners = ConcurrentHashMap.newKeySet();
74 public static BGPPeerRegistry instance() {
75 return new StrictBGPPeerRegistry();
79 public synchronized void addPeer(final IpAddressNoZone oldIp, final BGPSessionListener peer,
80 final BGPSessionPreferences preferences) {
81 IpAddressNoZone fullIp = getFullIp(oldIp);
82 Preconditions.checkArgument(!this.peers.containsKey(fullIp),
83 "Peer for %s already present", fullIp);
84 this.peers.put(fullIp, requireNonNull(peer));
85 requireNonNull(preferences.getMyAs());
86 requireNonNull(preferences.getParams());
87 requireNonNull(preferences.getBgpId());
88 this.peerPreferences.put(fullIp, preferences);
89 for (final PeerRegistryListener peerRegistryListener : this.listeners) {
90 peerRegistryListener.onPeerAdded(fullIp, preferences);
94 private static IpAddressNoZone getFullIp(final IpAddressNoZone ip) {
95 final Ipv6AddressNoZone addr = ip.getIpv6AddressNoZone();
96 return addr == null ? ip : new IpAddressNoZone(Ipv6Util.getFullForm(addr));
100 public synchronized void removePeer(final IpAddressNoZone oldIp) {
101 IpAddressNoZone fullIp = getFullIp(oldIp);
102 this.peers.remove(fullIp);
103 for (final PeerRegistryListener peerRegistryListener : this.listeners) {
104 peerRegistryListener.onPeerRemoved(fullIp);
109 public synchronized void removePeerSession(final IpAddressNoZone oldIp) {
110 IpAddressNoZone fullIp = getFullIp(oldIp);
111 this.sessionIds.remove(fullIp);
112 for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
113 peerRegistrySessionListener.onSessionRemoved(fullIp);
118 public boolean isPeerConfigured(final IpAddressNoZone oldIp) {
119 IpAddressNoZone fullIp = getFullIp(oldIp);
120 return this.peers.containsKey(fullIp);
123 private void checkPeerConfigured(final IpAddressNoZone ip) {
124 Preconditions.checkState(isPeerConfigured(ip),
125 "BGP peer with ip: %s not configured, configured peers are: %s",
126 ip, this.peers.keySet());
130 public synchronized BGPSessionListener getPeer(final IpAddressNoZone ip, final Ipv4AddressNoZone sourceId,
131 final Ipv4AddressNoZone remoteId, final Open openObj) throws BGPDocumentedException {
133 requireNonNull(sourceId);
134 requireNonNull(remoteId);
135 final AsNumber remoteAsNumber = AsNumberUtil.advertizedAsNumber(openObj);
136 requireNonNull(remoteAsNumber);
138 final BGPSessionPreferences prefs = getPeerPreferences(ip);
140 checkPeerConfigured(ip);
142 final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId, remoteAsNumber);
143 final BGPSessionListener p = this.peers.get(ip);
145 final BGPSessionId previousConnection = this.sessionIds.get(ip);
147 if (previousConnection != null) {
149 LOG.warn("Duplicate BGP session established with {}", ip);
151 // Session reestablished with different ids
152 if (!previousConnection.equals(currentConnection)) {
153 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip,
154 currentConnection, previousConnection);
155 throw new BGPDocumentedException(
156 String.format("BGP session with %s %s has to be dropped. Same session already present %s",
157 ip, currentConnection, previousConnection),
160 // Session reestablished with lower source bgp id, dropping current
161 } else if (previousConnection.isHigherDirection(currentConnection)
162 || previousConnection.hasHigherAsNumber(currentConnection)) {
163 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present",
164 ip, currentConnection);
165 throw new BGPDocumentedException(
166 String.format("BGP session with %s initiated %s has to be dropped. "
167 + "Opposite session already present", ip, currentConnection), BGPError.CEASE);
169 // Session reestablished with higher source bgp id, dropping previous
170 } else if (currentConnection.isHigherDirection(previousConnection)
171 || currentConnection.hasHigherAsNumber(previousConnection)) {
172 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
173 this.peers.get(ip).releaseConnection();
174 return this.peers.get(ip);
175 // Session reestablished with same source bgp id, dropping current as duplicate
177 LOG.warn("BGP session with {} initiated from {} to {} has to be dropped. Same session already present",
178 ip, sourceId, remoteId);
179 throw new BGPDocumentedException(
180 String.format("BGP session with %s initiated %s has to be dropped. "
181 + "Same session already present", ip, currentConnection), BGPError.CEASE);
184 validateAs(remoteAsNumber, openObj, prefs);
186 // Map session id to peer IP address
187 this.sessionIds.put(ip, currentConnection);
188 for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
189 peerRegistrySessionListener.onSessionCreated(ip);
194 private static void validateAs(final AsNumber remoteAs, final Open openObj, final BGPSessionPreferences localPref)
195 throws BGPDocumentedException {
196 if (!remoteAs.equals(localPref.getExpectedRemoteAs())) {
197 LOG.warn("Unexpected remote AS number. Expecting {}, got {}", localPref.getExpectedRemoteAs(), remoteAs);
198 throw new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS);
201 // https://tools.ietf.org/html/rfc6286#section-2.2
202 if (openObj.getBgpIdentifier() != null
203 && openObj.getBgpIdentifier().getValue().equals(localPref.getBgpId().getValue())) {
204 LOG.warn("Remote and local BGP Identifiers are the same: {}", openObj.getBgpIdentifier());
205 throw new BGPDocumentedException("Remote and local BGP Identifiers are the same.", BGPError.BAD_BGP_ID);
207 final List<BgpParameters> prefs = openObj.getBgpParameters();
209 final As4BytesCapability localCap = getAs4BytesCapability(localPref.getParams());
210 if (localCap != null && getAs4BytesCapability(prefs) == null) {
211 throw new BGPDocumentedException("The peer must advertise AS4Bytes capability.",
212 BGPError.UNSUPPORTED_CAPABILITY, serializeAs4BytesCapability(localCap));
214 if (!prefs.containsAll(localPref.getParams())) {
215 LOG.info("BGP Open message session parameters differ, session still accepted.");
218 throw new BGPDocumentedException("Open message unacceptable. Check the configuration of BGP speaker.",
219 BGPError.UNSPECIFIC_OPEN_ERROR);
223 private static @Nullable As4BytesCapability getAs4BytesCapability(final List<BgpParameters> prefs) {
224 for (final BgpParameters param : prefs) {
225 for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
226 final CParameters cParam = capa.getCParameters();
227 final As4BytesCapability asCapa = cParam.getAs4BytesCapability();
228 if (asCapa != null) {
236 private static byte[] serializeAs4BytesCapability(final As4BytesCapability as4Capability) {
237 final ByteBuf buffer = Unpooled.buffer(1 /*CODE*/ + 1 /*LENGTH*/
238 + Integer.SIZE / Byte.SIZE /*4 byte value*/);
239 final As4CapabilityHandler serializer = new As4CapabilityHandler();
240 serializer.serializeCapability(new CParametersBuilder().setAs4BytesCapability(as4Capability).build(), buffer);
241 return buffer.array();
245 public BGPSessionPreferences getPeerPreferences(final IpAddressNoZone ip) {
247 checkPeerConfigured(ip);
248 return this.peerPreferences.get(ip);
252 * Creates IpAddress from SocketAddress. Only InetSocketAddress
253 * is accepted with inner address: Inet4Address and Inet6Address.
255 * @param socketAddress socket address to transform
256 * @return IpAddress equivalent to given socket address
257 * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
259 public static IpAddressNoZone getIpAddress(final SocketAddress socketAddress) {
260 requireNonNull(socketAddress);
261 Preconditions.checkArgument(socketAddress instanceof InetSocketAddress,
262 "Expecting InetSocketAddress but was %s", socketAddress.getClass());
263 final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
265 Preconditions.checkArgument(inetAddress instanceof Inet4Address
266 || inetAddress instanceof Inet6Address, "Expecting %s or %s but was %s",
267 Inet4Address.class, Inet6Address.class, inetAddress.getClass());
268 return IetfInetUtil.INSTANCE.ipAddressNoZoneFor(inetAddress);
272 public synchronized void close() {
274 this.sessionIds.clear();
278 public String toString() {
279 return MoreObjects.toStringHelper(this)
280 .add("peers", this.peers.keySet())
285 * Session identifier that contains (source Bgp Id) -> (destination Bgp Id) AsNumber is the remoteAs coming from
286 * remote Open message.
288 private static final class BGPSessionId {
290 private final Ipv4Address from;
291 private final Ipv4Address to;
292 private final AsNumber asNumber;
294 BGPSessionId(final Ipv4Address from, final Ipv4Address to, final AsNumber asNumber) {
295 this.from = requireNonNull(from);
296 this.to = requireNonNull(to);
297 this.asNumber = requireNonNull(asNumber);
301 * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal.
304 public boolean equals(final Object obj) {
308 if (obj == null || getClass() != obj.getClass()) {
312 final BGPSessionId bGPSessionId = (BGPSessionId) obj;
314 if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
317 if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
325 public int hashCode() {
326 final int prime = 31;
327 int result = this.from.hashCode() + this.to.hashCode();
328 result = prime * result;
333 * Check if this connection is equal to other and if it contains higher source bgp id.
335 boolean isHigherDirection(final BGPSessionId other) {
336 return toLong(this.from) > toLong(other.from);
339 boolean hasHigherAsNumber(final BGPSessionId other) {
340 return this.asNumber.getValue().compareTo(other.asNumber.getValue()) > 0;
343 private static long toLong(final Ipv4Address from) {
344 final int i = InetAddresses.coerceToInteger(InetAddresses.forString(from.getValue()));
345 return UnsignedInts.toLong(i);
349 public String toString() {
350 return MoreObjects.toStringHelper(this)
351 .add("from", this.from)
358 public synchronized Registration registerPeerRegisterListener(final PeerRegistryListener listener) {
359 this.listeners.add(listener);
360 for (final Entry<IpAddressNoZone, BGPSessionPreferences> entry : this.peerPreferences.entrySet()) {
361 listener.onPeerAdded(entry.getKey(), entry.getValue());
363 return new AbstractRegistration() {
365 protected void removeRegistration() {
366 StrictBGPPeerRegistry.this.listeners.remove(listener);
372 public synchronized Registration registerPeerSessionListener(final PeerRegistrySessionListener listener) {
373 this.sessionListeners.add(listener);
374 for (final IpAddressNoZone ipAddress : this.sessionIds.keySet()) {
375 listener.onSessionCreated(ipAddress);
377 return new AbstractRegistration() {
379 protected void removeRegistration() {
380 StrictBGPPeerRegistry.this.sessionListeners.remove(listener);
386 public void updatePeerPreferences(final IpAddressNoZone address, final BGPSessionPreferences preferences) {
387 if (this.peerPreferences.containsKey(address)) {
388 this.peerPreferences.put(address, preferences);