Upgrade to the Neon base platform
[netvirt.git] / vpnmanager / impl / src / main / java / org / opendaylight / netvirt / vpnmanager / VpnInterfaceOpListener.java
1 /*
2  * Copyright (c) 2015 - 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.vpnmanager;
9
10 import static org.opendaylight.netvirt.vpnmanager.VpnUtil.requireNonNullElse;
11
12 import com.google.common.base.Optional;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.List;
16 import java.util.concurrent.ExecutorService;
17 import java.util.concurrent.Executors;
18 import javax.annotation.PostConstruct;
19 import javax.inject.Inject;
20 import javax.inject.Singleton;
21 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
22 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
25 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
26 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
27 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
28 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
29 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
30 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.AdjacenciesOp;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnInterfaceOpData;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.adjacency.list.Adjacency;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.Prefixes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn._interface.op.data.VpnInterfaceOpDataEntry;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn._interface.op.data.VpnInterfaceOpDataEntryKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.to.vpn.id.VpnInstance;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 @Singleton
44 public class VpnInterfaceOpListener extends AsyncDataTreeChangeListenerBase<VpnInterfaceOpDataEntry,
45                                                                      VpnInterfaceOpListener> {
46     private static final Logger LOG = LoggerFactory.getLogger(VpnInterfaceOpListener.class);
47     private final DataBroker dataBroker;
48     private final ManagedNewTransactionRunner txRunner;
49     private final VpnInterfaceManager vpnInterfaceManager;
50     private final VpnFootprintService vpnFootprintService;
51     private final JobCoordinator jobCoordinator;
52     private final ExecutorService executorService = Executors.newSingleThreadExecutor();
53     private final VpnUtil vpnUtil;
54
55     /*public VpnInterfaceOpListener(final DataBroker dataBroker) {
56         super(VpnInterface.class);
57         this.dataBroker = dataBroker;
58     }*/
59
60     @Inject
61     public VpnInterfaceOpListener(final DataBroker dataBroker, final VpnInterfaceManager vpnInterfaceManager,
62         final VpnFootprintService vpnFootprintService, final JobCoordinator jobCoordinator,
63                                   final VpnUtil vpnUtil) {
64         super(VpnInterfaceOpDataEntry.class, VpnInterfaceOpListener.class);
65         this.dataBroker = dataBroker;
66         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
67         this.vpnInterfaceManager = vpnInterfaceManager;
68         this.vpnFootprintService = vpnFootprintService;
69         this.jobCoordinator = jobCoordinator;
70         this.vpnUtil = vpnUtil;
71     }
72
73     @PostConstruct
74     public void start() {
75         LOG.info("{} start", getClass().getSimpleName());
76         registerListener(LogicalDatastoreType.OPERATIONAL, dataBroker);
77     }
78
79     @Override
80     protected InstanceIdentifier<VpnInterfaceOpDataEntry> getWildCardPath() {
81         InstanceIdentifier<VpnInterfaceOpDataEntry> id = InstanceIdentifier.create(VpnInterfaceOpData.class
82                 ).child(VpnInterfaceOpDataEntry.class);
83         return id;
84     }
85
86     @Override
87     protected VpnInterfaceOpListener getDataTreeChangeListener() {
88         return VpnInterfaceOpListener.this;
89     }
90
91
92     @Override
93     protected void remove(final InstanceIdentifier<VpnInterfaceOpDataEntry> identifier,
94             final VpnInterfaceOpDataEntry del) {
95         final VpnInterfaceOpDataEntryKey key = identifier.firstKeyOf(VpnInterfaceOpDataEntry.class);
96         final String interfaceName = key.getName();
97         jobCoordinator.enqueueJob("VPNINTERFACE-" + interfaceName,
98             () -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(tx -> {
99                 postProcessVpnInterfaceRemoval(identifier, del, tx);
100                 LOG.info("remove: Removed vpn operational data for interface {} on dpn {} vpn {}", del.getName(),
101                         del.getDpnId(), del.getVpnInstanceName());
102             })));
103     }
104
105     private void postProcessVpnInterfaceRemoval(InstanceIdentifier<VpnInterfaceOpDataEntry> identifier,
106             VpnInterfaceOpDataEntry del, ReadWriteTransaction readWriteTxn) {
107         if (readWriteTxn == null) {
108             ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(tx ->
109                             postProcessVpnInterfaceRemoval(identifier, del, tx)), LOG,
110                     "Error post-processing VPN interface removal");
111             return;
112         }
113         final VpnInterfaceOpDataEntryKey key = identifier.firstKeyOf(VpnInterfaceOpDataEntry.class);
114         String interfaceName = key.getName();
115         String vpnName = del.getVpnInstanceName();
116         try {
117             LOG.info("postProcessVpnInterfaceRemoval: interface name {} vpnName {} dpn {}", interfaceName, vpnName,
118                     del.getDpnId());
119             //decrement the vpn interface count in Vpn Instance Op Data
120             Optional<VpnInstance> vpnInstance = readWriteTxn.read(LogicalDatastoreType.CONFIGURATION,
121                     VpnOperDsUtils.getVpnInstanceToVpnIdIdentifier(vpnName)).checkedGet();
122
123             if (vpnInstance.isPresent()) {
124                 String rd = vpnInstance.get().getVrfId();
125
126                 VpnInstanceOpDataEntry vpnInstOp = vpnUtil.getVpnInstanceOpData(rd);
127
128                 AdjacenciesOp adjs = del.augmentation(AdjacenciesOp.class);
129                 List<Adjacency> adjList = adjs != null ? adjs.getAdjacency() : null;
130
131                 if (vpnInstOp != null && adjList != null && adjList.size() > 0) {
132                 /*
133                  * When a VPN Interface is removed by FibManager (aka VrfEntryListener and its cohorts),
134                  * one adjacency or two adjacency (in case of dual-stack)
135                  * for that VPN Interface will be hanging around along with that
136                  * VPN Interface.   That adjacency could be primary (or) non-primary.
137                  * If its a primary adjacency, then a prefix-to-interface entry will be available for the
138                  * same.  If its a non-primary adjacency, then a prefix-to-interface entry will not be
139                  * available for the same, instead we will have vpn-to-extraroutes filled in for them.
140                  *
141                  * Here we try to remove prefix-to-interface entry for pending adjacency in the deleted
142                  * vpnInterface.   More importantly, we also update the vpnInstanceOpData by removing this
143                  * vpnInterface from it.
144                  */
145                     List<Prefixes> prefixToInterface = new ArrayList<>();
146                     for (Adjacency adjacency : adjs.getAdjacency()) {
147                         List<Prefixes> prefixToInterfaceLocal = new ArrayList<>();
148                         Optional<Prefixes> prefix = SingleTransactionDataBroker.syncReadOptional(dataBroker,
149                                 LogicalDatastoreType.OPERATIONAL,
150                                 VpnUtil.getPrefixToInterfaceIdentifier(vpnInstOp.getVpnId(),
151                                         VpnUtil.getIpPrefix(adjacency.getIpAddress())));
152                         if (prefix.isPresent()) {
153                             prefixToInterfaceLocal.add(prefix.get());
154                         }
155                         if (prefixToInterfaceLocal.isEmpty()) {
156                             for (String nh : requireNonNullElse(adjacency.getNextHopIpList(),
157                                     Collections.<String>emptyList())) {
158                                 prefix = SingleTransactionDataBroker.syncReadOptional(dataBroker,
159                                         LogicalDatastoreType.OPERATIONAL, VpnUtil.getPrefixToInterfaceIdentifier(
160                                                 vpnInstOp.getVpnId(), VpnUtil.getIpPrefix(nh)));
161                                 if (prefix.isPresent()) {
162                                     prefixToInterfaceLocal.add(prefix.get());
163                                 }
164                             }
165                         }
166                         if (!prefixToInterfaceLocal.isEmpty()) {
167                             prefixToInterface.addAll(prefixToInterfaceLocal);
168                         }
169                     }
170                 /*
171                  * In VPN Migration scenarios, there is a race condition where we use the new DPNID
172                  * for the migrated VM instead of old DPNID because when we read prefix-to-interface to cleanup
173                  * old DPNID, we actually get the new DPNID.
174                  *
175                  * More dangerously, we tend to alter the new prefix-to-interface which should be retained intac
176                  * for the migration to succeed in L3VPN.  As a workaround, here we are going to use the dpnId in
177                  * the deleted vpnInterface itself instead of tinkering with the prefix-to-interface.  Further we
178                  * will tinker prefix-to-interface only when are damn sure if its value matches our
179                  * deleted vpnInterface.
180                  *
181                  */
182                     for (Prefixes pref : prefixToInterface) {
183                         if (VpnUtil.isMatchedPrefixToInterface(pref, del)) {
184                             readWriteTxn.delete(LogicalDatastoreType.OPERATIONAL,
185                                     VpnUtil.getPrefixToInterfaceIdentifier(vpnInstOp.getVpnId(), pref.getIpAddress()));
186                         }
187                     }
188                 }
189                 if (del.getDpnId() != null) {
190                     vpnFootprintService.updateVpnToDpnMapping(del.getDpnId(), del.getVpnInstanceName(), rd,
191                             interfaceName, null /*ipAddressSourceValuePair*/,
192                             false /* do delete */);
193                 }
194                 LOG.info("postProcessVpnInterfaceRemoval: Removed vpn operational data and updated vpn footprint"
195                         + " for interface {} on dpn {} vpn {}", interfaceName, del.getDpnId(), vpnName);
196             } else {
197                 LOG.error("postProcessVpnInterfaceRemoval: rd not retrievable as vpninstancetovpnid for vpn {}"
198                         + " is absent, trying rd as {}. interface {} dpn {}", vpnName, vpnName, interfaceName,
199                         del.getDpnId());
200             }
201             notifyTaskIfRequired(interfaceName);
202         } catch (ReadFailedException e) {
203             LOG.error("postProcessVpnInterfaceRemoval: Failed to read data store for interface {} vpn {}",
204                     interfaceName, vpnName);
205         }
206     }
207
208     private void notifyTaskIfRequired(String intfName) {
209         Runnable notifyTask = vpnInterfaceManager.isNotifyTaskQueued(intfName);
210         if (notifyTask == null) {
211             LOG.debug("notifyTaskIfRequired: No tasks queued to wait for deletion of vpnInterface {}", intfName);
212             return;
213         }
214         executorService.execute(notifyTask);
215     }
216
217     @Override
218     protected void update(final InstanceIdentifier<VpnInterfaceOpDataEntry> identifier,
219             final VpnInterfaceOpDataEntry original, final VpnInterfaceOpDataEntry update) {
220         LOG.info("update: interface {} vpn {}", original.getName(), original.getVpnInstanceName());
221     }
222
223     @Override
224     protected void add(InstanceIdentifier<VpnInterfaceOpDataEntry> identifier, VpnInterfaceOpDataEntry add) {
225         LOG.info("add: interface {} vpn {}. Ignoring", add.getName(), add.getVpnInstanceName());
226     }
227 }