IllegalArgument Exception changed to Preconditions checks
[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      * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
174      */
175     public static IpAddress getIpAddress(final SocketAddress socketAddress) {
176         Preconditions.checkNotNull(socketAddress);
177         Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
178         final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
179
180         Preconditions.checkArgument(inetAddress instanceof Inet4Address || inetAddress instanceof Inet6Address, "Expecting %s or %s but was %s", Inet4Address.class, Inet6Address.class, inetAddress.getClass());
181         if(inetAddress instanceof Inet4Address) {
182             return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
183         }
184         return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
185     }
186
187     @Override
188     public synchronized void close() {
189         this.peers.clear();
190         this.sessionIds.clear();
191     }
192
193     @Override
194     public String toString() {
195         return MoreObjects.toStringHelper(this)
196             .add("peers", this.peers.keySet())
197             .toString();
198     }
199
200     /**
201      * Session identifier that contains (source Bgp Id) -> (destination Bgp Id)
202      */
203     private static final class BGPSessionId {
204
205         private final Ipv4Address from, to;
206         private final AsNumber asNumber;
207
208         BGPSessionId(final Ipv4Address from, final Ipv4Address to, final AsNumber asNumber) {
209             this.from = Preconditions.checkNotNull(from);
210             this.to = Preconditions.checkNotNull(to);
211             this.asNumber = Preconditions.checkNotNull(asNumber);
212         }
213
214         /**
215          * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
216          */
217         @Override
218         public boolean equals(final Object o) {
219             if (this == o) {
220                 return true;
221             }
222             if (o == null || getClass() != o.getClass()) {
223                 return false;
224             }
225
226             final BGPSessionId bGPSessionId = (BGPSessionId) o;
227
228             if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
229                 return false;
230             }
231             if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
232                 return false;
233             }
234
235             return true;
236         }
237
238         @Override
239         public int hashCode() {
240             final int prime = 31;
241             int result = this.from.hashCode() + this.to.hashCode();
242             result = prime * result;
243             return result;
244         }
245
246         /**
247          * Check if this connection is equal to other and if it contains higher source bgp id
248          */
249         boolean isHigherDirection(final BGPSessionId other) {
250             return toLong(this.from) > toLong(other.from);
251         }
252
253         boolean hasHigherAsNumber(final BGPSessionId other) {
254             return this.asNumber.getValue() > other.asNumber.getValue();
255         }
256
257         private static long toLong(final Ipv4Address from) {
258             final int i = InetAddresses.coerceToInteger(InetAddresses.forString(from.getValue()));
259             return UnsignedInts.toLong(i);
260         }
261
262         @Override
263         public String toString() {
264             return MoreObjects.toStringHelper(this)
265                 .add("from", this.from)
266                 .add("to", this.to)
267                 .toString();
268         }
269     }
270 }