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