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