6501d325604284962b01b9e6c414c3bf5d51eb54
[netvirt.git] / neutronvpn / impl / src / main / java / org / opendaylight / netvirt / neutronvpn / NeutronBgpvpnChangeListener.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. 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 package org.opendaylight.netvirt.neutronvpn;
9
10 import java.math.BigInteger;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.HashSet;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Set;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.Future;
20 import javax.annotation.PostConstruct;
21 import javax.inject.Inject;
22 import javax.inject.Singleton;
23 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
26 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronConstants;
27 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInputBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolOutput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMap;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.bgpvpns.rev150903.BgpvpnTypeBase;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.bgpvpns.rev150903.BgpvpnTypeL3;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.bgpvpns.rev150903.bgpvpns.attributes.Bgpvpns;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.bgpvpns.rev150903.bgpvpns.attributes.bgpvpns.Bgpvpn;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.common.RpcError;
41 import org.opendaylight.yangtools.yang.common.RpcResult;
42 import org.osgi.framework.BundleContext;
43 import org.osgi.framework.FrameworkUtil;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 @Singleton
48 public class NeutronBgpvpnChangeListener extends AsyncDataTreeChangeListenerBase<Bgpvpn, NeutronBgpvpnChangeListener> {
49     private static final Logger LOG = LoggerFactory.getLogger(NeutronBgpvpnChangeListener.class);
50     private final DataBroker dataBroker;
51     private final NeutronvpnManager nvpnManager;
52     private final IdManagerService idManager;
53     private final NeutronvpnUtils neutronvpnUtils;
54     private final String adminRDValue;
55
56     @Inject
57     public NeutronBgpvpnChangeListener(final DataBroker dataBroker, final NeutronvpnManager neutronvpnManager,
58                                        final IdManagerService idManager, final NeutronvpnUtils neutronvpnUtils) {
59         super(Bgpvpn.class, NeutronBgpvpnChangeListener.class);
60         this.dataBroker = dataBroker;
61         nvpnManager = neutronvpnManager;
62         this.idManager = idManager;
63         this.neutronvpnUtils = neutronvpnUtils;
64         BundleContext bundleContext = FrameworkUtil.getBundle(NeutronBgpvpnChangeListener.class).getBundleContext();
65         adminRDValue = bundleContext.getProperty(NeutronConstants.RD_PROPERTY_KEY);
66     }
67
68     @Override
69     @PostConstruct
70     public void init() {
71         LOG.info("{} init", getClass().getSimpleName());
72         createIdPool();
73         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
74     }
75
76     @Override
77     protected InstanceIdentifier<Bgpvpn> getWildCardPath() {
78         return InstanceIdentifier.create(Neutron.class).child(Bgpvpns.class).child(Bgpvpn.class);
79     }
80
81     @Override
82     protected NeutronBgpvpnChangeListener getDataTreeChangeListener() {
83         return NeutronBgpvpnChangeListener.this;
84     }
85
86     private boolean isBgpvpnTypeL3(Class<? extends BgpvpnTypeBase> bgpvpnType) {
87         if (BgpvpnTypeL3.class.equals(bgpvpnType)) {
88             return true;
89         } else {
90             LOG.warn("CRUD operations supported only for L3 type Bgpvpn");
91             return false;
92         }
93     }
94
95     @Override
96     // TODO Clean up the exception handling
97     @SuppressWarnings("checkstyle:IllegalCatch")
98     protected void add(InstanceIdentifier<Bgpvpn> identifier, Bgpvpn input) {
99         LOG.trace("Adding Bgpvpn : key: {}, value={}", identifier, input);
100         String vpnName = input.getUuid().getValue();
101         if (isBgpvpnTypeL3(input.getType())) {
102             VpnInstance.Type vpnInstanceType = VpnInstance.Type.L3;
103             // handle route-target(s)
104             List<String> inputRouteList = input.getRouteTargets();
105             List<String> inputImportRouteList = input.getImportTargets();
106             List<String> inputExportRouteList = input.getExportTargets();
107             Set<String> inputImportRouteSet = new HashSet<>();
108             Set<String> inputExportRouteSet = new HashSet<>();
109
110             if (inputRouteList != null && !inputRouteList.isEmpty()) {
111                 inputImportRouteSet.addAll(inputRouteList);
112                 inputExportRouteSet.addAll(inputRouteList);
113             }
114             if (inputImportRouteList != null && !inputImportRouteList.isEmpty()) {
115                 inputImportRouteSet.addAll(inputImportRouteList);
116             }
117             if (inputExportRouteList != null && !inputExportRouteList.isEmpty()) {
118                 inputExportRouteSet.addAll(inputExportRouteList);
119             }
120             List<String> importRouteTargets = new ArrayList<>();
121             List<String> exportRouteTargets = new ArrayList<>();
122             importRouteTargets.addAll(inputImportRouteSet);
123             exportRouteTargets.addAll(inputExportRouteSet);
124
125             List<String> rd = input.getRouteDistinguishers() != null
126                     ? input.getRouteDistinguishers() : new ArrayList<>();
127
128             if (rd == null || rd.isEmpty()) {
129                 // generate new RD
130                 // TODO - commented out for now to avoid "Dead store to rd" violation.
131                 //rd = generateNewRD(input.getUuid());
132             } else {
133                 String[] rdParams = rd.get(0).split(":");
134                 if (rdParams[0].trim().equals(adminRDValue)) {
135                     LOG.error("AS specific part of RD should not be same as that defined by DC Admin. Error "
136                             + "encountered for BGPVPN {} with RD {}", vpnName, rd.get(0));
137                     return;
138                 }
139                 List<String> existingRDs = neutronvpnUtils.getExistingRDs();
140                 if (!Collections.disjoint(existingRDs, rd)) {
141                     LOG.error("Failed to create VPN {} as another VPN with the same RD {} already exists.", vpnName,
142                             rd);
143                     return;
144                 }
145                 List<Uuid> routersList = null;
146                 if (input.getRouters() != null && !input.getRouters().isEmpty()) {
147                     // try to take all routers
148                     routersList = input.getRouters();
149                 }
150                 if (routersList != null && routersList.size() > NeutronConstants.MAX_ROUTERS_PER_BGPVPN) {
151                     LOG.error("Creation of BGPVPN for rd {} failed: maximum allowed number of associated "
152                              + "routers is {}.", rd, NeutronConstants.MAX_ROUTERS_PER_BGPVPN);
153                     return;
154                 }
155                 List<Uuid> networkList = null;
156                 if (input.getNetworks() != null && !input.getNetworks().isEmpty()) {
157                     networkList = input.getNetworks();
158                 }
159                 if (!rd.isEmpty()) {
160                     try {
161                         nvpnManager.createVpn(input.getUuid(), input.getName(), input.getTenantId(), rd,
162                                 importRouteTargets, exportRouteTargets, routersList, networkList,
163                                 vpnInstanceType, 0 /*l3vni*/);
164                     } catch (Exception e) {
165                         LOG.error("Creation of BGPVPN {} failed", vpnName, e);
166                     }
167                 } else {
168                     LOG.error("Create BgpVPN with id {} failed due to missing RD value", vpnName);
169                 }
170             }
171         } else {
172             LOG.warn("BGPVPN type for VPN {} is not L3", vpnName);
173         }
174     }
175
176     @Override
177     protected void remove(InstanceIdentifier<Bgpvpn> identifier, Bgpvpn input) {
178         LOG.trace("Removing Bgpvpn : key: {}, value={}", identifier, input);
179         Uuid vpnId = input.getUuid();
180         if (isBgpvpnTypeL3(input.getType())) {
181             VpnMap vpnMap = neutronvpnUtils.getVpnMap(vpnId);
182             if (vpnMap == null) {
183                 LOG.error("Failed to handle BGPVPN Remove for VPN {} as that VPN is not configured"
184                         + " yet as a VPN Instance", vpnId.getValue());
185                 return;
186             }
187             nvpnManager.removeVpn(input.getUuid());
188             // Release RD Id in pool
189             List<String> rd = input.getRouteDistinguishers();
190             if (rd == null || rd.isEmpty()) {
191                 int releasedId = neutronvpnUtils.releaseId(NeutronConstants.RD_IDPOOL_NAME, vpnId.getValue());
192                 if (releasedId == NeutronConstants.INVALID_ID) {
193                     LOG.error("NeutronBgpvpnChangeListener remove: Unable to release ID for key {}", vpnId.getValue());
194                 }
195             }
196         } else {
197             LOG.warn("BGPVPN type for VPN {} is not L3", vpnId.getValue());
198         }
199     }
200
201     @Override
202     protected void update(InstanceIdentifier<Bgpvpn> identifier, Bgpvpn original, Bgpvpn update) {
203         LOG.trace("Update Bgpvpn : key: {}, value={}", identifier, update);
204         Uuid vpnId = update.getUuid();
205         if (isBgpvpnTypeL3(update.getType())) {
206             try {
207                 handleVpnInstanceUpdate(original.getUuid().getValue(), original.getRouteDistinguishers(),
208                         update.getRouteDistinguishers());
209             } catch (UnsupportedOperationException e) {
210                 LOG.error("Error while processing Update Bgpvpn.", e);
211                 return;
212             }
213             List<Uuid> oldNetworks = original.getNetworks();
214             List<Uuid> newNetworks = update.getNetworks();
215             handleNetworksUpdate(vpnId, oldNetworks, newNetworks);
216             List<Uuid> oldRouters = original.getRouters();
217             List<Uuid> newRouters = update.getRouters();
218             handleRoutersUpdate(vpnId, oldRouters, newRouters);
219         } else {
220             LOG.warn("BGPVPN type for VPN {} is not L3", vpnId.getValue());
221         }
222     }
223
224     protected void handleVpnInstanceUpdate(String vpnInstanceName,final List<String> originalRds,
225                                            List<String> updateRDs) throws UnsupportedOperationException {
226         if (updateRDs == null || updateRDs.isEmpty()) {
227             return;
228         }
229         int oldRdsCount = originalRds.size();
230
231         for (String rd : originalRds) {
232             //If the existing rd is not present in the updateRds list, not allow to process the updateRDs.
233             if (!updateRDs.contains(rd)) {
234                 LOG.error("The existing RD {} not present in the updatedRDsList:{}", rd, updateRDs);
235                 throw new UnsupportedOperationException("The existing RD not present in the updatedRDsList");
236             }
237         }
238         if (updateRDs.size() == oldRdsCount) {
239             LOG.debug("There is no update in the List of Route Distinguisher for the VpnInstance:{}", vpnInstanceName);
240             return;
241         }
242         LOG.debug("update the VpnInstance:{} with the List of RDs: {}", vpnInstanceName, updateRDs);
243         nvpnManager.updateVpnInstanceWithRDs(vpnInstanceName, updateRDs);
244     }
245
246     protected void handleNetworksUpdate(Uuid vpnId, List<Uuid> oldNetworks, List<Uuid> newNetworks) {
247         if (newNetworks != null && !newNetworks.isEmpty()) {
248             if (oldNetworks != null && !oldNetworks.isEmpty()) {
249                 if (oldNetworks != newNetworks) {
250                     Iterator<Uuid> iter = newNetworks.iterator();
251                     while (iter.hasNext()) {
252                         Uuid net = iter.next();
253                         if (oldNetworks.contains(net)) {
254                             oldNetworks.remove(net);
255                             iter.remove();
256                         }
257                     }
258                     //clear removed networks
259                     if (!oldNetworks.isEmpty()) {
260                         LOG.trace("Removing old networks {} ", oldNetworks);
261                         List<String> errorMessages = nvpnManager.dissociateNetworksFromVpn(vpnId, oldNetworks);
262                         if (!errorMessages.isEmpty()) {
263                             LOG.error("handleNetworksUpdate: dissociate old Networks not part of bgpvpn update,"
264                                     + " from vpn {} failed due to {}", vpnId.getValue(), errorMessages);
265                         }
266                     }
267
268                     //add new (Delta) Networks
269                     if (!newNetworks.isEmpty()) {
270                         LOG.trace("Adding delta New networks {} ", newNetworks);
271                         List<String> errorMessages = nvpnManager.associateNetworksToVpn(vpnId, newNetworks);
272                         if (!errorMessages.isEmpty()) {
273                             LOG.error("handleNetworksUpdate: associate new Networks not part of original bgpvpn,"
274                                     + " to vpn {} failed due to {}", vpnId.getValue(), errorMessages);
275                         }
276                     }
277                 }
278             } else {
279                 //add new Networks
280                 LOG.trace("Adding New networks {} ", newNetworks);
281                 List<String> errorMessages = nvpnManager.associateNetworksToVpn(vpnId, newNetworks);
282                 if (!errorMessages.isEmpty()) {
283                     LOG.error("handleNetworksUpdate: associate new Networks to vpn {} failed due to {}",
284                             vpnId.getValue(), errorMessages);
285                 }
286             }
287         } else if (oldNetworks != null && !oldNetworks.isEmpty()) {
288             LOG.trace("Removing old networks {} ", oldNetworks);
289             List<String> errorMessages = nvpnManager.dissociateNetworksFromVpn(vpnId, oldNetworks);
290             if (!errorMessages.isEmpty()) {
291                 LOG.error("handleNetworksUpdate: dissociate old Networks from vpn {} failed due to {}",
292                         vpnId.getValue(), errorMessages);
293             }
294         }
295     }
296
297     protected void handleRoutersUpdate(Uuid vpnId, List<Uuid> oldRouters, List<Uuid> newRouters) {
298         // for dualstack case we can associate with one VPN instance maximum 2 routers: one with
299         // only IPv4 ports and one with only IPv6 ports, or only one router with IPv4/IPv6 ports
300         // TODO: check router ports ethertype to follow this restriction
301         if (oldRouters != null && !oldRouters.isEmpty()) {
302             //remove to oldRouters the newRouters if existing
303             List<Uuid> oldRoutersCopy = new ArrayList<>();
304             oldRoutersCopy.addAll(oldRouters);
305             if (newRouters != null) {
306                 newRouters.forEach(r -> oldRoutersCopy.remove(r));
307             }
308             /* dissociate old router */
309             oldRoutersCopy.forEach(r -> {
310                 nvpnManager.dissociateRouterFromVpn(vpnId, r);
311             });
312         }
313         if (newRouters != null && !newRouters.isEmpty()) {
314             if (newRouters.size() > NeutronConstants.MAX_ROUTERS_PER_BGPVPN) {
315                 LOG.debug("In handleRoutersUpdate: maximum allowed number of associated routers is 2. VPN: {} "
316                         + "is already associated with router: {} and with router: {}",
317                         vpnId, newRouters.get(0).getValue(), newRouters.get(1).getValue());
318                 return;
319             } else {
320                 for (Uuid routerId : newRouters) {
321                     if (oldRouters != null && oldRouters.contains(routerId)) {
322                         continue;
323                     }
324                     /* If the first time BGP-VPN is getting associated with router, then no need
325                        to validate if the router is already been associated with any other BGP-VPN.
326                        This will avoid unnecessary MD-SAL data store read operations in VPN-MAPS.
327                      */
328                     if (oldRouters == null || oldRouters.isEmpty()) {
329                         nvpnManager.associateRouterToVpn(vpnId, routerId);
330                     } else if (validateRouteInfo(routerId)) {
331                         nvpnManager.associateRouterToVpn(vpnId, routerId);
332                     }
333                 }
334             }
335         }
336     }
337
338     private void createIdPool() {
339         CreateIdPoolInput createPool = new CreateIdPoolInputBuilder().setPoolName(NeutronConstants.RD_IDPOOL_NAME)
340                 .setLow(NeutronConstants.RD_IDPOOL_START)
341                 .setHigh(new BigInteger(NeutronConstants.RD_IDPOOL_SIZE).longValue()).build();
342         try {
343             Future<RpcResult<CreateIdPoolOutput>> result = idManager.createIdPool(createPool);
344             Collection<RpcError> rpcErrors = null;
345             if (result != null && result.get() != null) {
346                 RpcResult<CreateIdPoolOutput> rpcResult = result.get();
347                 LOG.info("Created IdPool for Bgpvpn RD");
348                 if (rpcResult.isSuccessful()) {
349                     LOG.info("Created IdPool for Bgpvpn RD");
350                     return;
351                 }
352                 rpcErrors = rpcResult.getErrors();
353                 LOG.error("Failed to create ID pool for BGPVPN RD, result future returned {}", result);
354             }
355             LOG.error("createIdPool: Failed to create ID pool for BGPVPN RD, the call returned with RPC errors {}",
356                     rpcErrors != null ? rpcErrors : "RpcResult is null");
357         } catch (InterruptedException | ExecutionException e) {
358             LOG.error("Failed to create idPool for Bgpvpn RD", e);
359         }
360     }
361
362     private boolean validateRouteInfo(Uuid routerID) {
363         Uuid assocVPNId;
364         if ((assocVPNId = neutronvpnUtils.getVpnForRouter(routerID, true)) != null) {
365             LOG.warn("VPN router association failed due to router {} already associated to another VPN {}",
366                     routerID.getValue(), assocVPNId.getValue());
367             return false;
368         }
369         return true;
370     }
371
372 }