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