NETVIRT-1630 migrate to md-sal APIs
[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.genius.infra.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.genius.infra.Datastore;
21 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
22 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
23 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
24 import org.opendaylight.infrautils.utils.concurrent.Executors;
25 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
26 import org.opendaylight.mdsal.binding.api.DataBroker;
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             ListenableFutures.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         ListenableFutures.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                     snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
128                             SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_DISBL);
129                     if (origRouterToNaptSwitch.isEnableSnat()) {
130                         snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
131                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL);
132                     }
133                     natDataUtil.removeFromRouterMap(origRouter);
134                 }
135                 if (updatedRouter != null) {
136                     natDataUtil.updateRouterMap(updatedRouter);
137                     snatServiceManger.notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
138                             SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_ENBL);
139                     if (updatedRouterToNaptSwitch.isEnableSnat()) {
140                         snatServiceManger.notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
141                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
142                     }
143                 }
144             } else {
145                 boolean origIsSnatEnabled = false;
146                 boolean updatedIsSnatEnabled = false;
147                 if (origRouterToNaptSwitch.isEnableSnat() != null) {
148                     origIsSnatEnabled = origRouterToNaptSwitch.isEnableSnat();
149                 }
150                 if (updatedRouterToNaptSwitch.isEnableSnat() != null) {
151                     updatedIsSnatEnabled = updatedRouterToNaptSwitch.isEnableSnat();
152                 }
153                 if (origIsSnatEnabled != updatedIsSnatEnabled) {
154                     if (updatedRouterToNaptSwitch.isEnableSnat()) {
155                         snatServiceManger.notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
156                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
157                     } else {
158                         snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
159                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL);
160                     }
161                 }
162             }
163         }), LOG, "Error handling SNAT centralized switch update");
164     }
165
166     @Override
167     public void add(InstanceIdentifier<RouterToNaptSwitch> key, RouterToNaptSwitch routerToNaptSwitch) {
168         LOG.debug("Adding {}", routerToNaptSwitch);
169         if (natMode == NatMode.Controller) {
170             LOG.info("Do Not Processing this add() event for (routerName:designatedDpn) {}:{}"
171                             + "configured in Controller Mode",
172                     routerToNaptSwitch.getRouterName(), routerToNaptSwitch.getPrimarySwitchId());
173             return;
174         }
175         Uint64 primarySwitchId = routerToNaptSwitch.getPrimarySwitchId();
176         String routerName = routerToNaptSwitch.getRouterName();
177         Routers router = NatUtil.getRoutersFromConfigDS(dataBroker, routerName);
178         final boolean isEnableSnat;
179         if (routerToNaptSwitch.isEnableSnat() != null) {
180             isEnableSnat = routerToNaptSwitch.isEnableSnat();
181         } else {
182             isEnableSnat = false;
183         }
184         Uint32 vpnId = NatUtil.getVpnId(dataBroker, routerName);
185         if (vpnId == NatConstants.INVALID_ID) {
186             LOG.warn("VpnId not unavailable for router {} yet", routerName);
187             eventCallbacks.onAddOrUpdate(LogicalDatastoreType.CONFIGURATION,
188                 NatUtil.getVpnInstanceToVpnIdIdentifier(routerName), (unused, newVpnId) -> {
189                     ListenableFutures.addErrorLogging(
190                         txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
191                             innerConfTx -> handleAdd(innerConfTx, routerName, router, primarySwitchId,
192                                     isEnableSnat)), LOG,
193                         "Error handling router addition");
194                     return DataTreeEventCallbackRegistrar.NextAction.UNREGISTER;
195                 }, Duration.ofSeconds(5), iid -> LOG.error("VpnId not found for router {}", routerName));
196             return;
197         }
198         ListenableFutures.addErrorLogging(
199             txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
200                 confTx -> handleAdd(confTx, routerName, router, primarySwitchId,
201                         isEnableSnat)), LOG, "Error handling router addition");
202     }
203
204     private void handleAdd(TypedReadWriteTransaction<Datastore.Configuration> confTx,
205             String routerName, Routers router, Uint64 primarySwitchId, boolean isSnatEnabled)
206             throws ExecutionException, InterruptedException {
207         if (router != null) {
208             natDataUtil.addtoRouterMap(router);
209             snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
210                     SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_ENBL);
211             if (isSnatEnabled) {
212                 snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
213                         SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
214             }
215         } else {
216             LOG.error("Router {} not found for primarySwitch {}", routerName, primarySwitchId);
217         }
218     }
219 }