2 * Copyright (c) 2015 - 2016 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
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
8 package org.opendaylight.vpnservice;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.List;
13 import java.util.concurrent.*;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import org.opendaylight.bgpmanager.api.IBgpManager;
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
19 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
22 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
23 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets.VpnTarget;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstanceToVpnId;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstanceToVpnIdBuilder;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnRouteList;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryKey;
30 import org.opendaylight.yangtools.concepts.ListenerRegistration;
31 import org.opendaylight.yangtools.yang.binding.DataObject;
32 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
35 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnAfConfig;
36 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInterfaces;
37 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
38 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceKey;
39 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances;
40 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceBuilder;
41 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstanceOpData;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstanceOpDataBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.FibEntries;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTables;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTablesKey;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.vrfentries.VrfEntry;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.IdManagerService;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 import com.google.common.base.Optional;
53 import com.google.common.util.concurrent.FutureCallback;
54 import com.google.common.util.concurrent.Futures;
56 public class VpnManager extends AbstractDataChangeListener<VpnInstance> implements AutoCloseable {
57 private static final Logger LOG = LoggerFactory.getLogger(VpnManager.class);
58 private ListenerRegistration<DataChangeListener> listenerRegistration, fibListenerRegistration, opListenerRegistration;
59 private ConcurrentMap<String, Runnable> vpnOpMap = new ConcurrentHashMap<String, Runnable>();
60 private ExecutorService executorService = Executors.newSingleThreadExecutor();
61 private final DataBroker broker;
62 private final IBgpManager bgpManager;
63 private IdManagerService idManager;
64 private VpnInterfaceManager vpnInterfaceManager;
65 private final FibEntriesListener fibListener;
66 private final VpnInstanceOpListener vpnInstOpListener;
67 private NotificationService notificationService;
69 private static final FutureCallback<Void> DEFAULT_CALLBACK =
70 new FutureCallback<Void>() {
71 public void onSuccess(Void result) {
72 LOG.debug("Success in Datastore operation");
75 public void onFailure(Throwable error) {
76 LOG.error("Error in Datastore operation", error);
81 * Listens for data change related to VPN Instance
82 * Informs the BGP about VRF information
84 * @param db - dataBroker reference
86 public VpnManager(final DataBroker db, final IBgpManager bgpManager) {
87 super(VpnInstance.class);
89 this.bgpManager = bgpManager;
90 this.fibListener = new FibEntriesListener();
91 this.vpnInstOpListener = new VpnInstanceOpListener();
95 private void registerListener(final DataBroker db) {
97 listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
98 getWildCardPath(), VpnManager.this, DataChangeScope.SUBTREE);
99 fibListenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL,
100 getFibEntryListenerPath(), fibListener, DataChangeScope.BASE);
101 opListenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL,
102 getVpnInstanceOpListenerPath(), vpnInstOpListener, DataChangeScope.SUBTREE);
104 } catch (final Exception e) {
105 LOG.error("VPN Service DataChange listener registration fail !", e);
106 throw new IllegalStateException("VPN Service registration Listener failed.", e);
110 public void setIdManager(IdManagerService idManager) {
111 this.idManager = idManager;
114 public void setVpnInterfaceManager(VpnInterfaceManager vpnInterfaceManager) {
115 this.vpnInterfaceManager = vpnInterfaceManager;
118 private void waitForOpRemoval(String id, long timeout) {
119 //wait till DCN for update on VPN Instance Op Data signals that vpn interfaces linked to this vpn instance is zero
120 Runnable notifyTask = new VpnNotifyTask();
121 synchronized (id.intern()) {
123 vpnOpMap.put(id, notifyTask);
124 synchronized (notifyTask) {
126 notifyTask.wait(timeout);
127 } catch (InterruptedException e) {
138 protected void remove(InstanceIdentifier<VpnInstance> identifier, VpnInstance del) {
139 LOG.trace("Remove VPN event key: {}, value: {}", identifier, del);
140 String vpnName = del.getVpnInstanceName();
141 String rd = del.getIpv4Family().getRouteDistinguisher();
142 long vpnId = VpnUtil.getVpnId(broker, vpnName);
144 //TODO(vpnteam): Entire code would need refactoring to listen only on the parent object - VPNInstance
145 Optional<VpnInstanceOpDataEntry> vpnOpValue = null;
146 if ((rd != null) && (!rd.isEmpty())) {
147 vpnOpValue = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL,
148 VpnUtil.getVpnInstanceOpDataIdentifier(rd));
150 vpnOpValue = VpnUtil.read(broker, LogicalDatastoreType.OPERATIONAL,
151 VpnUtil.getVpnInstanceOpDataIdentifier(vpnName));
154 if ((vpnOpValue != null) && (vpnOpValue.isPresent())) {
155 VpnInstanceOpDataEntry vpnOpEntry = null;
156 long timeout = VpnConstants.MIN_WAIT_TIME_IN_MILLISECONDS;
159 vpnOpEntry = vpnOpValue.get();
160 intfCount = vpnOpEntry.getVpnInterfaceCount();
161 if (intfCount != null && intfCount > 0) {
162 // Minimum wait time of 10 seconds for one VPN Interface clearance (inclusive of full trace on)
163 timeout = intfCount * 10000;
164 // Maximum wait time of 90 seconds for all VPN Interfaces clearance (inclusive of full trace on)
165 if (timeout > VpnConstants.MAX_WAIT_TIME_IN_MILLISECONDS) {
166 timeout = VpnConstants.MAX_WAIT_TIME_IN_MILLISECONDS;
168 LOG.trace("VPNInstance removal count of interface at {} for for rd {}, vpnname {}",
169 intfCount, rd, vpnName);
171 LOG.trace("VPNInstance removal thread waiting for {} seconds for rd {}, vpnname {}",
172 (timeout/1000), rd, vpnName);
174 if ((rd != null) && (!rd.isEmpty())) {
175 waitForOpRemoval(rd, timeout);
177 waitForOpRemoval(vpnName, timeout);
180 LOG.trace("Returned out of waiting for Op Data removal for rd {}, vpnname {}", rd, vpnName);
182 // Clean up VpnInstanceToVpnId from Config DS
183 VpnUtil.removeVpnInstanceToVpnId(broker, vpnName);
184 LOG.trace("Removed vpnIdentifier for rd{} vpnname {}", rd, vpnName);
187 bgpManager.deleteVrf(rd);
188 } catch (Exception e) {
189 LOG.error("Exception when removing VRF from BGP for RD {} in VPN {} exception " + e, rd, vpnName);
192 // Clean up VPNExtraRoutes Operational DS
193 VpnUtil.removeVpnExtraRouteForVpn(broker, rd);
195 // Clean up VPNInstanceOpDataEntry
196 VpnUtil.removeVpnOpInstance(broker, rd);
198 // Clean up FIB Entries Config DS
199 VpnUtil.removeVrfTableForVpn(broker, vpnName);
201 // Clean up VPNExtraRoutes Operational DS
202 VpnUtil.removeVpnExtraRouteForVpn(broker, vpnName);
204 // Clean up VPNInstanceOpDataEntry
205 VpnUtil.removeVpnOpInstance(broker, vpnName);
208 // Clean up PrefixToInterface Operational DS
209 VpnUtil.removePrefixToInterfaceForVpnId(broker, vpnId);
211 // Clean up L3NextHop Operational DS
212 VpnUtil.removeL3nexthopForVpnId(broker, vpnId);
214 // Release the ID used for this VPN back to IdManager
216 VpnUtil.releaseId(idManager, VpnConstants.VPN_IDPOOL_NAME, vpnName);
220 protected void update(InstanceIdentifier<VpnInstance> identifier,
221 VpnInstance original, VpnInstance update) {
222 LOG.trace("Update VPN event key: {}, value: {}", identifier, update);
226 protected void add(InstanceIdentifier<VpnInstance> identifier,
228 LOG.trace("Add VPN event key: {}, value: {}", identifier, value);
229 VpnAfConfig config = value.getIpv4Family();
230 String rd = config.getRouteDistinguisher();
232 long vpnId = VpnUtil.getUniqueId(idManager, VpnConstants.VPN_IDPOOL_NAME, value.getVpnInstanceName());
233 LOG.trace("VPN instance to ID generated.");
234 org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance
235 vpnInstanceToVpnId = VpnUtil.getVpnInstanceToVpnId(value.getVpnInstanceName(), vpnId,
236 (rd != null) ? rd : value.getVpnInstanceName());
238 syncWrite(LogicalDatastoreType.CONFIGURATION,
239 VpnUtil.getVpnInstanceToVpnIdIdentifier(value.getVpnInstanceName()),
240 vpnInstanceToVpnId, DEFAULT_CALLBACK);
244 VpnInstanceOpDataEntryBuilder builder = new VpnInstanceOpDataEntryBuilder();
245 builder.setVrfId(value.getVpnInstanceName()).setVpnId(vpnId);
246 builder.setVpnInterfaceCount(0L);
247 syncWrite(LogicalDatastoreType.OPERATIONAL,
248 VpnUtil.getVpnInstanceOpDataIdentifier(value.getVpnInstanceName()),
249 builder.build(), DEFAULT_CALLBACK);
252 VpnInstanceOpDataEntryBuilder builder = new VpnInstanceOpDataEntryBuilder();
253 builder.setVrfId(rd).setVpnId(vpnId);
254 builder.setVpnInterfaceCount(0L);
255 syncWrite(LogicalDatastoreType.OPERATIONAL,
256 VpnUtil.getVpnInstanceOpDataIdentifier(rd),
257 builder.build(), DEFAULT_CALLBACK);
259 List<VpnTarget> vpnTargetList = config.getVpnTargets().getVpnTarget();
261 List<String> ertList = new ArrayList<String>();
262 List<String> irtList = new ArrayList<String>();
264 for (VpnTarget vpnTarget : vpnTargetList) {
265 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ExportExtcommunity) {
266 ertList.add(vpnTarget.getVrfRTValue());
268 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ImportExtcommunity) {
269 irtList.add(vpnTarget.getVrfRTValue());
271 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.Both) {
272 ertList.add(vpnTarget.getVrfRTValue());
273 irtList.add(vpnTarget.getVrfRTValue());
278 bgpManager.addVrf(rd, irtList, ertList);
279 } catch(Exception e) {
280 LOG.error("Exception when adding VRF to BGP", e);
283 //Try to add up vpn Interfaces if already in Operational Datastore
284 InstanceIdentifier<VpnInterfaces> vpnInterfacesId = InstanceIdentifier.builder(VpnInterfaces.class).build();
285 Optional<VpnInterfaces> optionalVpnInterfaces = read(LogicalDatastoreType.CONFIGURATION, vpnInterfacesId);
287 if(optionalVpnInterfaces.isPresent()) {
288 List<VpnInterface> vpnInterfaces = optionalVpnInterfaces.get().getVpnInterface();
289 for(VpnInterface vpnInterface : vpnInterfaces) {
290 if(vpnInterface.getVpnInstanceName().equals(value.getVpnInstanceName())) {
291 LOG.debug("VpnInterface {} will be added from VPN {}", vpnInterface.getName(), value.getVpnInstanceName());
292 vpnInterfaceManager.add(
293 VpnUtil.getVpnInterfaceIdentifier(vpnInterface.getName()), vpnInterface);
300 private InstanceIdentifier<?> getWildCardPath() {
301 return InstanceIdentifier.create(VpnInstances.class).child(VpnInstance.class);
304 private InstanceIdentifier<?> getFibEntryListenerPath() {
305 return InstanceIdentifier.create(FibEntries.class).child(VrfTables.class)
306 .child(VrfEntry.class);
309 private InstanceIdentifier<?> getVpnInstanceOpListenerPath() {
310 return InstanceIdentifier.create(VpnInstanceOpData.class).child(VpnInstanceOpDataEntry.class);
315 public void close() throws Exception {
316 if (listenerRegistration != null) {
318 listenerRegistration.close();
319 } catch (final Exception e) {
320 LOG.error("Error when cleaning up Vpn DataChangeListener.", e);
322 listenerRegistration = null;
324 if (fibListenerRegistration != null) {
326 fibListenerRegistration.close();
327 } catch (final Exception e) {
328 LOG.error("Error when cleaning up Fib entries DataChangeListener.", e);
330 fibListenerRegistration = null;
332 if (opListenerRegistration != null) {
334 opListenerRegistration.close();
335 } catch (final Exception e) {
336 LOG.error("Error when cleaning up VPN Instance Operational entries DataChangeListener.", e);
338 opListenerRegistration = null;
341 LOG.trace("VPN Manager Closed");
344 private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
345 InstanceIdentifier<T> path) {
347 ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
349 Optional<T> result = Optional.absent();
351 result = tx.read(datastoreType, path).get();
352 } catch (Exception e) {
353 throw new RuntimeException(e);
359 private <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
360 InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
361 WriteTransaction tx = broker.newWriteOnlyTransaction();
362 tx.put(datastoreType, path, data, true);
363 Futures.addCallback(tx.submit(), callback);
366 private <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
367 InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
368 WriteTransaction tx = broker.newWriteOnlyTransaction();
369 tx.put(datastoreType, path, data, true);
370 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
373 } catch (InterruptedException | ExecutionException e) {
374 LOG.error("Error writing VPN instance to ID info to datastore (path, data) : ({}, {})", path, data);
375 throw new RuntimeException(e.getMessage());
379 protected VpnInstanceOpDataEntry getVpnInstanceOpData(String rd) {
380 InstanceIdentifier<VpnInstanceOpDataEntry> id = VpnUtil.getVpnInstanceOpDataIdentifier(rd);
381 Optional<VpnInstanceOpDataEntry> vpnInstanceOpData = read(LogicalDatastoreType.OPERATIONAL, id);
382 if(vpnInstanceOpData.isPresent()) {
383 return vpnInstanceOpData.get();
388 private <T extends DataObject> void delete(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
389 WriteTransaction tx = broker.newWriteOnlyTransaction();
390 tx.delete(datastoreType, path);
391 Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
394 private class FibEntriesListener extends AbstractDataChangeListener<VrfEntry> {
396 public FibEntriesListener() {
397 super(VrfEntry.class);
401 protected void remove(InstanceIdentifier<VrfEntry> identifier,
403 LOG.trace("Remove Fib event - Key : {}, value : {} ", identifier, del);
404 final VrfTablesKey key = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
405 String rd = key.getRouteDistinguisher();
406 Long label = del.getLabel();
407 VpnInstanceOpDataEntry vpnInstanceOpData = getVpnInstanceOpData(rd);
408 if(vpnInstanceOpData != null) {
409 List<Long> routeIds = vpnInstanceOpData.getRouteEntryId();
410 if(routeIds == null) {
411 LOG.debug("Fib Route entry is empty.");
414 LOG.debug("Removing label from vpn info - {}", label);
415 routeIds.remove(label);
416 asyncWrite(LogicalDatastoreType.OPERATIONAL, VpnUtil.getVpnInstanceOpDataIdentifier(rd),
417 new VpnInstanceOpDataEntryBuilder(vpnInstanceOpData).setRouteEntryId(routeIds).build(), DEFAULT_CALLBACK);
419 LOG.warn("No VPN Instance found for RD: {}", rd);
424 protected void update(InstanceIdentifier<VrfEntry> identifier,
425 VrfEntry original, VrfEntry update) {
426 // TODO Auto-generated method stub
431 protected void add(InstanceIdentifier<VrfEntry> identifier,
433 LOG.trace("Add Vrf Entry event - Key : {}, value : {}", identifier, add);
434 final VrfTablesKey key = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
435 String rd = key.getRouteDistinguisher();
436 Long label = add.getLabel();
437 VpnInstanceOpDataEntry vpn = getVpnInstanceOpData(rd);
439 List<Long> routeIds = vpn.getRouteEntryId();
440 if(routeIds == null) {
441 routeIds = new ArrayList<>();
443 LOG.debug("Adding label to vpn info - {}", label);
445 asyncWrite(LogicalDatastoreType.OPERATIONAL, VpnUtil.getVpnInstanceOpDataIdentifier(rd),
446 new VpnInstanceOpDataEntryBuilder(vpn).setRouteEntryId(routeIds).build(), DEFAULT_CALLBACK);
448 LOG.warn("No VPN Instance found for RD: {}", rd);
453 class VpnInstanceOpListener extends org.opendaylight.vpnservice.mdsalutil.AbstractDataChangeListener<VpnInstanceOpDataEntry> {
455 public VpnInstanceOpListener() {
456 super(VpnInstanceOpDataEntry.class);
460 protected void remove(InstanceIdentifier<VpnInstanceOpDataEntry> identifier, VpnInstanceOpDataEntry del) {
465 protected void update(InstanceIdentifier<VpnInstanceOpDataEntry> identifier, VpnInstanceOpDataEntry original, VpnInstanceOpDataEntry update) {
466 final VpnInstanceOpDataEntryKey key = identifier.firstKeyOf(VpnInstanceOpDataEntry.class, VpnInstanceOpDataEntryKey.class);
467 String vpnName = key.getVrfId();
469 LOG.trace("VpnInstanceOpListener update: vpn name {} interface count in Old VpnOp Instance {} in New VpnOp Instance {}" ,
470 vpnName, original.getVpnInterfaceCount(), update.getVpnInterfaceCount() );
472 //if((original.getVpnToDpnList().size() != update.getVpnToDpnList().size()) && (update.getVpnToDpnList().size() == 0)) {
473 if((original.getVpnInterfaceCount() != update.getVpnInterfaceCount()) && (update.getVpnInterfaceCount() == 0)) {
474 notifyTaskIfRequired(vpnName);
478 private void notifyTaskIfRequired(String vpnName) {
479 Runnable notifyTask = vpnOpMap.remove(vpnName);
480 if (notifyTask == null) {
481 LOG.trace("VpnInstanceOpListener update: No Notify Task queued for vpnName {}", vpnName);
484 executorService.execute(notifyTask);
488 protected void add(InstanceIdentifier<VpnInstanceOpDataEntry> identifier, VpnInstanceOpDataEntry add) {