Convert Vpn Utilities to Singleton
[netvirt.git] / vpnmanager / impl / src / main / java / org / opendaylight / netvirt / vpnmanager / InterfaceStateChangeListener.java
1 /*
2  * Copyright (c) 2015, 2017 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 com.google.common.collect.HashBasedTable;
12 import com.google.common.collect.Table;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.math.BigInteger;
17 import java.util.ArrayList;
18 import java.util.List;
19 import javax.annotation.PostConstruct;
20 import javax.inject.Inject;
21 import javax.inject.Singleton;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
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.netvirt.vpnmanager.api.InterfaceUtils;
29 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface;
30 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.vpn._interface.VpnInstanceNames;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.L2vlan;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn._interface.op.data.VpnInterfaceOpDataEntry;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 @Singleton
41 public class InterfaceStateChangeListener
42     extends AsyncDataTreeChangeListenerBase<Interface, InterfaceStateChangeListener> {
43
44     private static final Logger LOG = LoggerFactory.getLogger(InterfaceStateChangeListener.class);
45     private static final short DJC_MAX_RETRIES = 3;
46     private final DataBroker dataBroker;
47     private final ManagedNewTransactionRunner txRunner;
48     private final VpnInterfaceManager vpnInterfaceManager;
49     private final VpnUtil vpnUtil;
50     private final JobCoordinator jobCoordinator;
51
52     Table<OperStatus, OperStatus, IntfTransitionState> stateTable = HashBasedTable.create();
53
54     enum IntfTransitionState {
55         STATE_UP,
56         STATE_DOWN,
57         STATE_IGNORE
58     }
59
60     private void initialize() {
61         //  Interface State Transition Table
62         //               Up                Down            Unknown
63         // ---------------------------------------------------------------
64         /* Up       { STATE_IGNORE,   STATE_DOWN,     STATE_IGNORE }, */
65         /* Down     { STATE_UP,       STATE_IGNORE,   STATE_IGNORE }, */
66         /* Unknown  { STATE_UP,       STATE_DOWN,     STATE_IGNORE }, */
67
68         stateTable.put(Interface.OperStatus.Up, Interface.OperStatus.Down, IntfTransitionState.STATE_DOWN);
69         stateTable.put(Interface.OperStatus.Down, Interface.OperStatus.Up, IntfTransitionState.STATE_UP);
70         stateTable.put(Interface.OperStatus.Unknown, Interface.OperStatus.Up, IntfTransitionState.STATE_UP);
71         stateTable.put(Interface.OperStatus.Unknown, Interface.OperStatus.Down, IntfTransitionState.STATE_DOWN);
72     }
73
74     @Inject
75     public InterfaceStateChangeListener(final DataBroker dataBroker, final VpnInterfaceManager vpnInterfaceManager,
76             final VpnUtil vpnUtil, final JobCoordinator jobCoordinator) {
77         super(Interface.class, InterfaceStateChangeListener.class);
78         this.dataBroker = dataBroker;
79         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
80         this.vpnInterfaceManager = vpnInterfaceManager;
81         this.vpnUtil = vpnUtil;
82         this.jobCoordinator = jobCoordinator;
83         initialize();
84     }
85
86     @PostConstruct
87     public void start() {
88         LOG.info("{} start", getClass().getSimpleName());
89         registerListener(LogicalDatastoreType.OPERATIONAL, dataBroker);
90     }
91
92
93     @Override
94     protected InstanceIdentifier<Interface> getWildCardPath() {
95         return InstanceIdentifier.create(InterfacesState.class).child(Interface.class);
96     }
97
98     @Override
99     protected InterfaceStateChangeListener getDataTreeChangeListener() {
100         return InterfaceStateChangeListener.this;
101     }
102
103
104     @Override
105     // TODO Clean up the exception handling
106     @SuppressWarnings("checkstyle:IllegalCatch")
107     protected void add(InstanceIdentifier<Interface> identifier, Interface intrf) {
108         try {
109             if (L2vlan.class.equals(intrf.getType())) {
110                 LOG.info("VPN Interface add event - intfName {} from InterfaceStateChangeListener",
111                                 intrf.getName());
112                 jobCoordinator.enqueueJob("VPNINTERFACE-" + intrf.getName(), () -> {
113                     List<ListenableFuture<Void>> futures = new ArrayList<>(3);
114                     futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(writeInvTxn -> {
115                         ListenableFuture<Void> configFuture
116                             = txRunner.callWithNewWriteOnlyTransactionAndSubmit(writeConfigTxn -> {
117                                 ListenableFuture<Void> operFuture
118                                     = txRunner.callWithNewWriteOnlyTransactionAndSubmit(writeOperTxn -> {
119                                         final String interfaceName = intrf.getName();
120                                         LOG.info("Detected interface add event for interface {}", interfaceName);
121                                         final VpnInterface vpnIf = vpnUtil.getConfiguredVpnInterface(interfaceName);
122                                         if (vpnIf != null) {
123                                             for (VpnInstanceNames vpnInterfaceVpnInstance :
124                                                     vpnIf.getVpnInstanceNames()) {
125                                                 String vpnName = vpnInterfaceVpnInstance.getVpnName();
126                                                 String primaryRd = vpnUtil.getPrimaryRd(vpnName);
127                                                 if (!vpnInterfaceManager.isVpnInstanceReady(vpnName)) {
128                                                     LOG.info("VPN Interface add event - intfName {} onto vpnName {} "
129                                                             + "running oper-driven, VpnInstance not ready, holding"
130                                                             + " on", vpnIf.getName(), vpnName);
131                                                 } else if (vpnUtil.isVpnPendingDelete(primaryRd)) {
132                                                     LOG.error("add: Ignoring addition of vpnInterface {}, as"
133                                                             + " vpnInstance {} with primaryRd {} is already marked for"
134                                                             + " deletion", interfaceName, vpnName, primaryRd);
135                                                 } else {
136                                                     BigInteger intfDpnId = BigInteger.ZERO;
137                                                     try {
138                                                         intfDpnId = InterfaceUtils.getDpIdFromInterface(intrf);
139                                                     } catch (Exception e) {
140                                                         LOG.error("Unable to retrieve dpnId for interface {}. "
141                                                                 + "Process vpn interface add failed",intrf.getName(),
142                                                                 e);
143                                                         return;
144                                                     }
145                                                     final BigInteger dpnId = intfDpnId;
146                                                     final int ifIndex = intrf.getIfIndex();
147                                                     LOG.info("VPN Interface add event - intfName {} onto vpnName {}"
148                                                             + " running oper-driven", vpnIf.getName(), vpnName);
149                                                     vpnInterfaceManager.processVpnInterfaceUp(dpnId, vpnIf, primaryRd,
150                                                             ifIndex, false, writeConfigTxn, writeOperTxn, writeInvTxn,
151                                                             intrf, vpnName);
152
153                                                 }
154                                             }
155
156                                         }
157                                     });
158                                 futures.add(operFuture);
159                                 operFuture.get(); //Synchronous submit of operTxn
160                             });
161                         futures.add(configFuture);
162                         //TODO: Allow immediateFailedFuture from writeCfgTxn to cancel writeInvTxn as well.
163                         Futures.addCallback(configFuture, new PostVpnInterfaceThreadWorker(intrf.getName(), true,
164                                 "Operational"));
165                     }));
166                     return futures;
167                 });
168             }
169         } catch (Exception e) {
170             LOG.error("Exception caught in Interface {} Operational State Up event", intrf.getName(), e);
171         }
172     }
173
174     @Override
175     // TODO Clean up the exception handling
176     @SuppressWarnings("checkstyle:IllegalCatch")
177     protected void remove(InstanceIdentifier<Interface> identifier, Interface intrf) {
178         final String ifName = intrf.getName();
179         BigInteger dpId = BigInteger.ZERO;
180         try {
181             if (L2vlan.class.equals(intrf.getType())) {
182                 LOG.info("VPN Interface remove event - intfName {} from InterfaceStateChangeListener",
183                                 intrf.getName());
184                 try {
185                     dpId = InterfaceUtils.getDpIdFromInterface(intrf);
186                 } catch (Exception e) {
187                     LOG.error("Unable to retrieve dpnId from interface operational data store for interface"
188                             + " {}. Fetching from vpn interface op data store. ", ifName, e);
189                 }
190                 final BigInteger inputDpId = dpId;
191                 jobCoordinator.enqueueJob("VPNINTERFACE-" + ifName, () -> {
192                     List<ListenableFuture<Void>> futures = new ArrayList<>(3);
193                     ListenableFuture<Void> configFuture = txRunner.callWithNewWriteOnlyTransactionAndSubmit(
194                         writeConfigTxn -> futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(
195                             writeOperTxn -> futures.add(
196                                     txRunner.callWithNewWriteOnlyTransactionAndSubmit(writeInvTxn -> {
197                                         VpnInterface cfgVpnInterface =
198                                                 vpnUtil.getConfiguredVpnInterface(ifName);
199                                         if (cfgVpnInterface == null) {
200                                             LOG.debug("Interface {} is not a vpninterface, ignoring.", ifName);
201                                             return;
202                                         }
203                                         for (VpnInstanceNames vpnInterfaceVpnInstance :
204                                                 cfgVpnInterface.getVpnInstanceNames()) {
205                                             String vpnName = vpnInterfaceVpnInstance.getVpnName();
206                                             Optional<VpnInterfaceOpDataEntry> optVpnInterface =
207                                                     vpnUtil.getVpnInterfaceOpDataEntry(ifName, vpnName);
208                                             if (!optVpnInterface.isPresent()) {
209                                                 LOG.debug("Interface {} vpn {} is not a vpninterface, or deletion"
210                                                         + " triggered by northbound agent. ignoring.", ifName, vpnName);
211                                                 continue;
212                                             }
213                                             final VpnInterfaceOpDataEntry vpnInterface = optVpnInterface.get();
214                                             String gwMac = intrf.getPhysAddress() != null ? intrf.getPhysAddress()
215                                                     .getValue() : vpnInterface.getGatewayMacAddress();
216                                             BigInteger dpnId = inputDpId;
217                                             if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
218                                                 dpnId = vpnInterface.getDpnId();
219                                             }
220                                             final int ifIndex = intrf.getIfIndex();
221                                             LOG.info("VPN Interface remove event - intfName {} onto vpnName {}"
222                                                     + " running oper-driver", vpnInterface.getName(), vpnName);
223                                             vpnInterfaceManager.processVpnInterfaceDown(dpnId, ifName, ifIndex, gwMac,
224                                                     vpnInterface, false, writeConfigTxn, writeOperTxn, writeInvTxn);
225                                         }
226                                     })))));
227                     futures.add(configFuture);
228                     Futures.addCallback(configFuture, new PostVpnInterfaceThreadWorker(intrf.getName(), false,
229                             "Operational"));
230                     return futures;
231                 }, DJC_MAX_RETRIES);
232             }
233         } catch (Exception e) {
234             LOG.error("Exception observed in handling deletion of VPN Interface {}. ", ifName, e);
235         }
236     }
237
238     // TODO Clean up the exception handling
239     @SuppressWarnings("checkstyle:IllegalCatch")
240     @Override
241     protected void update(InstanceIdentifier<Interface> identifier,
242                     Interface original, Interface update) {
243         final String ifName = update.getName();
244         try {
245             if (update.getIfIndex() == null) {
246                 return;
247             }
248             if (L2vlan.class.equals(update.getType())) {
249                 LOG.info("VPN Interface update event - intfName {} from InterfaceStateChangeListener",
250                         update.getName());
251                 jobCoordinator.enqueueJob("VPNINTERFACE-" + ifName, () -> {
252                     List<ListenableFuture<Void>> futures = new ArrayList<>(3);
253                     futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(writeOperTxn -> futures.add(
254                             txRunner.callWithNewWriteOnlyTransactionAndSubmit(writeConfigTxn -> futures.add(
255                                 txRunner.callWithNewWriteOnlyTransactionAndSubmit(writeInvTxn -> {
256                                     final VpnInterface vpnIf =
257                                             vpnUtil.getConfiguredVpnInterface(ifName);
258                                     if (vpnIf != null) {
259                                         final int ifIndex = update.getIfIndex();
260                                         BigInteger dpnId = BigInteger.ZERO;
261                                         try {
262                                             dpnId = InterfaceUtils.getDpIdFromInterface(update);
263                                         } catch (Exception e) {
264                                             LOG.error("remove: Unable to retrieve dpnId for interface {}", ifName, e);
265                                             return;
266                                         }
267                                         IntfTransitionState state = getTransitionState(original.getOperStatus(),
268                                                 update.getOperStatus());
269                                         if (state.equals(IntfTransitionState.STATE_IGNORE)) {
270                                             LOG.info("InterfaceStateChangeListener: Interface {} state original {}"
271                                                     + "updated {} not handled", ifName, original.getOperStatus(),
272                                                     update.getOperStatus());
273                                             return;
274                                         }
275                                         if (state.equals(IntfTransitionState.STATE_UP)) {
276                                             for (VpnInstanceNames vpnInterfaceVpnInstance :
277                                                     vpnIf.getVpnInstanceNames()) {
278                                                 String vpnName = vpnInterfaceVpnInstance.getVpnName();
279                                                 String primaryRd = vpnUtil.getPrimaryRd(vpnName);
280                                                 if (!vpnInterfaceManager.isVpnInstanceReady(vpnName)) {
281                                                     LOG.error(
282                                                             "VPN Interface update event - intfName {} onto vpnName {} "
283                                                                     + "running oper-driven UP, VpnInstance not ready,"
284                                                             + " holding on", vpnIf.getName(), vpnName);
285                                                 } else if (vpnUtil.isVpnPendingDelete(primaryRd)) {
286                                                     LOG.error("update: Ignoring UP event for vpnInterface {}, as "
287                                                             + "vpnInstance {} with primaryRd {} is already marked for"
288                                                             + " deletion", vpnIf.getName(), vpnName, primaryRd);
289                                                 } else {
290                                                     vpnInterfaceManager.processVpnInterfaceUp(dpnId, vpnIf, primaryRd,
291                                                             ifIndex, true, writeConfigTxn, writeOperTxn, writeInvTxn,
292                                                             update, vpnName);
293                                                 }
294                                             }
295                                         } else if (state.equals(IntfTransitionState.STATE_DOWN)) {
296                                             for (VpnInstanceNames vpnInterfaceVpnInstance :
297                                                     vpnIf.getVpnInstanceNames()) {
298                                                 String vpnName = vpnInterfaceVpnInstance.getVpnName();
299                                                 LOG.info("VPN Interface update event - intfName {} onto vpnName {}"
300                                                        + " running oper-driven DOWN", vpnIf.getName(), vpnName);
301                                                 Optional<VpnInterfaceOpDataEntry> optVpnInterface =
302                                                      vpnUtil.getVpnInterfaceOpDataEntry(vpnIf.getName(), vpnName);
303                                                 if (optVpnInterface.isPresent()) {
304                                                     VpnInterfaceOpDataEntry vpnOpInterface = optVpnInterface.get();
305                                                     vpnInterfaceManager.processVpnInterfaceDown(dpnId, vpnIf.getName(),
306                                                             ifIndex, update.getPhysAddress().getValue(), vpnOpInterface,
307                                                             true, writeConfigTxn, writeOperTxn, writeInvTxn);
308                                                 } else {
309                                                     LOG.error(
310                                                             "InterfaceStateChangeListener Update DOWN - vpnInterface {}"
311                                                             + " not available, ignoring event", vpnIf.getName());
312                                                     continue;
313                                                 }
314                                             }
315                                         }
316                                     } else {
317                                         LOG.debug("Interface {} is not a vpninterface, ignoring.", ifName);
318                                     }
319                                 }))))));
320                     return futures;
321                 });
322             }
323         } catch (Exception e) {
324             LOG.error("Exception observed in handling updation of VPN Interface {}. ", update.getName(), e);
325         }
326     }
327
328     private class PostVpnInterfaceThreadWorker implements FutureCallback<Void> {
329         private final String interfaceName;
330         private final boolean add;
331         private final String txnDestination;
332
333         PostVpnInterfaceThreadWorker(String interfaceName, boolean add, String transactionDest) {
334             this.interfaceName = interfaceName;
335             this.add = add;
336             this.txnDestination = transactionDest;
337         }
338
339         @Override
340         public void onSuccess(Void voidObj) {
341             if (add) {
342                 LOG.debug("InterfaceStateChangeListener: VrfEntries for {} stored into destination {} successfully",
343                         interfaceName, txnDestination);
344             } else {
345                 LOG.debug("InterfaceStateChangeListener:  VrfEntries for {} removed successfully", interfaceName);
346             }
347         }
348
349         @Override
350         public void onFailure(Throwable throwable) {
351             if (add) {
352                 LOG.error("InterfaceStateChangeListener: VrfEntries for {} failed to store into destination {}",
353                         interfaceName, txnDestination, throwable);
354             } else {
355                 LOG.error("InterfaceStateChangeListener: VrfEntries for {} removal failed", interfaceName, throwable);
356                 vpnUtil.unsetScheduledToRemoveForVpnInterface(interfaceName);
357             }
358         }
359     }
360
361     private IntfTransitionState getTransitionState(Interface.OperStatus original , Interface.OperStatus updated) {
362         IntfTransitionState transitionState = stateTable.get(original, updated);
363
364         if (transitionState == null) {
365             return IntfTransitionState.STATE_IGNORE;
366         }
367         return transitionState;
368     }
369 }