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