BUG-2109 : remove also sessionId when bgp session is closed
[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
98         if (this.sessionIds.containsKey(ip)) {
99             LOG.warn("Duplicate BGP session established with {}", ip);
100
101             final BGPSessionId previousConnection = this.sessionIds.get(ip);
102
103             // Session reestablished with different ids
104             if (!previousConnection.equals(currentConnection)) {
105                 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
106                 throw new BGPDocumentedException(
107                     String.format("BGP session with %s %s has to be dropped. Same session already present %s",
108                         ip, currentConnection, previousConnection),
109                         BGPError.CEASE);
110
111                 // Session reestablished with lower source bgp id, dropping current
112             } else if (previousConnection.isHigherDirection(currentConnection)) {
113                 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
114                 throw new BGPDocumentedException(
115                     String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
116                         ip, currentConnection),
117                         BGPError.CEASE);
118
119                 // Session reestablished with higher source bgp id, dropping previous
120             } else if (currentConnection.isHigherDirection(previousConnection)) {
121                 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
122                 this.peers.get(ip).releaseConnection();
123                 return this.peers.get(ip);
124
125                 // Session reestablished with same source bgp id, dropping current as duplicate
126             } else {
127                 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
128                 throw new BGPDocumentedException(
129                     String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
130                         ip, currentConnection),
131                         BGPError.CEASE);
132             }
133         }
134
135         // Map session id to peer IP address
136         this.sessionIds.put(ip, currentConnection);
137         return this.peers.get(ip);
138     }
139
140     @Override
141     public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
142         Preconditions.checkNotNull(ip);
143         checkPeerConfigured(ip);
144         return this.peerPreferences.get(ip);
145     }
146
147     /**
148      * Create IpAddress from SocketAddress. Only InetSocketAddress is accepted with inner address: Inet4Address and Inet6Address.
149      *
150      * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
151      * @param socketAddress socket address to transform
152      */
153     public static IpAddress getIpAddress(final SocketAddress socketAddress) {
154         Preconditions.checkNotNull(socketAddress);
155         Preconditions.checkArgument(socketAddress instanceof InetSocketAddress, "Expecting InetSocketAddress but was %s", socketAddress.getClass());
156         final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
157
158         if(inetAddress instanceof Inet4Address) {
159             return new IpAddress(new Ipv4Address(inetAddress.getHostAddress()));
160         } else if(inetAddress instanceof Inet6Address) {
161             return new IpAddress(new Ipv6Address(inetAddress.getHostAddress()));
162         }
163
164         throw new IllegalArgumentException("Expecting " + Inet4Address.class + " or " + Inet6Address.class + " but was " + inetAddress.getClass());
165     }
166
167     @Override
168     public synchronized void close() {
169         this.peers.clear();
170         this.sessionIds.clear();
171     }
172
173     @Override
174     public String toString() {
175         return Objects.toStringHelper(this)
176             .add("peers", this.peers.keySet())
177             .toString();
178     }
179
180     /**
181      * Session identifier that contains (source Bgp Id) -> (destination Bgp Id)
182      */
183     private static final class BGPSessionId {
184         private final Ipv4Address from, to;
185
186         BGPSessionId(final Ipv4Address from, final Ipv4Address to) {
187             this.from = Preconditions.checkNotNull(from);
188             this.to = Preconditions.checkNotNull(to);
189         }
190
191         /**
192          * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
193          */
194         @Override
195         public boolean equals(final Object o) {
196             if (this == o) {
197                 return true;
198             }
199             if (o == null || getClass() != o.getClass()) {
200                 return false;
201             }
202
203             final BGPSessionId bGPSessionId = (BGPSessionId) o;
204
205             if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
206                 return false;
207             }
208             if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
209                 return false;
210             }
211
212             return true;
213         }
214
215         @Override
216         public int hashCode() {
217             final int prime = 31;
218             int result = this.from.hashCode() + this.to.hashCode();
219             result = prime * result;
220             return result;
221         }
222
223         /**
224          * Check if this connection is equal to other and if it contains higher source bgp id
225          */
226         boolean isHigherDirection(final BGPSessionId other) {
227             Preconditions.checkState(!this.isSameDirection(other), "Equal sessions with same direction");
228             return toLong(this.from) > toLong(other.from);
229         }
230
231         private long toLong(final Ipv4Address from) {
232             return Long.parseLong(NONDIGIT.removeFrom(from.getValue()));
233         }
234
235         /**
236          * Check if 2 connections are equal and face same direction
237          */
238         boolean isSameDirection(final BGPSessionId other) {
239             Preconditions.checkState(this.equals(other), "Only equal sessions can be compared");
240             return this.from.equals(other.from);
241         }
242
243         @Override
244         public String toString() {
245             return Objects.toStringHelper(this)
246                 .add("from", this.from)
247                 .add("to", this.to)
248                 .toString();
249         }
250     }
251 }