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