Fixed some java8 non-compliant javadocs.
[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.Preconditions;
13 import com.google.common.collect.Maps;
14 import com.google.common.net.InetAddresses;
15 import com.google.common.primitives.UnsignedInts;
16 import java.net.Inet4Address;
17 import java.net.Inet6Address;
18 import java.net.InetAddress;
19 import java.net.InetSocketAddress;
20 import java.net.SocketAddress;
21 import java.util.Map;
22 import javax.annotation.concurrent.GuardedBy;
23 import javax.annotation.concurrent.ThreadSafe;
24 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
25 import org.opendaylight.protocol.bgp.parser.BGPError;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
28 import org.opendaylight.protocol.bgp.rib.impl.spi.ReusableBGPPeer;
29 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * BGP peer registry that allows only 1 session per BGP peer.
39  * If second session with peer is established, one of the sessions will be dropped.
40  * The session with lower source BGP id will be dropped.
41  */
42 @ThreadSafe
43 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
44
45     private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
46
47     // TODO remove backwards compatibility
48     public static final StrictBGPPeerRegistry GLOBAL = new StrictBGPPeerRegistry();
49
50     @GuardedBy("this")
51     private final Map<IpAddress, ReusableBGPPeer> peers = Maps.newHashMap();
52     @GuardedBy("this")
53     private final Map<IpAddress, BGPSessionId> sessionIds = Maps.newHashMap();
54     @GuardedBy("this")
55     private final Map<IpAddress, BGPSessionPreferences> peerPreferences = Maps.newHashMap();
56
57     @Override
58     public synchronized void addPeer(final IpAddress ip, final ReusableBGPPeer peer, final BGPSessionPreferences preferences) {
59         Preconditions.checkNotNull(ip);
60         Preconditions.checkArgument(!this.peers.containsKey(ip), "Peer for %s already present", ip);
61         this.peers.put(ip, Preconditions.checkNotNull(peer));
62         Preconditions.checkNotNull(preferences.getMyAs());
63         Preconditions.checkNotNull(preferences.getHoldTime());
64         Preconditions.checkNotNull(preferences.getParams());
65         Preconditions.checkNotNull(preferences.getBgpId());
66         this.peerPreferences.put(ip, preferences);
67     }
68
69     @Override
70     public synchronized void removePeer(final IpAddress ip) {
71         Preconditions.checkNotNull(ip);
72         this.peers.remove(ip);
73     }
74
75     @Override
76     public synchronized void removePeerSession(final IpAddress ip) {
77         Preconditions.checkNotNull(ip);
78         this.sessionIds.remove(ip);
79     }
80
81     @Override
82     public boolean isPeerConfigured(final IpAddress ip) {
83         Preconditions.checkNotNull(ip);
84         return this.peers.containsKey(ip);
85     }
86
87     private void checkPeerConfigured(final IpAddress ip) {
88         Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, this.peers.keySet());
89     }
90
91     @Override
92     public synchronized BGPSessionListener getPeer(final IpAddress ip, final Ipv4Address sourceId,
93         final Ipv4Address remoteId, final AsNumber asNumber) throws BGPDocumentedException {
94         Preconditions.checkNotNull(ip);
95         Preconditions.checkNotNull(sourceId);
96         Preconditions.checkNotNull(remoteId);
97         Preconditions.checkNotNull(asNumber);
98
99         checkPeerConfigured(ip);
100
101         final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId, asNumber);
102         final BGPSessionListener p = this.peers.get(ip);
103
104         final BGPSessionId previousConnection = this.sessionIds.get(ip);
105
106         if (previousConnection != null) {
107
108             LOG.warn("Duplicate BGP session established with {}", ip);
109
110             // Session reestablished with different ids
111             if (!previousConnection.equals(currentConnection)) {
112                 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
113                 throw new BGPDocumentedException(
114                     String.format("BGP session with %s %s has to be dropped. Same session already present %s",
115                         ip, currentConnection, previousConnection),
116                         BGPError.CEASE);
117
118                 // Session reestablished with lower source bgp id, dropping current
119             } else if (previousConnection.isHigherDirection(currentConnection)) {
120                 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
121                 throw new BGPDocumentedException(
122                     String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
123                         ip, currentConnection),
124                         BGPError.CEASE);
125
126                 // Session reestablished with higher source bgp id, dropping previous
127             } else if (currentConnection.isHigherDirection(previousConnection)) {
128                 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
129                 this.peers.get(ip).releaseConnection();
130                 return this.peers.get(ip);
131
132             } else if (previousConnection.hasHigherAsNumber(currentConnection)) {
133                 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
134                 throw new BGPDocumentedException(
135                     String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
136                         ip, currentConnection),
137                         BGPError.CEASE);
138             } else if (currentConnection.hasHigherAsNumber(previousConnection)) {
139                 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
140                 this.peers.get(ip).releaseConnection();
141                 return this.peers.get(ip);
142             // Session reestablished with same source bgp id, dropping current as duplicate
143             } else {
144                 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
145                 throw new BGPDocumentedException(
146                     String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
147                         ip, currentConnection),
148                         BGPError.CEASE);
149             }
150         } else {
151             if (!getPeerPreferences(ip).getMyAs().equals(asNumber)) {
152                 LOG.warn("Unexpected remote AS number. Expecting {}, got {}", getPeerPreferences(ip).getMyAs(), asNumber);
153                 throw new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS);
154             }
155         }
156
157         // Map session id to peer IP address
158         this.sessionIds.put(ip, currentConnection);
159         return p;
160     }
161
162     @Override
163     public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
164         Preconditions.checkNotNull(ip);
165         checkPeerConfigured(ip);
166         return this.peerPreferences.get(ip);
167     }
168
169     /**
170      * Creates IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
171      *
172      * @param socketAddress socket address to transform
173      * @return IpAddress equivalent to given socket address
174      * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
175      */
176     public static IpAddress getIpAddress(final SocketAddress socketAddress) {
177         Preconditions.checkNotNull(socketAddress);
178         Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
179         final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
180
181         Preconditions.checkArgument(inetAddress instanceof Inet4Address || inetAddress instanceof Inet6Address, "Expecting %s or %s but was %s", Inet4Address.class, Inet6Address.class, inetAddress.getClass());
182         if(inetAddress instanceof Inet4Address) {
183             return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
184         }
185         return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
186     }
187
188     @Override
189     public synchronized void close() {
190         this.peers.clear();
191         this.sessionIds.clear();
192     }
193
194     @Override
195     public String toString() {
196         return MoreObjects.toStringHelper(this)
197             .add("peers", this.peers.keySet())
198             .toString();
199     }
200
201     /**
202      * Session identifier that contains (source Bgp Id) -> (destination Bgp Id)
203      */
204     private static final class BGPSessionId {
205
206         private final Ipv4Address from, to;
207         private final AsNumber asNumber;
208
209         BGPSessionId(final Ipv4Address from, final Ipv4Address to, final AsNumber asNumber) {
210             this.from = Preconditions.checkNotNull(from);
211             this.to = Preconditions.checkNotNull(to);
212             this.asNumber = Preconditions.checkNotNull(asNumber);
213         }
214
215         /**
216          * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
217          */
218         @Override
219         public boolean equals(final Object o) {
220             if (this == o) {
221                 return true;
222             }
223             if (o == null || getClass() != o.getClass()) {
224                 return false;
225             }
226
227             final BGPSessionId bGPSessionId = (BGPSessionId) o;
228
229             if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
230                 return false;
231             }
232             if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
233                 return false;
234             }
235
236             return true;
237         }
238
239         @Override
240         public int hashCode() {
241             final int prime = 31;
242             int result = this.from.hashCode() + this.to.hashCode();
243             result = prime * result;
244             return result;
245         }
246
247         /**
248          * Check if this connection is equal to other and if it contains higher source bgp id
249          */
250         boolean isHigherDirection(final BGPSessionId other) {
251             return toLong(this.from) > toLong(other.from);
252         }
253
254         boolean hasHigherAsNumber(final BGPSessionId other) {
255             return this.asNumber.getValue() > other.asNumber.getValue();
256         }
257
258         private static long toLong(final Ipv4Address from) {
259             final int i = InetAddresses.coerceToInteger(InetAddresses.forString(from.getValue()));
260             return UnsignedInts.toLong(i);
261         }
262
263         @Override
264         public String toString() {
265             return MoreObjects.toStringHelper(this)
266                 .add("from", this.from)
267                 .add("to", this.to)
268                 .toString();
269         }
270     }
271 }