63c188665f778d781b57bab4dc07f106b3034b97
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / StrictBGPPeerRegistry.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.protocol.bgp.rib.impl;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.Maps;
17 import com.google.common.net.InetAddresses;
18 import com.google.common.primitives.UnsignedInts;
19 import io.netty.buffer.ByteBuf;
20 import io.netty.buffer.Unpooled;
21 import java.net.Inet4Address;
22 import java.net.Inet6Address;
23 import java.net.InetAddress;
24 import java.net.InetSocketAddress;
25 import java.net.SocketAddress;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Set;
31 import javax.annotation.concurrent.GuardedBy;
32 import javax.annotation.concurrent.ThreadSafe;
33 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
34 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
35 import org.opendaylight.protocol.bgp.parser.BGPError;
36 import org.opendaylight.protocol.bgp.parser.impl.message.open.As4CapabilityHandler;
37 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
38 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
39 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistryListener;
40 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistrySessionListener;
41 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.Open;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.BgpParameters;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.OptionalCapabilities;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.CParameters;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapability;
52 import org.opendaylight.yangtools.concepts.AbstractRegistration;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * BGP peer registry that allows only 1 session per BGP peer.
58  * If second session with peer is established, one of the sessions will be dropped.
59  * The session with lower source BGP id will be dropped.
60  */
61 @ThreadSafe
62 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
63
64     private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
65
66     @GuardedBy("this")
67     private final Map<IpAddress, BGPSessionListener> peers = Maps.newHashMap();
68     @GuardedBy("this")
69     private final Map<IpAddress, BGPSessionId> sessionIds = Maps.newHashMap();
70     @GuardedBy("this")
71     private final Map<IpAddress, BGPSessionPreferences> peerPreferences = Maps.newHashMap();
72     @GuardedBy("this")
73     private final Set<PeerRegistryListener> listeners = new HashSet<>();
74     @GuardedBy("this")
75     private final Set<PeerRegistrySessionListener> sessionListeners = new HashSet<>();
76
77     public static BGPPeerRegistry instance() {
78         return new StrictBGPPeerRegistry();
79     }
80
81     @Override
82     public synchronized void addPeer(final IpAddress ip, final BGPSessionListener peer, final BGPSessionPreferences preferences) {
83         requireNonNull(ip);
84         Preconditions.checkArgument(!this.peers.containsKey(ip), "Peer for %s already present", ip);
85         this.peers.put(ip, requireNonNull(peer));
86         requireNonNull(preferences.getMyAs());
87         requireNonNull(preferences.getHoldTime());
88         requireNonNull(preferences.getParams());
89         requireNonNull(preferences.getBgpId());
90         this.peerPreferences.put(ip, preferences);
91         for (final PeerRegistryListener peerRegistryListener : this.listeners) {
92             peerRegistryListener.onPeerAdded(ip, preferences);
93         }
94     }
95
96     @Override
97     public synchronized void removePeer(final IpAddress ip) {
98         requireNonNull(ip);
99         this.peers.remove(ip);
100         for (final PeerRegistryListener peerRegistryListener : this.listeners) {
101             peerRegistryListener.onPeerRemoved(ip);
102         }
103     }
104
105     @Override
106     public synchronized void removePeerSession(final IpAddress ip) {
107         requireNonNull(ip);
108         this.sessionIds.remove(ip);
109         for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
110             peerRegistrySessionListener.onSessionRemoved(ip);
111         }
112     }
113
114     @Override
115     public boolean isPeerConfigured(final IpAddress ip) {
116         requireNonNull(ip);
117         return this.peers.containsKey(ip);
118     }
119
120     private void checkPeerConfigured(final IpAddress ip) {
121         Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, this.peers.keySet());
122     }
123
124     @Override
125     public synchronized BGPSessionListener getPeer(final IpAddress ip, final Ipv4Address sourceId,
126         final Ipv4Address remoteId, final Open openObj) throws BGPDocumentedException {
127         requireNonNull(ip);
128         requireNonNull(sourceId);
129         requireNonNull(remoteId);
130         final AsNumber remoteAsNumber = AsNumberUtil.advertizedAsNumber(openObj);
131         requireNonNull(remoteAsNumber);
132
133         final BGPSessionPreferences prefs = getPeerPreferences(ip);
134
135         checkPeerConfigured(ip);
136
137         final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId, remoteAsNumber);
138         final BGPSessionListener p = this.peers.get(ip);
139
140         final BGPSessionId previousConnection = this.sessionIds.get(ip);
141
142         if (previousConnection != null) {
143
144             LOG.warn("Duplicate BGP session established with {}", ip);
145
146             // Session reestablished with different ids
147             if (!previousConnection.equals(currentConnection)) {
148                 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
149                 throw new BGPDocumentedException(
150                     String.format("BGP session with %s %s has to be dropped. Same session already present %s",
151                         ip, currentConnection, previousConnection),
152                         BGPError.CEASE);
153
154                 // Session reestablished with lower source bgp id, dropping current
155             } else if (previousConnection.isHigherDirection(currentConnection) ||
156                     previousConnection.hasHigherAsNumber(currentConnection)) {
157                 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
158                 throw new BGPDocumentedException(
159                     String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
160                         ip, currentConnection),
161                         BGPError.CEASE);
162
163                 // Session reestablished with higher source bgp id, dropping previous
164             } else if (currentConnection.isHigherDirection(previousConnection) ||
165                     currentConnection.hasHigherAsNumber(previousConnection)) {
166                 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
167                 this.peers.get(ip).releaseConnection();
168                 return this.peers.get(ip);
169                 // Session reestablished with same source bgp id, dropping current as duplicate
170             } else {
171                 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
172                 throw new BGPDocumentedException(
173                     String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
174                         ip, currentConnection),
175                         BGPError.CEASE);
176             }
177         }
178         validateAs(remoteAsNumber, openObj, prefs);
179
180         // Map session id to peer IP address
181         this.sessionIds.put(ip, currentConnection);
182         for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
183             peerRegistrySessionListener.onSessionCreated(ip);
184         }
185         return p;
186     }
187
188     private static void validateAs(final AsNumber remoteAs, final Open openObj, final BGPSessionPreferences localPref) throws BGPDocumentedException {
189         if (!remoteAs.equals(localPref.getExpectedRemoteAs())) {
190             LOG.warn("Unexpected remote AS number. Expecting {}, got {}", remoteAs, localPref.getExpectedRemoteAs());
191             throw new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS);
192         }
193
194         // https://tools.ietf.org/html/rfc6286#section-2.2
195         if (openObj.getBgpIdentifier() != null && openObj.getBgpIdentifier().getValue().equals(localPref.getBgpId().getValue())) {
196             LOG.warn("Remote and local BGP Identifiers are the same: {}", openObj.getBgpIdentifier());
197             throw new BGPDocumentedException("Remote and local BGP Identifiers are the same.", BGPError.BAD_BGP_ID);
198         }
199         final List<BgpParameters> prefs = openObj.getBgpParameters();
200         if (prefs != null) {
201             if (getAs4BytesCapability(localPref.getParams()).isPresent() && !getAs4BytesCapability(prefs).isPresent()) {
202                 throw new BGPDocumentedException("The peer must advertise AS4Bytes capability.", BGPError.UNSUPPORTED_CAPABILITY, serializeAs4BytesCapability(getAs4BytesCapability(localPref.getParams()).get()));
203             }
204             if (!prefs.containsAll(localPref.getParams())) {
205                 LOG.info("BGP Open message session parameters differ, session still accepted.");
206             }
207         } else {
208             throw new BGPDocumentedException("Open message unacceptable. Check the configuration of BGP speaker.", BGPError.UNSPECIFIC_OPEN_ERROR);
209         }
210     }
211
212     private static Optional<As4BytesCapability> getAs4BytesCapability(final List<BgpParameters> prefs) {
213         for (final BgpParameters param : prefs) {
214             for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
215                 final CParameters cParam = capa.getCParameters();
216                 if (cParam.getAs4BytesCapability() != null) {
217                     return Optional.of(cParam.getAs4BytesCapability());
218                 }
219             }
220         }
221         return Optional.absent();
222     }
223
224     private static byte[] serializeAs4BytesCapability(final As4BytesCapability as4Capability) {
225         final ByteBuf buffer = Unpooled.buffer(1 /*CODE*/ + 1 /*LENGTH*/ + Integer.SIZE / Byte.SIZE /*4 byte value*/);
226         final As4CapabilityHandler serializer = new As4CapabilityHandler();
227         serializer.serializeCapability(new CParametersBuilder().setAs4BytesCapability(as4Capability).build(), buffer);
228         return buffer.array();
229     }
230
231     @Override
232     public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
233         requireNonNull(ip);
234         checkPeerConfigured(ip);
235         return this.peerPreferences.get(ip);
236     }
237
238     /**
239      * Creates IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
240      *
241      * @param socketAddress socket address to transform
242      * @return IpAddress equivalent to given socket address
243      * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
244      */
245     public static IpAddress getIpAddress(final SocketAddress socketAddress) {
246         requireNonNull(socketAddress);
247         Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
248         final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
249
250         Preconditions.checkArgument(inetAddress instanceof Inet4Address || inetAddress instanceof Inet6Address, "Expecting %s or %s but was %s", Inet4Address.class, Inet6Address.class, inetAddress.getClass());
251         return IetfInetUtil.INSTANCE.ipAddressFor(inetAddress);
252     }
253
254     @Override
255     public synchronized void close() {
256         this.peers.clear();
257         this.sessionIds.clear();
258     }
259
260     @Override
261     public String toString() {
262         return MoreObjects.toStringHelper(this)
263             .add("peers", this.peers.keySet())
264             .toString();
265     }
266
267     /**
268      * Session identifier that contains (source Bgp Id) -> (destination Bgp Id) AsNumber is the remoteAs coming from
269      * remote Open message
270      */
271     private static final class BGPSessionId {
272
273         private final Ipv4Address from, to;
274         private final AsNumber asNumber;
275
276         BGPSessionId(final Ipv4Address from, final Ipv4Address to, final AsNumber asNumber) {
277             this.from = requireNonNull(from);
278             this.to = requireNonNull(to);
279             this.asNumber = requireNonNull(asNumber);
280         }
281
282         /**
283          * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
284          */
285         @Override
286         public boolean equals(final Object o) {
287             if (this == o) {
288                 return true;
289             }
290             if (o == null || getClass() != o.getClass()) {
291                 return false;
292             }
293
294             final BGPSessionId bGPSessionId = (BGPSessionId) o;
295
296             if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
297                 return false;
298             }
299             if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
300                 return false;
301             }
302
303             return true;
304         }
305
306         @Override
307         public int hashCode() {
308             final int prime = 31;
309             int result = this.from.hashCode() + this.to.hashCode();
310             result = prime * result;
311             return result;
312         }
313
314         /**
315          * Check if this connection is equal to other and if it contains higher source bgp id
316          */
317         boolean isHigherDirection(final BGPSessionId other) {
318             return toLong(this.from) > toLong(other.from);
319         }
320
321         boolean hasHigherAsNumber(final BGPSessionId other) {
322             return this.asNumber.getValue() > other.asNumber.getValue();
323         }
324
325         private static long toLong(final Ipv4Address from) {
326             final int i = InetAddresses.coerceToInteger(InetAddresses.forString(from.getValue()));
327             return UnsignedInts.toLong(i);
328         }
329
330         @Override
331         public String toString() {
332             return MoreObjects.toStringHelper(this)
333                 .add("from", this.from)
334                 .add("to", this.to)
335                 .toString();
336         }
337     }
338
339     @Override
340     public synchronized AutoCloseable registerPeerRegisterListener(final PeerRegistryListener listener) {
341         this.listeners.add(listener);
342         for (final Entry<IpAddress, BGPSessionPreferences> entry : this.peerPreferences.entrySet()) {
343             listener.onPeerAdded(entry.getKey(), entry.getValue());
344         }
345         return new AbstractRegistration() {
346             @Override
347             protected void removeRegistration() {
348                 synchronized (StrictBGPPeerRegistry.this) {
349                     StrictBGPPeerRegistry.this.listeners.remove(listener);
350                 }
351             }
352         };
353     }
354
355     @Override
356     public synchronized AutoCloseable registerPeerSessionListener(final PeerRegistrySessionListener listener) {
357         this.sessionListeners.add(listener);
358         for (final IpAddress ipAddress : this.sessionIds.keySet()) {
359             listener.onSessionCreated(ipAddress);
360         }
361         return new AbstractRegistration() {
362             @Override
363             protected void removeRegistration() {
364                 synchronized (StrictBGPPeerRegistry.this) {
365                     StrictBGPPeerRegistry.this.sessionListeners.remove(listener);
366                 }
367             }
368         };
369     }
370 }