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