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