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