Freeze upstream versions
[netvirt.git] / natservice / impl / src / main / java / org / opendaylight / netvirt / natservice / ha / SnatCentralizedSwitchChangeListener.java
1 /*
2  * Copyright (c) 2017, 2018 Red Hat, Inc. 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
9 package org.opendaylight.netvirt.natservice.ha;
10
11 import static org.opendaylight.mdsal.binding.util.Datastore.CONFIGURATION;
12
13 import java.time.Duration;
14 import java.util.Objects;
15 import java.util.concurrent.ExecutionException;
16 import javax.annotation.PreDestroy;
17 import javax.inject.Inject;
18 import javax.inject.Singleton;
19 import org.opendaylight.genius.datastoreutils.listeners.DataTreeEventCallbackRegistrar;
20 import org.opendaylight.infrautils.utils.concurrent.Executors;
21 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
22 import org.opendaylight.mdsal.binding.api.DataBroker;
23 import org.opendaylight.mdsal.binding.util.Datastore.Configuration;
24 import org.opendaylight.mdsal.binding.util.ManagedNewTransactionRunner;
25 import org.opendaylight.mdsal.binding.util.ManagedNewTransactionRunnerImpl;
26 import org.opendaylight.mdsal.binding.util.TypedReadWriteTransaction;
27 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.netvirt.natservice.api.SnatServiceManager;
29 import org.opendaylight.netvirt.natservice.internal.NatConstants;
30 import org.opendaylight.netvirt.natservice.internal.NatUtil;
31 import org.opendaylight.serviceutils.tools.listener.AbstractAsyncDataTreeChangeListener;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig.NatMode;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.NaptSwitches;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.Routers;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitch;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
38 import org.opendaylight.yangtools.yang.common.Uint32;
39 import org.opendaylight.yangtools.yang.common.Uint64;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * CentralizedSwitchChangeListener detect changes in switch:router mapping and
45  * update flows accordingly.
46  */
47 @Singleton
48 public class SnatCentralizedSwitchChangeListener
49         extends AbstractAsyncDataTreeChangeListener<RouterToNaptSwitch> {
50
51     private static final Logger LOG = LoggerFactory.getLogger(SnatCentralizedSwitchChangeListener.class);
52     private final DataBroker dataBroker;
53     private final ManagedNewTransactionRunner txRunner;
54     private final SnatServiceManager snatServiceManger;
55     private final NatDataUtil natDataUtil;
56     private final DataTreeEventCallbackRegistrar eventCallbacks;
57     private final NatMode natMode;
58
59     @Inject
60     public SnatCentralizedSwitchChangeListener(final DataBroker dataBroker,
61             final SnatServiceManager snatServiceManger, NatDataUtil natDataUtil, final NatserviceConfig config,
62             final DataTreeEventCallbackRegistrar dataTreeEventCallbackRegistrar) {
63         super(dataBroker, LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(NaptSwitches.class)
64                 .child(RouterToNaptSwitch.class),
65                 Executors.newListeningSingleThreadExecutor("SnatCentralizedSwitchChangeListener", LOG));
66         this.dataBroker = dataBroker;
67         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
68         this.snatServiceManger = snatServiceManger;
69         this.natDataUtil = natDataUtil;
70         this.eventCallbacks = dataTreeEventCallbackRegistrar;
71         if (config != null) {
72             this.natMode = config.getNatMode();
73         } else {
74             LOG.info("NAT mode configured default as Controller as config is missing");
75             this.natMode = NatMode.Controller;
76         }
77     }
78
79     public void init() {
80         LOG.info("{} init", getClass().getSimpleName());
81     }
82
83     @Override
84     @PreDestroy
85     public void close() {
86         super.close();
87         Executors.shutdownAndAwaitTermination(getExecutorService());
88     }
89
90     @Override
91     public void remove(InstanceIdentifier<RouterToNaptSwitch> key, RouterToNaptSwitch routerToNaptSwitch) {
92         LOG.debug("Deleting {}", routerToNaptSwitch);
93         if (natMode == NatMode.Controller) {
94             LOG.info("Do Not Processing this remove() event for (routerName:designatedDpn) {}:{}"
95                     + "configured in Controller Mode",
96                     routerToNaptSwitch.getRouterName(), routerToNaptSwitch.getPrimarySwitchId());
97             return;
98         }
99         Uint64 primarySwitchId = routerToNaptSwitch.getPrimarySwitchId();
100         Routers router = natDataUtil.getRouter(routerToNaptSwitch.getRouterName());
101         if (router != null) {
102             LoggingFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
103                 confTx -> snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
104                     SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL)), LOG,
105                 "error handling SNAT centralized switch removal");
106             natDataUtil.removeFromRouterMap(router);
107         }
108     }
109
110     @Override
111     public void update(InstanceIdentifier<RouterToNaptSwitch> key, RouterToNaptSwitch origRouterToNaptSwitch,
112             RouterToNaptSwitch updatedRouterToNaptSwitch) {
113         LOG.debug("Updating old {} new {}", origRouterToNaptSwitch, updatedRouterToNaptSwitch);
114         if (natMode == NatMode.Controller) {
115             LOG.info("Do Not Processing this update() event for (routerName:designatedDpn) {}:{}"
116                             + "configured in Controller Mode",
117                     updatedRouterToNaptSwitch.getRouterName(), updatedRouterToNaptSwitch.getPrimarySwitchId());
118             return;
119         }
120         Uint64 origPrimarySwitchId = origRouterToNaptSwitch.getPrimarySwitchId();
121         Uint64 updatedPrimarySwitchId = updatedRouterToNaptSwitch.getPrimarySwitchId();
122         LoggingFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, confTx -> {
123             Routers origRouter = NatUtil.getRoutersFromConfigDS(confTx, origRouterToNaptSwitch.getRouterName());
124             Routers updatedRouter = NatUtil.getRoutersFromConfigDS(confTx, updatedRouterToNaptSwitch.getRouterName());
125             if (!Objects.equals(origPrimarySwitchId, updatedPrimarySwitchId)) {
126                 if (origRouter != null) {
127                     try {
128                         snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
129                                 SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_DISBL);
130                         if (origRouterToNaptSwitch.isEnableSnat()) {
131                             snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
132                                     SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL);
133                         }
134                     } catch (ExecutionException | InterruptedException e) {
135                         LOG.error("Exception while notifying snatManager for : {}", origRouter, e);
136                     }
137                     natDataUtil.removeFromRouterMap(origRouter);
138                 }
139                 if (updatedRouter != null) {
140                     natDataUtil.updateRouterMap(updatedRouter);
141                     try {
142                         snatServiceManger
143                             .notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
144                                 SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_ENBL);
145                         if (updatedRouterToNaptSwitch.isEnableSnat()) {
146                             snatServiceManger
147                                 .notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
148                                     SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
149                         }
150                     } catch (ExecutionException | InterruptedException e) {
151                         LOG.error("Exception while notifying snatManager for : {}", updatedRouter, e);
152                     }
153                 }
154             } else {
155                 boolean origIsSnatEnabled = false;
156                 boolean updatedIsSnatEnabled = false;
157                 if (origRouterToNaptSwitch.isEnableSnat() != null) {
158                     origIsSnatEnabled = origRouterToNaptSwitch.isEnableSnat();
159                 }
160                 if (updatedRouterToNaptSwitch.isEnableSnat() != null) {
161                     updatedIsSnatEnabled = updatedRouterToNaptSwitch.isEnableSnat();
162                 }
163                 if (origIsSnatEnabled != updatedIsSnatEnabled) {
164                     if (updatedRouterToNaptSwitch.isEnableSnat()) {
165                         snatServiceManger.notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
166                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
167                     } else {
168                         snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
169                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL);
170                     }
171
172                 }
173             }
174         }), LOG, "Error handling SNAT centralized switch update");
175     }
176
177     @Override
178     public void add(InstanceIdentifier<RouterToNaptSwitch> key, RouterToNaptSwitch routerToNaptSwitch) {
179         LOG.debug("Adding {}", routerToNaptSwitch);
180         if (natMode == NatMode.Controller) {
181             LOG.info("Do Not Processing this add() event for (routerName:designatedDpn) {}:{}"
182                             + "configured in Controller Mode",
183                     routerToNaptSwitch.getRouterName(), routerToNaptSwitch.getPrimarySwitchId());
184             return;
185         }
186         Uint64 primarySwitchId = routerToNaptSwitch.getPrimarySwitchId();
187         String routerName = routerToNaptSwitch.getRouterName();
188         Routers router = NatUtil.getRoutersFromConfigDS(dataBroker, routerName);
189         final boolean isEnableSnat;
190         if (routerToNaptSwitch.isEnableSnat() != null) {
191             isEnableSnat = routerToNaptSwitch.isEnableSnat();
192         } else {
193             isEnableSnat = false;
194         }
195         Uint32 vpnId = NatUtil.getVpnId(dataBroker, routerName);
196         if (vpnId == NatConstants.INVALID_ID) {
197             LOG.warn("VpnId not unavailable for router {} yet", routerName);
198             eventCallbacks.onAddOrUpdate(LogicalDatastoreType.CONFIGURATION,
199                 NatUtil.getVpnInstanceToVpnIdIdentifier(routerName), (unused, newVpnId) -> {
200                     LoggingFutures.addErrorLogging(
201                         txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
202                             innerConfTx -> handleAdd(innerConfTx, routerName, router, primarySwitchId,
203                                     isEnableSnat)), LOG,
204                         "Error handling router addition");
205                     return DataTreeEventCallbackRegistrar.NextAction.UNREGISTER;
206                 }, Duration.ofSeconds(5), iid -> LOG.error("VpnId not found for router {}", routerName));
207             return;
208         }
209         LoggingFutures.addErrorLogging(
210             txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
211                 confTx -> handleAdd(confTx, routerName, router, primarySwitchId,
212                         isEnableSnat)), LOG, "Error handling router addition");
213     }
214
215     private void handleAdd(TypedReadWriteTransaction<Configuration> confTx,
216             String routerName, Routers router, Uint64 primarySwitchId, boolean isSnatEnabled) {
217         if (router != null) {
218             natDataUtil.addtoRouterMap(router);
219             try {
220                 snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
221                     SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_ENBL);
222                 if (isSnatEnabled) {
223                     snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
224                         SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
225                 }
226             } catch (ExecutionException | InterruptedException e) {
227                 LOG.error("Exception while notfiying for {}", router, e);
228             }
229         } else {
230             LOG.error("Router {} not found for primarySwitch {}", routerName, primarySwitchId);
231         }
232     }
233 }